Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install agent-platform-architecture@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin agent-platform-architecture v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install agent-platform-architecture

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/agent-platform-architecture/

Extract the ZIP to .github/skills/ in your repo. The folder name must match agent-platform-architecture for Copilot to auto-discover it.

Skill Files (9)

SKILL.md 14.5 KB
---
name: agent-platform-architecture
description: >-
  Designs, engineers, and validates enterprise Gemini platform
  architectures. Use when designing multi-project
  hierarchies (Host, Central Governance Hub, Runtime Spoke, Tool/MCP Spoke),
  configuring Agent Gateway, authoring Agent Connectivity Templates (ALL_TRAFFIC
  vs PRIVATE_RANGES_ONLY), deploying Secure Web Proxy (SWP) with Policy-Based
  Routing (PBR) or Cross-Cloud mTLS Egress Hubs, configuring Private CA
  TrustConfig with Internal ALB + Serverless NEG, implementing Unified Access
  Policies (UAP Policy V2 CEL) and Semantic Governance (SGP), configuring 3P IdP
  Token Exchange (EntraID/Ping/Okta via ext_proc + STS) or Agent Identity Auth
  Manager (SPIFFE), enforcing Model Armor Floor Settings and Fail-Closed
  guardrails, deploying Cross-Project Registry sync, binding ADK agents on Agent
  Runtime, or executing Day-2 lifecycle operations. Don't use for read-only live
  log triage or incident diagnosis, or generic Google Cloud Identity and Access
  Management (IAM) debugging.
license: Apache-2.0
metadata:
  version: "1.0.2"
  category: AiAndMachineLearning
---

# Gemini platform Architecture and Engineering Guide

This skill is the reference system for designing, engineering, and validating enterprise-grade **Gemini platform** architectures across multi-project hierarchies, hybrid/cross-cloud networks, zero-trust identity boundaries, and inline safety/policy enforcement planes.

## Usage Attribution

When executing `gcloud`, REST API, or MCP commands directly against Google Cloud
with this skill, see [Usage Attribution](references/attribution.md) to attach a
standard non-PII Google Cloud skill identifier (carries no user, project, or
prompt data; users may opt out at any time).

> [!IMPORTANT] **Architectural Scope and Reference Discipline**: Use `SKILL.md` to
> select the target topology, egress mode, ingress pattern, and governance
> plane, then consult the authoritative `references/*.md` manual for exact CLI
> commands, REST/YAML schemas, Common Expression Language (CEL) expressions, and
> Python Agent Development Kit (ADK) runtime code (`references/*.md` is the
> single source of truth for all implementation syntax). When remote Model
> Context Protocol (MCP) tools (such as the Google Developer Knowledge MCP
> server or Google-managed MCP endpoints) are available, prefer remote MCP tool
> invocation over raw CLI/REST commands. Do not execute unrequested live
> mutations against customer projects when asked for architectural designs.

> [!CAUTION] **Human Approval Gate for Sensitive Operations**: Always prompt the
> user for explicit confirmation before executing commands or applying
> configurations that grant permissive Identity and Access Management (IAM)
> bindings (`roles/iap.egressor`, `roles/compute.networkUser`,
> `roles/networkservices.admin`), modify Organization Policies
> (`constraints/iam.managed.disableAccessPolicyBinding`), update Unified Access
> Policy (UAP) or VPC Service Controls (VPC-SC) policies, or delete resources
> (REST `DELETE ...?force=true` or CLI `--quiet`).

---

## Prerequisites, Authentication, Region, and Billing Setup

1.  **Google Cloud SDK, Authentication, and Project Setup**:
    -   Install the
        [Google Cloud SDK (`gcloud`)](https://cloud.google.com/sdk/docs/install)
        and authenticate CLI and Application Default Credentials
        (`gcloud auth login && gcloud auth application-default login`, or set
        `GOOGLE_APPLICATION_CREDENTIALS`).
    -   Select or create the target project (`gcloud projects create
        {project_id}` / `gcloud config set project {project_id}`), set the
        default region (`gcloud config set compute/region {region}`, defaulting
        to **`us-central1`**; see
        [Google Cloud Locations](https://cloud.google.com/about/locations)), and
        enable required APIs:

        ```bash
        gcloud services enable aiplatform.googleapis.com agentregistry.googleapis.com \
          agentidentity.googleapis.com agentidentitycredentials.googleapis.com \
          networkservices.googleapis.com networksecurity.googleapis.com iap.googleapis.com \
          modelarmor.googleapis.com compute.googleapis.com dns.googleapis.com \
          certificatemanager.googleapis.com servicenetworking.googleapis.com
        ```
2.  **Billing, Least-Privilege IAM, and Product Terminology**:
    -   Verify an active billing account is attached (`gcloud billing projects
        describe {project_id} --format="value(billingEnabled)"`) across
        `{host_project_id}`, `{gov_project_id}`, `{runtime_project_id}`, and
        `{mcp_project_id}` (required even when evaluating free-tier allowances;
        review [Google Cloud Pricing](https://cloud.google.com/pricing)).
    -   Grant explicit least-privilege IAM roles (`roles/aiplatform.user`,
        `roles/networkservices.admin`, `roles/compute.networkAdmin`,
        `roles/compute.networkUser`, `roles/iap.egressor`, or a custom role with
        `networkservices.agentGateways.get,networkservices.agentGateways.use,networkservices.operations.get`)
        rather than primitive `roles/owner` or `roles/editor`.
    -   Use approved product names: **Gemini platform**,
        **Agent Runtime** (`reasoningEngines`), **Agent Gateway**
        (`240.0.0.2:443`), **Agent Connectivity Template (ACT)**, **Agent
        Registry**, and **Unified Access Policy (UAP Policy V2)** / **Semantic
        Governance Policy (SGP)**.

---

## 3-Phase Architect Workflow and Decision Tree

```mermaid
graph TD
    Start["Enterprise Gemini platform Architecture"] --> Q1{"1. Egress Destinations?"}
    Q1 -->|"RFC 1918 + Google APIs Only"| Priv["ACT: vpcEgress = PRIVATE_RANGES_ONLY<br/>• Direct Private Google Access (PGA)"]
    Q1 -->|"Public Internet, VPC-SC, or Non-RFC 1918 PUPI"| All["ACT: vpcEgress = ALL_TRAFFIC<br/>• 100% Egress via AGW VIP 240.0.0.2:443<br/>• Consolidate Core Google APIs FQDNs"]
    All --> Q2{"2. Layer 7 URL List or Cross-Cloud mTLS?"}
    Q2 -->|"No (Standard NAT)"| Nat["Direct Cloud NAT on PSC-I Subnet<br/>• ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG"]
    Q2 -->|"Yes (Next-Hop SWP)"| Swp["Next-Hop SWP (NEXT_HOP_ROUTING_MODE) + PBR<br/>• Internal and Google API DEFAULT_ROUTING bypasses<br/>• Default route via SWP ILB IP<br/>• Exclude PSC-I from manual Cloud NAT"]
```

1.  **Phase 1 — Scope Verification and Architecture Discovery**:
    -   **Scope Boundaries and Single-Region Discovery**: Decline generic Google
        Cloud IAM/Compute/Storage debugging unrelated to the Gemini platform
        stack or requests to run broad multi-region live project scanning loops,
        pointing instead to `gcloud ai reasoning-engines list --region={region}`.
    -   **Architecture Design and Engineering**: Identify the project
        hierarchy (`Host`, `Governance Hub`, `Runtime Spoke`, `Tool/MCP Spoke`),
        egress mode (`ALL_TRAFFIC` vs `PRIVATE_RANGES_ONLY`), policy plane (UAP
        V2, SGP, Model Armor), and target output format (topology
        specification, `gcloud` CLI commands, or REST/YAML manifests).
2.  **Phase 2 — Draft Architecture Plan and Resource Mapping**:
    -   Synthesize the topology diagram, project/VPC layout, IAM bootstrap
        matrix, and security controls using the **Domain Router and Symptom
        Matrix**, and map each manual's canonical REST/YAML schema and CLI
        commands into the target deployment artifacts.
3.  **Phase 3 — Post-Deployment and Audit Log Verification**:
    -   Pair every architecture design with the **Post-Deployment and Cloud Audit
        Log Verification** checklist
        (`references/topologies_and_project_layouts.md`) and runtime query
        validation (`references/agent_runtime_and_identity.md`).

---

## Domain Router and Symptom Matrix

Each reference manual in `references/` is the **single source of truth** for its
domain's CLI commands, REST/YAML schemas, quotas, and CEL expressions. Always
read the corresponding reference manual before generating configurations or
answering domain-specific questions:

Architecture Domain                                               | Topics and Architectural Decisions Covered                                                                                                                                                                                                                                            | Symptoms and Failure Modes Routed Here                                                                                                                                                                                         | Canonical Reference Manual
:---------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------
**1. Project Hierarchy, Shared VPC, VPC-SC, and Custom Routing**  | Multi-project separation (`Host`, `Governance Hub`, `Runtime Spoke`, `Tool/MCP Spoke`), PSC-I subnet sizing, cross-project Service Agent IAM bootstrap, VPC-SC perimeters, non-RFC 1918 PUPI/peered custom route exchange, and post-deployment Cloud Audit Log verification.          | PSC-I IP exhaustion, cross-project attachment or `addressGroup` permission denials, VPC-SC perimeter blocks, dropped non-RFC 1918 internal routes, or post-deployment verification.                                            | [`references/topologies_and_project_layouts.md`](references/topologies_and_project_layouts.md)
**2. Agent Connectivity Template (ACT) and Agent Gateway**        | Choosing `ALL_TRAFFIC` vs `PRIVATE_RANGES_ONLY`, ACT and Agent Gateway REST/YAML schemas, control-plane URI formatting, registry attachment limits, and container custom Root CA bundle trust.                                                                                        | Control-plane URI validation errors, registry attachment limit errors, or container TLS verification failures (`[SSL: UNEXPECTED_EOF_WHILE_READING]`).                                                                         | [`references/agent_gateway_and_act.md`](references/agent_gateway_and_act.md)
**3. Outbound Routing, Next-Hop SWP, PBR, and Hybrid mTLS**       | Source-range Policy-Based Routes (PBR) for PSC-I subnets, Next-Hop Secure Web Proxy (`NEXT_HOP_ROUTING_MODE`), `swg-autogen-nat` vs manual Cloud NAT coexistence, gRPC/A2A/WebSocket routing, Spanner SA impersonation, and Cross-Cloud mTLS Egress Hubs (`Hybrid NEG`).              | Asymmetric return-routing drops between manual Cloud NAT and `swg-autogen-nat`, outbound URL filtering on PSC-I interfaces, or cross-cloud mTLS origination over Cloud Interconnect/VPN.                                       | [`references/egress_routing_and_swp.md`](references/egress_routing_and_swp.md)
**4. Ingress ALB, URL Rewrites, Private CA, and 3P IdP STS**      | Two-Tier and Single-Tier ALB ingress with URL Map `hostRewrite`/`pathPrefixRewrite`, Private CA `TrustConfig` with Regional Internal ALB + Serverless NEG for Cloud Run MCP servers, and 3P IdP (`EntraID`/`Ping`/`Okta`) token exchange via `LbTrafficExtension` (`ext_proc` + STS). | WebPKI root stripping (`NO_ADDITIONAL_ROOTS`), empty `:authority` drops on Serverless NEGs, `*.run.app` Google-managed certificate mismatches, or OAuth/IAP header collisions.                                                 | [`references/ingress_patterns_and_rewrites.md`](references/ingress_patterns_and_rewrites.md)
**5. UAP Policy V2, IAP V1, SGP, and Model Armor Governance**     | Organization/Folder/Project UAP Policy V2 and IAP V1 CEL authorization rules, Semantic Governance Policy (SGP `CONTENT_AUTHZ`), custom `AuthzExtension` / `AuthzPolicy` targets, and fail-closed Model Armor Floor Settings, templates, and ADK callbacks.                            | `Egress request is not authorized` (`HTTP 403` / `status.code=7`) on MCP `initialize` or `tools/list`, `failed to parse the service URL` on `AuthzExtension`, binary gRPC parser crashes, or fail-open safety bypasses.        | [`references/governance_security_policies.md`](references/governance_security_policies.md)
**6. Agent Registry, Consolidated `googleapis`, and Federation**  | Consolidating core Google APIs FQDNs into a single `googleapis` service (`ALL_TRAFFIC`), registering MCP/A2A/REST services, extracting server-generated `registryResource` UUIDs for `roles/iap.egressor`, and Event-Driven Spoke-to-Hub Registry Federation.                         | `ALL_TRAFFIC` agent startup or telemetry blackholing, IAM binding target mismatches on Registry resources, OpenAPI/MCP spec size rejections, or multi-project catalog drift.                                                   | [`references/registry_and_federation.md`](references/registry_and_federation.md)
**7. ADK Runtime Packaging, Agent Identity, and Day-2 Operations**| Packaging ADK agents with `AGENT_IDENTITY` (SPIFFE) and Auth Manager, regional residency, BigQuery pre-execution cost guards, in-place ACT updates, reverse-dependency teardown, and external Cloud NAT IP verification.                                                              | Raw credential exposure, `HTTP 409 ABORTED` control-plane mutex locks, `HTTP 400 FAILED_PRECONDITION` (`FROM_AGENT_GATEWAY*` or `contains child resources: sessions`), or `X-Forwarded-For: 0.0.0.0` when probing `*.run.app`. | [`references/agent_runtime_and_identity.md`](references/agent_runtime_and_identity.md)

---

## Supporting Public Documentation Links

- [Agent Runtime Overview](https://docs.cloud.google.com/gemini-enterprise-agent-platform/agents.md.txt)
- [Agent Gateway Overview](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/agent-gateway-overview.md.txt)
- [Policies Overview](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/policies/overview.md.txt)
- [Agent Identity Overview](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/agent-identity-overview.md.txt)
- [Agent Registry Overview](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/agent-registry.md.txt)
- [Deploy Agent Gateway Runtime](https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-gateway-runtime-deploy.md.txt)
- [Private Service Connect Interface](https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/private-service-connect-interface.md.txt)
references/
agent_gateway_and_act.md 14.7 KB
# Agent Gateway, Agent Connectivity Template (ACT), and Security Policies

This reference provides technical specifications, YAML templates, REST/CLI
commands, resource attribute contracts, and lifecycle management workflows for
Agent Gateway, Agent Connectivity Templates (ACT), Authorization Extensions
(`AuthzExtension`), Authorization Policies (`AuthzPolicy`), and Semantic
Governance Policies (SGP).

--------------------------------------------------------------------------------

## Table of Contents

-   [1. Architecture: Tenant Bridging and Control Plane Topology](#1-architecture-tenant-bridging-and-control-plane-topology): Lines 21-83
-   [2. ACT Egress Modes: ALL_TRAFFIC vs PRIVATE_RANGES_ONLY](#2-act-egress-modes-all_traffic-vs-private_ranges_only): Lines 84-108
-   [3. Production Resource Manifests and REST Deployment](#3-production-resource-manifests-and-rest-deployment): Lines 109-203
-   [4. Authorization Extensions and Policies (`authzExtensions` and `authzPolicies`)](#4-authorization-extensions-and-policies-authzextensions-and-authzpolicies): Lines 204-245
-   [5. Operational Gotchas and Container Trust](#5-operational-gotchas-and-container-trust): Lines 246-279

--------------------------------------------------------------------------------

## 1. Architecture: Tenant Bridging and Control Plane Topology

The **Agent Connectivity Template (ACT)** defines the foundational networking
contract between Google-managed tenant projects (where agent reasoning engines
run) and the customer VPC.

```mermaid
graph TD
    subgraph Google Tenant Project
        RE["Agent Runtime (reasoningEngines / ADK Agent)"]
        GW_Proxy["Agent Gateway Envoy Proxy"]
    end

    subgraph Consumer Project
        ACT["Agent Connectivity Template<br/>• vpcEgress: ALL_TRAFFIC<br/>• dnsPeeringConfig: internal.example.com."]
        NA["PSC-I Network Attachment<br/>• ACCEPT_AUTOMATIC<br/>• Subnet >= /26"]
        ConsumerVPC["Consumer VPC Network"]
    end

    RE -->|Local Bonding| GW_Proxy
    GW_Proxy -->|Bound via Template| ACT
    ACT -->|PSC Interface| NA
    NA -->|Enters Network| ConsumerVPC
```

### Control Plane Policy and Extension Hierarchy

```text
+-----------------------------------------------------------------------------------------+
| Agent Connectivity Template (ACT)                                                       |
|   - Template ID: ${TEMPLATE_ID}                                                         |
|   - vpcEgress: ALL_TRAFFIC (or PRIVATE_RANGES_ONLY)                                     |
|   - networkAttachment: projects/${PROJECT_NUMBER}/regions/${REGION}/networkAttachments  |
|   - dnsPeeringConfig: domain: ${PEERING_DOMAIN} -> targetNetwork: ${VPC_NAME}           |
+--------------------------------------------+--------------------------------------------+
                                             |
                                             v (Referenced by Gateway)
+-----------------------------------------------------------------------------------------+
| Agent Gateway (${GATEWAY_ID})                                                           |
|   - Governed Access Path: AGENT_TO_ANYWHERE                                             |
|   - Registries: //agentregistry.googleapis.com/projects/${PROJECT_NUMBER}/locations/... |
|                 (Max 2: 1 global + 1 regional; never register in us/eu multi-regions)   |
+---------------------+---------------------------------------------+---------------------+
                      |                                             |
                      v                                             v
+-------------------------------------------+ +-------------------------------------------+
| IAP Request Authz Extension & Policy      | | Model Armor Content Authz Ext & Policy    |
| • service: iap.googleapis.com             | | • service: modelarmor.REGION.rep:443      |
| • metadata: iapPolicyVersion: "V1" / "V2" | | • metadata: model_armor_settings          |
| • policyProfile: REQUEST_AUTHZ            | | • policyProfile: CONTENT_AUTHZ            |
+-------------------------------------------+ +-------------------------------------------+
                      |                                             |
                      v                                             v
+-------------------------------------------+ +-------------------------------------------+
| Semantic Governance Policies (SGP)        | | Secure Web Proxy (SWP) Egress             |
| • Semantic Governance Policy Engine       | | • Dedicated Proxy-Only Subnet (/26)       |
| • Stripped DNS Trailing Dot Record        | | • Gateway: NEXT_HOP_ROUTING_MODE          |
| • CEL gRPC Exclusion Rule                 | | • Policy-Based Route (PBR) from PSC-I     |
+-------------------------------------------+ +-------------------------------------------+
```

--------------------------------------------------------------------------------

## 2. ACT Egress Modes: ALL_TRAFFIC vs PRIVATE_RANGES_ONLY

| Feature | `ALL_TRAFFIC` Mode | `PRIVATE_RANGES_ONLY` Mode |
| :------------- | :-------------------------------------------------------- | :-------------------- |
| **Outbound DNS Resolution** | All public and private hostnames resolve to synthetic PSC VIP `240.0.0.2:443`. | Only RFC 1918 / private domains route to VPC; public domains resolve via Google default DNS. |
| **Proxy Interception** | **100% of outbound traffic** is intercepted, inspected, and governed by the Agent Gateway Envoy proxy. | Only internal private endpoints are intercepted; external SaaS/public API traffic bypasses the gateway entirely. |
| **Internet Egress Path** | Egresses the consumer VPC through the PSC-I subnet via **Next-Hop SWP** (`swg-autogen-nat` on proxy-only subnet, with any custom Cloud NAT using `LIST_OF_SUBNETWORKS` excluding the PSC-I subnet) or explicit **Cloud NAT** (`--nat-custom-subnet-ip-ranges="${PSCI_SUBNET_NAME}"`—or `--nat-all-subnet-ip-ranges` in dedicated single-subnet VPCs—with `ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG`, which the Agent Gateway control plane validates even when SWP is not deployed). | Direct internet egress from Google tenant infrastructure; no static customer egress IP. |
| **Enterprise Use Case** | Highly regulated production environments, zero-trust data exfiltration prevention, strict egress auditing. | Dev/test sandboxes, internal-only tools where external web scraping is ungoverned. |

> [!NOTE] **Consumer VPC, `addressGroup` IAM and Registry Prerequisites for
> `ALL_TRAFFIC`**: 1. Provision a `/26` or larger `PRIVATE` PSC-I subnet
> (avoiding reserved `10.0.0.0/24` through `10.0.2.0/24` ranges, with Private
> Google Access enabled; see `references/topologies_and_project_layouts.md`
> Section 2.2) and register the consolidated `googleapis` service with the core
> Google APIs FQDNs in Agent Registry (see
> `references/registry_and_federation.md` Section 4). 2. Creating an ACT
> auto-provisions Network Security `addressGroup` `act-${TEMPLATE_ID}`; grant
> `roles/compute.networkUser` (`networksecurity.addressGroups.use`,
> `networksecurity.addressGroups.get`) on `act-${TEMPLATE_ID}` to the Agent
> Runtime service agent
> `service-${PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com` (see
> `references/topologies_and_project_layouts.md` Section 3.1).

--------------------------------------------------------------------------------

## 3. Production Resource Manifests and REST Deployment

### 3.1 Agent Connectivity Template (`ALL_TRAFFIC`)

```yaml
name: projects/${PROJECT_NUMBER}/locations/${REGION}/agentConnectivityTemplates/${TEMPLATE_ID}
description: "Production ACT with full egress governance and DNS peering"
accessPath: AGENT_TO_ANYWHERE
accessTypes:
  - PRIVATE
agentCompute: GKE
deploymentModel: CENTRALIZED
egressNetworkConfig:
  networkAttachment: "projects/${PROJECT_NUMBER}/regions/${REGION}/networkAttachments/${ATTACHMENT_NAME}"
  vpcEgress: ALL_TRAFFIC
  dnsPeeringConfig:
    domains:
      - "internal.example.com."
    targetNetwork: "projects/${PROJECT_NUMBER}/global/networks/${VPC_NAME}" # Use ${HOST_PROJECT_NUMBER} in Shared VPC topologies
  # Optional when using Private CA TrustConfig:
  # tlsConfig:
  #   trustConfig: "projects/${PROJECT_NUMBER}/locations/${REGION}/trustConfigs/${TRUST_CONFIG_ID}"
  #   additionalRoots: PUBLICLY_TRUSTED_ROOTS
```

### 3.2 Agent Connectivity Template (`PRIVATE_RANGES_ONLY`)

```yaml
name: projects/${PROJECT_NUMBER}/locations/${REGION}/agentConnectivityTemplates/${TEMPLATE_ID}
description: "Private-only ACT for internal RFC 1918 tool routing"
accessPath: AGENT_TO_ANYWHERE
accessTypes:
  - PRIVATE
agentCompute: GKE
deploymentModel: CENTRALIZED
egressNetworkConfig:
  networkAttachment: "projects/${PROJECT_NUMBER}/regions/${REGION}/networkAttachments/${ATTACHMENT_NAME}"
  vpcEgress: PRIVATE_RANGES_ONLY
  dnsPeeringConfig:
    domains:
      - "internal.example.com."
    targetNetwork: "projects/${PROJECT_NUMBER}/global/networks/${VPC_NAME}"
```

### 3.3 ACT and Agent Gateway REST Deployment Commands

```bash
pip install "pyyaml>=6.0,<7.0"
ACCESS_TOKEN=$(gcloud auth print-access-token)
BASE_URL="https://networkservices.googleapis.com/v1/projects/${PROJECT_NUMBER}/locations/${REGION}"

# 1. Deploy Agent Connectivity Template (using act.yaml from Section 3.1 / 3.2)
curl -s -X POST "${BASE_URL}/agentConnectivityTemplates?agentConnectivityTemplateId=${TEMPLATE_ID}" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" -H "X-Goog-User-Project: ${PROJECT_ID}" \
  -H "Content-Type: application/json" \
  -d "$(envsubst < act.yaml | python3 -c 'import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin)))')"

# 2. Deploy Agent Gateway referencing ACT and dual registries (using agw.yaml from Section 3.4)
curl -s -X POST "${BASE_URL}/agentGateways?agentGatewayId=${GATEWAY_ID}" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" -H "X-Goog-User-Project: ${PROJECT_ID}" \
  -H "Content-Type: application/json" \
  -d "$(envsubst < agw.yaml | python3 -c 'import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin)))')"
```

### 3.4 Agent Gateway (Standard and Standalone Registry-Only Modes)

```yaml
name: projects/${PROJECT_NUMBER}/locations/${REGION}/agentGateways/${GATEWAY_ID}
description: "Production Agent Gateway referencing ACT and Agent Registry"
# Mandatory in VPC-SC / SWP-inspected enterprise environments (mutually exclusive with inline networkConfig):
agentConnectivityTemplate: "projects/${PROJECT_NUMBER}/locations/${REGION}/agentConnectivityTemplates/${TEMPLATE_ID}"
# Note: In stable v1 environments without a standalone ACT, omit agentConnectivityTemplate and specify inline networkConfig:
# networkConfig:
#   egress:
#     networkAttachment: "projects/${PROJECT_NUMBER}/regions/${REGION}/networkAttachments/${ATTACHMENT_NAME}"
#   dnsPeeringConfig:
#     domains: ["internal.example.com."]
#     targetProject: "${HOST_PROJECT_ID}"
#     targetNetwork: "projects/${HOST_PROJECT_ID}/global/networks/${VPC_NAME}"
googleManaged:
  governedAccessPath: AGENT_TO_ANYWHERE
registries:
  - "//agentregistry.googleapis.com/projects/${PROJECT_NUMBER}/locations/global"
  - "//agentregistry.googleapis.com/projects/${PROJECT_NUMBER}/locations/${REGION}"
```

> [!IMPORTANT] **The Dual-Registry Invariant**: An Agent Gateway supports a
> **maximum of two registries**, and each entry must use the numeric
> `PROJECT_NUMBER` (`uint64`). When two registries are configured, **exactly ONE
> must be `global`** and the second must be **`regional`**
> (`locations/${REGION}`; never register custom services manually in `us` or
> `eu` multi-regions).

--------------------------------------------------------------------------------

## 4. Authorization Extensions and Policies (`authzExtensions` and `authzPolicies`)

*   **Collections**: Manage `authzExtensions` under
    `networkservices.googleapis.com/v1` and `authzPolicies` under
    `networksecurity.googleapis.com/v1` (never legacy `authorizationPolicies`).
*   **Agent Gateway Target Rules**: When targeting an `AgentGateway`, **omit
    `loadBalancingScheme`** on both `AuthzExtension` and `AuthzPolicy.target`
    (whereas `SecureWebProxy` and `ForwardingRule` targets use
    `INTERNAL_MANAGED`). Attach at most **4 `CUSTOM` `AuthzPolicy` resources**
    per gateway and **omit `iamEnforcementMode`** for active enforcement (see
    `references/governance_security_policies.md` for UAP Policy V2, SGP
    `CONTENT_AUTHZ`, and Model Armor manifests).

```yaml
# iap_request_authz_extension.yaml
name: projects/${PROJECT_NUMBER}/locations/${REGION}/authzExtensions/${IAP_EXT_ID}
authority: iap.googleapis.com
service: iap.googleapis.com
timeout: 1s
failOpen: false
forwardHeaders:
  - Authorization
metadata:
  iapPolicyVersion: "V2" # Use "V2" for Unified Access Policy (or "V1" for IAM condition mode)
```

```yaml
# iap_request_authz_policy.yaml
name: projects/${PROJECT_NUMBER}/locations/${REGION}/authzPolicies/${IAP_POLICY_ID}
action: CUSTOM
policyProfile: REQUEST_AUTHZ
target:
  resources:
    - projects/${PROJECT_NUMBER}/locations/${REGION}/agentGateways/${GATEWAY_ID}
customProvider:
  authzExtension:
    resources:
      - projects/${PROJECT_NUMBER}/locations/${REGION}/authzExtensions/${IAP_EXT_ID}
```

--------------------------------------------------------------------------------

## 5. Operational Gotchas and Container Trust

*   **Day-2 Lifecycle (In-Place ACT PATCH, Control-Plane `HTTP 409 ABORTED` Mutex, Avoiding `FROM_AGENT_GATEWAY*` Reference Locks via LRO Polling, and
    `?force=true` Runtime Deletion)**: See
    `references/agent_runtime_and_identity.md`.
*   **Misleading `agent-gateways import` Config Validation Error**: If
    `agent-gateways import` returns `"code": 3, "message": "Config validation
    failed"` citing `agentregistry.agents.list`, enable the API in the project:
    `gcloud services enable agentregistry.googleapis.com
    --project=${PROJECT_ID}`.
*   **Custom Container Root CA Trust Injection**: When an agent runs in
    a custom Docker container bonded to an Egress Agent Gateway, export the
    gateway's root CA (`gcloud network-services agent-gateways describe
    "${GATEWAY_NAME}" --location="${REGION}"
    --format="value(agentGatewayCard.rootCertificates)" > agw_root.crt`) and
    inject it into the OS, Python (`SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`), and
    gRPC (`GRPC_DEFAULT_SSL_ROOTS_FILE_PATH`) trust stores:

```dockerfile
FROM python:3.11-slim

RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Copy exported Egress Agent Gateway Root CA into system trust store
COPY agw_root.crt /usr/local/share/ca-certificates/agw_root.crt
RUN update-ca-certificates

# Point Python SSL, Requests, httpx, and gRPC C-core at the updated bundle
ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
ENV REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
ENV GRPC_DEFAULT_SSL_ROOTS_FILE_PATH=/etc/ssl/certs/ca-certificates.crt
```
agent_runtime_and_identity.md 27.8 KB
# ADK Agent Runtime Packaging, Identity Token Exchange, Observability and Day-2 Operations

This reference details configuring Python Agent Development Kit (ADK) agents for
**Agent Runtime in Gemini platform** (`reasoningEngines`), configuring **Agent
Identity (`AGENT_IDENTITY`)**, **Third-Party IdP Token Exchange (`ext_proc` +
STS)**, **Data Residency, Distributed W3C Trace Correlation and BigQuery Cost
Governance**, and **Day-2 Lifecycle Operations**.

--------------------------------------------------------------------------------

## Table of Contents

-   [1. End-to-End ADK Packaging and Runtime Architecture Overview](#1-end-to-end-adk-packaging-and-runtime-architecture-overview): Lines 27-44
-   [2. Python Packaging and Artifact Preparation](#2-python-packaging-and-artifact-preparation): Lines 45-120
-   [3. Conflict Teardown and Active Session Deletion (`?force=true`)](#3-conflict-teardown-and-active-session-deletion-forcetrue): Lines 121-137
-   [4. `CreateReasoningEngine` REST and Python SDK Specification](#4-createreasoningengine-rest-and-python-sdk-specification): Lines 138-224
-   [5. End-to-End Validation Queries](#5-end-to-end-validation-queries): Lines 225-242
-   [6. Third-Party IdP Token Exchange (`ext_proc` / STS) and Agent Identity Auth Manager](#6-third-party-idp-token-exchange-ext_proc-sts-and-agent-identity-auth-manager): Lines 243-300
-   [7. Data Residency, Regional Endpoints, Sovereign Cloud and Global Anycast Failover](#7-data-residency-regional-endpoints-sovereign-cloud-and-global-anycast-failover): Lines 301-355
-   [8. Day-2 Operations: Updating Agent Connectivity Templates In-Place and Control-Plane Mutex Locks](#8-day-2-operations-updating-agent-connectivity-templates-in-place-and-control-plane-mutex-locks): Lines 356-388
-   [9. Avoiding Dangling Reference Locks on ACT Deletion (`FROM_AGENT_GATEWAY*`)](#9-avoiding-dangling-reference-locks-on-act-deletion-from_agent_gateway): Lines 389-405
-   [10. Teardown and Clean Recreation Lifecycle](#10-teardown-and-clean-recreation-lifecycle): Lines 406-454
-   [11. Egress NAT Reflection and Cloud Run Ingress Routing Behavior](#11-egress-nat-reflection-and-cloud-run-ingress-routing-behavior): Lines 455-478

--------------------------------------------------------------------------------

## 1. End-to-End ADK Packaging and Runtime Architecture Overview

```text
+-----------------------------------------------------------------------------------------+
| GCS Artifact Contract: gs://${PROJECT_ID}-${REGION}/agent_artifacts/                    |
|   • agent_engine.pkl (cloudpickle protocol=4) | dependencies.tar.gz | requirements.txt  |
+--------------------------------------------+--------------------------------------------+
                                             | (REST CreateReasoningEngine / ADK SDK)
                                             v
+-----------------------------------------------------------------------------------------+
| Agent Runtime Container (reasoningEngines)                                              |
|   • identityType: AGENT_IDENTITY (SPIFFE PrincipalSet / Principal X.509 SVID)           |
|   • agentGateway: projects/${PROJECT_NUMBER}/locations/${REGION}/agentGateways/${ID}    |
+--------------------------------------------+--------------------------------------------+
```

--------------------------------------------------------------------------------

## 2. Python Packaging and Artifact Preparation

### 2.1 Model Version and Regional Availability Configuration

Always verify the target model's supported regions in official documentation
(`https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/{model_version}.md.txt`):

-   **Global Endpoint Models (such as `gemini-4-argon` via `global`)**:
    -   When targeting the `global`, `us`, or `eu` endpoint rather than a
        standalone regional endpoint, instantiate
        `Gemini(model="gemini-4-argon", client_kwargs={"location": "global",
        "http_options": {"api_transport": "rest"}})` and set
        `GOOGLE_CLOUD_LOCATION="global"`, `VERTEXAI_LOCATION="global"`, and
        `GOOGLE_GENAI_API_TRANSPORT="rest"` in `deploymentSpec.env` (using REST
        transport guarantees `:generateContent` / `:streamGenerateContent` calls
        emit `application/json` so inline SGP and Model Armor `CONTENT_AUTHZ`
        extensions inspect 100% of LLM payloads).
    -   Ensure `aiplatform.googleapis.com`, `aiplatform.mtls.googleapis.com`,
        `us-aiplatform.googleapis.com`, `us-aiplatform.mtls.googleapis.com`, and
        `aiplatform.us.rep.googleapis.com` are registered in the `googleapis`
        Agent Registry service with `protocol_binding = "HTTP_JSON"`.
-   **Regional Models (such as `gemini-3.8-flash` in `us-central1`)**:
    -   Set `location="us-central1"` in `client_kwargs` and
        `deploymentSpec.env`, and include
        `us-central1-aiplatform.googleapis.com`,
        `us-central1-aiplatform.mtls.googleapis.com`, and
        `aiplatform.us-central1.rep.googleapis.com` in `googleapis` when the
        runtime is hosted in another region.

### 2.2 GCS Package Artifact Contract and Staging Bucket Integrity Hardening

The Agent Runtime reconstructs the agent from three Cloud Storage objects
(`packageSpec`):

1.  **`pickleObjectGcsUri` (`agent_engine.pkl`)**: Serialized with
    `cloudpickle.dump(agent_instance, f, protocol=4)` (protocol 4 guarantees
    compatibility with the container's Python 3.11 runtime).
2.  **`dependencyFilesGcsUri` (`dependencies.tar.gz`)**: Gzipped tarball
    containing local Python source modules.
3.  **`requirementsGcsUri` (`requirements.txt`)**: Pinned runtime dependencies
    (`google-adk>=1.17.0,<2.0.0`, `google-cloud-aiplatform[agent_engines,adk]>=1.90.0,<2.0.0`,
    `cloudpickle>=3.0.0,<4.0.0`, `httpx>=0.27.0,<1.0.0`, `opentelemetry-api==1.37.0`,
    `opentelemetry-sdk==1.37.0`, `opentelemetry-exporter-gcp-trace==1.11.0`).
4.  **Staging Bucket Integrity and Service Agent Read Access (`cloudpickle`
    Supply-Chain Guard)**: Because `cloudpickle` deserialization executes code
    at container startup, configure the staging bucket with
    `uniform_bucket_level_access = true`, `public_access_prevention =
    "enforced"`, and `versioning { enabled = true }`, restrict
    `roles/storage.objectAdmin` strictly to the CI/CD build service account,
    verify object `crc32c` / `md5Hash` checksums on upload, and grant read-only
    `roles/storage.objectViewer` on `gs://${PROJECT_ID}-${REGION}` to both
    `service-${PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com` and
    `service-${PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com`.

### 2.3 Multi-Agent ADK Orchestration, Deterministic Pre-Model Callbacks and Grounded Retrieval

When designing regulated multi-agent systems (such as supervisor-to-specialist
topologies with domain triage, grounded vector/SQL retrieval, and policy review):

1.  **Deterministic Pre-Model Short-Circuiting (`before_model_callback`)**:
    Never rely solely on probabilistic LLM prompts for mandatory safety
    escalations or encoded prompt-injection filtering. Attach a deterministic
    `before_model_callback` on the root `LlmAgent` that runs the 3-step
    pre-sanitization normalization pipeline (`references/governance_security_policies.md`
    Section 9.4) and evaluates deterministic escalation rules (returning an
    immediate `LlmResponse` short-circuit before invoking Gemini or specialist
    sub-agents when a high-risk condition is triggered).
2.  **Supervisor and Specialist Sub-Agent Hierarchy**: Compose specialist
    `LlmAgent` instances (`sub_agents=[retrieval_specialist, compliance_specialist]`)
    under the root orchestrator `LlmAgent`, scoping MCP toolsets per specialist
    so only the retrieval specialist holds read-only MCP/database tools and
    every synthesized response includes verifiable source citations (`source_id`,
    `document_uri`) from the retrieved corpus.

--------------------------------------------------------------------------------

## 3. Conflict Teardown and Active Session Deletion (`?force=true`)

A consumer project's regional Agent Runtime tenant project (`*-tp`) can only
bond to **one** Agent Gateway per region (multiple `ReasoningEngine` instances
in the same project/region can share that gateway, or use separate spoke
projects if distinct gateways are required).

> [!IMPORTANT] **Active Session Deletion Invariant (`?force=true`)**: Calling
> `DELETE` on an Agent Runtime instance that has existing conversations or child
> `sessions` fails with `HTTP 400 FAILED_PRECONDITION: The ReasoningEngine ...
> contains child resources: sessions`. Always append **`?force=true`** (`DELETE
> https://${REGION}-aiplatform.googleapis.com/v1/${RE_NAME}?force=true`) and
> poll the resulting LRO until `done: true` (see Section 10 for the complete CLI
> teardown script).

--------------------------------------------------------------------------------

## 4. `CreateReasoningEngine` REST and Python SDK Specification

### 4.1 REST Specification (`reasoningEngines`)

```json
{
  "displayName": "adk-enterprise-agent",
  "description": "ADK Agent with governed egress via Agent Gateway and AGENT_IDENTITY",
  "spec": {
    "identityType": "AGENT_IDENTITY",
    "agentFramework": "google-adk",
    "classMethods": [
      {"name": "async_create_session", "apiMode": "async", "parameters": {"type": "object", "properties": {"user_id": {"type": "string"}}}},
      {"name": "query", "apiMode": "", "parameters": {"type": "object", "properties": {"message": {"type": "string"}}}},
      {"name": "stream_query", "apiMode": "stream", "parameters": {"type": "object", "properties": {"message": {"type": "string"}, "user_id": {"type": "string"}, "session_id": {"type": "string"}}}}
    ],
    "packageSpec": {
      "pickleObjectGcsUri": "gs://${PROJECT_ID}-${REGION}/agent_artifacts/agent_engine.pkl",
      "dependencyFilesGcsUri": "gs://${PROJECT_ID}-${REGION}/agent_artifacts/dependencies.tar.gz",
      "requirementsGcsUri": "gs://${PROJECT_ID}-${REGION}/agent_artifacts/requirements.txt",
      "pythonVersion": "3.11"
    },
    "deploymentSpec": {
      "env": [
        {"name": "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY", "value": "true"},
        {"name": "GOOGLE_CLOUD_LOCATION", "value": "global"},
        {"name": "VERTEXAI_LOCATION", "value": "global"},
        {"name": "GOOGLE_GENAI_USE_ENTERPRISE", "value": "1"},
        {"name": "GOOGLE_GENAI_API_TRANSPORT", "value": "rest"},
        {"name": "OTEL_SERVICE_NAME", "value": "adk-enterprise-agent"},
        {"name": "ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS", "value": "false"},
        {"name": "GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES", "value": "False"}
      ],
      "agentGatewayConfig": {
        "agentToAnywhereConfig": {
          "agentGateway": "projects/${PROJECT_NUMBER}/locations/${REGION}/agentGateways/${GATEWAY_ID}"
        }
      }
    }
  }
}
```

Submit via `POST
https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_NUMBER}/locations/${REGION}/reasoningEngines`
and poll the returned operation URL until `.done == true`.

### 4.2 Python SDK Deployment (`client.agent_engines.create`)

When binding a Runtime Spoke `ReasoningEngine` to a Governance Hub
`AgentGateway`, both resources must reside in the **exact same region** and use
**numeric `uint64` project numbers** (`AGW_PROJECT_NUMBER`); grant
`(networkservices.agentGateways.get, networkservices.agentGateways.use,
networkservices.operations.get)` (or `roles/networkservices.admin`) to the
deployer and `gcp-sa-aiplatform`, and `roles/compute.networkUser` on
`act-${TEMPLATE_ID}` to `gcp-sa-aiplatform-re` (see
`references/topologies_and_project_layouts.md` Section 3.1):

```python
remote_agent = client.agent_engines.create(
    agent=local_agent,
    config={
        "agent_gateway_config": {
            "agent_to_anywhere_config": {
                "agent_gateway": f"projects/{AGW_PROJECT_NUMBER}/locations/{REGION}/agentGateways/{GATEWAY_ID}"
            },
        },
        "identity_type": "AGENT_IDENTITY",
        "env_vars": {
            "GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES": "False",
        },
    },
)
```

> [!CAUTION] **Token-Sharing Boundary (`GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES="False"`)**:
> Setting `GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES="False"` is
> required so the Agent Runtime container can present its platform token across
> a cross-project Agent Gateway (`AGW_PROJECT_ID`) to registered Google APIs
> (`googleapis`). Never pass raw Google Cloud platform access tokens to external
> 3P or untrusted MCP servers; enforce UAP Policy V2 host/resource scoping and
> use Agent Identity Auth Manager (`AuthProvider`) or `X-Serverless-Authorization`
> scoped OIDC ID tokens (`references/egress_routing_and_swp.md` Section 5) for
> downstream MCP tool authentication.

--------------------------------------------------------------------------------

## 5. End-to-End Validation Queries

```bash
# 5.1 Session Creation (:query with async_create_session)
curl -s -X POST "https://${REGION}-aiplatform.googleapis.com/v1/${RE_NAME}:query" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{"classMethod": "async_create_session", "input": {"user_id": "test-user"}}' | jq .

# 5.2 Streaming Query Execution (:streamQuery NDJSON)
curl -N -X POST "https://${REGION}-aiplatform.googleapis.com/v1/${RE_NAME}:streamQuery" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{"input": {"message": "Verify governed tool connectivity", "user_id": "test-user"}}'
```

--------------------------------------------------------------------------------

## 6. Third-Party IdP Token Exchange (`ext_proc` / STS) and Agent Identity Auth Manager

### 6.1 External IdP (EntraID, Ping, Okta) to Google Cloud Token Swap (`ext_proc`)

1.  **Workforce Identity Federation and Security Token Service (STS)**: Configure
    a Workforce Identity Pool and Provider (`WorkforcePool`,
    `WorkforcePoolProvider`) mapped to the corporate
    EntraID/Okta/Ping OIDC issuer and JWKS URI.
2.  **Envoy `ext_proc` Service Extension Callout**: Attach a Service Extension
    (`LbTrafficExtension`) on the ingress ALB that intercepts `Authorization:
    Bearer <IdP_JWT>`, calls `https://sts.googleapis.com/v1/token`
    (`urn:ietf:params:oauth:grant-type:token-exchange`), and swaps the corporate
    token for a short-lived Google Cloud STS token (see
    `references/ingress_patterns_and_rewrites.md` Section 7 for the complete
    `LbTrafficExtension` YAML and Python `ext_proc` implementation).
3.  **Multi-Agent 3LO Token Propagation**: Propagate end-user 3-legged OAuth
    (3LO) context across Agent2Agent (A2A) calls via Agent Identity Auth Manager
    rather than falling back to ambient service account privileges.

### 6.2 Agent Identity Auth Manager and X.509 SPIFFE Attestation

1.  **Enable Auth Manager APIs and Add to VPC-SC Perimeter `restricted_services`**:
    Run `gcloud services enable aiplatform.googleapis.com
    agentidentity.googleapis.com agentidentitycredentials.googleapis.com` and
    explicitly add both **`agentidentity.googleapis.com`** and
    **`agentidentitycredentials.googleapis.com`** to the **VPC-SC perimeter
    `restricted_services`** list so outbound credential brokering is governed by
    the perimeter.
2.  **Configure `AuthProvider`**: Create a managed `AuthProvider` (`2LO` client
    credentials, `3LO` user consent flow, or vaulted API key) in Auth Manager
    (scoping `workloadIds` and IAM access strictly to the agent's `principal://`
    URI; never hardcode OAuth client secrets or static API keys in Python code
    or container environment variables) and reference it in the Agent Registry
    `AuthProviderBinding` or ADK MCP tool specification so Agent Gateway injects
    outbound `Authorization` headers over the wire:

```bash
export PROJECT_ID="gov-hub-proj" PROJECT_NUMBER="111111111111" REGION="us-central1"
export ORG_ID="999999999999" ENGINE_ID="5555555555555555555" AUTH_PROVIDER_ID="downstream-api-oauth"
AGENT_PRINCIPAL="principal://agents.global.org-${ORG_ID}.system.id.goog/resources/aiplatform/projects/${PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${ENGINE_ID}"

curl -s -X POST "https://agentidentity.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/authProviders?authProviderId=${AUTH_PROVIDER_ID}" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" \
  -d "{\"description\":\"Managed outbound OAuth provider for agent tool calls\",\"authProviderTypeParams\":{\"twoLeggedOauth\":{\"clientId\":\"${OAUTH_CLIENT_ID}\",\"clientSecret\":\"${OAUTH_CLIENT_SECRET}\",\"tokenUrl\":\"https://idp.example.com/oauth2/v2.0/token\"}},\"allowedScopes\":[\"https://api.internal.example.com/.default\"],\"workloadIds\":[\"${AGENT_PRINCIPAL}\"]}"
```

3.  **SPIFFE X.509 URI vs. IAM Principal Translation Format**:
    -   **X.509 Certificate SAN (SPIFFE URI)**:
        `spiffe://agents.global.org-${ORG_ID}.system.id.goog/resources/aiplatform/projects/${PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${ENGINE_ID}`
    -   **Google Cloud IAM and UAP Policy V2 Principal Format**:
        `principal://agents.global.org-${ORG_ID}.system.id.goog/resources/aiplatform/projects/${PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${ENGINE_ID}`
        (always use the full
        `system.id.goog/resources/aiplatform/projects/${PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${ENGINE_ID}`
        path with numeric `PROJECT_NUMBER`, never a shortened
        `vertex/reasoning-engine/<name>` slug).

--------------------------------------------------------------------------------

## 7. Data Residency, Regional Endpoints, Sovereign Cloud and Global Anycast Failover

### 7.1 Regional Sovereignty, Air-Gapped GDC/TPC and Global Anycast Failover

1.  **Sovereign Data Residency (APRA, MAS, GDPR, EU)**: Align the Agent Runtime
    region, Agent Gateway region, and Model Armor callout endpoint
    (`modelarmor.${REGION}.rep.googleapis.com:443`) within the mandated
    sovereign boundary.
2.  **Google Distributed Cloud (GDC) Air-Gapped and Trusted Partner Cloud (TPC)**:
    Where global `agentregistry.googleapis.com` is unavailable, deploy the
    **Two-Tier Regional Internal ALB + Next-Hop SWP + Local Envoy `ext_proc`**
    pattern inside the sovereign VPC perimeter with Private CA `TrustConfig`
    roots.
3.  **Multi-Region Active/Active and Global Anycast Routing**: Front regional
    Tier-2 Internal ALBs (each routing to a co-located regional Agent Runtime +
    Egress Agent Gateway stack in `us-central1` and `us-east4`) with a
    single **Tier-1 Global External ALB** using a global anycast IP and
    health-checked Cross-Region PSC NEG failover.
4.  **Spanner and Data-Plane Service Account Impersonation**: Grant the agent
    principal `roles/iam.serviceAccountTokenCreator` on a dedicated IAM Service
    Account holding `roles/spanner.databaseUser`.

### 7.2 Observability, BigQuery `dry_run` Cost Guard and Data-Tier Governance

1.  **Privacy-Preserving W3C Trace Propagation**: Set
    `ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS="false"` in `deploymentSpec.env` so
    OpenTelemetry W3C `traceparent` spans correlate latency across Ingress,
    Agent Runtime, Agent Gateway, and MCP tool hops in Cloud Trace without
    recording raw user prompts or PII/PHI in span attributes.
2.  **BigQuery Pre-Execution `dry_run` Cost and Read-Only Guard**: When agents
    query `bigquery.googleapis.com/mcp` or analytical SQL tools, execute a
    pre-flight `QueryJobConfig(dry_run=True, use_query_cache=False)` check to
    verify `statement_type == "SELECT"` and enforce a `maximum_bytes_billed`
    ceiling with caller attribution labels before running the query:

```python
from google.cloud import bigquery

def run_governed_query(client: bigquery.Client, sql: str, max_bytes: int, caller: str) -> list[dict]:
  dry_job = client.query(sql, job_config=bigquery.QueryJobConfig(dry_run=True, use_query_cache=False))
  if dry_job.statement_type != "SELECT" or (dry_job.total_bytes_processed or 0) > max_bytes:
    raise PermissionError("Blocked non-SELECT or over-budget BigQuery query")
  job_cfg = bigquery.QueryJobConfig(maximum_bytes_billed=max_bytes, labels={"caller": caller})
  return [dict(row) for row in client.query(sql, job_config=job_cfg).result()]
```

3.  **Cloud SQL (`pgvector`) and Spanner Tool Spoke Access**: Place database
    backends inside the Tool Spoke (`MCP_PROJECT_ID`), connect via Private
    Service Connect (PSC) endpoints, and authenticate using IAM database
    authentication (`roles/cloudsql.instanceUser` /
    `roles/spanner.databaseUser`) via short-lived SA impersonation rather than
    static database passwords.

--------------------------------------------------------------------------------

## 8. Day-2 Operations: Updating Agent Connectivity Templates In-Place and Control-Plane Mutex Locks

### 8.1 In-Place PATCH via `updateMask=agentConnectivityTemplate`

Never use legacy `update_mask=traffic_select,network_config` or destroy/recreate
an active Agent Gateway. Grant `roles/compute.networkUser`
(`networksecurity.addressGroups.use`, `networksecurity.addressGroups.get`) on
the new ACT's auto-created `addressGroups/act-${NEW_TEMPLATE_ID}` via the
Network Security v1 `:getIamPolicy` / `:setIamPolicy` REST API first (see
`references/topologies_and_project_layouts.md` Section 3.1), then submit an
in-place `PATCH` with `updateMask=agentConnectivityTemplate`:

```bash
PATCH_RESP=$(curl -s -X PATCH \
  "https://networkservices.googleapis.com/v1/projects/${PROJECT_NUMBER}/locations/${REGION}/agentGateways/${GATEWAY_ID}?updateMask=agentConnectivityTemplate" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "X-Goog-User-Project: ${PROJECT_ID}" \
  -H "Content-Type: application/json" \
  -d "{\"name\":\"projects/${PROJECT_NUMBER}/locations/${REGION}/agentGateways/${GATEWAY_ID}\",\"agentConnectivityTemplate\":\"projects/${PROJECT_NUMBER}/locations/${REGION}/agentConnectivityTemplates/${NEW_TEMPLATE_ID}\"}")
OP_NAME=$(echo "${PATCH_RESP}" | jq -r '.name')
gcloud network-services operations wait "${OP_NAME}" --location="${REGION}" --project="${PROJECT_ID}"
```

### 8.2 Handling Control-Plane Resource Mutation Mutex Locks (`HTTP 409 ABORTED`)

The Network Services control plane enforces a per-resource mutex lock (`HTTP 409 ABORTED:
unable to queue the operation; an operation is already in progress`). Before
queueing sequential mutations, list active operations at
`https://networkservices.googleapis.com/v1/projects/${PROJECT_NUMBER}/locations/${REGION}/operations`
and poll until `done: true`.

--------------------------------------------------------------------------------

## 9. Avoiding Dangling Reference Locks on ACT Deletion (`FROM_AGENT_GATEWAY*`)

Deleting an ACT immediately after issuing an Agent Gateway `DELETE` fails with
`HTTP 400 FAILED_PRECONDITION: Resource ... is already being used by resource(s)
.../agentGateways/...` because Network Services retains an internal
`FROM_AGENT_GATEWAY<ID>` lock until the gateway deletion LRO and Agent Runtime
`DeprovisionAgentGatewayBinding` workflow settle:

1.  **Delete `ReasoningEngine` First with `?force=true`** and poll its LRO to
    completion.
2.  **Wait for Agent Gateway Deletion LRO + 20s Settle Window** (`sleep 20`
    cooldown) before calling `DELETE` on the parent ACT.
3.  **Wait 180s After ACT Deletion** (`sleep 180` cooldown) before deleting the
    PSC-I Network Attachment so tenant router NICs detach cleanly.

--------------------------------------------------------------------------------

## 10. Teardown and Clean Recreation Lifecycle

```mermaid
graph TD
    Step1["1. Delete Agent Runtime Instances (?force=true)"] --> Step2["2. Delete AuthzPolicies & UAP PolicyBindings"]
    Step2 --> Step3["3. Delete Agent Gateway (Poll LRO + 20s Settle) & AuthzExtensions"]
    Step3 --> Step4["4. Delete ACT (Poll LRO + 180s Drain) & act-TEMPLATE_ID AddressGroup"]
    Step4 --> Step5["5. Delete Agent Registry Services & PSC-I Network Attachment"]
    Step5 --> Step6["6. Delete PBR Routes, SWP Gateway, Cloud NAT, Subnets & VPC"]
```

### 10.1 Complete Reverse-Dependency CLI Teardown Script

```bash
# 1. Force-delete active Agent Runtime instance (drops child sessions cleanly) and poll LRO
RE_DEL_RESP=$(curl -s -X DELETE \
  "https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${RE_ID}?force=true" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "X-Goog-User-Project: ${PROJECT_ID}")
RE_OP=$(echo "${RE_DEL_RESP}" | jq -r '.name // empty')
while [[ -n "${RE_OP}" ]]; do
  OP_JSON=$(curl -s -X GET "https://${REGION}-aiplatform.googleapis.com/v1/${RE_OP}" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "X-Goog-User-Project: ${PROJECT_ID}")
  [[ "$(echo "${OP_JSON}" | jq -r '.done // false')" == "true" ]] && break
  sleep 10
done

# 2. Delete AuthzPolicies, Agent Gateway (poll LRO + 20s control-plane settle), and AuthzExtensions
gcloud network-security authz-policies delete "${AUTHZ_POLICY_NAME}" --location="${REGION}" --project="${PROJECT_ID}" --quiet
GW_OP=$(curl -s -X DELETE \
  "https://networkservices.googleapis.com/v1/projects/${PROJECT_NUMBER}/locations/${REGION}/agentGateways/${GATEWAY_ID}" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "X-Goog-User-Project: ${PROJECT_ID}" | jq -r '.name')
gcloud network-services operations wait "${GW_OP}" --location="${REGION}" --project="${PROJECT_ID}"
gcloud service-extensions authz-extensions delete "${AUTHZ_EXT_NAME}" --location="${REGION}" --project="${PROJECT_ID}" --quiet
sleep 20

# 3. Delete ACT (poll LRO + 180s PSC-I NIC drain), auto-created addressGroup, Registry & Network Attachment
ACT_OP=$(curl -s -X DELETE \
  "https://networkservices.googleapis.com/v1/projects/${PROJECT_NUMBER}/locations/${REGION}/agentConnectivityTemplates/${TEMPLATE_ID}" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "X-Goog-User-Project: ${PROJECT_ID}" | jq -r '.name')
gcloud network-services operations wait "${ACT_OP}" --location="${REGION}" --project="${PROJECT_ID}"
gcloud network-security address-groups delete "act-${TEMPLATE_ID}" --location="${REGION}" --project="${PROJECT_ID}" --quiet || true
sleep 180
gcloud agent-registry services delete "googleapis" --location="${REGION}" --project="${PROJECT_ID}" --quiet
gcloud compute network-attachments delete "${ATTACHMENT_NAME}" --region="${REGION}" --project="${PROJECT_ID}" --quiet
```

--------------------------------------------------------------------------------

## 11. Egress NAT Reflection and Cloud Run Ingress Routing Behavior

### 11.1 Cloud NAT vs Cloud Run Ingress Routing Behavior

> [!IMPORTANT] **Internal Google Cloud Ingress Routing Behavior**: When an Agent
> Gateway or Compute Engine instance in Google Cloud calls a default Cloud Run
> domain (`*.run.app`), Google Cloud routes traffic internally to the Cloud Run
> ingress proxy, **bypassing Cloud NAT** and setting `X-Forwarded-For: 0.0.0.0`.
> To verify that outbound traffic reflects the Cloud NAT static external IP
> (`STATIC_NAT_IP`), test queries must target an external non-Google service
> (such as `https://api.ipify.org`) as part of the 3-phase verification runbook
> (`references/topologies_and_project_layouts.md` Section 10):
> 1.  **Control-Plane Readiness**: Verify via `gcloud ... describe` that the
>     Agent Gateway state is `ACTIVE`, the PSC-I Network Attachment endpoint is
>     `ACCEPTED`, and the consolidated `googleapis` service is registered in
>     Agent Registry.
> 2.  **Outbound TLS Peer and External NAT Probe**: Verify that the agent
>     container's outbound TLS connection terminates at `240.0.0.2` (`Agent
>     Gateway TLS Inspection CA`) and an external reflector probe
>     (`https://api.ipify.org`) returns the consumer Cloud NAT IP.
> 3.  **Security Probes and Cloud Audit Log Receipts**: Execute positive and
>     negative security probes and verify server-side Cloud Audit Log deny
>     receipts (`protoPayload.status.code=7` on `iap.googleapis.com` and
>     `modelarmor.googleapis.com`).
attribution.md 2.1 KB
# Usage Attribution

When executing `gcloud`, REST API, or MCP commands directly in the terminal
against Google Cloud while using this skill, attach Google Cloud's standard
first-party skill identifier to those existing Google Cloud requests so usage
can be attributed. The identifier names only this skill and its version, carries
no user, project, credential, or prompt data, is never sent to third-party
endpoints, and is strictly optional if the user chooses to opt out.

-   **`gcloud` CLI Commands**: On direct `gcloud` invocations run in the
    terminal for Google Cloud, set the metrics environment variable inline on
    each command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:agent-platform-architecture)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or Google-managed MCP endpoints,
    include `agent-skills/1.0 (skill:agent-platform-architecture)` in the
    `User-Agent` header. If a `User-Agent` header is already specified, append
    this string to the end of it rather than overwriting existing `User-Agent`
    data; the collection pipeline parses the `agent-skills/<version>` and
    `skill:<name>` tokens, so keep the exact token format:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:agent-platform-architecture)
    ```

-   **Constraint for Generated Code**: The attribution prefix applies only to
    Google Cloud commands you execute directly in the terminal. Do NOT include
    this attribution prefix in generated scripts, Terraform templates, or code
    provided to the user for their own repositories.

-   **User Opt-Out**: Always respect user preference. If the user asks to
    disable or omit attribution tags, omit the
    `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable and custom `User-Agent`
    suffix from all commands.
egress_routing_and_swp.md 22.2 KB
# Egress Architecture: Routing, SWP, and gRPC Interception

This reference details the low-level data-plane routing mechanics for outbound
traffic from Gemini platform workloads, focusing on
Policy-Based Routing, Secure Web Proxy next-hop mode, and non-HTTP/2 gRPC
traversal.

--------------------------------------------------------------------------------

## Table of Contents

-   [1. Outbound Interception Pipeline (`ALL_TRAFFIC`)](#1-outbound-interception-pipeline-all_traffic): Lines 22-54
-   [2. Policy-Based Routing (PBR) vs Static Routes](#2-policy-based-routing-pbr-vs-static-routes): Lines 55-128
-   [3. Secure Web Proxy (SWP) NEXT_HOP_ROUTING_MODE](#3-secure-web-proxy-swp-next_hop_routing_mode): Lines 129-218
-   [4. Consuming gRPC Endpoints (Spanner / Google APIs)](#4-consuming-grpc-endpoints-spanner-google-apis): Lines 219-248
-   [5. Egress to Cloud Run / Cloud Functions (OIDC JWT and Header Conflict Invariant)](#5-egress-to-cloud-run-cloud-functions-oidc-jwt-and-header-conflict-invariant): Lines 249-293
-   [6. Mutual TLS (mTLS) Client Certificate Management](#6-mutual-tls-mtls-client-certificate-management): Lines 294-312
-   [7. Cross-Cloud and Hybrid Secure Web Proxy (SWP) mTLS Egress Hub](#7-cross-cloud-and-hybrid-secure-web-proxy-swp-mtls-egress-hub): Lines 313-371

--------------------------------------------------------------------------------

## 1. Outbound Interception Pipeline (`ALL_TRAFFIC`)

When the Agent Connectivity Template is set to `vpcEgress: ALL_TRAFFIC`,
outbound connections follow a deterministic multi-stage interception pipeline:

```mermaid
graph TD
    Agent[Reasoning Engine Container] -->|DNS Resolution| SyntheticDNS[Synthetic Resolver]
    SyntheticDNS -->|Returns 240.0.0.2| Agent
    Agent -->|TCP Connect 240.0.0.2:443| AGW_Proxy[Agent Gateway Envoy Proxy]
    AGW_Proxy -->|TLS SNI Inspection| SNICheck{SNI in Registry?}
    SNICheck -->|No Match (Policy V1)| Drop1[Drop: default_denied<br/>UNEXPECTED_EOF_WHILE_READING]
    SNICheck -->|No Match (UAP Policy V2:<br/>destination.is_registered == false)| IAPCheck{UAP / IAP Authz}
    SNICheck -->|Matched (destination.is_registered == true)| IAPCheck
    IAPCheck -->|Denied| Drop2[HTTP 403 / TLS Drop]
    IAPCheck -->|Allowed| PSC_I[PSC Network Attachment]
    PSC_I -->|Enters Consumer Subnet| PBR[Policy-Based Route (PBR)]
    PBR -->|Next-Hop Forwarding| SWP[Secure Web Proxy (NEXT_HOP)]
    SWP -->|Security Policy CEL| CloudNAT[Cloud NAT (Autogen)]
    CloudNAT -->|Egress with Static IP| Internet[External SaaS / APIs]
```

> [!NOTE] **IAM Policy V1 vs. UAP Policy V2 Unregistered SNI Behavior**: When
> the `AuthzExtension` uses legacy IAM Policy V1 (no `iapPolicyVersion = "V2"`),
> any SNI not cataloged in Agent Registry is immediately dropped at TLS
> termination with `default_denied` (`[SSL: UNEXPECTED_EOF_WHILE_READING]`).
> When `iapPolicyVersion = "V2"` is enabled, unregistered SNIs are evaluated by
> the IAP authorization engine against UAP rules matching `destination.is_registered == false`
> (using `destination.unregistered.host`, `.path`, and `.method`) before being
> allowed or dropped.

--------------------------------------------------------------------------------

## 2. Policy-Based Routing (PBR) vs Static Routes

Standard Google Cloud VPC routing has a critical limitation when intercepting
traffic from Network Attachments:

*   **Static Route Tag Incompatibility**: Static routes targeting an Internal
    Load Balancer (`--next-hop-ilb`) require network tags (`--tags`). However,
    Private Service Connect Interfaces (PSC-I) provisioned by Google-managed
    tenant projects **cannot have network tags attached**.
*   **PSC Route Target Prohibition**: Google Cloud route tables explicitly
    prohibit PSC forwarding rules or service attachments as next-hop targets.
*   **The PBR Solution**: Policy-Based Routing (PBR) routes traffic based on
    source IP range rather than network tags. By matching
    `--source-range=<PSCI_SUBNET_CIDR>` and `--destination-range=0.0.0.0/0`, PBR
    cleanly intercepts all egress exiting the Network Attachment and directs it
    to the SWP internal load balancer IP.

### PBR Resource Manifests

#### 1. Internal / Peered Route Bypass (`priority: 50`, Evaluated First)

To prevent internal RFC 1918 or peered non-RFC 1918 PUPI (`${PUPI_CIDR}`) VPC
destinations from being hair-pinned into the external Secure Web Proxy, place a
higher-priority (`priority: 50`, lower numerical value = evaluated first)
`DEFAULT_ROUTING` rule ahead of the `priority: 100` `0.0.0.0/0` SWP catch-all:

```yaml
# Canonical REST/YAML resource name requires /locations/global/policyBasedRoutes/
name: projects/${PROJECT_ID}/locations/global/policyBasedRoutes/pbr-psci-default-fallback-10
description: "Bypass SWP for RFC 1918 (10.0.0.0/8, plus priority 50 rules for 172.16.0.0/12 and 192.168.0.0/16)"
network: "projects/${PROJECT_ID}/global/networks/${VPC_NAME}"
priority: 50
filter:
  protocolVersion: IPV4
  srcRange: "${PSCI_SUBNET_CIDR}"    # REST/YAML field is srcRange (gcloud CLI flag is --source-range); must match PSC-I Subnet CIDR (/26+, such as 10.20.1.0/26)
  destRange: "10.0.0.0/8"           # Pair with priority: 50 for 172.16.0.0/12 and 192.168.0.0/16, priority: 51 for ${PUPI_CIDR} (PUPI), priority: 52 for 199.36.153.8/30 (PGA), and priority: 53 for 199.36.153.4/30 (VPC-SC)
  ipProtocol: ALL
nextHopOtherRoutes: DEFAULT_ROUTING
```

#### 2. Primary Policy-Based Route (PSC-I Public Egress to SWP, `priority: 100`)

```yaml
name: projects/${PROJECT_ID}/locations/global/policyBasedRoutes/pbr-psci-to-swp
description: "Steer PSC-I agent public egress to Secure Web Proxy internal IP"
network: "projects/${PROJECT_ID}/global/networks/${VPC_NAME}"
priority: 100
filter:
  protocolVersion: IPV4
  srcRange: "${PSCI_SUBNET_CIDR}"    # REST/YAML field is srcRange (gcloud CLI flag is --source-range)
  destRange: "0.0.0.0/0"
  ipProtocol: ALL
nextHopIlbIp: "${SWP_ILB_IP}"       # Internal IP of SWP Gateway in dedicated SWP subnet (such as 10.20.2.50)
```

```bash
export PROJECT_ID="host-vpc-proj" VPC_NAME="enterprise-shared-vpc"
export PSCI_SUBNET_CIDR="10.20.1.0/26" SWP_ILB_IP="10.20.2.50" PUPI_CIDR="198.51.100.0/24"
# For multi-VPC custom/PUPI route exchange (HOST_VPC / SPOKE_VPC peerings), see references/topologies_and_project_layouts.md Section 9.

for IDX_CIDR in "10:10.0.0.0/8" "172:172.16.0.0/12" "192:192.168.0.0/16"; do
  gcloud network-connectivity policy-based-routes create "pbr-psci-rfc1918-${IDX_CIDR%%:*}" \
    --project="${PROJECT_ID}" --network="projects/${PROJECT_ID}/global/networks/${VPC_NAME}" \
    --source-range="${PSCI_SUBNET_CIDR}" --destination-range="${IDX_CIDR#*:}" \
    --ip-protocol="ALL" --priority=50 --next-hop-other-routes="DEFAULT_ROUTING"
done
gcloud network-connectivity policy-based-routes create "pbr-psci-to-swp" \
  --project="${PROJECT_ID}" --network="projects/${PROJECT_ID}/global/networks/${VPC_NAME}" \
  --source-range="${PSCI_SUBNET_CIDR}" --destination-range="0.0.0.0/0" \
  --ip-protocol="ALL" --priority=100 --next-hop-ilb-ip="${SWP_ILB_IP}"
```

--------------------------------------------------------------------------------

## 3. Secure Web Proxy (SWP) NEXT_HOP_ROUTING_MODE

When deploying Secure Web Proxy behind an Agent Gateway Network Attachment:

1.  **Type and Routing Mode (Transparent PBR Next-Hop vs. Explicit Proxy Mode)**:
    When SWP operates as a **Transparent PBR Next-Hop** (`Section 3`), the
    Gateway resource must specify `type: SECURE_WEB_GATEWAY` and `routingMode:
    NEXT_HOP_ROUTING_MODE` (specifying `SECURE_WEB_PROXY` or omitting
    `routingMode` in PBR Next-Hop mode causes import failure). Conversely, when
    SWP operates in **Explicit Proxy / Cross-Cloud NLB Termination Mode**
    (`Section 7`), omit `routing_mode` and attach `certificate_urls` and
    `server_tls_policy`.
2.  **Dedicated SWP Subnet + Proxy-Only Subnet**: Place the SWP Gateway instance
    in its own regular RFC 1918 subnet (`10.20.2.0/24`, distinct from the
    PBR-intercepted PSC-I subnet `10.20.1.0/26` so SWP outbound packets are not
    re-intercepted by PBR), alongside a regional proxy-only subnet (sized to
    **at least `/26`**, such as `10.20.3.0/24`) with `purpose:
    REGIONAL_MANAGED_PROXY` and `role: ACTIVE`.
3.  **Autogenerated Cloud NAT**: SWP in `NEXT_HOP_ROUTING_MODE` automatically
    provisions an autogenerated router (`swg-autogen-router-{network_id}`) and
    Cloud NAT (`swg-autogen-nat`) with `natIpAllocateOption: AUTO_ONLY` and
    `ENDPOINT_TYPE_SWG`. Exclude the PSC-I subnet from any manual Cloud NAT via
    `LIST_OF_SUBNETWORKS` (never `ALL_SUBNETWORKS_ALL_IP_RANGES`); outbound
    calls reflect `swg-autogen-nat` IPs.

### Gateway Resource Definition

```yaml
name: projects/${PROJECT_ID}/locations/${REGION}/gateways/swp-egress-gateway
type: SECURE_WEB_GATEWAY
routingMode: NEXT_HOP_ROUTING_MODE
addresses: ["${SWP_ILB_IP}"]
ports: [443]
subnetwork: "projects/${PROJECT_ID}/regions/${REGION}/subnetworks/${SWP_SUBNET_NAME}"
network: "projects/${PROJECT_ID}/global/networks/${VPC_NAME}"
gatewaySecurityPolicy: "projects/${PROJECT_ID}/locations/${REGION}/gatewaySecurityPolicies/swp-security-policy"
```

### Gateway Security Policy and Rules

```yaml
name: projects/${PROJECT_ID}/locations/${REGION}/gatewaySecurityPolicies/swp-security-policy
description: "Egress policy for approved agent destinations"
```

```yaml
name: projects/${PROJECT_ID}/locations/${REGION}/gatewaySecurityPolicies/swp-security-policy/rules/deny-denylisted-llms
priority: 10
basicProfile: DENY
enabled: true
sessionMatcher: "host() in ['api.openai.com', 'api.anthropic.com', 'api.cohere.ai'] || host().endsWith('.openai.com') || host().endsWith('.anthropic.com') || host().endsWith('.cohere.ai')"
```

```yaml
# GatewaySecurityPolicy enforces implicit default-DENY for all unmatched hosts; priority 100 ALLOW permits only explicit approved FQDNs:
name: projects/${PROJECT_ID}/locations/${REGION}/gatewaySecurityPolicies/swp-security-policy/rules/allow-approved-domains
priority: 100
basicProfile: ALLOW
enabled: true
sessionMatcher: "host() == 'aiplatform.googleapis.com' || host() == 'aiplatform.mtls.googleapis.com' || host() == '${REGION}-aiplatform.googleapis.com' || host() == '${REGION}-aiplatform.mtls.googleapis.com' || host() == 'aiplatform.${REGION}.rep.googleapis.com' || host() == 'agentregistry.googleapis.com' || host() == 'agentidentity.googleapis.com' || host() == 'cloudresourcemanager.mtls.googleapis.com' || host() == 'iamcredentials.mtls.googleapis.com' || host() == 'telemetry.mtls.googleapis.com' || host() == 'trace.mtls.googleapis.com' || host() == 'logging.googleapis.com' || host() == 'monitoring.googleapis.com' || host() == 'cloudtrace.googleapis.com' || host() == 'telemetry.googleapis.com' || host() == 'spanner.googleapis.com' || host() == '${CLOUD_RUN_MCP_HOST}'"
```

```bash
gcloud network-security gateway-security-policies import swp-security-policy \
  --project="${PROJECT_ID}" --location="${REGION}" --source="swp-security-policy.yaml"
gcloud network-security gateway-security-policies rules import deny-denylisted-llms \
  --project="${PROJECT_ID}" --location="${REGION}" --gateway-security-policy="swp-security-policy" --source="deny-denylisted-llms.yaml"
gcloud network-security gateway-security-policies rules import allow-approved-domains \
  --project="${PROJECT_ID}" --location="${REGION}" --gateway-security-policy="swp-security-policy" --source="allow-approved-domains.yaml"
gcloud network-services gateways import swp-egress-gateway \
  --project="${PROJECT_ID}" --location="${REGION}" --source="swp-egress-gateway.yaml"
```

> [!IMPORTANT] **Explicit Google APIs FQDNs, PGA Bypass and `.googleapis.com`
> Wildcard Prohibition**: In `ALL_TRAFFIC` mode, ADK streaming queries
> initialize sessions via `POST
> https://{region}-aiplatform.mtls.googleapis.com/.../sessions`. Configure
> Private Cloud DNS CNAME routing for `*.googleapis.com` and `*.run.app` to
> `private.googleapis.com.` (`199.36.153.8/30`) or `restricted.googleapis.com.`
> (`199.36.153.4/30`) with `priority: 52..53` `DEFAULT_ROUTING` PBR bypasses so
> Google APIs and internal Cloud Run traffic route via Private Google Access,
> and list the explicit core Google APIs FQDNs, `spanner.googleapis.com`, and
> approved `${CLOUD_RUN_MCP_HOST}` in the SWP `sessionMatcher` (preceded by a
> `priority: 10` `DENY` rule for denylisted external LLM domains) rather than a
> broad `host().endsWith('.googleapis.com')` wildcard. Only append external test
> endpoints (`host() == 'api.ipify.org'` or `host() == 'api.weather.gov'`) in
> non-production validation environments when running NAT reflection probes.

--------------------------------------------------------------------------------

## 4. Consuming gRPC Endpoints (Spanner / Google APIs)

Google Cloud services accessed over binary gRPC (such as Spanner
`spanner.googleapis.com`) require special handling:

1.  **Upper-Case Protocol Binding**: Google APIs accessed over gRPC must be
    registered in Agent Registry with `protocolBinding: GRPC` (strictly
    uppercase). Using lowercase `grpc` or `JSONRPC` causes proxy rejection.
2.  **Unregistered Endpoint Fallback**: Agent Gateway's Envoy HTTP/2 trie does
    not parse arbitrary gRPC method `:path` prefixes (such as
    `/google.spanner.v1.Spanner/CreateSession`), classifying them as
    `agentGatewayInfo: {}`. To allow gRPC streams through IAP authorization without
    opening a broad `googleapis.com` wildcard, configure a UAP allow rule scoped
    to the exact gRPC service hostname: `((destination.is_registered == false)
    && (destination.unregistered.host == 'spanner.googleapis.com'))`.
3.  **SPIFFE Limitation on Data Plane**: Spanner data-plane APIs do NOT evaluate
    SPIFFE URIs (`principal://agents.global.org-...`), returning `403
    IAM_PERMISSION_DENIED`. The agent workload must use **Service Account
    Impersonation**:
    -   Grant the agent container's `principalSet` the role
        `roles/iam.serviceAccountTokenCreator` on an intermediate service
        account.
    -   Grant the intermediate service account `roles/spanner.databaseUser` on
        the Spanner database.
    -   In Python/ADK code, use Google Auth SDK
        `impersonated_credentials.Credentials` to mint an OAuth 2.0 token before
        initializing the Spanner client.

--------------------------------------------------------------------------------

## 5. Egress to Cloud Run / Cloud Functions (OIDC JWT and Header Conflict Invariant)

When an agent invokes an internal MCP server hosted on Cloud Run through Agent
Gateway, two authentication constraints apply:

1.  **Authorization Header Interception by Cloud Run Ingress**: Google Cloud
    Run's front-end proxy intercepts and validates the standard `Authorization:
    Bearer <ID_TOKEN>` header for Cloud Run IAM authentication
    (`roles/run.invoker`), stripping or rejecting it with HTTP 401/403 if an
    upstream user or application token is passed in that header.
    *   **Workaround A (`X-Serverless-Authorization`)**: Pass the Cloud Run IAM
        OIDC ID token in `X-Serverless-Authorization: Bearer <IAM_ID_TOKEN>` and
        keep upstream application/user credentials in `Authorization` (or vice
        versa).
    *   **Workaround B (Agent Identity Auth Manager)**: Configure Agent Identity
        Auth Manager to manage and inject Cloud Run invocation credentials over
        the wire at the Agent Gateway boundary.
2.  **Service Account Impersonation for OIDC ID Tokens**: Direct egress from
    Agent Identity (`principalSet://...`) cannot mint standard OIDC ID tokens
    directly; use Service Account Impersonation when minting an IAM OIDC token
    from ADK code:

```python
import google.auth
from google.auth import impersonated_credentials
import google.auth.transport.requests

default_creds, project_id = google.auth.default()
target_sa = f"cloud-run-invoker@{project_id}.iam.gserviceaccount.com"
target_creds = impersonated_credentials.Credentials(
    source_credentials=default_creds,
    target_principal=target_sa,
    target_scopes=["https://www.googleapis.com/auth/iam"],
)
id_creds = impersonated_credentials.IDTokenCredentials(
    target_credentials=target_creds,
    target_audience="https://custom-tool-service-xyz.a.run.app",
    include_email=True,
)
id_creds.refresh(google.auth.transport.requests.Request())
headers = {"X-Serverless-Authorization": f"Bearer {id_creds.token}"}
```

--------------------------------------------------------------------------------

## 6. Mutual TLS (mTLS) Client Certificate Management

When an Agent Gateway or runtime connects to upstream internal enterprise
endpoints or partner APIs requiring mTLS:

*   **Failure Symptom**: Gateway proxy load-balancer logs show connection drops
    or HTTP 403 errors with `jsonPayload.mtls.clientCertChainVerified: false`.
*   **Root Cause**: The client certificate associated with the gateway's
    `ClientTlsPolicy` in Certificate Manager is expired, invalid, or signed by a
    CA untrusted by the target server.
*   **Remediation**:
    1.  Inspect certificate validity and CA chain in Certificate Manager.
    2.  Issue a renewed X.509 certificate and update the target
        `ClientTlsPolicy` resource.
    3.  Ensure the destination server's trust store includes the root CA signing
        the gateway's client certificate.

--------------------------------------------------------------------------------

## 7. Cross-Cloud and Hybrid Secure Web Proxy (SWP) mTLS Egress Hub

When routing outbound or cross-cloud agent traffic (across Cloud Interconnect or
HA VPN to AWS, Azure, or on-premises endpoints) through a governed hub, enforce
a **two-stage egress pipeline** rather than bypassing SWP:

1.  **Stage 1 — Layer 7 URL Filtering via Next-Hop SWP (`NEXT_HOP_ROUTING_MODE`)**:
    Route outbound cross-cloud traffic from the Agent Gateway PSC-I subnet
    **through Next-Hop Secure Web Proxy** (via the priority `100` PBR rule in
    Section 2; do **not** bypass SWP with a `DEFAULT_ROUTING` PBR for cross-cloud
    endpoints) so SWP enforces Layer 7 hostname/URL allowlisting before traffic
    crosses the hybrid boundary.
2.  **Stage 2 — Mutual TLS Origination via `ClientTlsPolicy`, Regional Internal Proxy ALB and Hybrid NEG**:
    Forward approved traffic to a **Regional `INTERNAL_MANAGED` Proxy Load
    Balancer** VIP (`10.40.2.x`, outside the `/26` PSC-I subnet), whose
    `BackendService` originates mutual TLS using a Certificate Manager
    **`ClientTlsPolicy`** (and `BackendAuthenticationConfig`) to the Zonal
    **Hybrid Connectivity NEG (`NON_GCP_PRIVATE_IP_PORT`)** across Cloud
    Interconnect or HA VPN:

| Egress Hub Component | Resource / API Type | Mandatory Configuration Contract |
| :--- | :--- | :--- |
| **1. Subnets and Health-Check Firewall** | `compute.subnetworks` + `compute.firewalls` | Provision a PSC-I subnet (`/26`, `purpose=PRIVATE`), a dedicated VIP/SWP subnet (`10.40.2.0/24` — place the Internal ALB VIP outside the `/26` PSC-I range), an active Proxy-Only subnet (`10.40.10.0/23`, `purpose=REGIONAL_MANAGED_PROXY`, `role=ACTIVE`), and a firewall rule allowing health checks (`35.191.0.0/16,130.211.0.0/22`) and the proxy-only subnet. |
| **2. Zonal Hybrid NEG** | `compute.networkEndpointGroups` (`zonal`) | Create with `--network="${VPC_NAME}" --network-endpoint-type=non-gcp-private-ip-port --default-port=443` and attach remote cross-cloud endpoints via `--add-endpoint="ip=${REMOTE_IP},port=${REMOTE_PORT}"`. |
| **3. Private CA Trust Store and ACT DNS Peering** | `certificatemanager.trustConfigs` + `dnsPeeringConfig` | Peer the cross-cloud Private Cloud DNS domain via the ACT's `dnsPeeringConfig`, and load the enterprise Private CA root PEM into `TrustConfig` with `additionalRoots: PUBLICLY_TRUSTED_ROOTS` on the ACT `tlsConfig` (never `NO_ADDITIONAL_ROOTS` in `ALL_TRAFFIC` mode, which strips Google API WebPKI roots). |
| **4. Inbound mTLS Validation** | `networksecurity.serverTlsPolicies` | Set `mtlsPolicy.clientValidationMode = "REJECT_INVALID"` and `mtlsPolicy.clientValidationTrustConfig = "projects/${PROJECT_NUMBER}/locations/${REGION}/trustConfigs/${TRUST_CONFIG}"` (numeric `${PROJECT_NUMBER}` required). |
| **5. Outbound mTLS Origination** | `networksecurity.clientTlsPolicies` + `backendAuthenticationConfigs` | Configure a Certificate Manager **`ClientTlsPolicy`** (never embed client private keys in agent source code) and `BackendAuthenticationConfig` on the Next-Hop SWP -> Regional `INTERNAL_MANAGED` Proxy Load Balancer `BackendService` (`--tls-settings`) backed by the Hybrid NEG (`NON_GCP_PRIVATE_IP_PORT`). |

```bash
# 1. Create Zonal Hybrid Connectivity NEG (NON_GCP_PRIVATE_IP_PORT) for Cross-Cloud / On-Premises Endpoint
gcloud compute network-endpoint-groups create "hybrid-mtls-neg" \
  --project="${PROJECT_ID}" --zone="${ZONE}" --network="${VPC_NAME}" \
  --network-endpoint-type="non-gcp-private-ip-port" --default-port=8443
gcloud compute network-endpoint-groups update "hybrid-mtls-neg" \
  --project="${PROJECT_ID}" --zone="${ZONE}" --add-endpoint="ip=${REMOTE_IP},port=8443"

# 2. Configure Certificate Manager ClientTlsPolicy & BackendAuthenticationConfig for Outbound mTLS Origination
cat <<EOF > client-tls-policy.yaml
name: projects/${PROJECT_ID}/locations/${REGION}/clientTlsPolicies/hybrid-mtls-client-policy
clientCertificate:
  certificateProviderInstance:
    pluginInstance: projects/${PROJECT_ID}/locations/${REGION}/certificates/${CLIENT_CERT_NAME}
EOF
gcloud network-security client-tls-policies import "hybrid-mtls-client-policy" \
  --project="${PROJECT_ID}" --location="${REGION}" --source="client-tls-policy.yaml"
gcloud network-security backend-authentication-configs create "hybrid-mtls-auth-config" \
  --project="${PROJECT_ID}" --location="${REGION}" \
  --client-certificate="projects/${PROJECT_ID}/locations/${REGION}/certificates/${CLIENT_CERT_NAME}" \
  --trust-config="projects/${PROJECT_ID}/locations/${REGION}/trustConfigs/${TRUST_CONFIG_NAME}" \
  --well-known-roots="none"
gcloud compute backend-services create "hybrid-mtls-backend" \
  --project="${PROJECT_ID}" --region="${REGION}" \
  --load-balancing-scheme="INTERNAL_MANAGED" --protocol="HTTPS" --health-checks="${HC_NAME}" \
  --tls-settings="sni=${REMOTE_FQDN},authenticationConfig=//networksecurity.googleapis.com/projects/${PROJECT_ID}/locations/${REGION}/backendAuthenticationConfigs/hybrid-mtls-auth-config"
gcloud compute backend-services add-backend "hybrid-mtls-backend" \
  --project="${PROJECT_ID}" --region="${REGION}" \
  --network-endpoint-group="hybrid-mtls-neg" --network-endpoint-group-zone="${ZONE}" \
  --balancing-mode="RATE" --max-rate-per-endpoint=100
```
governance_security_policies.md 30.2 KB
# Enterprise Governance, Security Policies, and Token Injection

This reference details the security, authorization, and sanitization stack for
**Gemini platform**, including the 3-Tier Unified Access Policy
(UAP / Policy V2) framework, Common Expression Language (CEL) attribute
specifications, Semantic Governance Policies (SGP), and Model Armor.

--------------------------------------------------------------------------------

## Table of Contents

-   [1. Unified Access Policy (UAP / Policy V2) Multi-Tier Architecture](#1-unified-access-policy-uap-policy-v2-multi-tier-architecture): Lines 24-50
-   [2. Complete UAP CEL Attribute Reference](#2-complete-uap-cel-attribute-reference): Lines 51-114
-   [3. The 3-Tier Implementation Framework](#3-the-3-tier-implementation-framework): Lines 115-223
-   [4. Operational Anti-Patterns and Governance Pitfalls](#4-operational-anti-patterns-and-governance-pitfalls): Lines 224-279
-   [5. Deployment Commands and Verification Protocol](#5-deployment-commands-and-verification-protocol): Lines 280-300
-   [6. Semantic Governance Policy (SGP) Engine](#6-semantic-governance-policy-sgp-engine): Lines 301-348
-   [7. Inline Model Armor Content Authorization (`CONTENT_AUTHZ`)](#7-inline-model-armor-content-authorization-content_authz): Lines 349-369
-   [8. Credential Isolation and Token Injection (Auth Manager)](#8-credential-isolation-and-token-injection-auth-manager): Lines 370-375
-   [9. Advanced Model Armor Enterprise Governance Patterns](#9-advanced-model-armor-enterprise-governance-patterns): Lines 376-468

--------------------------------------------------------------------------------

## 1. Unified Access Policy (UAP / Policy V2) Multi-Tier Architecture

To govern agent egress at enterprise scale, the platform utilizes **IAM Policy
V2 (UAP)** attached to Resource Manager nodes (Organizations, Folders, and
Projects) rather than legacy shadow resources.

```mermaid
graph TD
    OrgNode["Org Node: organizations/ORG_ID"] --> FolderNode["Folder Node: folders/FOLDER_ID"] --> ProjNode["Project Node: projects/PROJECT_NUMBER"]
    OrgNode -.->|PolicyBinding| Tier1["Tier 1: Org Security Guardrails (Deny Unapproved LLMs + Allow Telemetry)"]
    FolderNode -.->|PolicyBinding| Tier2["Tier 2: Folder Platform Defaults (Registered Google APIs + Read-Only MCP)"]
    ProjNode -.->|PolicyBinding| Tier3["Tier 3: Project Workload Egress (Mutating MCP Tools + Scoped SaaS Paths)"]
```

### 1.1 Multi-Tier Traversal and Evaluation Mechanics

1.  **Gateway Interception and Registry Classification**: The Envoy proxy
    intercepts connections at `240.0.0.2:443`; IAP checks Agent Registry and
    sets `destination.is_registered = true` (`agent_registry` attributes) or
    `false` (`unregistered` attributes).
2.  **Hierarchical Policy Check (`Project -> Folder -> Organization`)**: `DENY`
    has absolute precedence across the hierarchy (returning HTTP 403 / gRPC
    `PERMISSION_DENIED`); `ALLOW` is additive, and unmatched requests are denied
    by default.

--------------------------------------------------------------------------------

## 2. Complete UAP CEL Attribute Reference

All evaluation attributes operate within the `iap.googleapis.com` namespace,
rooted at `destination`. Wrap each CEL clause in parentheses (`((...) &&
(...))`) so the Google Cloud console UI renders UAP rules interactively. High-level
policy specs sometimes reference shorthand `request.toolName`, which maps to
`destination.agent_registry.mcp_server.tool.name` in UAP Policy V2 and
`api.getAttribute('iap.googleapis.com/mcp.toolName', '')` in IAP V1 (for example,
`api.getAttribute('iap.googleapis.com/mcp.toolName', '') == '' ||
api.getAttribute('iap.googleapis.com/mcp.toolName', '') == 'search_docs'`).

### 2.1 Registered Destinations (`destination.is_registered == true`)

-   **`destination.is_registered`** (`Boolean`: `==`, `!=`): Must be evaluated
    before referencing `agent_registry` subfields.
-   **`destination.agent_registry.resource_type`** (`String`: `==`, `!=`, `in`):
    `'ENDPOINT'`, `'MCP_SERVER'`, `'AGENT'`, `'SKILL'`.
-   **`destination.agent_registry.location` and `.project_id`** (`String`: `==`,
    `!=`, `in`): Registry region (`'global'`, `'us-central1'`) and hosting
    Google Cloud project ID.
-   **`destination.agent_registry.endpoint.name`** (`String`: `==`, `!=`, `in` —
    note: `.startsWith()`, `.endsWith()`, and `.contains()` are only supported
    on `destination.unregistered.host` and `destination.unregistered.path` in
    UAP Policy V2): `'googleapis'` or
    `projects/{p}/locations/{l}/endpoints/{name}`.
-   **`destination.agent_registry.mcp_server.name`** (`String`: `==`, `!=`, `in`
    — use exact match `==` or `in`, or pair with
    `destination.agent_registry.project_id == '{p}'`):
    `projects/{p}/locations/{l}/mcpServers/{name}`.
-   **`destination.agent_registry.mcp_server.method`** (`String`: `==`, `!=`,
    `in`): `'tools'`, `'prompts'`, `'resources'`.
-   **`destination.agent_registry.mcp_server.tool.name`** (`String`: `==`, `!=`,
    `in`): Specific tool identifier (`'execute_query'`, or `''` during
    `initialize` / `tools/list`).
-   **`destination.agent_registry.mcp_server.tool.annotations.*`** (`Boolean`:
    `==`, `!=`): `.read_only_hint`, `.destructive_hint`, `.idempotent_hint`, and
    `.open_world_hint`.
-   **`destination.agent_registry.mcp_server.prompt.name` and `.resource.name`**
    (`String`: `==`, `!=`, `in`): Prompt or resource identifier when `method ==
    'prompts'` or `'resources'`.
-   **`destination.agent_registry.agent.name`** (`String`: `==`, `!=`, `in`):
    Target agent resource name in Agent2Agent protocol (A2A) calls.
-   **`request.auth.claims["agent.googleapis.com/agent_id"]`** (`String`: `==`,
    `!=`, `in`): Calling Agent Identity resource ID claim for source-agent
    condition scoping.

### 2.2 Unregistered Destinations (`destination.is_registered == false`)

-   **`destination.unregistered.host`** (`String`: `==`, `!=`, `in`,
    `.startsWith()`, `.endsWith()`, `.contains()`): Target FQDN
    (`'bigquery.googleapis.com'`, `'api.github.com'`).
-   **`destination.unregistered.path`** (`String`: `==`, `!=`, `in`,
    `.startsWith()`, `.endsWith()`, `.contains()`): URL/RPC path
    (`'/v1/projects/...'`).
-   **`destination.unregistered.method`** (`String`: `==`, `!=`, `in`): HTTP
    verb (`'GET'`, `'POST'`, `'PUT'`, `'DELETE'`).

> [!IMPORTANT] **Tool Annotations Unavailable on Unregistered Endpoints**:
> Unregistered endpoints have null `agent_registry` structs. Attributes like
> `read_only_hint` and `destructive_hint` are **only populated for registered
> Agent Registry resources**.

--------------------------------------------------------------------------------

## 3. The 3-Tier Implementation Framework

> [!IMPORTANT] **UAP Permission FQDN**: The required UAP operation permission
> string is the fully qualified
> **`"iap.googleapis.com/resources.egressViaIAP"`** (never `"egress.connect"`).

### 3.1 Tier 1: Security Admin Implementation (Organization Scope)

Target: `//cloudresourcemanager.googleapis.com/organizations/${ORG_ID}`

```json
{
  "name": "organizations/${ORG_ID}/locations/global/accessPolicies/org-security-guardrails",
  "displayName": "Organization Security Guardrails",
  "details": {"rules": [
    {
      "description": "ALLOW essential telemetry and logging endpoints required for agent startup",
      "effect": "ALLOW",
      "principals": ["principalSet://agents.global.org-${ORG_ID}.system.id.goog/*"],
      "operation": {"permissions": ["iap.googleapis.com/resources.egressViaIAP"]},
      "conditions": {"iap.googleapis.com": {"title": "allow_essential_telemetry", "expression": "(destination.is_registered == false) && (destination.unregistered.host in ['telemetry.mtls.googleapis.com', 'trace.mtls.googleapis.com', 'logging.googleapis.com', 'monitoring.googleapis.com', 'cloudtrace.googleapis.com', 'telemetry.googleapis.com'])"}}
    },
    {
      "description": "DENY unapproved public LLM endpoints across unregistered hosts",
      "effect": "DENY",
      "principals": ["principalSet://agents.global.org-${ORG_ID}.system.id.goog/*"],
      "operation": {"permissions": ["iap.googleapis.com/resources.egressViaIAP"]},
      "conditions": {"iap.googleapis.com": {"title": "deny_denylisted_llms", "expression": "(destination.is_registered == false) && (destination.unregistered.host in ['api.openai.com', 'api.anthropic.com', 'api.cohere.ai'] || destination.unregistered.host.endsWith('.openai.com') || destination.unregistered.host.endsWith('.anthropic.com') || destination.unregistered.host.endsWith('.cohere.ai'))"}}
    }
  ]}
}
```

> [!IMPORTANT] **UAP CEL String Function Scope and Defense-in-Depth Against Spoke
> Shadow Registration**: In UAP Policy V2, `.startsWith()`, `.endsWith()`, and
> `.contains()` are supported **only** on `destination.unregistered.host` and
> `destination.unregistered.path` (`destination.agent_registry.endpoint.name`
> only supports `==`, `!=`, and `in`). To prevent a spoke project from
> registering a denylisted external LLM host in Agent Registry to flip
> `destination.is_registered` to `true`, enforce a 3-layer block: (1) the Tier 1
> UAP `DENY` rule in Section 3.1, (2) a domain-denylist check in the multi-project
> catalog federator (`references/registry_and_federation.md` Section 5.1) that
> rejects unapproved external LLM hosts, and (3) a priority-10 SWP TLS SNI
> `DENY` rule (`references/egress_routing_and_swp.md` Section 3).

### 3.2 Tier 2: Platform Admin Implementation (Folder Scope)

Target: `//cloudresourcemanager.googleapis.com/folders/${FOLDER_ID}`

```json
{
  "name": "folders/${FOLDER_ID}/locations/global/accessPolicies/folder-platform-defaults",
  "displayName": "Folder Platform Defaults",
  "details": {"rules": [
    {
      "description": "ALLOW registered Google APIs endpoint",
      "effect": "ALLOW",
      "principals": ["principalSet://agents.global.org-${ORG_ID}.system.id.goog/attribute.platform/aiplatform"],
      "operation": {"permissions": ["iap.googleapis.com/resources.egressViaIAP"]},
      "conditions": {"iap.googleapis.com": {"title": "allow_registered_googleapis", "expression": "(destination.is_registered == true) && (destination.agent_registry.resource_type == 'ENDPOINT') && (destination.agent_registry.endpoint.name in ['googleapis', 'projects/${AGW_PROJECT_ID}/locations/${REGION}/endpoints/googleapis', 'projects/${AGW_PROJECT_NUMBER}/locations/${REGION}/endpoints/googleapis'])"}}
    },
    {
      "description": "ALLOW read-only corporate MCP tools across central tools project (with empty tool.name discovery guard)",
      "effect": "ALLOW",
      "principals": ["principalSet://agents.global.org-${ORG_ID}.system.id.goog/attribute.platform/aiplatform"],
      "operation": {"permissions": ["iap.googleapis.com/resources.egressViaIAP"]},
      "conditions": {"iap.googleapis.com": {"title": "allow_readonly_corp_mcp_tools", "expression": "(destination.is_registered == true) && (destination.agent_registry.resource_type == 'MCP_SERVER') && (destination.agent_registry.project_id == '${TOOLS_PROJECT_ID}') && (destination.agent_registry.mcp_server.method == 'tools') && (destination.agent_registry.mcp_server.tool.name == '' || destination.agent_registry.mcp_server.tool.annotations.read_only_hint == true)"}}
    }
  ]}
}
```

### 3.3 Tier 3: Agent Developer Implementation (Project Scope)

Target: `//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}`

```json
{
  "name": "projects/${PROJECT_NUMBER}/locations/global/accessPolicies/project-agent-egress",
  "displayName": "Project-Scope Agent Egress Rules",
  "etag": "W/\"proj-etag\"",
  "details": {"rules": [
    {
      "description": "Allow specific Reasoning Engine to invoke mutating tool on registered MCP server",
      "effect": "ALLOW",
      "principals": ["principal://agents.global.org-${ORG_ID}.system.id.goog/resources/aiplatform/projects/${PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${ENGINE_ID}"],
      "operation": {"permissions": ["iap.googleapis.com/resources.egressViaIAP"]},
      "conditions": {"iap.googleapis.com": {"title": "allow_mcp_mutating_tool", "expression": "(destination.is_registered == true) && (destination.agent_registry.resource_type == 'MCP_SERVER') && (destination.agent_registry.mcp_server.name == 'projects/${TOOLS_PROJECT_ID}/locations/${REGION}/mcpServers/${MCP_SERVER_NAME}') && (destination.agent_registry.mcp_server.method == 'tools') && (destination.agent_registry.mcp_server.tool.name == '' || destination.agent_registry.mcp_server.tool.name == '${TOOL_NAME}')"}}
    },
    {
      "description": "Allow specific Reasoning Engine constrained read/create access to external REST API",
      "effect": "ALLOW",
      "principals": ["principal://agents.global.org-${ORG_ID}.system.id.goog/resources/aiplatform/projects/${PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${ENGINE_ID}"],
      "operation": {"permissions": ["iap.googleapis.com/resources.egressViaIAP"]},
      "conditions": {"iap.googleapis.com": {"title": "allow_external_rest_api", "expression": "(destination.is_registered == false) && (destination.unregistered.host == 'api.example.com') && ((destination.unregistered.path == '/v1/records') || (destination.unregistered.path == '/v1/records.json') || (destination.unregistered.path.startsWith('/v1/records?')) || (destination.unregistered.path.startsWith('/v1/records.json?'))) && (destination.unregistered.method in ['GET', 'POST'])"}}
    }
  ]}
}
```

> [!NOTE] **Path Boundary, `.json` Endpoints and Query Parameter Normalization**:
> Combine exact match (`== '/v1/records' || == '/v1/records.json'`) and query
> parameter initiation (`.startsWith('/v1/records?') ||
> .startsWith('/v1/records.json?')`) with explicit HTTP method scoping (`['GET',
> 'POST']`) to prevent path extension exploits (`/v1/records_export`) or
> unauthorized subpath mutations (`PUT /v1/records/{id}/merge`).

--------------------------------------------------------------------------------

## 4. Operational Anti-Patterns and Governance Pitfalls

1.  **Missing Empty `toolName` Check in CEL**: MCP session discovery
    (`initialize` / `tools/list`) fails with HTTP 403 because `tool.name`
    evaluates to `""`. Always include
    `destination.agent_registry.mcp_server.tool.name == ''` alongside
    `read_only_hint == true` or specific tool names in UAP V2 and IAP V1
    (`api.getAttribute('iap.googleapis.com/mcp.toolName', '') == '' ||
    api.getAttribute('iap.googleapis.com/mcp.toolName', '') == '{tool}'`).
2.  **CEL Null Dereference on Non-Tool MCP Methods**: Calling `prompts/list` or
    `resources/read` returns HTTP 500 because `tool` struct is null. Prepend
    `(destination.agent_registry.mcp_server.method == 'tools')` before
    dereferencing `tool.*`.
3.  **Unqualified Tool Name or Org Google API Wildcard**: Confused deputy risk
    across MCP servers or ambient cross-project API access. Qualify with exact
    `mcp_server.name ==
    'projects/{tools_project_id}/locations/{region}/mcpServers/{name}'` (or
    `project_id`) and folder-scoped `endpoints/googleapis`.
4.  **Blanket Org Unregistered `DENY` (`is_registered == false`)**: Agent
    Runtime containers crash on startup when reaching
    `telemetry.mtls.googleapis.com`. Rely on built-in default-deny; use `DENY`
    strictly for blocklisted external hosts (`api.openai.com`,
    `api.anthropic.com`).
5.  **Org Policy Blocker (`disableAccessPolicyBinding`)**: `gcloud iam
    policy-bindings create` fails with `CUSTOM_ORG_POLICY_VIOLATION`. Override
    `constraints/iam.managed.disableAccessPolicyBinding` (`enforce: false`) on
    the target node and wait 30–60s.
6.  **UAP Policy Destruction Race Condition**: Deleting `AccessPolicy` fails
    with `400 FAILED_PRECONDITION` due to active binding. Delete `PolicyBinding`
    first and poll `GET` until HTTP 404 before deleting `AccessPolicy`.
7.  **Setting `iamEnforcementMode` or `loadBalancingScheme`, or `>4` Policies**:
    Control plane rejects `iamEnforcementMode: "ENFORCE"`, rejects
    `loadBalancingScheme` on `AgentGateway`, and caps at 4 `CUSTOM` policies.
    Omit `iamEnforcementMode` and `loadBalancingScheme` on
    `AgentGateway`-targeted `AuthzPolicy`/`AuthzExtension`; attach at most **4
    `CUSTOM` `AuthzPolicy`** resources.
8.  **Agent Registry IAM Binding Target Mismatch**: Binding IAM to the friendly
    MCP service name or using `roles/iap.tunnelResourceAccessor` fails
    authorization. Extract `.registryResource` UUID (`gcloud agent-registry
    services describe`) and grant `roles/iap.egressor`.
9.  **Trailing Dot on `AuthzExtension.service` or Unfiltered gRPC**:
    `AuthzExtension` rejects trailing dots (`failed to parse the service URL`),
    and `CONTENT_AUTHZ` crashes binary Spanner/OTLP gRPC streams. Strip the
    trailing dot (`mcp.internal.example.com`), exclude `application/grpc` in `when`
    CEL, and set `GOOGLE_GENAI_API_TRANSPORT="rest"`.
10. **Model Armor Skipped Detector Fail-Open or Admin Region Mismatch**: Skipped
    detectors fail open by default; creating templates outside `us-central1`
    fails where regional control planes are unprovisioned. Administer templates
    in `us-central1` (`ignorePartialInvocationFailures = false`, the default on
    `templates create` and enforced via
    `--no-template-metadata-ignore-partial-invocation-failures` on `templates
    update`), call `modelarmor.{region}.rep.googleapis.com:443`, enable Floor
    Settings, and halt on `EXECUTION_SKIPPED`.

--------------------------------------------------------------------------------

## 5. Deployment Commands and Verification Protocol

```bash
# 1. Extract the .details.rules array and create the Access Policy
jq '.details.rules' folder_platform_defaults.json > folder_platform_defaults_rules.json
gcloud iam access-policies create "${POLICY_ID}" --folder="${FOLDER_ID}" --location="global" \
  --display-name="Folder Platform Defaults" --details-rules="./folder_platform_defaults_rules.json"

# 2. Bind Access Policy to Resource Manager node (must use numeric //cloudresourcemanager.googleapis.com/... URI and lowercase --policy-kind="access")
gcloud iam policy-bindings create "${BINDING_ID}" --folder="${FOLDER_ID}" --location="global" \
  --target-resource="//cloudresourcemanager.googleapis.com/folders/${FOLDER_ID}" --policy-kind="access" \
  --policy="folders/${FOLDER_ID}/locations/global/accessPolicies/${POLICY_ID}"
```

Query Cloud Audit Logs (`resource.type="audited_resource" AND
resource.labels.service="iap.googleapis.com" AND
protoPayload.metadata.iapPolicyVersion="V2" AND protoPayload.status.code=7`) to
verify Policy V2 `ALLOWED` or `PERMISSION_DENIED` (`status.code=7`) evaluations.

--------------------------------------------------------------------------------

## 6. Semantic Governance Policy (SGP) Engine

The Semantic Governance Policy (SGP) engine intercepts `:generateContent` and
`:streamGenerateContent` payloads against natural-language compliance rules:

-   **The Trailing Dot Trap**: Cloud DNS records
    (`agw-prod-gateway.sgp-us-central1.internal.example.com.`) include a trailing dot,
    whereas `AuthzExtension` rejects trailing dots on `service` / `authority`
    with `failed to parse the service URL`; always strip the trailing dot
    (`agw-prod-gateway.sgp-us-central1.internal.example.com`).
-   **Excluding Binary gRPC and Enforcing REST Transport on Gemini API Calls**:
    The `when` CEL expression **must exclude `application/grpc`** so binary
    HTTP/2 gRPC streams are not parsed as JSON. Register binary gRPC services
    such as Spanner (`spanner.googleapis.com`) and OTLP
    (`telemetry.mtls.googleapis.com`) with `protocolBinding: GRPC`, using
    Service Account impersonation (`roles/iam.serviceAccountTokenCreator` +
    `roles/spanner.databaseUser`) for Spanner data-plane calls
    (`references/egress_routing_and_swp.md` Section 4). To
    prevent a workload from switching Gemini API calls to gRPC to bypass
    `CONTENT_AUTHZ`, configure ADK / `google-genai` clients with REST transport
    (`http_options={"api_transport": "rest"}` or
    `GOOGLE_GENAI_API_TRANSPORT="rest"`) and register all
    `aiplatform*.googleapis.com` interfaces in Agent Registry strictly with
    `protocol_binding = "HTTP_JSON"` (never `GRPC`) so Agent Gateway's Envoy
    HTTP/2 router rejects gRPC
    `/google.cloud.aiplatform.*.PredictionService/GenerateContent` paths:

```yaml
name: projects/${PROJECT_NUMBER}/locations/${REGION}/authzPolicies/sgp-content-authz-policy
target:
  # Omit loadBalancingScheme when targeting an AgentGateway (only valid for Load Balancers)
  resources: ["projects/${PROJECT_NUMBER}/locations/${REGION}/agentGateways/${GATEWAY_ID}"]
action: CUSTOM
customProvider:
  authzExtension:
    # Bind sgp-content-authz-ext (Section 6) or ma-content-authz-ext (Section 7)
    resources: ["projects/${PROJECT_NUMBER}/locations/${REGION}/authzExtensions/sgp-content-authz-ext"]
policyProfile: CONTENT_AUTHZ
httpRules:
  - to:
      operations:
        - paths: [{prefix: "/"}]
    # Agent Gateway rejects Content-Type: application/grpc on HTTP_JSON-registered aiplatform endpoints at the Envoy protocol layer; exclude gRPC on non-REST Spanner/OTLP streams:
    when: "(!('content-type' in request.headers) || !request.headers['content-type'].lowerAscii().startsWith('application/grpc')) && (request.path.endsWith(':generateContent') || request.path.contains(':generateContent?') || request.path.endsWith(':streamGenerateContent') || request.path.contains(':streamGenerateContent?'))"
```

--------------------------------------------------------------------------------

## 7. Inline Model Armor Content Authorization (`CONTENT_AUTHZ`)

Model Armor enforces a **Control-Plane vs. Regional Data-Plane Endpoint Split**:
-   **Control-Plane Template Administration (`us-central1`)**: Administer (`create` / `update`) Model Armor templates via the **`us-central1` control-plane endpoint** (`projects/${PROJECT_ID}/locations/us-central1/templates/${MA_TEMPLATE_NAME}`), because regional template control planes outside `us-central1` may be unprovisioned.
-   **Inline `CONTENT_AUTHZ` Regional Data-Plane Callout (`modelarmor.${REGION}.rep.googleapis.com:443`)**: Bind an `AuthzPolicy` with **`policyProfile: CONTENT_AUTHZ`** and `action: CUSTOM` (using the gRPC-excluding `when` CEL rule from Section 6) to the `ma-content-authz-ext` `AuthzExtension` targeting the **regional data-plane endpoint `modelarmor.${REGION}.rep.googleapis.com:443`** (`failOpen: false`), and grant `roles/modelarmor.user`, `roles/modelarmor.calloutUser`, and `roles/serviceusage.serviceUsageConsumer` to `service-${PROJECT_NUMBER}@gcp-sa-dep.iam.gserviceaccount.com`:

```yaml
name: projects/${PROJECT_NUMBER}/locations/${REGION}/authzExtensions/ma-content-authz-ext
# Omit loadBalancingScheme when binding to an AgentGateway (bind via an AuthzPolicy with policyProfile: CONTENT_AUTHZ)
authority: "modelarmor.${REGION}.rep.googleapis.com"
service: "modelarmor.${REGION}.rep.googleapis.com:443"
timeout: 1s
failOpen: false
metadata:
  model_armor_settings: >-
    [{"request_template_id":"projects/${PROJECT_ID}/locations/${MA_TEMPLATE_REGION:-us-central1}/templates/${MA_TEMPLATE_NAME}",
      "response_template_id":"projects/${PROJECT_ID}/locations/${MA_TEMPLATE_REGION:-us-central1}/templates/${MA_TEMPLATE_NAME}"}]
```

--------------------------------------------------------------------------------

## 8. Credential Isolation and Token Injection (Auth Manager)

Orchestrate over-the-wire token injection via Agent Identity Auth Manager (`AuthProvider` for `3LO` user OAuth consent and `2LO` vaulted API keys/client credentials) and `ext_proc` + STS token exchange (`references/agent_runtime_and_identity.md` Section 6.2; `references/ingress_patterns_and_rewrites.md` Section 7.2).

--------------------------------------------------------------------------------

## 9. Advanced Model Armor Enterprise Governance Patterns

### 9.1 Fail-Closed on Skipped Detection (`Floor Settings`, `ignorePartialInvocationFailures = false` and `CONTENT_AUTHZ` Callout)

By default, if an individual Model Armor detector is skipped (`UnsupportedContentContext`, oversized binary payload, detector timeout, or quota exhaustion), the request may fail open. Regulated enterprise deployments require strict **Fail-Closed** enforcement across three layers:

-   **1. Global/Project Floor Settings and `us-central1` Template (`ignorePartialInvocationFailures = false`)**: Configure Model Armor Floor Settings (`projects/${PROJECT_ID}/locations/global/floorSetting`) with `enableFloorSettingEnforcement = true`, `integratedServices = ["AI_PLATFORM"]`, `aiPlatformFloorSetting.inspectAndBlock = true`, and `aiPlatformFloorSetting.enableCloudLogging = true`, paired with a Template administered in **`us-central1`** specifying `ignorePartialInvocationFailures = false` (the default when omitting `--template-metadata-ignore-partial-invocation-failures` on `templates create`, or set explicitly via `--no-template-metadata-ignore-partial-invocation-failures` on `templates update`), `enforcementType = "INSPECT_AND_BLOCK"`, `piAndJailbreakFilterSettings` (`ENABLED`, `MEDIUM_AND_ABOVE`), `maliciousUriFilterSettings` (`ENABLED`), and `sdpSettings` (`ENABLED`).
-   **2. Inline Agent Gateway `CONTENT_AUTHZ` Regional Data-Plane Callout (`modelarmor.${REGION}.rep.googleapis.com:443`)**: Attach an `AuthzPolicy` with **`policyProfile: CONTENT_AUTHZ`** (`action: CUSTOM`) bound to an `AuthzExtension` (`failOpen: false`, Section 7) that invokes the **regional `modelarmor.${REGION}.rep.googleapis.com:443` data-plane endpoint** while referencing the template administered in `us-central1`.
-   **3. Application PEP Layer (`EXECUTION_SKIPPED` Rejection)**: Halt generation whenever `invocationResult` is `PARTIAL` or `FAILURE`, or any detector reports `executionState == "EXECUTION_SKIPPED"`.

```bash
# 1. Create strict fail-closed Model Armor template in ${MA_TEMPLATE_REGION:-us-central1}
# (Omit --template-metadata-ignore-partial-invocation-failures on create so ignorePartialInvocationFailures defaults to false; use --no-template-metadata-ignore-partial-invocation-failures on templates update)
gcloud model-armor templates create "${MA_TEMPLATE_NAME}" \
  --project="${PROJECT_ID}" --location="${MA_TEMPLATE_REGION:-us-central1}" \
  --pi-and-jailbreak-filter-settings-enforcement=enabled \
  --pi-and-jailbreak-filter-settings-confidence-level=medium-and-above \
  --malicious-uri-filter-settings-enforcement=enabled \
  --rai-settings-filters="filterType=DANGEROUS,confidenceLevel=MEDIUM_AND_ABOVE" \
  --basic-config-filter-enforcement=enabled \
  --template-metadata-log-operations \
  --template-metadata-log-sanitize-operations

# 2. Enforce GA v1 Floor Settings
curl -s -X PATCH \
  "https://modelarmor.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/floorSetting?updateMask=enableFloorSettingEnforcement,integratedServices,aiPlatformFloorSetting.inspectAndBlock,aiPlatformFloorSetting.enableCloudLogging,filterConfig" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{"enableFloorSettingEnforcement":true,"integratedServices":["AI_PLATFORM"],"aiPlatformFloorSetting":{"inspectAndBlock":true,"enableCloudLogging":true},"filterConfig":{"piAndJailbreakFilterSettings":{"filterEnforcement":"ENABLED","confidenceLevel":"MEDIUM_AND_ABOVE"}}}'
```

### 9.2 Asymmetric Prompt vs. Response Policies and Per-User-Group / Per-Agent Overrides

-   **Asymmetric Input vs. Output Templates**: Configure `policyProfile:
    CONTENT_AUTHZ` and pass distinct `request_template_id` and
    `response_template_id` inside `AuthzExtension.metadata.model_armor_settings`
    (such as `DEIDENTIFY` / mask on input vs `BLOCK` on output).
-   **Per-User-Group and Per-Agent Dynamic Template Routing**: Bind
    workload-specific `AuthzPolicy` rules matching
    `agent.googleapis.com/agent_id` or `request.auth.claims['groups']` to route
    privileged agents vs. general workforce agents to dedicated Model Armor
    templates.

### 9.3 Multi-Protocol, MCP and Streamed Response (SSE) Payload Sanitization

-   **Streamed Server-Sent Events (SSE) Chunk Windowing**: Buffer
    `:streamGenerateContent` SSE chunks into sliding semantic windows (such as a
    64-token overlap) in the ADK `after_model_callback` or Envoy `ext_proc`
    (`STREAMED` body mode) and flush when `end_of_stream == true` so split
    PII/PHI spans across chunk boundaries are caught.
-   **Custom Multi-Protocol and Binary MCP Traffic**: Invoke the Model Armor REST
    API (`sanitizeUserPrompt` / `sanitizeModelResponse`) directly from the ADK
    runtime callbacks (`before_model_callback`, `after_model_callback`,
    `before_tool_callback`) rather than applying proxy-level JSON SHIM parsing
    to custom MCP wire shapes.
-   **Intermediate Thinking Token Exclusion (`part.thought == true`)**: Filter
    out internal reasoning parts (`part.thought == true`) before calling Model
    Armor sanitization to avoid false-positive blocks and TTFT latency spikes.

### 9.4 Base64, Hex, Obfuscated and Multilingual Prompt Injection Defense

To prevent Base64, URL-encoded, `0x`-hex, or Unicode homoglyph payloads from
evading single-pass scanners, enforce a **3-step pre-sanitization normalization
pipeline** in `before_model_callback` prior to `sanitizeUserPrompt`:

1.  **Unicode NFKC and URL-Decode**: Apply `unicodedata.normalize("NFKC",
    urllib.parse.unquote(prompt))` with a `32,768`-character cap.
2.  **Bounded Recursive Base64 and `0x`-Hex Unpacking (`max_depth = 3`)**: Extract
    Base64 and `0x`/`\x`-hex spans, decode UTF-8 text, and append
    `[DECODED_SPAN: ...]` to the inspection buffer.
3.  **Fail-Closed Binary and Skipped-Detector Rejection**: Reject any payload
    decoding to non-UTF-8 binary bytes or control characters, then invoke
    `SanitizeUserPromptRequest` and fail closed on `MATCH_FOUND`, `PARTIAL`,
    `FAILURE`, or `EXECUTION_SKIPPED`:

```python
import unicodedata, urllib.parse
from google.cloud import modelarmor_v1

def sanitize_prompt_fail_closed(client: modelarmor_v1.ModelArmorClient, template_name: str, raw_prompt: str) -> None:
  normalized = unicodedata.normalize("NFKC", urllib.parse.unquote(raw_prompt[:32768]))
  resp = client.sanitize_user_prompt(
      request=modelarmor_v1.SanitizeUserPromptRequest(
          name=template_name, user_prompt_data=modelarmor_v1.DataItem(text=normalized)
      )
  )
  sr = resp.sanitization_result
  if sr.filter_match_state == modelarmor_v1.FilterMatchState.MATCH_FOUND or sr.invocation_result in (
      modelarmor_v1.InvocationResult.PARTIAL,
      modelarmor_v1.InvocationResult.FAILURE,
  ):
    raise PermissionError("Blocked by Model Armor fail-closed policy")
```
ingress_patterns_and_rewrites.md 25.5 KB
# Ingress Architecture: Self-Managed Gateways, Rewrites, and Mesh

This reference details production patterns for ingress into
Gemini platform workloads, including Two-Tier and Single-Tier Self-Managed
Ingress Gateways, URL Map host/path rewrites, API management integration, and
Agent2Agent protocol (A2A protocol) mesh networking.

--------------------------------------------------------------------------------

## Table of Contents

-   [1. Self-Managed Ingress Gateway Architecture](#1-self-managed-ingress-gateway-architecture): Lines 22-88
-   [2. Ingress Traffic Flow and URL Map Rewriting](#2-ingress-traffic-flow-and-url-map-rewriting): Lines 89-201
-   [3. Routing Strategy: Hostname vs Path-Prefix](#3-routing-strategy-hostname-vs-path-prefix): Lines 202-220
-   [4. Policy Enforcement Matrix: IAP and Model Armor](#4-policy-enforcement-matrix-iap-and-model-armor): Lines 221-234
-   [5. Workload Ingress and Apigee API Management](#5-workload-ingress-and-apigee-api-management): Lines 235-259
-   [6. Private CA `TrustConfig` and Internal Regional ALB for Cloud Run MCP](#6-private-ca-trustconfig-and-internal-regional-alb-for-cloud-run-mcp): Lines 260-335
-   [7. Ingress ALB Service Extensions (`LbTrafficExtension` / Envoy `ext_proc`)](#7-ingress-alb-service-extensions-lbtrafficextension-envoy-ext_proc): Lines 336-451

--------------------------------------------------------------------------------

## 1. Self-Managed Ingress Gateway Architecture

Exposing internal Agent Runtime (`reasoningEngines`) workloads directly to
external clients without an ingress gateway creates inconsistent access control,
unmonitored endpoints, and prevents custom corporate domain branding.

A Self-Managed Ingress Gateway provides:

-   Custom enterprise hostnames (`https://agent-a.example.com`) and edge TLS
    termination.
-   Fine-grained Identity-Aware access control (IAP) and Context-Aware Access
    (CAA) policies.
-   Inline AI payload security (Model Armor prompt inspection and response
    sanitization).
-   Protocol, host, and path rewriting for Agent Runtime (`reasoningEngines`)
    streaming and synchronous queries.

### Two-Tier vs. Single-Tier Gateway Architecture

```mermaid
graph TB
    subgraph Client Space
        Client[Enterprise Users / Applications]
    end

    subgraph Tier 1: Public Front Door (Consumer Project)
        ExtALB[Global External Application Load Balancer<br/>• Single Anycast IP<br/>• Client TLS / SNI Termination<br/>• Edge Cloud Armor / Coarse IAP<br/>• Hostname Routing]
        PSC_NEG1[Regional PSC NEG<br/>global access mode]
        ExtALB --> PSC_NEG1
    end

    subgraph Tier 2: Per-Agent Ingress (Producer / Governance Project)
        SA[PSC Service Attachment]
        IntALB[Regional Internal Application Load Balancer<br/>• Per-Agent IAP & CAA Enforcement<br/>• URL Map Host & Path Rewrite<br/>• Model Armor Service Extensions ext_proc]
        PSC_NEG2[PSC NEG to Google APIs<br/>psc_target_service: REGION-aiplatform.googleapis.com]

        PSC_NEG1 -->|Private Service Connect| SA
        SA --> IntALB
        IntALB --> PSC_NEG2
    end

    subgraph Google Managed Tenant
        RE[Agent Runtime (reasoningEngines / ADK Agent)]
        PSC_NEG2 -->|Private VPC Egress| RE
    end

    Client -->|HTTPS agent-a.example.com| ExtALB
```

### Architectural Comparison Matrix (Single-Tier vs. Two-Tier Ingress)

-   **Single-Tier Ingress Gateway** (Single External ALB -> PSC NEG targeting
    regional AI Platform API directly): Gateway and all agents must reside in
    the same project and share a single IAP policy and URL map. Lowest cost and
    latency (~5–10 ms single hop), best for single-project deployments with
    unified policies.
-   **Two-Tier Ingress Gateway** (Recommended for Multi-Team — **Tier 1 Global
    External Application Load Balancer** with **Cloud Armor and IAP** fanning
    out over a Regional PSC NEG + PSC Service Attachment to **Tier 2 Regional
    Internal Application Load Balancers**): Tier 1 and Tier 2 run in separate
    projects; Tier 1 enforces global anycast TLS termination, **edge Cloud Armor
    WAF/DDoS protection, and coarse-grained IAP**, while producer teams own Tier
    2 Regional Internal ALBs, per-agent IAP policies, Model Armor templates, and
    URL Map host/path rewrites independently (~15–25 ms across two hops).

--------------------------------------------------------------------------------

## 2. Ingress Traffic Flow and URL Map Rewriting

### Step-by-Step Two-Tier Request Flow

1.  **Tier 1 Global External ALB (TLS, Cloud Armor and IAP)**: Client resolves
    `agent-a.example.com` to Tier 1's global anycast IP. The Tier 1 **Global
    External Application Load Balancer** terminates TLS using Server Name
    Indication (SNI) and enforces **edge Cloud Armor** security policies and
    **IAP** authentication.
2.  **Tier 1 Host Routing**: Tier 1 URL map matches `Host: agent-a.example.com`
    and routes to the dedicated backend service.
3.  **PSC Traversal (Regional PSC NEG -> Service Attachment)**: The Tier 1
    backend service forwards traffic through its Regional PSC NEG (`global`
    access mode) to the Tier 2 PSC Service Attachment.
4.  **Tier 2 Regional Internal ALB**: The Service Attachment forwards the
    request to the Tier 2 **Regional Internal Application Load Balancer**
    forwarding rule in the producer/governance project.
5.  **Tier 2 Per-Agent IAP and Model Armor**: Evaluates per-agent IAP/Context-Aware
    Access (device posture, IP location) and invokes Model Armor Service
    Extensions (`ext_proc`).
6.  **Tier 2 URL Map Rewriting**: Updates headers and paths required by Agent
    Runtime:
    -   `Host` rewritten to `${REGION}-aiplatform.googleapis.com`
    -   Path prefix `/chat` rewritten to
        `/v1/projects/{AGENT_PROJECT_NUMBER}/locations/{REGION}/reasoningEngines/{RE_ID}:streamQuery`
7.  **Model Armor Inspection (Service Extensions)**: Envoy `ext_proc` sends the
    prompt payload to Model Armor. Prompt injections or jailbreaks trigger
    immediate `HTTP 403` rejection.
8.  **PSC to Google APIs**: The rewritten request routes across Tier 2's Google
    APIs PSC NEG to the regional Agent Runtime (`aiplatform.googleapis.com`)
    backend.
9.  **Execution and Egress Sanitization**: The Agent Runtime executes and streams
    responses. The return payload is sanitized by Model Armor (PII masking)
    before returning to the client.

### Tier 2 URL Map (`tier2-urlmap.yaml`) and Provisioning Commands

```yaml
# tier2-urlmap.yaml (use numeric ${AGENT_PROJECT_NUMBER} in pathPrefixRewrite)
name: tier2-re-urlmap
defaultService: projects/${PRODUCER_PROJECT_ID}/regions/${REGION}/backendServices/tier2-re-backend
hostRules:
  - hosts:
      - "agent-a.example.com"
    pathMatcher: agent-matcher
pathMatchers:
  - name: agent-matcher
    defaultService: projects/${PRODUCER_PROJECT_ID}/regions/${REGION}/backendServices/tier2-re-backend
    pathRules:
      - paths:
          - /chat
          - /stream
        service: projects/${PRODUCER_PROJECT_ID}/regions/${REGION}/backendServices/tier2-re-backend
        routeAction:
          urlRewrite:
            hostRewrite: "${REGION}-aiplatform.googleapis.com"
            pathPrefixRewrite: "/v1/projects/${AGENT_PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${RE_ID}:streamQuery"
      - paths:
          - /query
        service: projects/${PRODUCER_PROJECT_ID}/regions/${REGION}/backendServices/tier2-re-backend
        routeAction:
          urlRewrite:
            hostRewrite: "${REGION}-aiplatform.googleapis.com"
            pathPrefixRewrite: "/v1/projects/${AGENT_PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${RE_ID}:query"
```

```bash
# Tier 2 Producer Project (${PRODUCER_PROJECT_ID}): Proxy-Only Subnet, Google APIs PSC NEG, Internal ALB & PSC Service Attachment
gcloud compute networks subnets create "tier2-proxy-only-subnet" --project="${PRODUCER_PROJECT_ID}" \
  --network="${PRODUCER_VPC}" --region="${REGION}" --range="10.129.0.0/23" --purpose="REGIONAL_MANAGED_PROXY" --role="ACTIVE"
gcloud compute networks subnets create "tier2-psc-nat-subnet" --project="${PRODUCER_PROJECT_ID}" \
  --network="${PRODUCER_VPC}" --region="${REGION}" --range="10.129.2.0/24" --purpose="PRIVATE_SERVICE_CONNECT"
gcloud compute network-endpoint-groups create "psc-aiplatform-neg" --project="${PRODUCER_PROJECT_ID}" \
  --region="${REGION}" --network-endpoint-type="private-service-connect" --psc-target-service="${REGION}-aiplatform.googleapis.com"
# Note: Add --iap=enabled ONLY if authenticating via Google IAP; omit --iap=enabled when Tier 1 ext_proc injects an STS OAuth access token for Agent Runtime
gcloud compute backend-services create "tier2-re-backend" --project="${PRODUCER_PROJECT_ID}" \
  --region="${REGION}" --load-balancing-scheme="INTERNAL_MANAGED" --protocol="HTTPS"
gcloud compute backend-services add-backend "tier2-re-backend" --project="${PRODUCER_PROJECT_ID}" \
  --region="${REGION}" --network-endpoint-group="psc-aiplatform-neg" --network-endpoint-group-region="${REGION}"
gcloud compute url-maps import "tier2-re-urlmap" --project="${PRODUCER_PROJECT_ID}" --region="${REGION}" --source="tier2-urlmap.yaml" --quiet
gcloud compute target-https-proxies create "tier2-re-https-proxy" --project="${PRODUCER_PROJECT_ID}" \
  --region="${REGION}" --url-map="tier2-re-urlmap" --certificate-manager-certificates="${TIER2_CERT_NAME}"
gcloud compute forwarding-rules create "tier2-re-fwd-rule" --project="${PRODUCER_PROJECT_ID}" \
  --region="${REGION}" --load-balancing-scheme="INTERNAL_MANAGED" --network="${PRODUCER_VPC}" \
  --subnet="${PRODUCER_SUBNET}" --target-https-proxy="tier2-re-https-proxy" --target-https-proxy-region="${REGION}" --ports=443
gcloud compute service-attachments create "tier2-re-service-attachment" --project="${PRODUCER_PROJECT_ID}" \
  --region="${REGION}" --producer-forwarding-rule="tier2-re-fwd-rule" --connection-preference="ACCEPT_AUTOMATIC" --nat-subnets="tier2-psc-nat-subnet"

# Tier 1 Consumer Front-Door Project (${FRONTDOOR_PROJECT_ID}): Global External ALB (with Edge Cloud Armor & IAP) -> PSC NEG -> Tier 2 Service Attachment
gcloud compute network-endpoint-groups create "tier1-to-tier2-psc-neg" --project="${FRONTDOOR_PROJECT_ID}" \
  --region="${REGION}" --network-endpoint-type="private-service-connect" \
  --psc-target-service="projects/${PRODUCER_PROJECT_ID}/regions/${REGION}/serviceAttachments/tier2-re-service-attachment" \
  --network="${FRONTDOOR_VPC}" --subnet="${FRONTDOOR_SUBNET}"
gcloud compute backend-services create "tier1-ext-backend" --project="${FRONTDOOR_PROJECT_ID}" \
  --global --load-balancing-scheme="EXTERNAL_MANAGED" --protocol="HTTPS" \
  --security-policy="${CLOUD_ARMOR_POLICY}" \
  --iap=enabled,oauth2-client-id="${IAP_CLIENT_ID}",oauth2-client-secret="${IAP_CLIENT_SECRET}"
gcloud compute backend-services add-backend "tier1-ext-backend" --project="${FRONTDOOR_PROJECT_ID}" \
  --global --network-endpoint-group="tier1-to-tier2-psc-neg" --network-endpoint-group-region="${REGION}"
gcloud compute url-maps create "tier1-ext-urlmap" --project="${FRONTDOOR_PROJECT_ID}" --default-service="tier1-ext-backend"
gcloud compute target-https-proxies create "tier1-ext-https-proxy" --project="${FRONTDOOR_PROJECT_ID}" \
  --url-map="tier1-ext-urlmap" --ssl-certificates="${TIER1_SSL_CERT}"
gcloud compute forwarding-rules create "tier1-ext-fwd-rule" --project="${FRONTDOOR_PROJECT_ID}" \
  --global --load-balancing-scheme="EXTERNAL_MANAGED" --target-https-proxy="tier1-ext-https-proxy" --ports=443

# Grant Edge & Backend IAM (Workforce Pool / Service Account roles/aiplatform.user; add roles/iap.httpsResourceAccessor if using IAP)
gcloud projects add-iam-policy-binding "${PRODUCER_PROJECT_ID}" \
  --member="principalSet://iam.googleapis.com/locations/global/workforcePools/${WORKFORCE_POOL_ID}/*" --role="roles/aiplatform.user"
gcloud projects add-iam-policy-binding "${PRODUCER_PROJECT_ID}" --member="${EXT_PROC_IDENTITY}" --role="roles/aiplatform.user"
```

--------------------------------------------------------------------------------

## 3. Routing Strategy: Hostname vs Path-Prefix

1.  **Hostname Routing (Recommended)**:
    -   Each agent has a unique FQDN: `finance-agent.example.com`,
        `hr-agent.example.com`.
    -   **Advantages**: Complete domain isolation, clean mapping to DNS and TLS
        SAN certificates, straightforward per-agent IAP binding.
2.  **Path-Prefix Routing**:
    -   Single domain `agents.example.com` with routes `/finance/*` and `/hr/*`.
    -   **Operational Footgun**: Tier 1 must strip the path prefix (such as
        rewriting `/finance/chat` to `/chat`) **and** either rewrite the `Host`
        header to the Tier 2 per-agent hostname (`agent-a.example.com`) or
        include `"agents.example.com"` in Tier 2's `host_rule.hosts`; otherwise,
        Tier 2 misses the `agent-matcher` host rule or receives nested paths
        that conflict with the destination Agent Runtime `:streamQuery` path
        rewrite.

--------------------------------------------------------------------------------

## 4. Policy Enforcement Matrix: IAP and Model Armor

-   **Transport Security (`TLS 1.3 / mTLS` at Tier 1 and Tier 2)**: Terminates
    public HTTPS at the edge and enforces private mTLS across PSC.
-   **Identity and Access (`Identity-Aware Proxy (IAP)` at Tier 1 or Tier 2)**:
    Validates workforce principal, Context-Aware Access (CAA) device context,
    and IAM `roles/iap.httpsResourceAccessor`. Deploying at Tier 2 allows
    independent per-agent policies.
-   **AI Payload Inspection (`Model Armor via Service Extensions` at Tier 2
    Internal ALB)**: Real-time `ext_proc` gRPC callout inspecting prompts for
    jailbreaks/injections and sanitizing responses for PII/DLP leaks.

--------------------------------------------------------------------------------

## 5. Workload Ingress and Apigee API Management

### Workload Ingress (mTLS and SPIFFE Trust Federation)

For machine-to-agent ingress across clouds, terminate transport-level mTLS at
the Ingress ALB using Certificate Manager with Private CA trust configs, and map
external machine OIDC tokens or SPIFFE X.509 SVIDs into Google Cloud principals
using **Workload Identity Federation** (`WorkloadIdentityPool`), while using
**Workforce Identity Federation** (`WorkforcePool`) for human workforce users
(`EntraID`, `Okta`, `Ping`).

### Apigee X API Management Inline Integration (Northbound and Southbound Private)

1.  **Northbound Ingress Governance**: Place Apigee X in front of the Ingress
    Gateway to validate external consumer JWTs, enforce spike arrest/quotas, and
    route over Southbound PSC into the Tier 2 Regional Internal ALB.
2.  **Southbound Tool and MCP Mediation (`Agent Gateway -> Apigee X Private ->
    Cloud Run / Google MCP / Internal APIs`)**: Egress Agent Gateway enforces
    UAP CEL and Model Armor first, then routes over the PSC-I network attachment
    into an **Apigee X Private Endpoint** (`PSC Endpoint Attachment` inside the
    Governance or Tool Spoke VPC) for protocol mediation, API key / 3LO token
    injection, and rate limiting.

--------------------------------------------------------------------------------

## 6. Private CA `TrustConfig` and Internal Regional ALB for Cloud Run MCP

When an enterprise requires custom Private CA leaf certificates
(`*.internal.example.com`) rather than standard Google-managed certificates on
internal Cloud Run MCP servers:

1.  **Why a Regional Internal ALB Is Required**: Native Cloud Run (`*.run.app`)
    terminates TLS at the Cloud Run ingress edge using Google-managed
    certificates. To serve a custom Private CA certificate, front the Cloud Run
    service with an `INTERNAL_MANAGED` Regional Internal Application Load
    Balancer backed by a `SERVERLESS` Network Endpoint Group and a Private Cloud
    DNS zone peered via the ACT's `dnsPeeringConfig` (using a Certificate
    Manager self-managed certificate or Private CA certificate issuance config).
2.  **Preserving Public Root Trust (`PUBLICLY_TRUSTED_ROOTS`)**: When attaching
    a Certificate Manager `TrustConfig` to an Agent Connectivity Template's
    `tlsConfig`, always set `additionalRoots = "PUBLICLY_TRUSTED_ROOTS"`.
    Setting `NO_ADDITIONAL_ROOTS` in `ALL_TRAFFIC` mode strips the WebPKI root
    bundle and breaks outbound TLS handshakes to Google APIs
    (`aiplatform.googleapis.com`).
3.  **Handling Empty `:authority` on Serverless NEGs (`defaultService`, Wildcard `"*"` Host Rule and Mandatory IAP/mTLS)**:
    When an `INTERNAL_MANAGED` Regional Internal ALB fronts a Cloud Run
    Serverless NEG, configure the URL Map `defaultService` and include the
    wildcard `"*"` alongside `"{mcp_internal_fqdn}"` in `hostRules[].hosts`
    (`--hosts="${MCP_INTERNAL_FQDN},*"`, since Compute Engine `HostRule` schema
    regex only accepts RFC-1034 hostnames or `"*"`). Because `defaultService`
    and `"*"` match requests with empty `:authority` / `Host` headers, **always
    enforce transport and IAM authentication (`--iap=enabled` with
    `roles/iap.egressor` and/or `ServerTlsPolicy` mTLS)** on the Internal ALB so
    omitting `Host` never bypasses access control:

```bash
export PROJECT_ID="gov-hub-proj" MCP_PROJECT_ID="mcp-spoke-proj" REGION="us-central1"
export TRUST_CONFIG_ID="enterprise-private-ca-trust" MCP_SERVICE_NAME="mcp-server-prod"
export MCP_VPC="mcp-spoke-vpc" MCP_SUBNET="mcp-ilb-subnet" MCP_ILB_IP="10.20.10.10"
export MCP_INTERNAL_FQDN="mcp.internal.example.com" MCP_INTERNAL_CERT="mcp-internal-private-cert"

# 1. Import Certificate Manager TrustConfig in ${REGION} (reference in ACT tlsConfig with additionalRoots: PUBLICLY_TRUSTED_ROOTS so WebPKI roots for aiplatform.googleapis.com are preserved)
cat <<EOF > trust-config.yaml
trustStores:
  - trustAnchors:
      - pemCertificate: |
          -----BEGIN CERTIFICATE-----
          ...Enterprise Private Root CA PEM...
          -----END CERTIFICATE-----
EOF
gcloud certificate-manager trust-configs import "${TRUST_CONFIG_ID}" \
  --project="${PROJECT_ID}" --location="${REGION}" --source="trust-config.yaml"

# 2. Because native Cloud Run (*.run.app) uses Google-managed certificates, front Cloud Run with a Serverless NEG and Regional INTERNAL_MANAGED ALB (with IAP enabled; --protocol="HTTP" is required by GCE for Serverless NEGs)
gcloud compute network-endpoint-groups create "mcp-serverless-neg" \
  --project="${MCP_PROJECT_ID}" --region="${REGION}" \
  --network-endpoint-type="serverless" --cloud-run-service="${MCP_SERVICE_NAME}"
gcloud compute backend-services create "mcp-internal-backend" \
  --project="${MCP_PROJECT_ID}" --region="${REGION}" \
  --load-balancing-scheme="INTERNAL_MANAGED" --protocol="HTTP" \
  --iap=enabled,oauth2-client-id="${IAP_CLIENT_ID}",oauth2-client-secret="${IAP_CLIENT_SECRET}"
gcloud compute backend-services add-backend "mcp-internal-backend" \
  --project="${MCP_PROJECT_ID}" --region="${REGION}" \
  --network-endpoint-group="mcp-serverless-neg" --network-endpoint-group-region="${REGION}"
# Configure defaultService + wildcard "*" hostRule alongside ${MCP_INTERNAL_FQDN} (requires IAP and/or ServerTlsPolicy mTLS)
gcloud compute url-maps create "mcp-internal-urlmap" \
  --project="${MCP_PROJECT_ID}" --region="${REGION}" --default-service="mcp-internal-backend"
gcloud compute url-maps add-path-matcher "mcp-internal-urlmap" \
  --project="${MCP_PROJECT_ID}" --region="${REGION}" --path-matcher-name="mcp-matcher" \
  --default-service="mcp-internal-backend" --new-hosts="${MCP_INTERNAL_FQDN},*"
gcloud compute target-https-proxies create "mcp-internal-https-proxy" \
  --project="${MCP_PROJECT_ID}" --region="${REGION}" --url-map="mcp-internal-urlmap" \
  --certificate-manager-certificates="${MCP_INTERNAL_CERT}"
gcloud compute forwarding-rules create "mcp-internal-fwd-rule" \
  --project="${MCP_PROJECT_ID}" --region="${REGION}" --load-balancing-scheme="INTERNAL_MANAGED" \
  --network="${MCP_VPC}" --subnet="${MCP_SUBNET}" --address="${MCP_ILB_IP}" \
  --target-https-proxy="mcp-internal-https-proxy" --target-https-proxy-region="${REGION}" --ports=443
```

--------------------------------------------------------------------------------

## 7. Ingress ALB Service Extensions (`LbTrafficExtension` / Envoy `ext_proc`)

When an Application Load Balancer (ALB) requires custom header mutation,
external token exchange (`sts.googleapis.com/v1/token`), or custom request
authentication before forwarding to a Google Cloud backend
(`aiplatform.googleapis.com` or Cloud Run), attach a **Service Extensions
`LbTrafficExtension`** (`ext_proc` gRPC callout).

### 7.1 GA `LbTrafficExtension` YAML Schema and `gcloud service-extensions lb-traffic-extensions import`

> [!IMPORTANT] **Location Scope and HTTP/2 Callout Backend**: `gcloud
> service-extensions lb-traffic-extensions` uses `import <name>
> --location=<location> --source=<file.yaml>`. For a **Global External
> Application Load Balancer** (`EXTERNAL_MANAGED` with global forwarding rules),
> use `--location="global"` and reference `global/forwardingRules/...` and
> `global/backendServices/...` (configured with `--protocol=HTTP2`); for a
> **Regional Internal Application Load Balancer** (`INTERNAL_MANAGED`), use
> `--location="${REGION}"` and `regions/${REGION}/...`.

```yaml
# lb-traffic-extension.yaml (Global External ALB: --location=global; use regions/${REGION}/... for Regional Internal ALB)
name: ext-proc-token-exchange
loadBalancingScheme: EXTERNAL_MANAGED
forwardingRules:
  - https://www.googleapis.com/compute/v1/projects/${PROJECT_ID}/global/forwardingRules/${FORWARDING_RULE_NAME}
extensionChains:
  - name: token-exchange-chain
    matchCondition:
      celExpression: 'true'
    extensions:
      - name: ext-proc-auth-swap
        authority: ext-proc.internal.example.com
        service: https://www.googleapis.com/compute/v1/projects/${PROJECT_ID}/global/backendServices/${EXT_PROC_BACKEND_SERVICE}
        supportedEvents:
          - REQUEST_HEADERS
        timeout: 1.0s
        failOpen: false
```

```bash
gcloud compute backend-services create "${EXT_PROC_BACKEND_SERVICE}" --project="${PROJECT_ID}" \
  --global --load-balancing-scheme="EXTERNAL_MANAGED" --protocol="HTTP2" --health-checks="${EXT_PROC_HC}"
gcloud service-extensions lb-traffic-extensions import ext-proc-token-exchange \
  --location="global" \
  --source="lb-traffic-extension.yaml" \
  --project="${PROJECT_ID}"
```

### 7.2 Envoy `ext_proc` Credential Caching, STS Federation and Fail-Closed Header Mutation

When implementing a Python `ExternalProcessorServicer`:

1.  **Fail Closed on Missing or Malformed Bearer Tokens**: Return an immediate
    `HTTP 401` `ImmediateResponse` (`StatusCode.Unauthorized`) whenever
    `Authorization: Bearer <token>` is absent or empty.
2.  **Thread-Safe Credential Caching and Connection Pooling**: Reuse a persistent
    `httpx.Client(timeout=0.4)` and cache federated STS tokens from
    `https://sts.googleapis.com/v1/token` (`expiry - 60s`, keyed by SHA-256
    token digest) so callouts stay well within Envoy's `timeout: 1.0s`. For OIDC
    Workforce Identity Federation (`Okta`, `EntraID`, `Ping`), pass
    `"subject_token_type": "urn:ietf:params:oauth:token-type:id_token"` (or
    `"urn:ietf:params:oauth:token-type:jwt"` for generic workload JWTs).
3.  **Preserving Upstream Caller Context**: Replace `Authorization` with the
    Google Cloud STS access token for edge IAM (`roles/aiplatform.user` or
    `roles/run.invoker`) and copy the caller's original token into
    `X-Forwarded-User-Authorization` using `HeaderValue(key=..., raw_value=...)`
    with `OVERWRITE_IF_EXISTS_OR_ADD`. Pair this inbound exchange with **Agent
    Identity Auth Manager (`AuthProvider`)** for outbound `2LO`/`3LO` tool calls
    (`references/agent_runtime_and_identity.md` Section 6.2):

```python
import hashlib, json, threading, time, urllib.parse, httpx
from envoy.config.core.v3 import base_pb2
from envoy.service.ext_proc.v3 import external_processor_pb2 as ep_pb2

_STS_CLIENT = httpx.Client(timeout=0.4)
_STS_LOCK = threading.Lock()
_STS_CACHE: dict[str, tuple[str, float]] = {}

def exchange_workforce_token_via_sts(idp_jwt: str, workforce_pool_provider: str, user_project: str = "") -> str:
  digest = hashlib.sha256(f"{workforce_pool_provider}:{idp_jwt}".encode("utf-8")).hexdigest()
  now = time.time()
  if (cached := _STS_CACHE.get(digest)) and now < cached[1] - 60:
    return cached[0]
  provider_path = workforce_pool_provider.strip().removeprefix("//iam.googleapis.com/").lstrip("/")
  payload = {
      "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
      "audience": f"//iam.googleapis.com/{provider_path}",
      "scope": "https://www.googleapis.com/auth/cloud-platform",
      "requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
      "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
      "subject_token": idp_jwt,
  }
  if user_project:
    payload["options"] = json.dumps({"userProject": user_project})
  resp = _STS_CLIENT.post("https://sts.googleapis.com/v1/token", content=urllib.parse.urlencode(payload), headers={"Content-Type": "application/x-www-form-urlencoded"})
  resp.raise_for_status()
  body = resp.json()
  with _STS_LOCK:
    _STS_CACHE[digest] = (str(body["access_token"]), now + float(body.get("expires_in", 3600)))
  return str(body["access_token"])

def build_ext_proc_header_mutation(original_auth: str, gcp_token: str) -> ep_pb2.HeaderMutation:
  return ep_pb2.HeaderMutation(
      set_headers=[
          base_pb2.HeaderValueOption(
              header=base_pb2.HeaderValue(key="X-Forwarded-User-Authorization", raw_value=original_auth.encode("utf-8")),
              append_action=base_pb2.HeaderValueOption.OVERWRITE_IF_EXISTS_OR_ADD,
          ),
          base_pb2.HeaderValueOption(
              header=base_pb2.HeaderValue(key="Authorization", raw_value=f"Bearer {gcp_token}".encode("utf-8")),
              append_action=base_pb2.HeaderValueOption.OVERWRITE_IF_EXISTS_OR_ADD,
          ),
      ]
  )
```
registry_and_federation.md 19.6 KB
# Agent Registry Architecture, MCP Services, and Multi-Project Federation

This reference details the design, TLS SNI inspection mechanics, consolidated
`googleapis` service patterns, manual cross-project MCP and Agent2Agent (A2A)
registration workflows, service catalog schemas, and automated federation engines
for **Agent Registry**.

--------------------------------------------------------------------------------

## Table of Contents

-   [1. Registry Architecture, TLS SNI Inspection, and Centralized Catalog Model](#1-registry-architecture-tls-sni-inspection-and-centralized-catalog-model): Lines 21-71
-   [2. Manual Cross-Project Registration Runbook](#2-manual-cross-project-registration-runbook): Lines 72-167
-   [3. Scoping, Identity Decision Matrix, and Critical CEL Guards](#3-scoping-identity-decision-matrix-and-critical-cel-guards): Lines 168-198
-   [4. The Consolidated `googleapis` Service Invariant](#4-the-consolidated-googleapis-service-invariant): Lines 199-293
-   [5. Automated Multi-Project Registry Federation](#5-automated-multi-project-registry-federation): Lines 294-329
-   [6. Agent Registry Taxonomy Metadata, Resource Labels and CI/CD Catalog Automation](#6-agent-registry-taxonomy-metadata-resource-labels-and-cicd-catalog-automation): Lines 330-342

--------------------------------------------------------------------------------

## 1. Registry Architecture, TLS SNI Inspection, and Centralized Catalog Model

The Agent Registry acts as the Service Directory and L7 routing table for the
Agent Gateway. When an Agent Connectivity Template operates in `ALL_TRAFFIC`
mode, outbound TCP connections from the Agent Runtime resolve to synthetic
Private Service Connect VIP `240.0.0.2:443`. The Gateway inspects the TLS Server
Name Indication (SNI) header:

-   Under IAM Policy V1 (when `iapPolicyVersion = "V2"` is not set), if the SNI
    does not match an authorized entry in Agent Registry, the connection is
    dropped immediately with `default_denied` (`[SSL:
    UNEXPECTED_EOF_WHILE_READING]`).
-   When UAP Policy V2 (`iapPolicyVersion = "V2"`) is enabled on the
    `AuthzExtension`, unregistered SNIs evaluate against UAP rules matching
    `destination.is_registered == false` (`destination.unregistered.host`)
    before being allowed or dropped.

```text
+-----------------------------------------------------------------------------------------+
| Agent Runtime -> Connects to synthetic VIP: 240.0.0.2:443                               |
+--------------------------------------------+--------------------------------------------+
                                             | (TLS SNI Inspection)
                                             v
+-----------------------------------------------------------------------------------------+
| Agent Gateway (Managed Envoy)                                                           |
|   • SNI Match: Evaluate UAP / IAP Egressor Policy (destination.is_registered == true)   |
|   • No Match (Policy V1): Reject with default_denied (UNEXPECTED_EOF_WHILE_READING)     |
|   • No Match (UAP V2): Evaluate destination.is_registered == false rules                |
+--------------------------------------------+--------------------------------------------+
                                             |
                        +--------------------+--------------------+
                        v                                         v
+-----------------------------------------------+ +---------------------------------------+
| Consolidated googleapis Service (Core FQDNs)  | | External REST & MCP Services (/mcp)   |
+-----------------------------------------------+ +---------------------------------------+
```

In enterprise governance architectures, the Agent Registry resides in the
**Centralized Governance Project (`AGW_PROJECT_ID`)** alongside the Agent
Gateway:

-   **Catalog Registration (Governance Plane)**: Service definitions, interface
    URLs, and OpenAPI/MCP tool specs are published into the central Agent
    Registry (`agentregistry.googleapis.com`).
-   **Access Authorization (Data Plane)**: Egress authorization is governed in
    the central project via UAP Policy V2 or `roles/iap.egressor`, while runtime
    invocation permissions (`roles/run.invoker`) are granted on backend compute
    resources (Cloud Run, GKE) in the producer project.

--------------------------------------------------------------------------------

## 2. Manual Cross-Project Registration Runbook

In Agent Registry, `mcp-servers`, `endpoints`, and `agents` are read-only
projections. All write operations target GA `gcloud agent-registry services`
(use GA `gcloud agent-registry` commands across all runbooks). In GA `gcloud iap
web add-iam-policy-binding`, resource type flags use singular names
(`--mcp-server`, `--agent`, `--endpoint`), never plural flag names
(`--mcp-servers`, `--agents`, `--endpoints`).

### 2.1 Cross-Project MCP Server Registration

> [!IMPORTANT] **MCP Protocol Binding and URL Invariants**: 1. Protocol binding in
> `gcloud` CLI MUST be **`JSONRPC`** (`HTTP_JSON` is rejected for MCP
> servers). 2. The interface URL path MUST end with **`/mcp`** (such as
> `https://${MCP_HOST}/mcp`). 3. MCP tool specifications
> (`--mcp-server-spec-content`) must stay under the **10 KB payload limit**.

```bash
# Option A: Register MCP Server with Tool Spec (< 10 KB)
gcloud agent-registry services create "${MCP_SERVICE_NAME}" \
  --project="${AGW_PROJECT_ID}" --location="${REGION}" \
  --display-name="${MCP_SERVICE_DISPLAY_NAME}" \
  --mcp-server-spec-type=tool-spec --mcp-server-spec-content="$(cat toolspec.json)" \
  --interfaces="protocolBinding=JSONRPC,url=https://${MCP_HOST}/mcp" --quiet

# Option B: Register MCP Server without Tool Spec (Dynamic Discovery)
gcloud agent-registry services create "${MCP_SERVICE_NAME}" \
  --project="${AGW_PROJECT_ID}" --location="${REGION}" \
  --display-name="${MCP_SERVICE_DISPLAY_NAME}" \
  --mcp-server-spec-type=no-spec \
  --interfaces="protocolBinding=JSONRPC,url=https://${MCP_HOST}/mcp" --quiet
```

### 2.2 Cross-Project Agent2Agent Protocol (A2A Protocol) Registration

-   **Option A (`--agent-spec-type=a2a-agent-card`)**: Target URL
    (`https://${REGION}-aiplatform.googleapis.com/v1/projects/${TARGET_PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${TARGET_ENGINE_ID}:query`
    or custom A2A ingress URL) is declared inside `agentspec.json`
    (`--interfaces` must be omitted when `--agent-spec-type=a2a-agent-card` is
    set).
-   **Option B (`--agent-spec-type=no-spec`)**: Pass the custom A2A proxy
    endpoint URL via
    `--interfaces="protocolBinding=JSONRPC,url=https://a2a-agent.internal.example.com/a2a"`.

```bash
gcloud agent-registry services create "${TARGET_AGENT_NAME}" \
  --project="${AGW_PROJECT_ID}" --location="${REGION}" \
  --display-name="${TARGET_AGENT_DISPLAY_NAME}" \
  --agent-spec-type=a2a-agent-card --agent-spec-content="$(cat agentspec.json)"
```

### 2.3 External REST and SaaS API Registration

External public REST APIs accessed by agent tools under Policy V1 (or registered
endpoints under Policy V2) are registered with `protocolBinding=HTTP_JSON` and
`--endpoint-spec-type=no-spec`:

```bash
gcloud agent-registry services create "ip-lookup-service" \
  --project="${AGW_PROJECT_ID}" --location="${REGION}" \
  --display-name="IP Lookup Service" --endpoint-spec-type=no-spec \
  --interfaces="protocolBinding=HTTP_JSON,url=https://api.ipify.org" --quiet
```

### 2.4 Server-Generated Resource ID Extraction and IAP Authorization

Agent Registry generates unique internal resource UUIDs (the last segment of
`registryResource`, such as `agentregistry-00000000-...`). IAP policy bindings
require this server-generated UUID and `roles/iap.egressor` (never the friendly
service name or `roles/iap.tunnelResourceAccessor`):

```bash
# 1. Extract Server-Generated Resource ID (via gcloud agent-registry mcp-servers describe or gcloud agent-registry services describe)
REGISTRY_RESOURCE=$(gcloud agent-registry mcp-servers describe "${MCP_SERVICE_NAME}" \
  --project="${AGW_PROJECT_ID}" --location="${REGION}" --format='value(registryResource)')
RESOURCE_ID=$(basename "${REGISTRY_RESOURCE}")

# 2. Grant roles/iap.egressor separating discovery (empty toolName) from specific tools/call invocation
gcloud iap web add-iam-policy-binding \
  --project="${AGW_PROJECT_ID}" --region="${REGION}" \
  --resource-type=agent-registry --mcp-server="${RESOURCE_ID}" \
  --member="principal://agents.global.org-${ORG_ID}.system.id.goog/resources/aiplatform/projects/${AE_PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${ENGINE_ID}" \
  --role="roles/iap.egressor" \
  --condition="^:^expression=(api.getAttribute('iap.googleapis.com/mcp.method', '') in ['initialize', 'tools/list'] && api.getAttribute('iap.googleapis.com/mcp.toolName', '') == '') || (api.getAttribute('iap.googleapis.com/mcp.method', '') == 'tools/call' && api.getAttribute('iap.googleapis.com/mcp.toolName', '') == 'get_weather'):title=AllowDiscoveryAndTool" \
  --quiet

# 3. Grant roles/iap.egressor to Agent Runtime Service Account
gcloud iap web add-iam-policy-binding \
  --project="${AGW_PROJECT_ID}" --region="${REGION}" \
  --resource-type=agent-registry --mcp-server="${RESOURCE_ID}" \
  --member="serviceAccount:service-${AE_PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com" \
  --role="roles/iap.egressor" --quiet
```

--------------------------------------------------------------------------------

## 3. Scoping, Identity Decision Matrix, and Critical CEL Guards

-   **Google APIs Endpoint** (`Project` or `Org` scope, `principalSet://`,
    `roles/iap.egressor`): Unconditional allow for registered `googleapis`.
-   **Internal MCP Server — Read-Only** (`Per-Agent` scope,
    `principal://.../reasoningEngines/ID`, `roles/iap.egressor`):
    -   IAP V1: `api.getAttribute('iap.googleapis.com/mcp.tool.isReadOnly',
        false) == true || api.getAttribute('iap.googleapis.com/mcp.toolName',
        '') == ''`
    -   UAP V2: `(destination.agent_registry.mcp_server.method == 'tools') &&
        (destination.agent_registry.mcp_server.tool.name == '' ||
        destination.agent_registry.mcp_server.tool.annotations.read_only_hint ==
        true)`
-   **Internal MCP Server — Read/Write** (`Per-Agent` scope,
    `principal://.../reasoningEngines/ID`, `roles/iap.egressor`): Specific tool
    allowlist plus empty `toolName` (`tool.name == ''`).
-   **Agent2Agent protocol (A2A)** (`Per-Agent` scope, `principal://` Calling
    Agent ID, `roles/iap.egressor`): Optional method filter.

### 3.1 Empty `toolName` and Null-Dereference Guards

During MCP `initialize` and `tools/list` handshakes, no specific tool name is
present (`""`), and during non-tool calls (`prompts/list`, `resources/read`),
`destination.agent_registry.mcp_server.tool` is null. Always check `method ==
'tools'` first and permit empty tool names (`tool.name == ''` in UAP Policy V2
or `api.getAttribute('iap.googleapis.com/mcp.toolName', '') == ''` in IAP V1).
See `references/governance_security_policies.md` Sections 2–4 for full UAP
Policy V2 templates.

--------------------------------------------------------------------------------

## 4. The Consolidated `googleapis` Service Invariant

> [!IMPORTANT] **Consolidated Registry Rule**: Never create fragmented, per-API
> service entries in Agent Registry. Consolidate all Google Cloud APIs under a
> **single service entry named `googleapis`**. Separate standalone Google API
> service entries fail Envoy route matching and evaluate as
> `unregisteredEndpoint` (`destination.is_registered == false`).

### 4.1 The 8 Required Base FQDN Interfaces (Plus Telemetry)

Every consolidated `googleapis` registry service must define the 8 mandatory
base Google API FQDNs plus the 9th telemetry mTLS endpoint:

1.  `https://agentregistry.googleapis.com`
2.  `https://aiplatform.googleapis.com`
3.  `https://aiplatform.mtls.googleapis.com`
4.  `https://cloudresourcemanager.mtls.googleapis.com`
5.  `https://iamcredentials.mtls.googleapis.com`
6.  `https://${REGION}-aiplatform.mtls.googleapis.com`
7.  `https://${REGION}-aiplatform.googleapis.com`
8.  `https://aiplatform.${REGION}.rep.googleapis.com`
9.  `https://telemetry.mtls.googleapis.com`

### 4.2 Additional Telemetry, Global/Multi-Region Model and Hostname Permutations

-   **Telemetry and Tracing Endpoints**: Include
    `https://monitoring.googleapis.com`, `https://trace.mtls.googleapis.com`,
    `https://cloudtrace.googleapis.com`, `https://logging.googleapis.com`, and
    `https://telemetry.googleapis.com` so OpenTelemetry and Cloud Logging
    exporters do not drop on container startup.
-   **Global and Multi-Region Foundation Models**: When using models via the
    `global` endpoint (such as `gemini-4-argon` with
    `GOOGLE_CLOUD_LOCATION="global"`) or cross-region `us-central1` models,
    include `https://us-aiplatform.googleapis.com`,
    `https://us-aiplatform.mtls.googleapis.com`,
    `https://aiplatform.us.rep.googleapis.com` (and `us-central1-aiplatform.*`
    when deployed outside `us-central1`).
-   **Hostname Permutation Matrix**: Agent Gateway matches SNI hostnames
    strictly across all 6 Google API forms: Base REST
    (`aiplatform.googleapis.com`), Base mTLS (`aiplatform.mtls.googleapis.com`),
    Locational REST (`${REGION}-aiplatform.googleapis.com`), Locational mTLS
    (`${REGION}-aiplatform.mtls.googleapis.com`), Regional REP
    (`aiplatform.${REGION}.rep.googleapis.com`), and Private PSC REP
    (`aiplatform.${REGION}.p.rep.googleapis.com`).
-   **10 KB Spec Limit, Dual-Registry Cap and Multi-Region Registration
    Prohibition**: `--mcp-server-spec-content` and `--agent-spec-content`
    enforce a hard **10 KB** limit. An Agent Gateway supports a **maximum of 2
    registries** (at most 1 `global` and 1 regional, referenced using numeric
    `uint64` project numbers; see `references/agent_gateway_and_act.md` Section
    3.4). Manual registration in multi-region locations (`--location=us` or
    `--location=eu`) is **unsupported** and returns HTTP 400; always register in
    a specific region (such as `us-central1` or `us-east4`) or `global`.

### 4.3 Canonical Consolidated `googleapis` Registration Command and Schema Rules

When registering Agent Registry services (`agentregistry.services`), provide
`serviceId`, `location`, one spec block (`endpointSpec`, `mcpServerSpec`, or
`agentSpec`), and `interfaces` entries (`url` and `protocolBinding` =
`"HTTP_JSON"`, `"JSONRPC"`, or `"GRPC"`). Use `"GRPC"` for binary HTTP/2 gRPC
endpoints (`spanner.googleapis.com`, `telemetry.mtls.googleapis.com`,
`trace.mtls.googleapis.com`) and `"HTTP_JSON"` for all `aiplatform*.googleapis.com`
REST endpoints:

```bash
gcloud agent-registry services create "googleapis" \
  --project="${PROJECT_ID}" \
  --location="${REGION}" \
  --display-name="Google Cloud APIs" \
  --description="Consolidated Google Cloud APIs catalog for Agent Gateway egress" \
  --endpoint-spec-type=no-spec \
  --interfaces="url=https://agentregistry.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://aiplatform.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://aiplatform.mtls.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://${REGION}-aiplatform.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://${REGION}-aiplatform.mtls.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://aiplatform.${REGION}.rep.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://us-aiplatform.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://us-aiplatform.mtls.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://aiplatform.us.rep.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://cloudresourcemanager.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://cloudresourcemanager.mtls.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://iamcredentials.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://iamcredentials.mtls.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://storage.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://telemetry.mtls.googleapis.com,protocolBinding=GRPC" \
  --interfaces="url=https://monitoring.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://trace.mtls.googleapis.com,protocolBinding=GRPC" \
  --interfaces="url=https://cloudtrace.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://logging.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://telemetry.googleapis.com,protocolBinding=HTTP_JSON" \
  --interfaces="url=https://spanner.googleapis.com,protocolBinding=GRPC"
```

--------------------------------------------------------------------------------

## 5. Automated Multi-Project Registry Federation

### 5.1 The Read-Through Invalidation and Anti-Entropy Pattern

Treat Cloud Audit Logs or Cloud Asset Inventory (CAI) feeds strictly as **cache
invalidation triggers**:

1.  **Folder Log Sink**: Catches `CreateService`, `UpdateService`, or
    `DeleteService` on `agentregistry.googleapis.com` across spoke projects
    (excluding `projects/${HUB_PROJECT_ID}/`, `projects/${HUB_PROJECT_NUMBER}/`,
    and the replicator service account email to prevent echo loops) and
    publishes to Pub/Sub with a dead-letter topic (`maxDeliveryAttempts = 5`).
2.  **Authoritative Spoke Read-Through and Validation**: A Cloud Run Replicator
    service calls `GetService` against the spoke
    (`projects/{spoke}/locations/{loc}/services/{spoke_service}`), verifies that
    the interface URL uses an approved FQDN (rejecting raw IP literals or
    blocklisted external domains so spoke registrations cannot bypass Org UAP
    guardrails), and upserts the federated service into the Central Hub Registry
    (`projects/{hub}/locations/{loc}/services/{spoke_project}--{spoke_service}`)
    using
    `updateMask=displayName,description,interfaces,agentSpec,mcpServerSpec,endpointSpec`
    and watermark comparison (`replicated_from_update_time=...`).
3.  **Hourly Anti-Entropy Sweep**: A Cloud Run Job (triggered by Cloud
    Scheduler) reconciles spoke `ListServices` / CAI against Hub records older
    than 2 hours (`updateTime < NOW - 2h`) before pruning deleted spoke services
    via `DeleteService`.

```bash
gcloud logging sinks create "agent-registry-events-sink" \
  "pubsub.googleapis.com/projects/${HUB_PROJECT_ID}/topics/agent-registry-events" \
  --folder="${FOLDER_ID}" --include-children \
  --log-filter="protoPayload.serviceName=\"agentregistry.googleapis.com\" AND protoPayload.methodName:(\"CreateService\" OR \"UpdateService\" OR \"DeleteService\") AND NOT protoPayload.resourceName:\"projects/${HUB_PROJECT_ID}/\" AND NOT protoPayload.resourceName:\"projects/${HUB_PROJECT_NUMBER}/\" AND NOT protoPayload.authenticationInfo.principalEmail=\"${REPLICATOR_SA_EMAIL}\""
```

--------------------------------------------------------------------------------

## 6. Agent Registry Taxonomy Metadata, Resource Labels and CI/CD Catalog Automation

1.  **Standardized Taxonomy Metadata and Resource Labels**: Attach standard Google
    Cloud resource labels (`labels = { env = "...", team = "...", cost_center =
    "...", owner = "..." }`) to underlying compute/runtime resources
    (`ReasoningEngine`, Cloud Run, GKE) and encode structured taxonomy metadata
    (`env=...;team=...;cost_center=...;owner=...`) into the Agent Registry
    `service_id` naming convention (`{team}-{env}-{service_name}`) and
    `--description` field.
2.  **Automated CI/CD Registration and Verification**: Combine declarative service
    definitions in spoke projects with the event-driven catalog replicator
    (Section 5) and gate promotion using the Post-Deployment Verification
    Checklist (`references/topologies_and_project_layouts.md` Section 10).
topologies_and_project_layouts.md 31.6 KB
# Enterprise Topologies, Consumer Infrastructure, and IAM Bootstrap

This reference details production-proven resource hierarchies, consumer
networking provisioning, Shared VPC attachment models, VPC Service Controls
(VPC-SC) perimeters, custom/peered and non-RFC 1918 (PUPI) routing, and the
complete Google-managed Service Agent and Agent Identity IAM bootstrap matrix for
**Gemini platform**.

--------------------------------------------------------------------------------

## Table of Contents

-   [1. The 4-Tier Enterprise Project Architecture](#1-the-4-tier-enterprise-project-architecture): Lines 26-62
-   [2. Consumer Infrastructure Provisioning and API Enablement](#2-consumer-infrastructure-provisioning-and-api-enablement): Lines 63-138
-   [3. Cross-Project Agent Runtime and Agent Gateway Architecture](#3-cross-project-agent-runtime-and-agent-gateway-architecture): Lines 139-206
-   [4. Shared VPC Network Attachment and DNS Peering Models](#4-shared-vpc-network-attachment-and-dns-peering-models): Lines 207-227
-   [5. Complete Google-Managed Service Agent and Identity IAM Bootstrap Matrix](#5-complete-google-managed-service-agent-and-identity-iam-bootstrap-matrix): Lines 228-265
-   [6. Architectural Constraints and Platform Invariants](#6-architectural-constraints-and-platform-invariants): Lines 266-282
-   [7. VPC Service Controls (VPC-SC) Perimeter Design](#7-vpc-service-controls-vpc-sc-perimeter-design): Lines 283-387
-   [8. Agent Runtime Multi-Tenancy, Management Boundary, and Regional Colocation](#8-agent-runtime-multi-tenancy-management-boundary-and-regional-colocation): Lines 388-405
-   [9. Custom, Peered, and Non-RFC 1918 (`PUPI`) Enterprise Routing](#9-custom-peered-and-non-rfc-1918-pupi-enterprise-routing): Lines 406-445
-   [10. Post-Deployment Verification and Cloud Audit Log Validation](#10-post-deployment-verification-and-cloud-audit-log-validation): Lines 446-482

--------------------------------------------------------------------------------

## 1. The 4-Tier Enterprise Project Architecture

Enterprise deployments separate concerns across four dedicated Google Cloud
project tiers under an Organizational Management Folder:

```mermaid
graph TD
    subgraph Management Folder [Enterprise Management Folder]
        direction TB
        HostProj["Shared VPC Host Project<br/>• Custom VPC & /26+ PSC-I Subnets<br/>• PSC-I Network Attachments & Cloud NAT"]
        GovProj["AI Governance Hub Project (AGW_PROJECT_ID)<br/>• Central Agent Gateways & Agent Registry<br/>• UAP Policy V2, SGP, Model Armor & Auth Manager"]
        RuntimeProj1["Agent Runtime Spoke Project (AE_PROJECT_ID)<br/>• Agent Runtime Workloads (ADK)"]
        MCPProj["Tool & MCP Service Project (MCP_PROJECT_ID)<br/>• Cloud Run / GKE MCP, Internal ALBs & Cloud SQL"]
    end

    RuntimeProj1 -.->|Service Project| HostProj
    GovProj -.->|Service Project| HostProj
    MCPProj -.->|Service Project| HostProj
    RuntimeProj1 -->|Cross-Project Gateway Binding| GovProj
    GovProj -->|Central Egress Interception| MCPProj
```

-   **Tier 1 — Shared VPC Host (`HOST_PROJECT_ID`, Central NetOps)**: Custom VPC
    (`10.10.0.0/16` or enterprise PUPI supernet), PSC-I subnets (`/26+`),
    Proxy-Only Subnets, Cloud NAT, Private Cloud DNS.
-   **Tier 2 — Central Governance Hub (`AGW_PROJECT_ID`, Central SecOps)**:
    Agent Gateways, Global/Regional Agent Registries, UAP Policy V2, Model Armor
    Floor Settings and Templates, SGP, Auth Manager.
-   **Tier 3 — Agent Runtime Spokes (`AE_PROJECT_ID`, AI Engineering)**: Agent
    Runtime (`reasoningEngines`), ADK Agent artifacts, staging Cloud Storage
    buckets (`10.30.0.0/16`).
-   **Tier 4 — Tool and MCP Service Producers (`MCP_PROJECT_ID`, API and Tool
    Teams)**: Cloud Run / GKE MCP servers, Regional Internal ALBs, Apigee X
    Private proxies, Spanner / BigQuery / Cloud SQL (`10.40.0.0/16`).

--------------------------------------------------------------------------------

## 2. Consumer Infrastructure Provisioning and API Enablement

### 2.1 API Enablement Matrix

```bash
gcloud services enable \
  compute.googleapis.com dns.googleapis.com networkservices.googleapis.com \
  networksecurity.googleapis.com aiplatform.googleapis.com modelarmor.googleapis.com \
  agentregistry.googleapis.com iap.googleapis.com cloudresourcemanager.googleapis.com \
  iamcredentials.googleapis.com storage.googleapis.com networkconnectivity.googleapis.com \
  cloudtrace.googleapis.com certificatemanager.googleapis.com \
  --project="${PROJECT_ID}" --quiet
```

### 2.2 Custom VPC, PSC-I Subnet (`/26` Minimum), and Network Attachment

> [!IMPORTANT] **The `/26` Subnet Sizing and Reserved CIDR Invariant**: 1. Size
> the PSC-I subnet to **at least `/26` (64 IPs)** with `purpose = "PRIVATE"`
> (never `PRIVATE_SERVICE_CONNECT` or `REGIONAL_MANAGED_PROXY`) and
> `private_ip_google_access = true`. Legacy `/28` or `/29` sandbox subnets cause
> IP exhaustion and gateway provisioning failures. 2. **Reserved Agent Gateway
> Ranges**: Never allocate consumer VPC or PSC-I subnets overlapping
> **`10.0.0.0/24`**, **`10.0.1.0/24`**, or **`10.0.2.0/24`** (`10.10.1.0/26` or
> `10.20.1.0/26` is recommended).

```bash
gcloud compute networks create "${VPC_NAME}" --subnet-mode=custom --project="${PROJECT_ID}" --quiet
gcloud compute networks subnets create "${PSCI_SUBNET_NAME}" \
  --network="${VPC_NAME}" --region="${REGION}" --range="${PSCI_SUBNET_RANGE}" \
  --stack-type=IPV4_ONLY --enable-private-ip-google-access --project="${PROJECT_ID}" --quiet
gcloud compute network-attachments create "${ATTACHMENT_NAME}" \
  --region="${REGION}" --subnets="${PSCI_SUBNET_NAME}" \
  --connection-preference=ACCEPT_AUTOMATIC --project="${PROJECT_ID}" --quiet
gcloud compute firewall-rules create "${VPC_NAME}-allow-internal" \
  --network="${VPC_NAME}" --allow=tcp:443,tcp:8080 --source-ranges="${PSCI_SUBNET_RANGE}" \
  --project="${PROJECT_ID}" --quiet
```

### 2.3 Deterministic Egress: Static IP, Cloud Router, and Cloud NAT

-   **Mandatory Dual Endpoint Types (`ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG`)**:
    Always configure Cloud NAT with
    `--endpoint-types=ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG` (the Agent Gateway
    control plane validates that `ENDPOINT_TYPE_SWG` is present on Cloud NAT
    even when Secure Web Proxy is not deployed).
-   **Direct Cloud NAT Subnet Scoping vs. Next-Hop SWP + PBR**: Scope Direct
    Cloud NAT explicitly to the PSC-I subnet via
    `--nat-custom-subnet-ip-ranges="${PSCI_SUBNET_NAME}"` so multi-subnet Shared
    VPCs do not indiscriminately SNAT other subnets
    (`--nat-all-subnet-ip-ranges` is only suitable in dedicated single-subnet
    VPCs). When using Next-Hop SWP + PBR, use `LIST_OF_SUBNETWORKS` and
    **exclude the PSC-I subnet** from manual Cloud NAT so `swg-autogen-nat`
    handles SNAT without conflict.

```bash
gcloud compute addresses create "${STATIC_IP_NAME}" --region="${REGION}" --project="${PROJECT_ID}" --quiet
gcloud compute routers create "${ROUTER_NAME}" --network="${VPC_NAME}" --region="${REGION}" --project="${PROJECT_ID}" --quiet
# Agent Gateway control plane validates that ENDPOINT_TYPE_SWG is present on the NAT even when SWP is not deployed
gcloud compute routers nats create "${NAT_NAME}" \
  --router="${ROUTER_NAME}" --region="${REGION}" \
  --nat-external-ip-pool="${STATIC_IP_NAME}" --nat-custom-subnet-ip-ranges="${PSCI_SUBNET_NAME}" \
  --enable-logging --endpoint-types=ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG \
  --project="${PROJECT_ID}" --quiet
```

### 2.4 Private Cloud DNS and Model Armor Template (`us-central1`)

```bash
gcloud dns managed-zones create "${DNS_ZONE_NAME}" \
  --dns-name="${PEERING_DOMAIN}" --visibility=private --networks="${VPC_NAME}" --project="${PROJECT_ID}" --quiet
gcloud model-armor templates create "${MA_TEMPLATE_NAME}" --location="us-central1" \
  --pi-and-jailbreak-filter-settings-enforcement=enabled --malicious-uri-filter-settings-enforcement=enabled --project="${PROJECT_ID}" --quiet
```

--------------------------------------------------------------------------------

## 3. Cross-Project Agent Runtime and Agent Gateway Architecture

### 3.1 Cross-Project Service Agent, Deploying Caller and AddressGroup IAM Requirements

1.  **Same-Region Colocation**: Both the Spoke `ReasoningEngine` and Hub
    `AgentGateway` must reside in the exact same Google Cloud region and use
    numeric `uint64` project numbers.
2.  **Cross-Project Gateway Get/Use Permissions
    (`networkservices.agentGateways.get`,
    `networkservices.agentGateways.use`)**: Both Spoke
    `service-${AE_PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com` and
    the deploying caller require `networkservices.agentGateways.get`,
    `networkservices.agentGateways.use`, and `networkservices.operations.get` in
    `AGW_PROJECT_ID` (via a least-privilege custom IAM role or
    `roles/networkservices.admin`).
3.  **ACT AddressGroup `roles/compute.networkUser` Binding**: After creating the
    ACT, grant `roles/compute.networkUser` (`networksecurity.addressGroups.use`,
    `networksecurity.addressGroups.get`, `networksecurity.addressGroups.list`)
    on the server-managed `act-${TEMPLATE_ID}` AddressGroup to Spoke
    `service-${AE_PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com`.
4.  **Cross-Project Token Sharing Variable**: Set
    `GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES="False"` in
    `deploymentSpec.env` when a Spoke `ReasoningEngine` binds to a dedicated
    central Hub `AgentGateway` across projects (with `AGENT_IDENTITY` SPIFFE
    SVIDs and UAP `principal://` rules enforcing per-agent isolation at the
    Gateway); keep `"True"` if untrusted multi-tenant agents share a project
    without `principal://` UAP scoping.

```bash
gcloud compute network-attachments create "${ATTACHMENT_NAME}" --project="${AGW_PROJECT_ID}" \
  --region="${REGION}" --connection-preference="ACCEPT_AUTOMATIC" \
  --subnets="projects/${HOST_PROJECT_ID}/regions/${REGION}/subnetworks/${PSCI_SUBNET_NAME}"
gcloud iam roles create agw_cross_project_binder --project="${AGW_PROJECT_ID}" \
  --title="Cross-Project Agent Gateway Binder" \
  --permissions="networkservices.agentGateways.get,networkservices.agentGateways.use,networkservices.operations.get" --stage="GA"
for MEMBER in "serviceAccount:service-${AE_PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com" "user:${DEPLOYER_EMAIL}"; do
  gcloud projects add-iam-policy-binding "${AGW_PROJECT_ID}" --member="${MEMBER}" --role="projects/${AGW_PROJECT_ID}/roles/agw_cross_project_binder"
done
# Run AFTER creating the AgentConnectivityTemplate (which auto-provisions addressGroups/act-${TEMPLATE_ID})
ETAG=$(curl -s "https://networksecurity.googleapis.com/v1/projects/${AGW_PROJECT_ID}/locations/${REGION}/addressGroups/act-${TEMPLATE_ID}:getIamPolicy?options.requestedPolicyVersion=3" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" | jq -r '.etag // empty')
curl -s -X POST "https://networksecurity.googleapis.com/v1/projects/${AGW_PROJECT_ID}/locations/${REGION}/addressGroups/act-${TEMPLATE_ID}:setIamPolicy" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" \
  -d "{\"policy\":{\"version\":3,\"etag\":\"${ETAG}\",\"bindings\":[{\"role\":\"roles/compute.networkUser\",\"members\":[\"serviceAccount:service-${AE_PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com\"]}]}}"
export AGENT_PRINCIPAL_SET="principalSet://agents.global.org-${ORG_ID}.system.id.goog/attribute.platformContainer/aiplatform/projects/${AE_PROJECT_NUMBER}"
export AGENT_PRINCIPAL="principal://agents.global.org-${ORG_ID}.system.id.goog/resources/aiplatform/projects/${AE_PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${RE_ID}"
gcloud projects add-iam-policy-binding "${AGW_PROJECT_ID}" --member="${AGENT_PRINCIPAL_SET}" --role="roles/agentregistry.viewer"
gcloud run services add-iam-policy-binding "${MCP_SERVICE}" --project="${MCP_PROJECT_ID}" --region="${REGION}" \
  --member="${AGENT_PRINCIPAL}" --role="roles/run.invoker"
```

Attach Tier-1 (`--endpoint="${GOOGLEAPIS_UUID}"`) and Tier-2
(`--mcp-server="${MCP_UUID}"`) `roles/iap.egressor` bindings using the
server-generated UUID commands in `references/registry_and_federation.md`
Section 2.4.

### 3.2 Cross-Project Agent Runtime Deployment (Python SDK)

Deploy the `AgentEngine` instance in `AE_PROJECT_ID` using the canonical
`client.agent_engines.create(...)` specification in
`references/agent_runtime_and_identity.md` Section 4.2, setting `agent_gateway`
to
`f"projects/{AGW_PROJECT_NUMBER}/locations/{REGION}/agentGateways/{AGENT_GATEWAY_NAME}"`
(numeric `AGW_PROJECT_NUMBER`), `"identity_type": "AGENT_IDENTITY"`, and
`"GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES": "False"`.

--------------------------------------------------------------------------------

## 4. Shared VPC Network Attachment and DNS Peering Models

-   **Model 1 (Recommended — Network Attachment in Governance Project)**: The
    `/26+` PSC-I subnet is defined in `HOST_PROJECT_ID`, and the Network
    Attachment is created in `AGW_PROJECT_ID` referencing the host subnet.
-   **Model 2 (Network Attachment in Host Project)**: Both the PSC-I subnet and
    Network Attachment are created in `HOST_PROJECT_ID`.

-   **Provisioning Identity (CI/CD) on Host Project**: Grant
    `roles/compute.networkViewer`, `roles/dns.reader`, and
    `roles/compute.networkUser` to validate host networks, subnets, and private
    DNS zones and create the PSC-I attachment.

-   **Gateway and Network Google-Managed Service Agents (`gcp-sa-networkservices`,
    `gcp-sa-agentgateway`, `gcp-sa-dep`) on Host Project**: Grant
    `roles/compute.networkUser` on the PSC-I subnet and `roles/dns.peer` on the
    Host Project so tenant proxy NICs attach and peer with private DNS zones
    (preventing gateway provisioning failures).

--------------------------------------------------------------------------------

## 5. Complete Google-Managed Service Agent and Identity IAM Bootstrap Matrix

```bash
export PROJECT_NUMBER=$(gcloud projects describe "${PROJECT_ID}" --format="value(projectNumber)")
export ORG_ID=$(gcloud projects get-ancestors "${PROJECT_ID}" --format="value(id)" | tail -n 1)
export AGENT_PRINCIPAL_SET="principalSet://agents.global.org-${ORG_ID}.system.id.goog/attribute.platformContainer/aiplatform/projects/${PROJECT_NUMBER}"

# 5.1 Subnet NetworkUser & DNS Peer for NetworkServices, AgentGateway, and DEP Service Agents
for SA_SUFFIX in "gcp-sa-networkservices" "gcp-sa-agentgateway" "gcp-sa-dep"; do
  SA="serviceAccount:service-${PROJECT_NUMBER}@${SA_SUFFIX}.iam.gserviceaccount.com"
  gcloud compute networks subnets add-iam-policy-binding "${PSCI_SUBNET_NAME}" \
    --region="${REGION}" --member="${SA}" --role="roles/compute.networkUser" --project="${HOST_PROJECT_ID:-$PROJECT_ID}" --quiet
  gcloud projects add-iam-policy-binding "${HOST_PROJECT_ID:-$PROJECT_ID}" \
    --member="${SA}" --role="roles/dns.peer" --condition=None --quiet
done

# 5.2 Model Armor Callout Grants for Service Extensions Service Agent (gcp-sa-dep)
DEP_SA="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-dep.iam.gserviceaccount.com"
for ROLE in "roles/modelarmor.user" "roles/modelarmor.calloutUser" "roles/serviceusage.serviceUsageConsumer"; do
  gcloud projects add-iam-policy-binding "${PROJECT_ID}" --member="${DEP_SA}" --role="${ROLE}" --condition=None --quiet
done

# 5.3 Agent PrincipalSet Baseline Roles (scoped strictly to the Runtime Spoke project; roles/browser is required so the ADK SDK resolves project_number -> project_id on startup; also grant roles/agentregistry.viewer on AGW_PROJECT_ID in cross-project topologies)
for ROLE in "roles/browser" "roles/aiplatform.expressUser" "roles/serviceusage.serviceUsageConsumer" "roles/logging.logWriter" "roles/monitoring.metricWriter" "roles/agentregistry.viewer"; do
  gcloud projects add-iam-policy-binding "${PROJECT_ID}" --member="${AGENT_PRINCIPAL_SET}" --role="${ROLE}" --condition=None --quiet
done

# 5.4 AI Platform & Reasoning Engine Service Agent Grants
gcloud projects add-iam-policy-binding "${PROJECT_ID}" \
  --member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com" \
  --role="roles/networkservices.admin" --condition=None --quiet
for ROLE in "roles/aiplatform.reasoningEngineServiceAgent" "roles/aiplatform.user" "roles/logging.logWriter" "roles/monitoring.metricWriter" "roles/telemetry.tracesWriter"; do
  gcloud projects add-iam-policy-binding "${PROJECT_ID}" --member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com" --role="${ROLE}" --condition=None --quiet
done
```

--------------------------------------------------------------------------------

## 6. Architectural Constraints and Platform Invariants

1.  **Gateway and Registry Project Co-location**: Agent Gateway and Agent
    Registry **must reside in the exact same project** (`AGW_PROJECT_ID`).
2.  **Folder-Level Governance Scoping via Principal Access Boundary (PAB)**:
    Because `attribute.platformContainer/aiplatform/folders/FOLDER_NUMBER` is
    **not** an indexed attribute in IAM SPIFFE `principalSet://` evaluation,
    enforce folder-level isolation via **Principal Access Boundary (PAB)**
    policies attached to
    `//cloudresourcemanager.googleapis.com/folders/${FOLDER_NUMBER}` or
    folder-level UAP Policy V2 bindings.
3.  **Private DNS Peering Rules**: Suffixes must end with a trailing dot
    (`internal.example.com.`, `example.com.`). **Never use root wildcard (`.`) or
    `googleapis.com.`**.

--------------------------------------------------------------------------------

## 7. VPC Service Controls (VPC-SC) Perimeter Design

### 7.1 Single-Project vs. Multi-Project VPC-SC Perimeter Behavior (`ALL_TRAFFIC` Native Support)

-   **Single-Project Deployments (Native VPC-SC Support)**: Single-project Gemini platform deployments work **natively inside a VPC-SC perimeter** out of the box—requiring zero custom cross-project VPC-SC ingress rules—when the Agent Connectivity Template (ACT) sets **`vpcEgress: ALL_TRAFFIC`** and the Agent Registry registers the **consolidated `googleapis` service** (routing 100% of control/data-plane and Google API traffic through the governed `240.0.0.2:443` VIP inside the perimeter). By contrast, multi-project Hub-and-Spoke deployments (`HOST`, `GOV`, `AGENT`, `MCP`) require the explicit cross-project VPC-SC ingress rules in Section 7.2.
-   **Perimeter `restricted_services` Catalog**: Include `aiplatform.googleapis.com`, `networkservices.googleapis.com`, `networksecurity.googleapis.com`, `agentregistry.googleapis.com`, `agentidentity.googleapis.com`, `agentidentitycredentials.googleapis.com`, `iamcredentials.googleapis.com`, `modelarmor.googleapis.com`, `iap.googleapis.com`, `compute.googleapis.com`, `dns.googleapis.com`, `run.googleapis.com`, `sqladmin.googleapis.com`, `spanner.googleapis.com`, `secretmanager.googleapis.com`, `bigquery.googleapis.com`, and `storage.googleapis.com` in `restricted_services`.
-   **In-Perimeter BigQuery Cost and Query Governance**: For agents querying BigQuery inside the perimeter, enforce a pre-execution `QueryJobConfig(dry_run=True)` byte-scan check verifying `statement_type == "SELECT"` and `maximum_bytes_billed` with caller attribution labels (`references/agent_runtime_and_identity.md` Section 7.2).

### 7.2 Multi-Project / Cross-Perimeter VPC-SC Ingress Reference Categories

When enclosing multi-project tiers (`HOST_PROJECT_NUMBER`, `GOV_PROJECT_NUMBER`,
`AGENT_PROJECT_NUMBER`, and `MCP_PROJECT_NUMBER` Tool Spoke — or a collapsed
Hub + Spoke layout) across strict or segmented VPC-SC perimeters, configure
ingress rules covering these principal categories:

1.  **Category 1 — Operator Access Level (`accessLevels/enterprise_admin_access`)**:
    Target `compute`, `networkservices`, `networksecurity`, `aiplatform`,
    `agentregistry`, `iap`, `modelarmor`, `run`, `sqladmin`, `spanner`,
    `storage` across `HOST`, `GOV`, `AGENT`, and `MCP` projects for scoped CI/CD
    and operator administration.
2.  **Category 2 —
    `serviceAccount:service-${GOV_PROJECT_NUMBER}@gcp-sa-agentgateway.iam.gserviceaccount.com`**:
    Target `compute`, `dns`, `networkservices`, `agentregistry`, `run` on
    `HOST`, `GOV`, and `MCP` projects to attach PSC-I NICs, peer DNS, and reach
    Tool Spoke services.
3.  **Category 3 —
    `serviceAccount:service-${GOV_PROJECT_NUMBER}@gcp-sa-networkservices.iam.gserviceaccount.com`**:
    Target `compute`, `dns`, `networksecurity` on `HOST` and `GOV` projects to
    manage `act-*` address groups and attachments.
4.  **Category 4 —
    `serviceAccount:service-${AGENT_PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com`**:
    Target `networkservices`, `aiplatform`, `storage` on `GOV` and `AGENT`
    projects to validate cross-project `agentGateways.get`.
5.  **Category 5 —
    `serviceAccount:service-${AGENT_PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com`**:
    Target `networksecurity`, `aiplatform`, `agentregistry`, `iap`, `storage`,
    `run` on `GOV`, `AGENT`, and `MCP` projects to read `act-${TEMPLATE_ID}`
    addressGroup (`roles/compute.networkUser`), staging buckets, and Tool Spoke
    services.
6.  **Category 6 —
    `principal://agents.global.org-${ORG_ID}.system.id.goog/resources/aiplatform/projects/${AGENT_PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${ENGINE_ID}`**
    (or `principalSet://...` plus the impersonated data-plane SA
    `serviceAccount:${DATA_PLANE_SA_EMAIL}`): Target `aiplatform`,
    `agentregistry`, `iap`, `agentidentity`, `agentidentitycredentials`,
    `iamcredentials`, `run`, `sqladmin`, `spanner`, `secretmanager`, `bigquery`,
    `cloudtrace`, `logging`, `monitoring` across `GOV`, `AGENT`, and `MCP`
    (`MCP_PROJECT_NUMBER`) projects for attested `AGENT_IDENTITY` SPIFFE calls
    and SA-impersonated Spanner/Cloud Run calls.
7.  **Category 7 —
    `serviceAccount:service-${GOV_PROJECT_NUMBER}@gcp-sa-dep.iam.gserviceaccount.com`**:
    Target `modelarmor.googleapis.com` and `serviceusage.googleapis.com` on
    `GOV` project for inline Service Extensions (`ext_proc`) Model Armor
    `SanitizeUserPrompt` / `SanitizeModelResponse` callouts.

```yaml
# Excerpt: Cross-Project Service Agents, SPIFFE Workload & Model Armor VPC-SC Ingress Rules
- ingressFrom:
    identities:
      - "serviceAccount:service-${GOV_PROJECT_NUMBER}@gcp-sa-agentgateway.iam.gserviceaccount.com"
      - "serviceAccount:service-${GOV_PROJECT_NUMBER}@gcp-sa-networkservices.iam.gserviceaccount.com"
  ingressTo:
    operations:
      - {serviceName: compute.googleapis.com, methodSelectors: [{method: "*"}]}
      - {serviceName: dns.googleapis.com, methodSelectors: [{method: "*"}]}
      - {serviceName: networkservices.googleapis.com, methodSelectors: [{method: "*"}]}
      - {serviceName: networksecurity.googleapis.com, methodSelectors: [{method: "*"}]}
    resources: ["projects/${GOV_PROJECT_NUMBER}", "projects/${HOST_PROJECT_NUMBER}"]
- ingressFrom:
    identities:
      - "serviceAccount:service-${AGENT_PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com"
      - "serviceAccount:service-${AGENT_PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com"
  ingressTo:
    operations:
      - {serviceName: networkservices.googleapis.com, methodSelectors: [{method: "*"}]}
      - {serviceName: networksecurity.googleapis.com, methodSelectors: [{method: "*"}]}
      - {serviceName: agentregistry.googleapis.com, methodSelectors: [{method: "*"}]}
      - {serviceName: iap.googleapis.com, methodSelectors: [{method: "*"}]}
      - {serviceName: storage.googleapis.com, methodSelectors: [{method: "*"}]}
    resources: ["projects/${AGENT_PROJECT_NUMBER}", "projects/${GOV_PROJECT_NUMBER}"]
- ingressFrom:
    identities:
      - "principal://agents.global.org-${ORG_ID}.system.id.goog/resources/aiplatform/projects/${AGENT_PROJECT_NUMBER}/locations/${REGION}/reasoningEngines/${ENGINE_ID}"
  ingressTo:
    operations:
      - {serviceName: iamcredentials.googleapis.com, methodSelectors: [{method: "*"}]}
      - {serviceName: run.googleapis.com, methodSelectors: [{method: "*"}]}
    resources: ["projects/${GOV_PROJECT_NUMBER}", "projects/${AGENT_PROJECT_NUMBER}", "projects/${MCP_PROJECT_NUMBER}"]
- ingressFrom:
    identities: ["serviceAccount:${DATA_PLANE_SA_EMAIL}"]
  ingressTo:
    operations:
      - {serviceName: spanner.googleapis.com, methodSelectors: [{method: "*"}]}
      - {serviceName: sqladmin.googleapis.com, methodSelectors: [{method: "*"}]}
    resources: ["projects/${GOV_PROJECT_NUMBER}", "projects/${MCP_PROJECT_NUMBER}"]
- ingressFrom:
    identities: ["serviceAccount:service-${GOV_PROJECT_NUMBER}@gcp-sa-dep.iam.gserviceaccount.com"]
  ingressTo:
    operations:
      - {serviceName: modelarmor.googleapis.com, methodSelectors: [{method: "*"}]}
      - {serviceName: serviceusage.googleapis.com, methodSelectors: [{method: "*"}]}
    resources: ["projects/${GOV_PROJECT_NUMBER}"]
```

--------------------------------------------------------------------------------

## 8. Agent Runtime Multi-Tenancy, Management Boundary, and Regional Colocation

1.  **One Bonded Agent Gateway Per Consumer Project / Region**: Agent Runtime
    provisions one shared tenant project (`*-tp`) per consumer project/region.
    Reuse the same Agent Gateway across `ReasoningEngine` instances in that
    project/region, or separate workloads into distinct spoke projects.
2.  **App Management Folder Capability and Boundary Configuration**: To enable
    cross-project Agent Registry discovery across an enterprise management
    folder or spoke project boundary, enable the `app-management` folder
    capability and attach the App Hub boundary:

```bash
gcloud resource-manager capabilities update "folders/${ENTERPRISE_FOLDER_ID}/capabilities/app-management" --enable
gcloud apphub boundary update --project="${AGW_PROJECT_ID}" --location=global --crm-node="projects/${AE_PROJECT_ID}"
```

--------------------------------------------------------------------------------

## 9. Custom, Peered, and Non-RFC 1918 (`PUPI`) Enterprise Routing

Enterprises routing across peered VPCs, Cloud Interconnect/VPN, or **Privately
Used Public IP (`PUPI`)** blocks outside RFC 1918 (such as `198.51.100.0/24`) must
align ACT egress mode, VPC peering route exchange, and PBR priorities:

1.  **Why `PRIVATE_RANGES_ONLY` Drops Non-RFC 1918 Internal Space**:
    `PRIVATE_RANGES_ONLY` only routes strict RFC 1918 (`10.0.0.0/8`,
    `172.16.0.0/12`, `192.168.0.0/16`) and CGNAT (`100.64.0.0/10`) to the
    consumer VPC, treating non-RFC 1918 internal/PUPI space as external public
    IP space. Always set `vpcEgress = ALL_TRAFFIC` on the ACT with Private DNS
    peering (`dnsPeeringConfig` ending with a trailing dot, such as
    `internal.example.com.`), and configure the PSC-I subnet with
    `--stack-type=IPV4_ONLY` (`protocolVersion = "IPV4"`) so IPv6 traffic cannot
    bypass PBR or SWP rules (never allow default Cloud NAT to SNAT internal PUPI
    traffic to the public internet).
2.  **Multi-VPC Custom Route Peering and PBR Bypass Commands**:

```bash
export GOV_PROJECT_ID="gov-hub-proj" HOST_VPC="enterprise-shared-vpc" GOV_VPC="${HOST_VPC}"
export SPOKE_PROJECT_ID="mcp-spoke-proj" SPOKE_VPC="spoke-pupi-vpc"
export PSCI_SUBNET_CIDR="10.20.1.0/26" CUSTOM_INTERNAL_CIDR="198.51.100.0/24"

# 1. Create bilateral VPC Peerings with custom route & public-IP (PUPI) subnet route export/import enabled
gcloud compute networks peerings create "peering-gov-to-spoke" --project="${GOV_PROJECT_ID}" \
  --network="${GOV_VPC}" --peer-project="${SPOKE_PROJECT_ID}" --peer-network="${SPOKE_VPC}" \
  --export-custom-routes --import-custom-routes --export-subnet-routes-with-public-ip --import-subnet-routes-with-public-ip
gcloud compute networks peerings create "peering-spoke-to-gov" --project="${SPOKE_PROJECT_ID}" \
  --network="${SPOKE_VPC}" --peer-project="${GOV_PROJECT_ID}" --peer-network="${GOV_VPC}" \
  --export-custom-routes --import-custom-routes --export-subnet-routes-with-public-ip --import-subnet-routes-with-public-ip

# 2. Bypass Next-Hop SWP for custom/peered/PUPI internal destinations (pair with priority 50 for RFC 1918)
gcloud network-connectivity policy-based-routes create "pbr-bypass-custom-internal" \
  --project="${GOV_PROJECT_ID}" --network="projects/${GOV_PROJECT_ID}/global/networks/${GOV_VPC}" \
  --source-range="${PSCI_SUBNET_CIDR}" --destination-range="${CUSTOM_INTERNAL_CIDR}" \
  --ip-protocol=ALL --next-hop-other-routes=DEFAULT_ROUTING --priority=51
```

--------------------------------------------------------------------------------

## 10. Post-Deployment Verification and Cloud Audit Log Validation

Validate production deployments across three phases—combining control-plane
resource inspection, data-plane connectivity probes, and Cloud Audit Log
verification:

1.  **Phase 1 — Control-Plane Configuration Audit (`gcloud ... describe --format=json`)**:
    -   **Agent Gateway and Consolidated `googleapis` Registry Readiness**: Confirm the **Agent Gateway state is `ACTIVE`** (`state == "ACTIVE"`, with `<= 2` numeric registries attached) and that the **consolidated `googleapis` service** (`8` Google APIs FQDNs) is registered in Agent Registry (`gcloud agent-registry services describe googleapis --location=${REGION}`).
    -   **PSC-I Network Attachment and Cloud NAT Readiness**: Confirm the PSC-I subnet is `/26+` `PRIVATE` (`IPV4_ONLY`, `privateIpGoogleAccess == true`), the **Network Attachment has an `ACCEPTED` endpoint** (`connectionPreference == "ACCEPT_AUTOMATIC"`), `act-${TEMPLATE_ID}` grants `roles/compute.networkUser`, Cloud NAT sets `ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG`, VPC peerings export/import custom and public-IP subnet routes (when applicable), and PBR `priority: 50..53` bypasses precede `priority: 100`.
    -   **Policy and Guardrail Readiness**: Confirm ACT sets `vpcEgress == "ALL_TRAFFIC"`, `roles/iap.egressor` is bound to the `registryResource` UUID, IAP `AuthzExtension` sets `failOpen == false` and `iapPolicyVersion == "V2"` (`<= 4` `CUSTOM` `AuthzPolicy` resources attached), and Model Armor Floor Settings and Templates enforce fail-closed inspection.
2.  **Phase 2 — Functional Data-Plane Traffic Verification**: Execute `:query`
    and `:streamQuery` probes (`references/agent_runtime_and_identity.md` §5) to
    confirm that the agent container connects to the local Agent Gateway VIP
    (`240.0.0.2` with `Agent Gateway TLS Inspection CA`) and that downstream
    backends observe requests arriving from the consumer PSC-I subnet CIDR (or
    static Cloud NAT IP for external endpoints such as `https://api.ipify.org`;
    never use an internal `*.run.app` endpoint to verify Cloud NAT IPs because
    Google Cloud routes `*.run.app` internally to the Cloud Run ingress proxy
    with `X-Forwarded-For: 0.0.0.0`, bypassing Cloud NAT — see
    `references/agent_runtime_and_identity.md` Section 11.1).
3.  **Phase 3 — Security Policy and Audit Log Validation**: Trigger negative
    security probes (unregistered external LLM domain `https://api.openai.com`,
    unauthorized mutating MCP tool, plaintext `http://:80`, and prompt injection
    payloads) and verify server-side Cloud Audit Log deny receipts
    (`protoPayload.status.code=7`):

```bash
# Phase 1: Verify ACTIVE Agent Gateway state, ACCEPTED PSC-I Network Attachment endpoint & consolidated googleapis Registry service
gcloud network-services agent-gateways describe "${GATEWAY_ID}" --location="${REGION}" --project="${GOV_PROJECT_ID}" --format="value(state)"
gcloud compute network-attachments describe "${ATTACHMENT_NAME}" --region="${REGION}" --project="${HOST_PROJECT_ID}" --format="json(connectionEndpoints)"
gcloud agent-registry services describe "googleapis" --location="${REGION}" --project="${GOV_PROJECT_ID}"

# Phase 3: Verify server-side Cloud Audit Log deny receipts (protoPayload.status.code=7) for negative security probes
gcloud logging read \
  '(resource.type="audited_resource" OR resource.type="agent_gateway") AND (resource.labels.service="iap.googleapis.com" OR resource.labels.service="modelarmor.googleapis.com") AND protoPayload.status.code=7' \
  --project="${GOV_PROJECT_ID}" --freshness=10m --limit=10 --format=json
```

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE