Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install agent-platform-troubleshooting@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin agent-platform-troubleshooting v1.0.0 follows the Agent Plugins spec.
gh skills-hub install agent-platform-troubleshooting Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/agent-platform-troubleshooting/ Extract the ZIP to .github/skills/ in your repo. The folder name must match agent-platform-troubleshooting for Copilot to auto-discover it.
Skill Files (8)
SKILL.md 26.1 KB
---
name: agent-platform-troubleshooting
description: >-
Troubleshoots Google Cloud Gemini Enterprise Agent Platform issues across Agent Gateway, Agent Connectivity Templates (ACT), Agent Registry, Agent Identity, Identity-Aware Proxy (IAP), Unified Access Policies (UAP), Model Armor, Semantic Governance Policies (SGP), Cloud DNS peering, Private CA TrustConfig, Next-Hop Secure Web Proxy (SWP), Explicit HTTPS Proxy (L4 AuthzPolicy), and Cloud Trace.
Use when agent requests fail with 401/403/404/498/500/503 or Code 13, Egress request is not authorized, HTTP CONNECT fails with 404, Agent Runtime crashes on startup, or gateway/ACT/IAP/Model Armor/SGP configs fail validation.
Don't use for general Google Cloud Identity and Access Management (IAM) debugging or networking issues unrelated to the Agent Platform stack.
metadata:
version: "1.1.1"
category: AiAndMachineLearning
---
# Agent Platform Troubleshooting
> **Important:** You MUST ONLY use the reference files located in this skill's
> `references/` directory (`references/field-manual.md`,
> `references/known-issues.md`, `references/agent-gateway.md`,
> `references/policies.md`, `references/agent-registry.md`,
> `references/agent-identity.md`). Do NOT search for or read external playbooks
> outside this directory.
Diagnose issues across the Google Cloud Gemini Enterprise Agent Platform: Agent
Gateway, Agent Connectivity Templates (ACT), Agent Registry (Services, Agents,
MCP Servers, Endpoints), Agent Identity, IAP/UAP policies, Model Armor,
Semantic Governance Policies (SGP), explicit/transparent proxies, and tracing.
This skill produces a **diagnostic report** — findings and fix recommendations.
It does not apply fixes; the user owns all mutations.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow [Usage Attribution](references/attribution.md). Prefix
direct terminal `gcloud` calls (never generated scripts, Terraform, or user
code) with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:agent-platform-troubleshooting)"`
and append `agent-skills/1.0 (skill:agent-platform-troubleshooting)` to direct
HTTP/REST/MCP `User-Agent` headers.
## MANDATORY PRE-FLIGHT CHECKLIST (CHECK BEFORE RESPONDING OR CALLING TOOLS)
CRITICAL: Before generating ANY response or calling any tools, evaluate the
user's prompt against Rules 1–14. When a Turn-0 rule matches, execute its
directive immediately and STOP.
### Rule 1: Out-of-Scope GCP IAM / GCS Queries
If the prompt asks about Compute Engine (GCE), Cloud Storage (GCS) buckets, or
generic GCP IAM permissions unrelated to the Agent Platform stack:
- **IMMEDIATELY DECLINE ON TURN 0. DO NOT CALL ANY TOOLS OR GIVE IAM GUIDES.**
- Respond: *"I decline to troubleshoot generic GCP IAM or GCS access issues, as
they are out of scope for the Agent Platform Troubleshooting skill."*
### Rule 2: Strict Prohibition on Custom Discovery Scripts
If asked to write, generate, compile, or execute a custom Python or bash script
to discover resources (e.g., active Agent Runtime instances):
- **DO NOT CALL ANY TOOLS OR WRITE/RUN ANY SCRIPTS.**
- **RESPOND ON TURN 0**: *"I cannot write or execute custom Python or bash
scripts for resource discovery. Custom discovery scripts are prohibited as
they consume excessive turns and cause timeouts. Instead, use standard gcloud
CLI commands (see [Google Cloud SDK Installation](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt))
or curl REST API calls with application default credentials:
`gcloud agent-registry agents list --location=us-central1` or `curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" "https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/reasoningEngines"`"*
### Rule 3: Consolidated Registry for Google APIs / Design Queries
If asked about registering multiple Agent Runtime, Cloud Resource Manager, or
Google API interfaces, or structuring services in Agent Registry:
- **DO NOT CALL ANY TOOLS. RESPOND ON TURN 0 WITH**:
1. Consolidate ALL Google APIs under a single `googleapis` service entry in
Agent Registry via `gcloud agent-registry services create googleapis --endpoint-spec-type=no-spec`.
2. Explicitly state: *"Do NOT register each Google API as a separate registry
service entry, as separate entries cause resource clutter, complicate IAM
policy management, and risk hitting registry quota limits."*
3. List all 8 required base FQDN interfaces (plus global
`https://aiplatform.googleapis.com` when calling global Gemini models):
- `https://agentregistry.googleapis.com`
- `https://aiplatform.mtls.googleapis.com`
- `https://cloudresourcemanager.mtls.googleapis.com`
- `https://iamcredentials.mtls.googleapis.com`
- `https://telemetry.mtls.googleapis.com`
- `https://{region}-aiplatform.mtls.googleapis.com`
- `https://{region}-aiplatform.googleapis.com`
- `https://aiplatform.{region}.rep.googleapis.com`
4. Refer to `references/agent-registry.md` §2 for the full command.
### Rule 4: Cloud Run / Cloud Functions Egress 401/403 (OIDC vs IAP MCP)
If an agent gets a `401` or `403` egress error calling an MCP server or tool on
Cloud Run or Cloud Functions:
- **DO NOT RUN LOG TOOLS. RESPOND ON TURN 0 WITH**:
1. Explain that direct Agent Identity (`principalSet://...` / `principal://...`)
to standard Cloud Run OIDC authentication is **not natively supported**.
2. Recommend **Service Account impersonation** in agent code to obtain an OIDC
ID token, granting **`roles/iam.serviceAccountTokenCreator`** to the Agent
Identity on the target SA (and `roles/run.invoker` to that SA on Cloud Run).
3. Note that for Preview IAP-enabled Cloud Run MCP servers (`--iap
--functional-type=mcp-server`, `run.app` short URL), authorize via IAP/UAP
instead of `roles/run.invoker` (see `references/known-issues.md` BKI 21 and
`references/agent-identity.md`).
### Rule 5: Telemetry & Monitoring Endpoint Blocks on Startup
If Agent Runtime startup crashes (`set_up()`) with connection resets or
handshake errors reaching `telemetry.mtls.googleapis.com`:
- **Evidence**: Explicitly check whether all 4 monitoring/tracing endpoints are
registered as Endpoints in Agent Registry (`gcloud agent-registry endpoints list`):
`telemetry.mtls.googleapis.com`, `monitoring.googleapis.com`,
`trace.mtls.googleapis.com`, and `cloudtrace.googleapis.com`.
- **Recommended Fix**:
1. Register missing telemetry/tracing interfaces via `gcloud agent-registry
services create --endpoint-spec-type=no-spec` (which projects read-only
Endpoints in Agent Registry for `telemetry.mtls.googleapis.com`,
`monitoring.googleapis.com`, `trace.mtls.googleapis.com`, and
`cloudtrace.googleapis.com`).
2. Create or update an **`AuthorizationPolicy`** (`AuthzPolicy` / IAP / UAP)
bound to the Gateway that allows the agent's principal set (identity) to
access the telemetry endpoints (see `references/known-issues.md` BKI 23).
### Rule 6: IAP Denial Troubleshooting (`403` / `Egress request is not authorized`)
When logs or symptoms show `403` / `Egress request is not authorized` via IAP:
1. **Check IAP Egressor bindings on the registry entry FIRST** (`roles/iap.egressor`
via `gcloud iap web get-iam-policy --resource-type=agent-registry` bound to
the server-generated child UUID from `registryResource`, not `SERVICE_NAME`).
2. **Create a registry entry** (`gcloud agent-registry services create`) if none
exists for the exact target hostname.
3. **Grant `roles/iap.egressor`** on the registry entry (IAM v1 — `set-iam-policy` requires top-level `{"bindings": [...]}` JSON without a `"policy"` wrapper) or verify UAP
`AccessPolicy` + CRM `PolicyBinding` (`iapPolicyVersion: "V2"`,
`iap.googleapis.com/resources.egressViaIAP`; see `references/policies.md` §2).
4. **Check IAP audit logs** (`protoPayload.serviceName="iap.googleapis.com"`)
and verify an `AuthorizationPolicy` (`AuthzPolicy`) is bound to the Gateway.
5. **Explicitly warn**: *"Do NOT use `roles/iap.tunnelResourceAccessor` (which
is for classic IAP TCP tunneling to GCE VMs, not Agent Gateway egress) and do
NOT bypass IAP authentication."*
### Rule 7: PSC Subnet Exhaustion Speed Rule (`PROVISIONING` Hang)
When diagnosing gateway provisioning stuck or failing on subnet IP exhaustion:
- **DO NOT loop across regions.** Run ONLY in the target region (default `us-central1`):
1. `gcloud network-services agent-gateways list --location=us-central1`
2. `gcloud network-services agent-gateways describe <GW> --location=us-central1`
3. `gcloud compute network-attachments describe <NA> --region=us-central1`
4. `gcloud compute networks subnets describe <SUBNET> --region=us-central1`
- Check free IP count (`Usable - Allocated = Free`) **before** recommending any
Network Attachment deletion; flag that a `/28` subnet is easily exhausted and
recommend expanding the CIDR range to at least `/26` (`known-issues.md` BKI 19).
### Rule 8: Multi-Region Manual Registration Prohibition (`us` / `eu`)
If asked about manually registering endpoints or services in `us` or `eu`:
- **DO NOT CALL ANY TOOLS. RESPOND ON TURN 0**:
1. *"Manual endpoint/service registration is NOT supported in `us` or `eu`
multi-region locations (`us` and `eu` are read-only roll-up locations for
auto-discovered resources)."* (Explicitly name BOTH `us` and `eu`.)
2. *"Register manually in a specific region (e.g., `us-central1`) or `global`."*
### Rule 9: VPC Service Controls (VPC-SC) Perimeter & ACT `ALL_TRAFFIC`
When diagnosing VPC-SC perimeter blocks or external API hangs under VPC-SC:
1. Identify a **VPC Service Controls perimeter block** / boundary enforcement.
2. Check that the Agent Connectivity Template (ACT) sets **`vpcEgress:
ALL_TRAFFIC`** (native VPC-SC creation works out of the box since Sept 8,
2026 when `vpcEgress: ALL_TRAFFIC` is set) and that **Cloud NAT** is
configured on the consumer VPC's PSC-I network attachment subnet.
3. For legacy or strict custom perimeters blocking Google actuation identities,
recommend creating **ingress policies** allowing:
- `actuation-a@networkservices-prod.iam.gserviceaccount.com`
- `cloud-aiplatform-pipeline-robot-prod@system.gserviceaccount.com`
4. Explicitly state: *"Do NOT disable VPC Service Controls or delete perimeters."*
Refer to `references/known-issues.md` BKI 18 & 28.
### Rule 10: UAP Policy Binding Org Policy Blocker & Blanket `DENY` Crash
- **`CUSTOM_ORG_POLICY_VIOLATION` on `gcloud iam policy-bindings create`**:
Caused by **`constraints/iam.managed.disableAccessPolicyBinding`** (note: some
docs misspell this plural). Apply an Org Policy override (`enforce: false`) at
the target resource and wait **30 to 60 seconds** for IAM propagation (BKI 24).
- **Startup crash after UAP `destination.is_registered == false` `DENY`**:
Explain that the blanket `DENY` blocked internal/unauthenticated SDK bootstrap
and metadata calls (such as Cloud Resource Manager project lookups) during
Reasoning Engine init; remove or scope the blanket `DENY` rule (BKI 5).
### Rule 11: Agent Gateway Dual-Registry & Jurisdiction Invariants
When configuring or validating `registries` on an Agent Gateway:
1. An Agent Gateway supports a **maximum of two registries**.
2. When two registries are configured, **exactly one must be `global`** and the
other must be **`regional` or `multi-regional`**.
3. Binding two regional registries (e.g., `us-central1` + `europe-west1`), two
multi-regionals, two globals, or a mismatched jurisdiction (e.g., `us-central1`
gateway + `eu` registry) is invalid and rejected with an **HTTP 400**
validation error (`references/agent-gateway.md` §4, BKI 26).
### Rule 12: Cross-Project Runtime-to-Gateway Binding Diagnosis
When Reasoning Engine in Project 1 fails to bind to a Gateway in Project 2:
1. **Deploying Identity**: Needs `networkservices.agentGateways.use` and
`networkservices.agentGateways.get` (or `roles/networkservices.viewer`) in Project 2.
2. **Vertex AI Service Agent**: Grant `roles/networkservices.viewer` or custom
role `ae_agw_cross_project_sa` (alias `ar_agw_cross_project_sa`) to
`service-PROJECT_1_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com` in Project 2.
3. **Regional Colocation**: Verify both runtime and gateway are in the **same region**.
4. **CAA Opt-Out**: Set `GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES`
to `False` (`references/known-issues.md` BKI 10, `references/agent-gateway.md` §11).
### Rule 13: Downstream SWP + PBR vs. Explicit Forward HTTPS Proxy
Distinguish the two supported consumer-VPC proxy architectures:
- **Pattern A — Transparent Next-Hop SWP + PBR** (no client `HTTPS_PROXY` needed):
1. Explain that **PSC endpoints cannot be route next-hops**, **SWP behind PSC
Service Attachments only supports explicit proxy mode (not transparent
next-hop mode)**, and **static routes cannot be used because Network
Attachments cannot have VM network tags**.
2. Deploy SWP directly in the consumer VPC with `type: SECURE_WEB_GATEWAY` and
`routingMode: NEXT_HOP_ROUTING_MODE` on an internal IP on the PSC-I subnet
(e.g., `10.20.1.250`), with a `/26` `REGIONAL_MANAGED_PROXY` `ACTIVE` subnet.
3. Configure **Policy-Based Routing (PBR)** matching source CIDR `10.20.1.0/24`
to `--next-hop-ilb-ip=10.20.1.250` (priority 200) + fallback PBR (1000).
4. Create **Cloud NAT with `ENDPOINT_TYPE_SWG`** (`nats create ... --endpoint-types=ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG`),
and allowlist `<region>-aiplatform.mtls.googleapis.com` in SWP CEL (BKI 33).
- **Pattern B — Explicit Forward HTTPS Proxy (`HTTPS_PROXY` + L4 `AuthzPolicy`)**:
1. Without L4 bypass, `HTTPS_PROXY=https://proxy.corp.internal:443` fails on
`HTTP CONNECT` with **HTTP `404`** because Agent Gateway's L7 HTTP manager
terminates TLS and rejects nested `CONNECT`.
2. Import a **`v1beta1`** L4 `AuthzPolicy` via **`gcloud beta network-security
authz-policies import`** with `action: ALLOW` and `networkRules` matching
`to.operations[].snis` (omit `target.loadBalancingScheme` and `ports`; max 5 rules;
omit `from` or include `7.0.0.0/8` + PSC-I CIDR in `from.sources[].ipBlocks`).
3. Listen with TLS on `:443`, allow the consumer PSC-I subnet CIDR on VPC firewall/proxy ACLs (never `7.0.0.0/8`),
set `NO_PROXY`/`no_proxy` to `.googleapis.com,googleapis.com,metadata.google.internal,169.254.169.254,localhost,127.0.0.1`,
bundle `agentGatewayCard.rootCertificates` + Private CA in container env
vars (`SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`), and warn L4 `ALLOW` bypasses
L7 IAP/UAP, Model Armor, SGP, and `httpRules` for matched SNIs (BKI 34).
### Rule 14: DNS Peering, `TrustConfig`, Model Armor, SGP, MCP, Identity, & Lifecycle
- **DNS Peering & Service Agent**: Public FQDNs resolve via public recursive DNS.
Private DNS requires `dnsPeeringConfig` (`domains` array with trailing `.`; ACT
uses string `targetNetwork` only, whereas inline `AgentGateway.networkConfig.dnsPeeringConfig`
also requires `targetProject`). Cloud DNS caps total peering hops at **2**
(Gateway consumes Hop 1 → max 1 consumer peering hop; a 2nd hop fails preflight
or returns `SERVFAIL` → `503`, BKI 35). Grant `roles/dns.peer`, `roles/dns.reader`,
`roles/compute.networkViewer`, and `roles/compute.networkUser` to
`service-GATEWAY_PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com`
(and `compute.networkAttachments.use` to caller, BKI 9). Never use authoritative `"."` private root zones (`"."` requires a Cloud DNS Private Forwarding Zone).
- **Private CA `TrustConfig` & Immutable ACT**: Set `egressNetworkConfig.tlsConfig.trustConfig`
**with `additionalRoots: PUBLICLY_TRUSTED_ROOTS`** (omitting breaks `*.googleapis.com`).
ACT fields are immutable — create a new ACT and rebind via `PATCH` with
`updateMask=agentConnectivityTemplate` (BKI 6).
- **Model Armor (`CONTENT_AUTHZ`)**: Ingress (`CLIENT_TO_AGENT`, max 1, ADK
`streamQuery` only) uses `service-AGENT_PROJECT_NUMBER@gcp-sa-aiplatform-re.iam.gserviceaccount.com`;
Egress (`AGENT_TO_ANYWHERE`, max 4) uses `service-GATEWAY_PROJECT_NUMBER@gcp-sa-dep.iam.gserviceaccount.com`.
Scope `httpRules` `when` to exclude gRPC and streams **>60 seconds** (`Stream removed`, BKI 13).
- **Semantic Governance Policies (SGP)**: Uses `gcp-sa-aiplatform`, non-streaming
LLM calls only, `.contains()` + `!request.headers['content-type'].startsWith('application/grpc')`
in `when`, and full-map updates on `PATCH ?updateMask=metadata` so
`sgpEnforcementMode: "DRY_RUN"` and `sgpUserIntentMatching` are preserved (BKI 38).
- **Native MCP, Identity, Trace, & Teardown**: Set `baseProtocolMethodsOption:
MATCH_BASE_PROTOCOL_METHODS` on MCP `ALLOW` rules (BKI 39). Orgless trust
domains use `agents.global.proj-PROJECT_NUMBER.system.id.goog` (`proj-`, never
`project-`); never grant `roles/aiplatform.expressUser` or project-wide
`roles/aiplatform.user` to Agent Identities. For Cloud Trace (`TelemetryPolicy`),
always recommend enabling `cloudtrace.googleapis.com` (`gcloud services enable cloudtrace.googleapis.com`)
and granting `roles/cloudtrace.agent` to `compute-system`, `gcp-sa-networksecurity`,
and `gcp-sa-agentgateway` (see `references/agent-gateway.md` §8.3 and `references/field-manual.md` Step 14.4). Tear down in strict 7-step order
(workloads → UAP bindings → `AuthzPolicy` → extensions → `AgentGateway` → ACT →
VPC) and use unique gateway IDs if deletion tombstones collide (BKIs 25, 30).
## Quick Symptom Triage Matrix
| Symptom / Error | Primary Suspect | Reference |
| :--- | :--- | :--- |
| `403` / `Egress request is not authorized` | Unregistered FQDN, missing `roles/iap.egressor` / UAP binding, or PAB | Rules 4, 6; `references/policies.md` §2; BKIs 4, 7, 8, 15 |
| `HTTP 404` on `HTTP CONNECT` (`HTTPS_PROXY`) | Missing `gcloud beta` L4 `AuthzPolicy` (`networkRules` `snis`) | Rule 13B; `references/agent-gateway.md` §6.3; BKI 34 |
| `HTTP 498` immediately after binding runtime | Enforcing gateway bound before allowlisting essential platform APIs | `references/agent-gateway.md` §2; BKI 37 |
| `500` / `PERMISSION_DENIED` / `Stream removed` | Model Armor SA roles (`gcp-sa-dep` vs `gcp-sa-aiplatform-re`) or 60s stream cap | Rule 14; `references/policies.md` §12; BKI 13 |
| `503` / `NXDOMAIN` / `SERVFAIL` on private host | >2-hop DNS peering, authoritative `"."` zone, Packet Intercept, or SWP | Rules 13A, 14; `references/agent-gateway.md` §3, §6; BKIs 33, 35, 36 |
| `Config validation failed` / `PERMISSION_DENIED` on import | Disabled `agentregistry.googleapis.com`, missing caller/`gcp-sa-agentgateway` IAM, or bad NA URI | Rule 14; BKIs 9, 20, 26 |
| `HTTP 409 ABORTED` / `400 already being used` | Active control-plane LRO mutex (~2 min), tombstone collision, or reverse teardown | `references/agent-gateway.md` §9, §10; BKIs 25, 29, 30 |
| Startup crash (`reasoning_engine_stderr`) | Blocked telemetry/CRM bootstrap, UAP blanket `DENY`, or SGP gRPC interception | Rules 5, 10, 14; BKIs 1, 5, 17, 23, 38 |
## When to use this skill
Trigger on Agent Gateway, Agent Connectivity Templates (ACT), Agent Registry,
Agent Identity, IAP/UAP policies, Model Armor, Semantic Governance Policies
(SGP), SWP/Explicit Proxy egress, Private CA `TrustConfig`, Cloud DNS peering,
Cloud Trace `TelemetryPolicy`, or Gemini Enterprise / Agent Runtime / GKE /
Cloud Run gateway bindings. Do **not** use for generic Google Cloud IAM, GCS,
GCE, or networking issues unrelated to the Agent Platform stack.
## Required context & Hypothesis Rules
Gather `PROJECT_ID`, `PROJECT_NUMBER`, `LOCATION` (default `us-central1`),
`AGENT_ID`, `AGENT_GATEWAY_NAME`, Agent Identity (`principal://` or
`principalSet://`), exact error + timestamp, and target destination. If missing,
ask or state unknowns using placeholders — never scan across projects or loop
over regions. Before Step 1 queries, formulate **at most 3 hypotheses** anchored
to *"Why did it start failing now?"* (e.g., recent Terraform/config changes).
## Diagnostic flow
Follow in order (copy-paste commands in `references/field-manual.md`):
- **Step 0 — Pre-Flight & Access**: Evaluate Rules 1–14. Verify project access
(`gcloud projects describe $PROJECT_ID`).
- **Step 1 — Agent & Startup Logs**: Classify error (`403`, `404 CONNECT`, `498`,
`500`, `503`, crash, timeout). Check PSC subnet IPs, ACT `ALL_TRAFFIC` + Cloud
NAT, and `agentGatewayCard.rootCertificates` CA trust.
- **Step 2 — Gateway Logs**: Query `networkservices.googleapis.com/Gateway`
(filtering `-httpRequest.requestMethod="CONNECT"` when inspecting L7 requests)
to find the exact failing SNI/hostname and `serviceExtensionsInfo`.
- **Step 3 — IAP / Model Armor / SGP Logs**: Check `iapPolicyVersion` (`V1` vs
`V2`), `DRY_RUN` vs enforced, Model Armor callout status, or
`logs/semantic-governance-policy` verdicts and rationales.
- **Step 4 — Registry State**: Verify exact hostname permutations in
`gcloud agent-registry {services,endpoints,mcp-servers,agents} list` and
confirm dual-registry + jurisdiction rules.
- **Step 5 — Identity & Policies**: Check `roles/iap.egressor` via
`--resource-type=agent-registry` on the child UUID (V1), UAP
`AccessPolicy`/`PolicyBinding` + `constraints/iam.managed.disableAccessPolicyBinding`
(V2), PAB overrides, and least-privilege Agent Identity roles (`proj-` for orgless).
- **Step 6 — AuthzPolicy & Extensions**: Verify L4 `networkRules` vs L7
`httpRules`, MCP `MATCH_BASE_PROTOCOL_METHODS`, Model Armor / SGP `when`
exclusions, `ExtensionBinding` scope, and policy caps (max 4 egress, max 1 ingress `CONTENT_AUTHZ`).
- **Step 7 — Connectivity, DNS, & TLS**: Verify ACT `TrustConfig`
(`PUBLICLY_TRUSTED_ROOTS`), `gcp-sa-agentgateway` IAM, <=2 DNS peering hops,
no Packet Intercept on the consumer VPC, and SWP/Explicit Proxy settings.
- **Step 8 — PrincipalSet & Trace Verification**: Test 1:1 `principal://`
binding if `principalSet://` lags; for Cloud Trace, enable `cloudtrace.googleapis.com`, verify `v1beta1` `TelemetryPolicy` (`telemetryTarget` referencing `agentGateways/*` and object `parentBasedSampling: {enabled: true, samplingRate: 1.0}`, never string `ENABLED`), and grant `roles/cloudtrace.agent` to `service-<PROJECT_NUMBER>@compute-system.iam.gserviceaccount.com`, `service-<PROJECT_NUMBER>@gcp-sa-networksecurity.iam.gserviceaccount.com`, and `service-<PROJECT_NUMBER>@gcp-sa-agentgateway.iam.gserviceaccount.com`.
## Tools & Layered References
Use `mcp__gcloud__run_gcloud_command` (or `gcloud --quiet`),
`mcp__gcloud-observability__list_log_entries` (or `gcloud logging read`),
`mcp__google-dev-knowledge__search_documents` / `get_documents` / `answer_query`,
and `curl` REST GETs, plus bundled references (load only the smallest set needed):
- [references/field-manual.md](references/field-manual.md) — read first for operational commands & log queries
- [references/known-issues.md](references/known-issues.md) — BKIs #1–#13, #15–#39 for fast pattern matches
- [references/agent-gateway.md](references/agent-gateway.md) — topologies, ACT, DNS, TLS, SWP/Explicit Proxy, Trace, teardown
- [references/policies.md](references/policies.md) — L4/L7 `AuthzPolicy`, MCP, UAP v3beta, Model Armor, SGP
- [references/agent-registry.md](references/agent-registry.md) — `services` vs projected `endpoints`, 9 API families, jurisdictions
- [references/agent-identity.md](references/agent-identity.md) — 3-identity delegation, Cloud Run OIDC vs IAP MCP, WIF
## Output report
Always produce a read-only diagnostic report using this exact structure:
```markdown
# Agent Platform Diagnostic — <one-line summary>
## Context
- Project: <id> (<number>) | Location: <region>
- Agent: <agent_id> | Gateway: <gateway_name>
- Symptom: <exact error message and when it started>
## Evidence gathered
- Agent log query: <filter, summary>
- Gateway log query: <filter, exact failing hostname / extension status>
- IAP / Policy log query: <filter, decision + enforcement mode>
- Registry & Policy state: <entries, AuthzPolicy bindings, roles/iap.egressor or UAP>
## Root cause hypothesis
<ranked root cause(s)>
## Why this fits the evidence
<connect log/config evidence to root cause>
## Recommended fix
<ordered gcloud / curl / YAML / Terraform changes for the user to apply>
## What to verify after the fix
<verification queries>
## Open questions / unknowns
<missing context or unverified items>
## Appendix: Raw Logs & Verified Links
- **Cloud Logging Filter**: <exact copy-pasteable filter or deep link>
- **Raw Logs**: <untruncated Agent, Gateway, and IAP/Policy log entries>
```
## Principles
- **Exact hostname match first**: Compare gateway log hostnames directly against Agent Registry.
- **Layered default-deny**: Registry → Gateway `AuthzPolicy` → Extension → IAP/UAP/Model Armor/SGP → PAB (PAB overrides IAM Allow).
- **L4 bypass vs L7 governance**: L4 `networkRules` enables `HTTP CONNECT` explicit proxies (`:443`) but bypasses L7 IAP, Model Armor, and SGP for matched SNIs.
- **Read-only, single-region, non-interactive**: Pull evidence first, never mutate resources, check `us-central1` unless logs indicate otherwise, and pass `--quiet`.
## Supporting Links
- [Agent Gateway Overview](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/agent-gateway-overview.md.txt)
- [Configure VPC Connectivity & DNS](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/set-up-vpc-connectivity.md.txt)
- [Delegate Authorization & MCP](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/delegate-authorization.md.txt)
- [Configure Model Armor](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/configure-model-armor.md.txt)
- [Configure Semantic Governance](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/policies/configure-semantic-governance.md.txt)
- [Monitor & Trace Agent Gateway](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/monitor-agent-gateway.md.txt)
- [Deploy Agent Gateway Runtime](https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-gateway-runtime-deploy.md.txt)
- [Troubleshoot Agent Gateway](https://docs.cloud.google.com/gemini-enterprise-agent-platform/troubleshooting/troubleshoot-agent-gateway.md.txt)
- [Troubleshoot IAM Policies (UAP)](https://docs.cloud.google.com/gemini-enterprise-agent-platform/troubleshooting/troubleshoot-iam-policies-uap.md.txt)
agent-gateway.md 55.0 KB
# Agent Gateway — Debugging Reference
Curated from Google Cloud's Gemini Enterprise Agent Platform architecture.
Focused on what a debugger needs to triage failed requests, routing issues, and
provisioning blocks on Agent Gateway and Agent Connectivity Templates (ACT).
## Table of Contents
- [TL;DR for debugging](#tldr-for-debugging): Lines 24-94
- [1. Architecture & Control Plane](#1-architecture--control-plane): Lines 95-118
- [2. Deployment Modes & Topologies](#2-deployment-modes--topologies): Lines 119-163
- [3. Agent Connectivity Template (ACT), Cloud DNS Peering, & Private CA](#3-agent-connectivity-template-act-cloud-dns-peering--private-ca): Lines 164-290
- [4. Dual-Registry Gateway Binding Rules](#4-dual-registry-gateway-binding-rules): Lines 291-340
- [5. Cloud NAT & Egress IP Mechanics](#5-cloud-nat--egress-ip-mechanics): Lines 341-380
- [6. Downstream Egress Proxies: Next-Hop SWP + PBR vs. Explicit HTTPS Proxy](#6-downstream-egress-proxies-next-hop-swp--pbr-vs-explicit-https-proxy): Lines 381-681
- [7. Delegated Authorization, Model Armor, SGP, & Native MCP](#7-delegated-authorization-model-armor-sgp--native-mcp): Lines 682-742
- [8. Logging, Monitoring, & Cloud Trace](#8-logging-monitoring--cloud-trace): Lines 743-808
- [9. Common Failure Modes & Troubleshooting Guide](#9-common-failure-modes--troubleshooting-guide): Lines 809-825
- [10. Reference Gateway, ACT Specifications, & Ordered Teardown](#10-reference-gateway-act-specifications--ordered-teardown): Lines 826-890
- [11. Cross-Project Centralized Governance Architecture](#11-cross-project-centralized-governance-architecture): Lines 891-1018
--------------------------------------------------------------------------------
## TL;DR for debugging
1. **Control Plane & Infrastructure**: Managed under Network Services
(`networkservices.googleapis.com`). Google-managed Agent Gateway proxy
infrastructure runs in Google-managed infrastructure outside your consumer
project.
> **Important:** All configuration changes, deployments, and debugging must
> be performed strictly on consumer-project resources.
2. **Native VPC-SC Support Mandates ACT in `ALL_TRAFFIC` Mode**: As of
September 8, 2026, Agent Gateway creation inside a VPC-SC perimeter works
natively out of the box when the gateway binds to an Agent Connectivity
Template (ACT) configured with `vpcEgress: ALL_TRAFFIC`. In `ALL_TRAFFIC`
mode, all outbound packets from runtime containers are captured and tunneled
through the PSC-I Network Attachment into the consumer VPC.
3. **The Cloud NAT Egress Prerequisite (Silent Black Hole)**: Under `vpcEgress:
ALL_TRAFFIC`, external public Internet traffic exiting the PSC-I Network
Attachment routes through the consumer VPC. The consumer VPC subnet **MUST**
have Cloud NAT configured; otherwise outbound SaaS/REST calls hang and time out.
4. **Google Front End (GFE) Bypass Exception**: Traffic directed to Google APIs
or Cloud Run default domains (`*.run.app`) does NOT exit through Cloud NAT.
Google's network routes Google IP ranges internally via Private Google Access.
5. **Dual-Registry & Jurisdiction Invariants**: Agent Gateway supports linking
up to **two** Agent Registries:
- Exactly **one** registry **MUST be `global`**.
- The second can be **`regional`** (e.g., `us-central1`) or
**`multi-regional`** (`us` or `eu`, matching the gateway's geographic
jurisdiction).
- Two regional registries, two multi-regional registries, or a
cross-jurisdiction pairing (`us-central1` + `eu`) fails validation with HTTP `400`.
6. **Concurrent Mutation Lock (`HTTP 409 ABORTED`) & Tombstones**: Submitting
concurrent `PATCH`, `import`, or `delete` operations while an LRO is active
on the same gateway aborts with `HTTP 409 ABORTED: unable to queue the
operation` (~1.5–2 minutes). Reusing a recently deleted gateway name before
cleanup finishes can also collide; poll LROs to completion or use a unique
versioned gateway ID.
7. **Multi-Runtime Sharing vs. In-Place Rebinding**: Multiple Agent Runtime
(Reasoning Engine) instances in the same region **can** share a single
`AGENT_TO_ANYWHERE` gateway (<https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/set-up-agent-gateway.md.txt>), provided gateway
mutations are serialized and essential platform APIs are allowlisted before
binding (binding an enforcing gateway before allowlisting APIs causes
immediate **`HTTP 498`** failures).
8. **Dependency-Ordered Teardown**: Delete bound workloads and UAP
`PolicyBinding` resources first, then `AuthzPolicy` → `AuthzExtension` /
`ExtensionBinding` / `TelemetryPolicy` → `AgentGateway` → `ACT` →
`TrustConfig` / `NetworkAttachment` / VPC, polling each LRO to `done: true`
before proceeding (see §10.3).
9. **Private CA `TrustConfig`, 2-Hop DNS Peering, & Explicit HTTPS Proxy**:
- **Private CA (`TrustConfig` GA)**: Always set `additionalRoots:
PUBLICLY_TRUSTED_ROOTS` alongside `tlsConfig.trustConfig`, and create a
new ACT + `PATCH` the gateway (`updateMask=agentConnectivityTemplate`)
when rotating trust configs.
- **Cloud DNS 2-Hop Limit**: Cloud DNS permits at most **2 peering hops
total** (Agent Gateway consumes Hop 1 → max 1 consumer peering hop; a
2nd consumer hop fails preflight or returns `SERVFAIL` → `503`).
- **Explicit HTTPS Proxy (`HTTPS_PROXY`)**: Requires a `v1beta1` L4
`AuthzPolicy` (`gcloud beta network-security authz-policies import`)
with `networkRules` matching `to.operations[].snis` (omitting
`loadBalancingScheme` and `ports`); otherwise `HTTP CONNECT` fails with
**`HTTP 404`** on the L7 listener (see §6.3).
--------------------------------------------------------------------------------
## 1. Architecture & Control Plane
Agent Gateway acts as the enterprise security gateway and Layer 7 policy
enforcement point for AI agent workloads:
- **Client-to-Agent (ingress):** External clients reaching agents or tools on
Google Cloud.
- **Agent-to-Anywhere (egress):** Agents on Google Cloud reaching external
services, APIs, MCP servers, or peer agents.
### Core Resource Types
| Type | Purpose |
| :--- | :--- |
| `networkservices.agentGateways` | Gateway resource governing Client-to-Agent (`CLIENT_TO_AGENT`) or Agent-to-Anywhere (`AGENT_TO_ANYWHERE`) traffic. |
| `networkservices.agentConnectivityTemplates` | Centralized VPC egress (`ALL_TRAFFIC` / `PRIVATE_RANGES_ONLY`), Private DNS peering, and Private CA `TrustConfig`. |
| `networksecurity.authzPolicies` | Attaches L7 `httpRules`/MCP rules, L4 `networkRules` (`v1beta1`), `CUSTOM` extensions, or `DENY_BY_DEFAULT` to gateways. |
| `networkservices.authzExtensions` / `serviceextensions.extensionBindings` | Attaches IAP/UAP, Model Armor, Semantic Governance Policies (SGP), or custom `ext_proc` extensions. |
| `networkservices.telemetryPolicies` | Preview distributed Cloud Trace sampling configuration (`gcloud beta network-services telemetry-policies`). |
| `certificatemanager.trustConfigs` | Private CA trust stores and self-signed leaf allowlists referenced by ACT `tlsConfig`. |
| `compute.networkAttachments` | PSC-Interface (PSC-I) attachment in the consumer VPC for private and `ALL_TRAFFIC` egress. |
--------------------------------------------------------------------------------
## 2. Deployment Modes & Topologies
### 2.1 Google-Managed vs. Self-Managed Topologies
- **Google-Managed Agent Gateway**: Google operates the Envoy proxy fleet for
Agent Runtime (Reasoning Engines), Gemini Enterprise apps, and IAP-protected
Cloud Run MCP ingress (`governedAccessPath: AGENT_TO_ANYWHERE` or
`CLIENT_TO_AGENT`).
- **Self-Managed Agent Gateway (Secure Web Proxy)**: Customer-managed Secure
Web Proxy instance in the consumer VPC governing GKE pods, Cloud Run jobs/services,
and Token Management Policies (`TokenAggregationPolicy` / `TokenBudgetPolicy`).
### 2.2 Standard Mode (ACT + Consumer VPC) vs. Standalone Mode
- **Standard Mode (Enterprise Isolated)**: Binds `agentConnectivityTemplate`
with a consumer VPC `NetworkAttachment` (PSC-I), optional `dnsPeeringConfig`,
and optional `tlsConfig.trustConfig`. Required for VPC-SC (`vpcEgress:
ALL_TRAFFIC`), private RFC 1918 backends, deterministic Cloud NAT egress IPs,
Next-Hop SWP, Explicit HTTPS Proxies, and Semantic Governance Policies (SGP).
- **Standalone Mode (Google-Managed Public Egress)**: Omits the ACT and
consumer VPC Network Attachment; governs public endpoints cataloged in Agent
Registry over Google-managed networking (not supported for VPC-SC private egress).
### 2.3 Workload Binding Nuances & Bootstrap Sequencing (`HTTP 498`)
- **Bootstrap Allowlist Order (`HTTP 498`)**: Before binding an Agent Runtime
or Gemini Enterprise engine to an enforcing gateway (or flipping `DRY_RUN` to
enforced), register the consolidated `googleapis` service (8 base FQDNs) and
grant UAP/IAP egress permissions. Binding an enforcing gateway before
allowlisting essential platform APIs causes immediate **`HTTP 498`** errors
and startup crashes.
- **Gemini Enterprise App Registration & Binding (`UpdateEngine`)**: Gemini
Enterprise apps (`discoveryengine.googleapis.com`) register into Agent
Registry and bind to an Agent Gateway via `PATCH .../engines/{ENGINE_ID}`
(`UpdateEngine`). Agent Gateways are strictly regional (never `global`):
deploy the gateway in `us-central1` for `global` or `us` Gemini Enterprise
apps and in `europe-west1` for `eu` apps, paired with the matching single
regional Agent Registry (`us-central1` or `europe-west1`), and remove the
binding via `UpdateEngine` before deleting the gateway.
- **Removing a Gateway from Agent Runtime**: Clear the runtime attachment via
`PATCH .../reasoningEngines/{ID}?updateMask=agentGatewayConfig` with an empty
`agentGatewayConfig: {}` body before deleting the gateway.
--------------------------------------------------------------------------------
## 3. Agent Connectivity Template (ACT), Cloud DNS Peering, & Private CA
The Agent Connectivity Template defines the compute model, network isolation,
and DNS topology for agent containers.
### 3.1 Egress Modes: `ALL_TRAFFIC` vs. `PRIVATE_RANGES_ONLY`
| Egress Mode | Network Path | VPC-SC | Use Case |
: : : Compatible? : :
| :------------------------ | :---------------- | :------------ | :----------- |
| **`ALL_TRAFFIC`** | Outbound TCP/UDP | **YES | Enterprise |
: : packets are : (Mandatory)** : production :
: : captured and : : environments :
: : tunneled through : : requiring :
: : the PSC-I Network : : VPC-SC :
: : Attachment into : : perimeter :
: : the consumer VPC. : : compliance :
: : External DNS : : and :
: : queries resolve : : controlled :
: : to synthetic PSC : : egress. :
: : VIP : : :
: : `240.0.0.2\:443`. : : :
| **`PRIVATE_RANGES_ONLY`** | Directs only RFC | **NO** | Dev/test |
: : 1918 traffic : : workloads :
: : (`10.0.0.0/8`, : : where public :
: : `172.16.0.0/12`, : : egress does :
: : `192.168.0.0/16`) : : not need VPC :
: : through PSC-I. : : inspection :
: : Public internet : : or VPC-SC :
: : traffic exits : : compliance. :
: : directly from the : : :
: : Google runtime. : : :
### 3.2 Consumer VPC Network Attachment (PSC-I) & Preflight Requirements
The Network Attachment bridges the Google-managed gateway fleet into the consumer VPC:
- **Subnet Configuration**:
- `purpose: PRIVATE` with `privateIpGoogleAccess: true`.
- **Subnet Sizing**: Minimum `/26` (recommended `/24`). **Never use `/28`** —
concurrent rollouts and dynamic PSC-I interfaces exhaust `/28` subnets.
- **No Consumer VPC Packet Intercept**: Do **not** attach a Network Security
`InterceptDeploymentGroup` / Packet Intercept policy to the consumer VPC
hosting the PSC-I subnet; intercepted gateway return packets drop with HTTP `503`.
- **Attachment Settings**: `connectionPreference: ACCEPT_AUTOMATIC`, residing in
the **exact same region** as the ACT and Agent Gateway (`projects/PROJECT_ID/regions/REGION/networkAttachments/NAME`).
- **Mandatory IAM Grants**:
1. **Deploying Caller**: Needs `compute.networkAttachments.use` (e.g.,
`roles/compute.networkAdmin` or custom role) on the Network Attachment;
otherwise ACT/gateway import fails preflight validation.
2. **Gateway & Extension Service Agents on Subnet/Project**: Grant
`roles/compute.networkUser` on the PSC-I subnet to **both**:
- `service-GATEWAY_PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com`
(also grant `roles/compute.networkViewer` on the VPC host project)
- `service-GATEWAY_PROJECT_NUMBER@gcp-sa-dep.iam.gserviceaccount.com`
### 3.3 Cloud DNS Architecture, Peering Schemas, & 2-Hop Peering Limit
- **Default Resolution**: Without `dnsPeeringConfig`, Agent Gateway resolves
target hostnames using **public recursive DNS** only; private Cloud DNS zones
in the consumer VPC are invisible until DNS peering is configured.
- **Schema Difference — ACT vs. Inline `AgentGateway`**:
- **ACT (`egressNetworkConfig.dnsPeeringConfig`)**: Accepts **only**
`domains` (YAML array of FQDNs **with trailing dots**, e.g., `["corp.internal."]`)
and string `targetNetwork` (`projects/VPC_PROJECT_ID/global/networks/VPC_NAME` —
**do NOT add `targetProject`**, and omit deprecated `accessTypes: [PRIVATE]`).
- **Inline `AgentGateway` (`networkConfig.dnsPeeringConfig`)**: Configured
as a sibling of `networkConfig.egress` when not using an ACT; requires
`domains`, `targetNetwork`, **and** `targetProject`.
- **Mandatory DNS Peering Service Agent IAM**: Grant **`roles/dns.peer`** and
**`roles/dns.reader`** (plus `roles/compute.networkViewer`) on the target
VPC project to **`service-GATEWAY_PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com`**
(do not grant only to `gcp-sa-networkservices`, which is not the Agent
Gateway DNS peering identity).
- **Cloud DNS 2-Hop Total Transitive Peering Limit (`SERVFAIL` → `503`)**:
Cloud DNS supports at most **2 peering hops end-to-end**:
`[Google-Managed Gateway VPC] --(Hop 1: ACT dnsPeeringConfig)--> [Consumer VPC A] --(Hop 2: Cloud DNS Peering)--> [Hub DNS VPC B]`.
If `VPC B` peers a **3rd** hop to `VPC C` (`Gateway -> VPC A -> VPC B -> VPC C`),
Cloud DNS drops transitive resolution: control-plane preflight either rejects
the peering chain or runtime queries return `SERVFAIL` (surfaced by Envoy as
`503 UF,URX` / `Upstream resolution failure`). **Fix**: Point
`dnsPeeringConfig.targetNetwork` directly at the authoritative DNS Hub VPC
(reducing hops to 1) or host an authoritative Cloud DNS forwarding/private
zone directly in `VPC A` or `VPC B`.
- **`"."` Root Zone Rule — Authoritative Forbidden (`NXDOMAIN`) vs. Private Forwarding Allowed**: Never peer to a
VPC hosting a private **authoritative** Cloud DNS zone for `"."` (root) without
explicit `*.googleapis.com` overrides — it shadows public & Private Google Access
resolution with `NXDOMAIN` (`503`). By contrast, `domains: ["."]` is supported
when the spoke VPC hosts a `"."` Cloud DNS **Private Forwarding Zone** forwarding
queries to a hub resolver.
### 3.4 Private CA & Self-Signed TLS (`TrustConfig` — GA)
- **When Needed**: Upstream private HTTPS endpoints or internal load balancers
signed by an internal Private CA or self-signed certificate fail Envoy TLS
verification (`CERTIFICATE_VERIFY_FAILED` / `503 UF`) unless trusted on the ACT.
- **Configuration**: Create a Certificate Manager `TrustConfig` in the **same
project and region** (`trustStores` for Private CA root/intermediate chains
or `allowlistedCertificates` for self-signed leaf certs) and attach it under
`egressNetworkConfig.tlsConfig`:
```yaml
egressNetworkConfig:
networkAttachment: projects/PROJECT_ID/regions/REGION/networkAttachments/agw-na
vpcEgress: ALL_TRAFFIC
tlsConfig:
trustConfig: projects/PROJECT_NUMBER/locations/REGION/trustConfigs/private-ca-trust
additionalRoots: PUBLICLY_TRUSTED_ROOTS
```
- **Critical Trap 1 (`additionalRoots: PUBLICLY_TRUSTED_ROOTS`)**: Omitting
`additionalRoots` defaults to `NO_ADDITIONAL_ROOTS`, stripping Mozilla/Google
public WebPKI roots and immediately breaking TLS to all public APIs and
`*.googleapis.com`!
- **Critical Trap 2 (ACT Immutability)**: `tlsConfig.trustConfig`,
`networkAttachment`, and `dnsPeeringConfig` cannot be mutated in-place on a
bound ACT. Create a **new** ACT (`agw-act-v2`) and rebind the gateway via
`PATCH .../agentGateways/{NAME}?updateMask=agentConnectivityTemplate` (or
`gcloud network-services agent-gateways import`), then delete the old ACT.
- **Runtime Container CA Bundle (`agentGatewayCard.rootCertificates`)**: For
runtimes requiring explicit trust of the gateway's regional TLS inspection CA,
extract `agentGatewayCard.rootCertificates` via `gcloud network-services
agent-gateways describe GATEWAY_NAME --location=REGION --format="value(agentGatewayCard.rootCertificates)"`
(there is no `export-cacerts` subcommand on `gcloud network-services`).
--------------------------------------------------------------------------------
## 4. Dual-Registry Gateway Binding Rules
Agent Gateway supports linking up to **two** Agent Registries in its
`registries` list:
```yaml
registries:
- //agentregistry.googleapis.com/projects/PROJECT_NUMBER/locations/global
- //agentregistry.googleapis.com/projects/PROJECT_NUMBER/locations/us-central1
```
> **Best-Practice Recommendation (Single Regional Registry):** Production
> deployments (including both Agent Runtime and Gemini Enterprise apps) should
> associate each `AgentGateway` with a **single regional Agent Registry
> instance** in the **same project and region** as the gateway
> (`//agentregistry.googleapis.com/projects/PROJECT_ID/locations/REGION`, using
> `us-central1` for `global` or `us` Gemini Enterprise apps and `europe-west1`
> for `eu` apps; both `PROJECT_ID` and numeric `PROJECT_NUMBER` are accepted).
> Multi-registry configurations remain permitted by the Network Services API
> validator up to the ceiling below.
### Network Services Validation Invariants
Agent Gateway control-plane validation enforces:
1. **Cardinality**: Maximum of two registries are permitted (`<= 2`).
2. **Mandatory Global Invariant**: If two registries are configured, **exactly
one of them MUST be `global`**.
3. **Second Registry Scope**: The second registry can be either **`regional`**
(matching the gateway's exact region, e.g., `us-central1`) OR
**`multi-regional`** (`us` or `eu`).
4. **Jurisdiction Alignment**: A regional gateway in `us-*` cannot bind an `eu`
multi-region registry, and an `europe-*` gateway cannot bind a `us`
multi-region registry (`us` and `eu` are read-only roll-up views for
auto-discovered resources; manual registration requires `global` or a
concrete region).
5. **Disallowed Configurations**:
- Two regional registries (e.g., `us-central1` + `europe-west1`): Rejected (`HTTP 400`).
- Two multi-regional registries (e.g., `us` + `eu`): Rejected (`HTTP 400`).
- One regional + one multi-regional (without `global`): Rejected (`HTTP 400`).
- Two global registries: Rejected (`HTTP 400`).
Validation error message on violation:
```text
maximum of two registries are supported. When it's two registries, one of them must be global, the other one can be either regional or multi-regional.
```
--------------------------------------------------------------------------------
## 5. Cloud NAT & Egress IP Mechanics
In `ALL_TRAFFIC` mode, outbound traffic behavior depends on the target domain:
```
[ Reasoning Engine ]
│
▼ (Captured via PSC-I)
[ Consumer PSC-I Subnet ] ── (10.20.1.0/24)
│
├─── Google APIs / *.run.app ──────► [ Private Google Access ] ──► [ GFE ]
│
└─── External Internet / SaaS ─────► [ Cloud Router + NAT ] ──► [ Static IP: 203.0.113.10 ]
```
### 5.1 Routing Path
- Packets exit the Network Attachment on the consumer subnet
(`agw-psci-subnet`, e.g., `10.20.1.0/24`).
- VPC route tables direct internet-bound CIDRs (`0.0.0.0/0`) through the
default internet gateway via Cloud Router (`agw-nat-router`) and Cloud NAT
(`agw-cloud-nat`).
### 5.2 Deterministic Static Egress IP
- Outbound calls to external destinations (`api.weather.gov`, `api.ipify.org`,
SaaS APIs) are Source-NAT'd (SNAT) to the Cloud NAT static regional IP
(for example, `203.0.113.10` in `us-central1` or `198.51.100.20` in
`europe-west1`) so external partners can allowlist a deterministic source IP.
### 5.3 Google Front End (GFE) Bypass Exception
- Traffic directed to Google APIs or Cloud Run default domains (`*.run.app`)
does **not** exit through Cloud NAT.
- Google's Andromeda SDN intercepts traffic matching Google IP ranges and
routes it internally to GFE via Private Google Access, bypassing the Cloud
NAT static external IP.
--------------------------------------------------------------------------------
## 6. Downstream Egress Proxies: Next-Hop SWP + PBR vs. Explicit HTTPS Proxy
Enterprise consumer VPCs use one of two downstream proxy patterns behind an Agent
Gateway: **Pattern A (Transparent Next-Hop SWP + Policy-Based Routing)** when
full Layer 7 Agent Gateway governance must precede VPC egress without client
proxy settings, or **Pattern B (Explicit Forward HTTPS Proxy + L4 `AuthzPolicy`)**
when routing via `HTTPS_PROXY` to an explicit Squid/SWP/corporate proxy on `:443`.
### 6.1 Pattern A Platform Constraints & Routing Incompatibilities
1. **PSC Endpoints Cannot Be Route Next-Hops**: Google Cloud route tables (both
static routes and Policy-Based Routes) do **not** permit Private Service
Connect (PSC) forwarding rules (`--load-balancing-scheme=""`) or service
attachments as next hops.
2. **SWP via PSC Service Attachment Lacks Next-Hop Mode**: Publishing Secure
Web Proxy behind a PSC Service Attachment operates strictly in **Explicit
Proxy Mode** (`HTTP CONNECT`). Transparent Layer 3/Layer 4 IP packets
emerging from an Agent Gateway Network Attachment lack `HTTP CONNECT`
framing (if an explicit proxy is required instead of Next-Hop SWP, configure
`HTTPS_PROXY` plus a `v1beta1` L4 `AuthzPolicy` as shown in §6.3).
3. **Static Route Tag Defect**: Next-hop routing mode with static routes
requires VM network instance tags (`--tags`). Network Attachments
(`compute network-attachments`) are consumer network interfaces, not VM
instances, and cannot bear network tags. Consequently, static routes cannot
match or steer traffic originating from an Agent Gateway Network Attachment.
### 6.2 The Working Architecture: Next-Hop SWP + Policy-Based Routing (PBR)
The only functional pattern for intercepting transparent egress from an Agent
Gateway Network Attachment is deploying Next-Hop SWP directly in the consumer VPC
and steering traffic via Policy-Based Routing:
```
[ Reasoning Engine ]
│
▼ (ACT vpcEgress: ALL_TRAFFIC)
[ Agent Gateway ]
│
▼ (PSC-I / Network Attachment, e.g. 10.20.1.0/24)
[ Consumer Subnet ]
│
├──► [ Policy-Based Route (PBR) ] ── (Matches source: 10.20.1.0/24, dest: 0.0.0.0/0)
│ │
│ ▼ (Priority 200: next-hop-ilb-ip = 10.20.1.250)
│ [ Next-Hop SWP Gateway (SECURE_WEB_GATEWAY) ]
│ │
│ ▼ (Proxy-Only Subnet: REGIONAL_MANAGED_PROXY /26)
│ [ GatewaySecurityPolicy (L7 CEL Rules) ]
│ │
│ ▼ (Outbound Internet SNAT)
│ [ Cloud NAT (ENDPOINT_TYPE_SWG) ]
│ │
│ ▼
│ [ External Internet / Public APIs ]
│
└──► [ Fallback PBR (Priority 1000) ] ──► DEFAULT_ROUTING
```
#### 1. SWP Gateway Deployment
SWP must be deployed directly in the consumer VPC with `type: SECURE_WEB_GATEWAY`
and `routingMode: NEXT_HOP_ROUTING_MODE`, listening on an internal IP on the
PSC-I subnet (e.g. `10.20.1.250`):
> **Important:** The Network Services API requires `type: SECURE_WEB_GATEWAY`.
> Passing `type: SECURE_WEB_PROXY` is rejected by schema validation.
```yaml
# swp-gateway.yaml
name: projects/PROJECT_ID/locations/REGION/gateways/swp-gateway
type: SECURE_WEB_GATEWAY
routingMode: NEXT_HOP_ROUTING_MODE
addresses:
- 10.20.1.250
subnetwork: projects/PROJECT_ID/regions/REGION/subnetworks/agw-psci-subnet
gatewaySecurityPolicy: projects/PROJECT_ID/locations/REGION/gatewaySecurityPolicies/swp-policy
ports:
- 443
- 80
```
Import via GA gcloud CLI:
```bash
gcloud network-services gateways import swp-gateway \
--source=swp-gateway.yaml \
--location=REGION \
--project=PROJECT_ID
```
#### 2. Envoy Proxy-Only Subnet Prerequisite
SWP runs on Envoy proxy instances managed within the consumer VPC. It requires a
dedicated proxy-only subnet in the target region:
```bash
gcloud compute networks subnets create swp-proxy-subnet \
--purpose=REGIONAL_MANAGED_PROXY \
--role=ACTIVE \
--region=REGION \
--network=VPC_NAME \
--range=10.20.2.0/26 \
--project=PROJECT_ID
```
#### 3. Policy-Based Routing (PBR) Configuration
Because Network Attachments cannot have VM network tags, routing must use PBR to
match traffic based on the source CIDR of the Network Attachment subnet:
- **Primary PBR (`agw-psci-to-swp-pbr`, Priority 200)**: Matches source CIDR
`10.20.1.0/24` (the PSC-I subnet where the Network Attachment resides) and
destination `0.0.0.0/0`, steering traffic to the SWP internal IP:
```bash
gcloud network-connectivity policy-based-routes create agw-psci-to-swp-pbr \
--network=projects/PROJECT_ID/global/networks/VPC_NAME \
--source-range=10.20.1.0/24 \
--destination-range=0.0.0.0/0 \
--next-hop-ilb-ip=10.20.1.250 \
--priority=200 \
--project=PROJECT_ID
```
- **Default Fallback PBR (`agw-pbr-default-routing`, Priority 1000)**: Directs
all non-matching or bypass traffic to default VPC routing:
```bash
gcloud network-connectivity policy-based-routes create agw-pbr-default-routing \
--network=projects/PROJECT_ID/global/networks/VPC_NAME \
--destination-range=0.0.0.0/0 \
--priority=1000 \
--project=PROJECT_ID
```
#### 4. L7 Policy Enforcement (GatewaySecurityPolicy)
Security rules attached to the SWP Gateway evaluate outbound traffic using CEL
(Common Expression Language) expressions. Rules allow authorized domains and
deny unauthorized traffic with HTTP 403 or TLS connection drops:
```cel
inUrlList(host(), ['api.weather.gov', 'api.ipify.org', 'REGION-aiplatform.mtls.googleapis.com'])
```
Or explicit hostname equality:
```cel
host() == 'api.weather.gov' || host() == 'api.ipify.org' || host() == 'REGION-aiplatform.mtls.googleapis.com'
```
#### 5. Cloud NAT Interdependence (`ENDPOINT_TYPE_SWG`)
SWP Envoy proxy instances reside on the private proxy-only subnet and do not
possess external IP addresses. Outbound internet egress from SWP requires a
Cloud NAT gateway **created** with `ENDPOINT_TYPE_SWG` (`--endpoint-types` is
immutable and **not** supported on `gcloud compute routers nats update` — create
a new NAT gateway or recreate an existing VM-only NAT):
```bash
gcloud compute routers nats create agw-cloud-nat \
--router=agw-nat-router \
--region=REGION \
--nat-all-subnet-ip-ranges \
--auto-allocate-nat-external-ips \
--endpoint-types=ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG \
--project=PROJECT_ID
```
> **Note:** In `NEXT_HOP_ROUTING_MODE`, the Google Cloud SWP control plane may
> autogenerate `swg-autogen-router-{network_id}` and `swg-autogen-nat` with
> `natIpAllocateOption: AUTO_ONLY` and `ENDPOINT_TYPE_SWG`. Outbound public IP
> queries (e.g. `api.ipify.org`) reflect the SWG NAT's auto-allocated public
> IPs rather than the VPC's manual Cloud NAT static IP, validating end-to-end
> traversal through SWP.
#### 6. The ADK Streaming Query Session Trap (HTTP 503)
In `ALL_TRAFFIC` ACT mode, Vertex AI Agent Development Kit (ADK) streaming
queries attempt to initialize session state via:
```text
POST https://<region>-aiplatform.mtls.googleapis.com/v1beta1/projects/.../locations/<region>/reasoningEngines/...:createSession
```
Because `ALL_TRAFFIC` forces all runtime egress through the Agent Gateway into
the Network Attachment, PBR intercepts and routes this session creation call to
SWP. If `<region>-aiplatform.mtls.googleapis.com` is omitted from the
GatewaySecurityPolicy allowlist, SWP rejects it (`default_denied`). This causes
ADK streaming queries to crash with:
```text
HTTP 503 Service Unavailable: remote connection failure
```
while direct, non-streaming `query()` calls (which do not create sessions)
continue to succeed. Always allowlist the regional aiplatform endpoint in SWP!
#### 7. Observability & Log Verification
SWP logs are emitted under resource type `networkservices.googleapis.com/Gateway`:
```
resource.type="networkservices.googleapis.com/Gateway"
resource.labels.gateway_name="swp-gateway"
resource.labels.location="REGION"
```
Verify `enforcedGatewaySecurityPolicy.matchedRules` with `action` (`ALLOWED` vs
`DENIED`), `tlsSniHostname`, `clientIp`, and `httpRequest.status`.
### 6.3 Pattern B: Explicit Forward HTTPS Proxy (`HTTPS_PROXY` + L4 `AuthzPolicy`)
Agent Runtime (Reasoning Engine) and containerized workloads **do** support
explicit forward HTTPS proxies (`HTTPS_PROXY=https://proxy.corp.internal:443`)
when Agent Gateway passes matching TLS SNIs through at Layer 4.
#### Why `HTTP CONNECT` Fails with `HTTP 404` by Default
By default, Agent Gateway's Envoy listener terminates TLS and passes decrypted
streams to an L7 HTTP connection manager (`loopback_tls`). When an SDK or `curl`
sends `CONNECT api.example.com:443 HTTP/1.1` inside the TLS session to an
explicit proxy, the L7 HTTP manager rejects nested `CONNECT` requests with
**`HTTP 404 Not Found`** (`curl: (56) CONNECT tunnel failed, response 404`).
#### Required 5-Part Configuration
1. **Import a `v1beta1` L4 `AuthzPolicy` (`networkRules`)**: Route the proxy's
SNI hostname to Agent Gateway's L4 TCP/SNI pass-through filter chain using
**`gcloud beta`** (`networkRules` is available only in `v1beta1`, supports
at most 5 rules and 10 `snis` per operation, is mutually exclusive with
`httpRules`, and **must omit** both `target.loadBalancingScheme` and `ports`;
either omit `from` or include **both** `7.0.0.0/8` and your PSC-I CIDR in
`networkRules[].from.sources[].ipBlocks`, and never set `from.sources[].resources`
on Agent Gateway targets):
```yaml
# proxy-l4-authz-policy.yaml
name: allow-explicit-proxy-l4
policyProfile: REQUEST_AUTHZ
action: ALLOW
target:
resources:
- projects/PROJECT_ID/locations/REGION/agentGateways/AGENT_GATEWAY_NAME
networkRules:
- to:
operations:
- snis:
- exact: "proxy.corp.internal"
```
```bash
gcloud beta network-security authz-policies import allow-explicit-proxy-l4 \
--source=proxy-l4-authz-policy.yaml \
--location=REGION \
--project=PROJECT_ID
```
2. **Configure TLS Listener on Port `:443` & Consumer VPC / Proxy Source ACLs**:
- Agent Gateway forwards egress on `:443`; configure the explicit proxy
(for example, Squid `https_port 443 tls-cert=...` or Explicit SWP on
`:443`) with a DNS record resolvable via `dnsPeeringConfig`.
- **Two-Plane Source IP Rule**: In your **consumer VPC GCE ingress firewall**
and **Squid `acl localnet src`**, allow **only your consumer PSC-I Network
Attachment subnet CIDR** (e.g., `10.20.1.0/24` — packets exiting the
PSC-I NIC into your VPC are sourced from the PSC-I subnet, never
`7.0.0.0/8`). Use `7.0.0.0/8` **only** inside Agent Gateway's
`AuthzPolicy` `networkRules[].from.sources[].ipBlocks` when `from` is set.
3. **Set `HTTPS_PROXY` and Mandatory `NO_PROXY` Exclusions on the Agent**:
- `HTTPS_PROXY="https://proxy.corp.internal:443"` (and lowercase `https_proxy`)
- `NO_PROXY=".googleapis.com,googleapis.com,metadata.google.internal,169.254.169.254,localhost,127.0.0.1"`
(and lowercase `no_proxy`). Omitting `169.254.169.254` /
`metadata.google.internal` breaks ADC token fetches; omitting
`.googleapis.com` tunnels Google API mTLS calls into the proxy.
4. **Trust Both CAs Inside the Runtime Container**:
Because L4 pass-through does **not** terminate TLS at Agent Gateway, ACT
`tlsConfig.trustConfig` does **not** validate the explicit proxy's
certificate. Combine `agentGatewayCard.rootCertificates` (for direct L7
Google API/MCP calls) **and** your Private CA root (for the explicit proxy
and any SSL-bumped upstream) into your container's CA bundle
(`SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`, `GRPC_DEFAULT_SSL_ROOTS_FILE_PATH`).
5. **Governance Trade-Off Warning**:
Traffic matching an L4 `networkRules` `ALLOW` policy **bypasses Layer 7
Agent Gateway governance** (IAP/UAP authorization, Model Armor
`CONTENT_AUTHZ`, Semantic Governance Policies, and `httpRules`) for that
proxy SNI. Enforce URL/domain filtering on the downstream proxy itself, or
use Pattern A (Next-Hop SWP + PBR) if full L7 Agent Gateway inspection is
required before VPC egress.
| Dimension | Pattern A: Transparent Next-Hop SWP + PBR (§6.2) | Pattern B: Explicit HTTPS Proxy + L4 `AuthzPolicy` (§6.3) |
| :--- | :--- | :--- |
| Container `HTTPS_PROXY` / `NO_PROXY` | None required (transparent L3/L4) | Required (`https://proxy:443` + `NO_PROXY` / `no_proxy`) |
| Agent Gateway Policy Layer | Full L7 (IAP/UAP, Model Armor, SGP, `httpRules`) | L4 SNI pass-through (`networkRules` bypasses L7 for proxy SNI) |
| Private CA Validation | Gateway ACT `tlsConfig.trustConfig` | Container trust bundle (`SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE`) |
| Routing Mechanism | Consumer VPC PBR → `NEXT_HOP_ROUTING_MODE` SWP + `ENDPOINT_TYPE_SWG` | Direct PSC-I routing + DNS peering to `:443` explicit proxy |
--------------------------------------------------------------------------------
## 7. Delegated Authorization, Model Armor, SGP, & Native MCP
Agent Gateway evaluates policies attached via `networksecurity.googleapis.com`
`authzPolicies` (never legacy `authorizationPolicies`). Always **omit
`target.loadBalancingScheme`** when targeting `agentGateways/*`.
### 7.1 Precedence, Profiles, & Cardinality Limits
- **Evaluation Order (`REQUEST_AUTHZ`)**: `CUSTOM` → `DENY` → `ALLOW` →
`DENY_BY_DEFAULT`. (`REQUEST_AUTHZ` executes before `CONTENT_AUTHZ`.)
- **Policy Caps**: Egress (`AGENT_TO_ANYWHERE`) supports up to **4**
`CONTENT_AUTHZ` policies; Ingress (`CLIENT_TO_AGENT`) supports at most **1**
`CONTENT_AUTHZ` policy.
### 7.2 Native MCP `AuthzPolicy` (`MATCH_BASE_PROTOCOL_METHODS`)
When restricting MCP tools via `httpRules[].to.operations[].mcp`, `ALLOW` rules
**must** set `baseProtocolMethodsOption: MATCH_BASE_PROTOCOL_METHODS`. Leaving
the default (`SKIP_BASE_PROTOCOL_METHODS`) blocks MCP session handshakes
(`initialize`, `ping`, `notifications/initialized`) when paired with `DENY_BY_DEFAULT`.
### 7.3 IAP Unified Access Policy (UAP / Policy V2)
- Set `iapPolicyVersion: "V2"` in the IAP `AuthzExtension` `metadata` (with
optional `iamEnforcementMode: "DRY_RUN"`; omit `iamEnforcementMode` or set
`"ENFORCE"` for active blocking).
- Rules grant FQDN permission `iap.googleapis.com/resources.egressViaIAP`
using singular `"operation"` and plural `"conditions": {"iap.googleapis.com": {...}}`
(see `references/policies.md` §2).
### 7.4 Model Armor Content Security (`CONTENT_AUTHZ`)
- **Ingress (`CLIENT_TO_AGENT`)**: Executes as
**`service-AGENT_PROJECT_NUMBER@gcp-sa-aiplatform-re.iam.gserviceaccount.com`**
(`roles/modelarmor.calloutUser` on agent project; `roles/modelarmor.user` on
template project). Inspects ADK `reasoningEngines.streamQuery` payloads only.
- **Egress (`AGENT_TO_ANYWHERE`)**: Executes as
**`service-GATEWAY_PROJECT_NUMBER@gcp-sa-dep.iam.gserviceaccount.com`**
(`roles/modelarmor.calloutUser` + `roles/serviceusage.serviceUsageConsumer`
on gateway project; `roles/modelarmor.user` on template project).
- **60-Second Stream Deadline**: Envoy enforces a hard **60-second total stream
deadline** on `CONTENT_AUTHZ` callouts. Scope `httpRules[].when` to exclude
`application/grpc` and streams >60s to avoid `Stream removed` / HTTP `500`/`504`.
### 7.5 Semantic Governance Policies (SGP)
- Evaluates natural-language constraints and user intent via **the LLM in the
semantic governance policy engine** (`gcloud beta ai semantic-governance-policy-engine` /
`semantic-governance-policies`, running under
`service-PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com`).
- Requires `AGENT_IDENTITY` + `agent_gateway_config` at runtime creation, ACT +
DNS peering (avoiding reserved SGP subnets `10.0.0.0/24`, `10.0.1.0/24`,
`10.0.2.0/24`), non-streaming model invocation (streamed responses return no
verdict or an error), and a non-streaming CEL `when` filter using `.contains()`:
`"!request.headers['content-type'].startsWith('application/grpc') && (request.path.contains(':generateContent') || request.path.contains(':rawPredict') || request.path.contains('/v1/messages') || request.path.contains('/chat/completions'))"`.
- **Wholesale `metadata` Overwrite Trap**: `PATCH .../authzExtensions/{NAME}?updateMask=metadata`
(or `import`) replaces the entire `metadata` map — always supply all active
keys (`sgpEnforcementMode: "DRY_RUN"`, `sgpUserIntentMatching`) together.
--------------------------------------------------------------------------------
## 8. Logging, Monitoring, & Cloud Trace
### 8.1 Monitored Resource & Log Analytics Prerequisite
Upgrade the `_Default` log bucket to **Log Analytics** to populate the Cloud
Console Agent Gateway Observability dashboard.
```text
resource.type="networkservices.googleapis.com/Gateway"
resource.labels.location="REGION"
resource.labels.gateway_name="AGENT_GATEWAY_NAME"
```
### 8.2 Inspecting L7 Decisions & Suppressing Outer `CONNECT 240.0.0.2:443` Noise
In ACT `ALL_TRAFFIC` mode, every connection logs an outer tunnel `CONNECT 240.0.0.2:443`
entry alongside the inner TLS-inspected request. Filter `-httpRequest.requestMethod="CONNECT"`
when triaging inner L7 status codes, or keep `CONNECT` when checking L4 pass-through:
```bash
# Inner L7 4xx/5xx decisions (suppressing outer 240.0.0.2:443 CONNECT entries)
gcloud logging read \
'resource.type="networkservices.googleapis.com/Gateway" AND resource.labels.gateway_name="AGENT_GATEWAY_NAME" AND -httpRequest.requestMethod="CONNECT" AND httpRequest.status>=400' \
--project=PROJECT_ID --limit=20 --freshness=1h --format=json
# Semantic Governance Policy (SGP) evaluation verdicts & rationales
gcloud logging read \
'logName="projects/PROJECT_ID/logs/semantic-governance-policy"' \
--project=PROJECT_ID --limit=20 --freshness=1h --format=json
```
### 8.3 Distributed Tracing with Cloud Trace (`TelemetryPolicy` — Preview)
1. Always verify `cloudtrace.googleapis.com` is enabled (`gcloud services enable cloudtrace.googleapis.com`)
and grant `roles/cloudtrace.agent` on the project to **all 3 platform service agents**
(granting `roles/cloudtrace.agent` only to the runtime workload SA emits zero
gateway spans; also grant to `service-PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com`
if using SGP):
- `service-PROJECT_NUMBER@compute-system.iam.gserviceaccount.com`
- `service-PROJECT_NUMBER@gcp-sa-networksecurity.iam.gserviceaccount.com`
- `service-PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com`
2. Import a schema-valid `TelemetryPolicy` via **`gcloud beta`**:
```yaml
# tracing-policy.yaml
name: "projects/PROJECT_ID/locations/REGION/telemetryPolicies/agw-trace-policy"
displayName: "Tracing policy for Agent Gateway traffic"
telemetryTarget:
resources:
- "//networkservices.googleapis.com/projects/PROJECT_ID/locations/REGION/agentGateways/AGENT_GATEWAY_NAME"
tracingConfiguration:
samplingRate: 1.0
parentBasedSampling:
enabled: true
samplingRate: 1.0
```
```bash
gcloud beta network-services telemetry-policies import agw-trace-policy \
--source=tracing-policy.yaml \
--location=REGION \
--project=PROJECT_ID
```
--------------------------------------------------------------------------------
## 9. Common Failure Modes & Troubleshooting Guide
| Symptom | Root Cause | Remediation |
| :--- | :--- | :--- |
| Gateway mutation fails with `HTTP 409 ABORTED: unable to queue the operation` | Resource-level LRO mutex active from concurrent `PATCH`/`import`/`delete`, or recent gateway tombstone | Poll active LRO to completion (~1.5–2 min) before retrying; use a new gateway ID if recreating immediately after delete. |
| `HTTP 404` on `HTTP CONNECT` when using `HTTPS_PROXY` | Missing `v1beta1` L4 `AuthzPolicy` (`networkRules` `snis`); L7 HTTP manager rejects nested `CONNECT` | Import `ALLOW` `AuthzPolicy` with `networkRules[].to.operations[].snis` via `gcloud beta` (omit `loadBalancingScheme` & `ports`; see §6.3). |
| `HTTP 498` immediately after binding runtime to gateway | Enforcing gateway bound before allowlisting essential Google APIs (`googleapis` service + UAP/IAP policy) | Register the 8 base Google API FQDNs and verify UAP/IAP allow rules (or `DRY_RUN`) before binding the runtime. |
| Outbound SaaS calls hang/time out under ACT `ALL_TRAFFIC` | Consumer VPC PSC-I subnet lacks Cloud NAT | Deploy Cloud Router and Cloud NAT covering the PSC-I subnet. |
| `503` / `SERVFAIL` or `NXDOMAIN` on private or Google API hosts | >2 total Cloud DNS peering hops, missing `gcp-sa-agentgateway` `roles/dns.peer`, or authoritative `"."` private root zone | Limit peering to <=1 consumer hop (2 total), grant `roles/dns.peer` + `roles/dns.reader` to `gcp-sa-agentgateway`, and replace any authoritative `"."` private root zone with specific domain suffixes or a Cloud DNS Private Forwarding Zone. |
| TLS fails to `*.googleapis.com` after attaching `TrustConfig` | Omitted `additionalRoots: PUBLICLY_TRUSTED_ROOTS` on ACT `tlsConfig` | Create a new ACT including `additionalRoots: PUBLICLY_TRUSTED_ROOTS` and `PATCH` `agentConnectivityTemplate` on the gateway. |
| Private VPC backend returns `503` despite valid DNS, routes, & firewall | Network Security Packet Intercept (`InterceptDeploymentGroup`) enabled on consumer VPC | Move the Agent Gateway Network Attachment to a consumer VPC without Packet Intercept, or exclude the PSC-I subnet. |
| `ACT` or `AuthzExtension` deletion fails with `HTTP 400 ... already being used` | Child resources deleted out of order while `AgentGateway` or `AuthzPolicy` still references them | Follow the 7-step teardown sequence in §10.3, polling each deletion LRO to completion. Open a Google Cloud Support case if an orphaned backend reference persists after zero gateways remain. |
| Agent Runtime deletion fails with `HTTP 400 FAILED_PRECONDITION` | Active sessions or memories exist on the Reasoning Engine | Pass `?force=true` on the `DELETE .../reasoningEngines/{ID}?force=true` REST call. |
| REST API egress returns `403` on `/api/v2/tickets.json` | Unregistered UAP CEL rule matched `/api/v2/tickets` without `.json` / `?` variants | Match exact path, `.json`, `/` subpaths, and `?` query strings on `destination.unregistered.path`. |
--------------------------------------------------------------------------------
## 10. Reference Gateway, ACT Specifications, & Ordered Teardown
### 10.1 Agent Connectivity Template YAML (`act.yaml`)
```yaml
name: projects/PROJECT_ID/locations/REGION/agentConnectivityTemplates/agw-all-traffic-template
accessPath: AGENT_TO_ANYWHERE
deploymentModel: CENTRALIZED
egressNetworkConfig:
networkAttachment: projects/PROJECT_ID/regions/REGION/networkAttachments/agw-network-attachment
vpcEgress: ALL_TRAFFIC
dnsPeeringConfig:
domains:
- corp.internal.
targetNetwork: projects/PROJECT_ID/global/networks/agw-consumer-vpc
tlsConfig:
trustConfig: projects/PROJECT_NUMBER/locations/REGION/trustConfigs/private-ca-trust
additionalRoots: PUBLICLY_TRUSTED_ROOTS
```
Import via GA CLI:
```bash
gcloud network-services agent-connectivity-templates import agw-all-traffic-template \
--source=act.yaml \
--location=REGION \
--project=PROJECT_ID
```
### 10.2 Agent Gateway YAML (`gateway.yaml`)
```yaml
name: projects/PROJECT_ID/locations/REGION/agentGateways/agw-prod-gateway
agentConnectivityTemplate: projects/PROJECT_NUMBER/locations/REGION/agentConnectivityTemplates/agw-all-traffic-template
googleManaged:
governedAccessPath: AGENT_TO_ANYWHERE
protocols:
- MCP
registries:
- //agentregistry.googleapis.com/projects/PROJECT_ID/locations/REGION
```
Import via GA CLI:
```bash
gcloud network-services agent-gateways import agw-prod-gateway \
--source=gateway.yaml \
--location=REGION \
--project=PROJECT_ID
```
### 10.3 Dependency-Ordered 7-Step Public Teardown Sequence
Deleting resources out of order causes `HTTP 400 FAILED_PRECONDITION` (`already being used`). Always tear down in this order and wait for each LRO to finish:
1. **Unbind or delete workloads**: Unbind (`?updateMask=agentGatewayConfig` / Gemini Enterprise `UpdateEngine`) or delete bound Reasoning Engines (`?force=true` if sessions exist).
2. **Delete UAP `PolicyBinding` then `AccessPolicy`**: Poll `gcloud iam policy-bindings describe` until `404` (10–30s consistency window) before deleting `AccessPolicy`.
3. **Delete `AuthzPolicy` resources**: Run `gcloud network-security authz-policies delete` (or `gcloud beta` for L4 `networkRules` policies) and wait for LRO completion *before* deleting extensions or gateways.
4. **Delete `AuthzExtension`, `ExtensionBinding`, & `TelemetryPolicy`**: Remove extensions (`gcloud service-extensions authz-extensions delete` / `gcloud beta service-extensions extension-bindings delete`) and tracing policies (`gcloud beta network-services telemetry-policies delete`). (If Token Management Policies are used on self-managed SWP, delete `CostPerTokenPolicy` → `TokenBudgetPolicy` → `TokenAggregationPolicy`.)
5. **Delete `AgentGateway`**: Run `gcloud network-services agent-gateways delete` and poll the operation to `done: true`.
6. **Delete `AgentConnectivityTemplate`**: Run `gcloud network-services agent-connectivity-templates delete` only after `gcloud network-services agent-gateways list --location=REGION` confirms zero gateways reference it.
7. **Delete `TrustConfig`, `NetworkAttachment`, Cloud NAT, & Subnet**: Clean up Certificate Manager and VPC networking resources last.
--------------------------------------------------------------------------------
## 11. Cross-Project Centralized Governance Architecture
Google Cloud's Gemini Enterprise Agent Platform supports cross-project bindings from Agent Runtimes (Vertex AI Reasoning Engines) in consumer projects to an Agent Gateway in a Centralized Governance Project.
### 11.1 Three-Tier Project Boundary Model
To separate policy authoring, network security, and runtime execution, enterprise deployments structure responsibilities across three distinct project tiers:
1. **Centralized Governance Project (`AGW_PROJECT_ID`):**
- **Agent Registry (`agentregistry.googleapis.com`):** The authoritative catalog of vetted MCP tools, endpoints, and peer agents. Both Gateway and Registry **MUST** reside in this same project.
- **Agent Gateway (`networkservices.googleapis.com`):** The managed `AGENT_TO_ANYWHERE` gateway instance mediating all outbound agent traffic.
- **Model Armor Templates & IAP/UAP Policies:** Guardrails for request/response DLP inspection, prompt injection detection, and CEL-based authorization.
- **Network Infrastructure:** Egress VPC with a Private Service Connect (PSC-I) Network Attachment, Cloud NAT, and Private DNS peering.
2. **Agent Runtime Projects (`AE_PROJECT_NUMBER`):**
- **Vertex AI Reasoning Engines:** Containerized agent execution environments deployed by product/application teams.
- **Cross-Project Gateway Binding:** Configured in `agentGatewayConfig.agentToAnywhereConfig.agentGateway` pointing directly to the central gateway resource.
- **No Local VPC Required:** Runtimes do not require local VPCs or interconnects; all private traffic tunnels into the governance project's network attachment.
3. **MCP & Service Backend Projects (`MCP_PROJECT_ID`):**
- Host business logic, databases, or microservices (Cloud Run, GKE, Compute Engine). Services are explicitly registered into the central Agent Registry catalog.
### 11.2 Cross-Project IAM Requirements
To bind an Agent Runtime to an Agent Gateway in another project, permissions must be granted to both the deploying caller and the runtime project's service agent:
1. **Deploying Principal (Developer EUC, Cloud Build, or CI/CD Service Account):**
The caller invoking `client.agent_engines.create` or Vertex AI REST API must hold:
- `networkservices.agentGateways.get`
- `networkservices.agentGateways.use`
(or role `roles/networkservices.viewer`) on `projects/AGW_PROJECT_ID/locations/REGION/agentGateways/GATEWAY_NAME`.
2. **Vertex AI Service Agent:**
Grant access to the runtime project's service agent on the governance project (`AGW_PROJECT_ID`):
*Option A: Predefined Role (Network Services Viewer):*
```bash
gcloud projects add-iam-policy-binding "AGW_PROJECT_ID" \
--member="serviceAccount:service-AE_PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com" \
--role="roles/networkservices.viewer"
```
*Option B: Least-Privilege Custom Role (`ae_agw_cross_project_sa` / `ar_agw_cross_project_sa`):*
```bash
gcloud iam roles create ae_agw_cross_project_sa \
--project="AGW_PROJECT_ID" \
--title="AE AGW Cross Project SA" \
--description="Custom role for cross-project service agent to access Agent Gateways and Operations" \
--permissions="networkservices.agentGateways.get,networkservices.operations.get" \
--stage="GA"
gcloud projects add-iam-policy-binding "AGW_PROJECT_ID" \
--member="serviceAccount:service-AE_PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com" \
--role="projects/AGW_PROJECT_ID/roles/ae_agw_cross_project_sa"
```
### 11.3 Agent Runtime Deployment Specification
Deploy the agent runtime referencing the central gateway and disabling bound token sharing via CAA opt-out:
```python
remote_agent = client.agent_engines.create(
agent=local_agent,
config={
"agent_gateway_config": {
"agent_to_anywhere_config": {
"agent_gateway": (
"projects/AGW_PROJECT_ID/locations/REGION/agentGateways/AGENT_GATEWAY_TO_ANYWHERE_NAME"
)
},
},
"identity_type": types.IdentityType.AGENT_IDENTITY,
"env_vars": {
# Opt out of default Context-Aware Access (CAA) token binding to allow
# token validation through cross-project gateway egress
"GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES": False,
},
},
)
```
> **Warning:** **Regional Colocation Invariant:** The Agent Runtime and the Agent Gateway **MUST reside in the exact same Google Cloud region** (e.g., `us-central1`). Cross-region bindings fail control plane validation with `INVALID_ARGUMENT`.
### 11.4 Two-Tier Registry Authorization Model
1. **Tier 1: Baseline Google APIs Access (Coarse-Grained via `principalSet://`):**
All runtimes require baseline access to Google Cloud APIs for discovery, telemetry, and platform operations. Register the consolidated `googleapis` endpoint in the central registry and authorize runtimes using project-level or trust-domain-wide principal sets:
- *Project-Level Scope:* `principalSet://TRUST_DOMAIN/attribute.platformContainer/aiplatform/projects/AE_PROJECT_NUMBER`
- *Trust-Domain-Wide Scope:* `principalSet://TRUST_DOMAIN/*`
- *Role:* `roles/iap.egressor` on the Google APIs endpoint.
> **Important:** **Folder-Level Syntax Limitation:** `attribute.platformContainer/aiplatform/folders/FOLDER_NUMBER` is **not an indexed attribute** in IAM SPIFFE URI evaluation. Scoping must strictly use project-level syntax or Principal Access Boundary (PAB) policies.
2. **Tier 2: Granular MCP Tools & Peer Agents (Fine-Grained via `principal://`):**
For sensitive business tools, grant `roles/iap.egressor` on the specific MCP server resource directly to the individual Reasoning Engine:
`principal://TRUST_DOMAIN/resources/aiplatform/projects/AE_PROJECT_NUMBER/locations/REGION/reasoningEngines/ENGINE_ID`
Optionally restrict with CEL conditions:
```cel
api.getAttribute('iap.googleapis.com/mcp.tool.isReadOnly', false) == true || api.getAttribute('iap.googleapis.com/mcp.toolName', '') == ''
```
### 11.5 Server-Generated Resource ID Extraction Pattern
In Agent Registry, all write operations use `gcloud agent-registry services create`. However, IAP authorization policies **must be bound to the server-generated resource ID** (`agentregistry-00000000-...`), NOT the friendly service name:
```bash
# 1. Fetch server-generated resource ID
REGISTRY_RESOURCE=$(gcloud agent-registry services describe MCP_SERVICE_NAME \
--project="AGW_PROJECT_ID" \
--location="REGION" \
--format='value(registryResource)')
RESOURCE_ID=$(basename "$REGISTRY_RESOURCE")
# 2. Grant roles/iap.egressor on iap_web/agentRegistry/mcpServers/{RESOURCE_ID}
# (Use agents.global.proj-AE_PROJECT_NUMBER.system.id.goog/... if orgless)
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"
```
### 11.6 VPC Service Controls (VPC-SC) Perimeter Bridging
If the Centralized Governance Project (`AGW_PROJECT_ID`) and the Agent Runtime Projects (`AE_PROJECT_NUMBER`) reside in different VPC-SC service perimeters:
1. Establish a **Perimeter Bridge** connecting both perimeters, OR
2. Configure explicit **Ingress and Egress Rules** on both perimeters permitting cross-perimeter communication for:
- `aiplatform.googleapis.com`
- `networkservices.googleapis.com`
- `agentregistry.googleapis.com`
agent-identity.md 33.5 KB
# Agent Identity — Debugging Reference
Reference for diagnosing "who is this request from?" issues on Gemini Enterprise
Agent Platform / Agent Runtime (Reasoning Engines).
Primary source:
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/agent-identity-overview.md.txt>
(mirrored at <https://docs.cloud.google.com/iam/docs/agent-identity-overview.md.txt>)
## Table of Contents
- [TL;DR for debugging](#tldr-for-debugging): Lines 27-69
- [What "agent identity" means (vs service account, vs principal set)](#what-agent-identity-means-vs-service-account-vs-principal-set): Lines 70-112
- [Identity format and trust domains](#identity-format-and-trust-domains): Lines 113-142
- [Principal set forms (for IAM policy debugging)](#principal-set-forms-for-iam-policy-debugging): Lines 143-210
- [How identities are created and bound to ReasoningEngines](#how-identities-are-created-and-bound-to-reasoningengines): Lines 211-280
- [How to inspect / enumerate the identity at runtime](#how-to-inspect--enumerate-the-identity-at-runtime): Lines 281-335
- [Token format / what shows up in logs](#token-format--what-shows-up-in-logs): Lines 336-370
- [Required roles for the identity to function](#required-roles-for-the-identity-to-function): Lines 371-475
- [Granting roles — exact gcloud commands](#granting-roles--exact-gcloud-commands): Lines 476-533
- [Common debugging scenarios](#common-debugging-scenarios): Lines 534-646
- [Code: pulling the bound token via ADC inside the agent](#code-pulling-the-bound-token-via-adc-inside-the-agent): Lines 647-672
- [Quick reference — useful URLs](#quick-reference--useful-urls): Lines 673-700
--------------------------------------------------------------------------------
## TL;DR for debugging
- An "agent identity" is a SPIFFE-based, per-agent principal — not a service
account. It is bound 1:1 to the runtime resource (e.g. a single
`reasoningEngines/<id>`).
- The runtime can use one of three identity modes (`identityType` enum on
`ReasoningEngineSpec`): `IDENTITY_TYPE_UNSPECIFIED` (legacy),
`SERVICE_ACCOUNT`, or `AGENT_IDENTITY`. Default is service-account behavior.
- The actual identity in use at runtime is exposed as `spec.effectiveIdentity`
on the ReasoningEngine resource. Read this first.
- IAM bindings use `principal://...` (single agent) and `principalSet://...`
(group of agents in a trust domain / project / org). The trust domain is
per-org or per-orgless-project and uses
`agents.global.org-<ORG_ID>.system.id.goog` or
`agents.global.proj-<PROJECT_NUMBER>.system.id.goog` (`proj-`, **never**
`project-`).
- The Agent Runtime SDK uses Application Default Credentials, which on the
runtime automatically pull the Agent Identity token from the metadata server
— no explicit code is required for it to take effect.
- A new Agent Identity automatically receives
`roles/aiplatform.agentDefaultAccess` and
`roles/aiplatform.agentContextEditor`, which already cover core model
inference, sessions, and memory. **Never** grant project-level
`roles/aiplatform.expressUser` or `roles/aiplatform.user` to an Agent
Identity (they permit deleting/modifying sibling `ReasoningEngine` resources
and escalating privileges). For standard project quota/observability, grant
only: `roles/serviceusage.serviceUsageConsumer`, `roles/browser`,
`roles/logging.logWriter`, `roles/monitoring.metricWriter`,
`roles/cloudapiregistry.viewer`.
- A `401 UNAUTHENTICATED` from a Google Cloud API in an Agent-Identity-enabled
runtime almost always means Context-Aware Access (mTLS / DPoP token-binding)
is rejecting the call — not an IAM permission problem. Check binding /
egress path before adding roles.
- Service-account mode default is the Google-managed
`service-<PROJECT_NUMBER>@gcp-sa-aiplatform-re.iam.gserviceaccount.com`
(role: `roles/aiplatform.reasoningEngineServiceAgent`). To see it in the IAM
page you must check "Include Google-provided role grants".
- Logs show *both* the agent SPIFFE identity and the end-user identity when an
agent is acting on behalf of a user; only the agent identity when acting on
its own authority.
--------------------------------------------------------------------------------
## What "agent identity" means (vs service account, vs principal set)
Source: <https://docs.cloud.google.com/iam/docs/agent-identity-overview.md.txt>
Agent Identity provides cryptographic, SPIFFE-based identities for agents so
they can authenticate to MCP servers, Google Cloud APIs, the Agent Gateway, and
other agents.
Compared to service accounts:
Property | Service account | Agent Identity
:--------------------------- | :-------------- | :---------------------------
Shared across workloads | Yes (default) | No — 1 per agent resource
Impersonable by other agents | Yes (with role) | No
Long-lived keys allowed | Yes | No (system-managed only)
Token binding | No | Yes (X.509-bound, DPoP)
Identity scope | Project | Tied to runtime resource URI
Three things commonly get conflated when debugging — keep them distinct:
1. **Service account** — `name@project.iam.gserviceaccount.com`. Used when
`identityType` is unset or `SERVICE_ACCOUNT`. Granted via `serviceAccount:`
IAM member.
2. **Agent identity (single agent)** — a SPIFFE principal bound to one
ReasoningEngine. Granted via `principal://<TRUST_DOMAIN>/resources/...`.
3. **Principal set** — a group of agent identities (all agents in a project,
trust domain, or org). Granted via `principalSet://<TRUST_DOMAIN>/...`. Used
to apply common roles (logging, quota, model access) to many agents at once
without per-agent bindings.
### Three-Identity Delegation Architecture
Across Client/Ingress, Agent Runtime/Broker, and Egress/Target Resource trust
boundaries, Google Cloud separates three distinct identity layers:
| Identity Layer | Boundary & Format | Security Role & Audit Behavior |
| :--- | :--- | :--- |
| **1. User identity** | Client → Agent (`CLIENT_TO_AGENT` OAuth / OIDC caller) | Identifies the human caller; evaluated by ingress IAP/UAP and Model Armor. |
| **2. Agent identity** | Agent → Gateway / Cloud APIs (`principal://agents.global.{org-ORG\|proj-NUM}.system.id.goog/resources/...`) | Cryptographic SPIFFE machine identity (24h auto-rotated X.509 cert + DPoP/CAA binding); brokers 2LO/API keys via Auth Manager when acting autonomously. |
| **3. Delegated identity** | Agent → Downstream tool on behalf of user (3LO token via Auth Manager) | Enforces the intersection of agent egress policy + user OAuth scopes; Cloud Audit Logs record **both** the agent SPIFFE identity and the end-user identity. |
--------------------------------------------------------------------------------
## Identity format and trust domains
Source: <https://docs.cloud.google.com/iam/docs/agent-identity-overview.md.txt> and
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/identity-delegation-architecture.md.txt>
- **SPIFFE ID (X.509 SAN)**: `spiffe://<TRUST_DOMAIN>/resources/<SERVICE>/<RESOURCE_PATH>`
- **IAM principal**: `principal://<TRUST_DOMAIN>/resources/<SERVICE>/<RESOURCE_PATH>`
Concrete runtime principal shapes (always use numeric `PROJECT_NUMBER`):
- **Agent Runtime (`ReasoningEngine`)**:
`principal://agents.global.org-123456789012.system.id.goog/resources/aiplatform/projects/9876543210/locations/us-central1/reasoningEngines/1234567890`
- **Gemini Enterprise (`Engine`)**:
`principal://agents.global.org-123456789012.system.id.goog/resources/discoveryengine/projects/9876543210/locations/global/collections/default_collection/engines/my-ge-app`
*(Note: Gemini Enterprise custom/ADK agents may also authenticate with the configured project/custom Service Account depending on connector configuration.)*
- **Cloud Run (`--identity-type=agent-identity`)**:
`principal://agents.global.org-123456789012.system.id.goog/resources/run/projects/9876543210/locations/us-central1/services/my-agent-service`
- **GKE (`iam.gke.io/spiffe-identity-type: agent-identity`)**:
SPIFFE agent identity provisioned via the GKE SPIFFE controller.
Trust domain (auto-provisioned when the Agent Platform API is first enabled):
- Org present: `agents.global.org-<ORGANIZATION_ID>.system.id.goog`
- Orgless project: `agents.global.proj-<PROJECT_NUMBER>.system.id.goog` (`proj-`, **not** `project-`)
Source:
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-identity.md.txt>
--------------------------------------------------------------------------------
## Principal set forms (for IAM policy debugging)
Source: <https://docs.cloud.google.com/iam/docs/principal-identifiers.md.txt>
| Scope | Identifier |
| :-------- | :------------------------------------------------------------------------------------------------------------------------------- |
| Single | `principal://<TRUST_DOMAIN>/resources/<SERVICE>/<RESOURCE_PATH>` |
: agent : :
| All | `principalSet://<TRUST_DOMAIN>/*` |
: agents in : :
: a trust : :
: domain : :
| All | `principalSet://<TRUST_DOMAIN>/attribute.platformContainer/aiplatform/projects/<PROJECT_NUMBER>` |
: agents in : :
: a project : :
| All | `principalSet://agents.global.org-<ORG_ID>.system.id.goog/attribute.platform/aiplatform` |
: agents in : :
: an org : :
| DIY | `principal://iam.googleapis.com/projects/<PROJECT_NUMBER>/locations/global/workloadIdentityPools/<POOL>/subject/ns/<NS>/sa/<SA>` |
: agents : :
: (workload : :
: identity : :
: pool) : :
Tips when debugging:
- If you see
`principalSet://...attribute.platformContainer/aiplatform/projects/<num>` in
a binding, that is *all* agents in that project. A binding here grants every
agent in the project the role — useful for shared roles (logging/quota), bad
for sensitive resources.
- The `attribute.platform/aiplatform` set covers an *entire org*.
### Principal Identifiers in Unified Access Policy (UAP / Policy V2)
Under **Unified Access Policy** (`iam.googleapis.com/v3` `AccessPolicy` and
`PolicyBinding`), principal identifiers are specified directly in the
`rules[].principals` array:
```yaml
# In AccessPolicy rule definition (singular 'operation', NOT 'operations'):
rules:
- description: "Allow project agents to access registered weather service"
principals:
- "principalSet://agents.global.org-123456789012.system.id.goog/attribute.platformContainer/aiplatform/projects/9876543210"
- "principal://agents.global.org-123456789012.system.id.goog/resources/aiplatform/projects/9876543210/locations/us-central1/reasoningEngines/1234567890"
operation:
permissions:
- "iap.googleapis.com/resources.egressViaIAP"
```
Important rules for UAP principal matching:
1. **Direct Principal vs. PrincipalSet**: You can specify either specific
`principal://...` URIs or broad `principalSet://...` group URIs in the
`principals` array.
2. **Audit Log Correlation**: In Cloud Audit Logs
(`protoPayload.authenticationInfo.principalSubject`), the runtime always
logs the exact `principal://` URI of the calling agent, which satisfies
either a direct `principal://` rule or a container-level `principalSet://`
rule.
3. **Service Accounts in UAP**: If an agent runs with a custom Service Account
(`SERVICE_ACCOUNT` mode), the principal string in UAP is
`serviceAccount:name@project.iam.gserviceaccount.com` (or
`principal://iam.googleapis.com/projects/...`).
--------------------------------------------------------------------------------
## How identities are created and bound to ReasoningEngines
Source:
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-identity.md.txt>
Source:
<https://docs.cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1beta1/projects.locations.reasoningEngines.md.txt>
The `IdentityType` enum on `ReasoningEngineSpec`:
- `IDENTITY_TYPE_UNSPECIFIED` — same as `SERVICE_ACCOUNT`. Uses the
`serviceAccount` field if set, else default Agent Runtime Service Agent.
- `SERVICE_ACCOUNT` — same behavior as `IDENTITY_TYPE_UNSPECIFIED`; explicit.
- `AGENT_IDENTITY` — uses Agent Identity. The `serviceAccount` field **must
not be set** when this is selected.
### Create with Agent Identity (Python SDK)
```python
import vertexai
from vertexai import types
from vertexai.agent_engines import AdkApp
# v1beta1 is required for Agent Identity support
client = vertexai.Client(
project=PROJECT_ID,
location=LOCATION,
http_options=dict(api_version="v1beta1"),
)
remote_app = client.agent_engines.create(
agent=AdkApp(agent=agent),
config={
"display_name": "running-agent-with-identity",
"identity_type": types.IdentityType.AGENT_IDENTITY,
"requirements": ["google-cloud-aiplatform[adk,agent_engines]"],
"staging_bucket": f"gs://{BUCKET_NAME}",
},
)
print(f"Effective Identity: {remote_app.api_resource.spec.effective_identity}")
```
### Create identity-only (no agent code yet) so you can pre-grant IAM
```python
remote_app = client.agent_engines.create(
config={"identity_type": types.IdentityType.AGENT_IDENTITY},
)
# Later: agent_engines.update(...) to add code.
```
### Other ways
- ADK CLI: `echo '{"identity_type": "AGENT_IDENTITY"}' >
.agent_engine_config.json; adk deploy ...`
- Agents CLI: `agents-cli deploy --agent-identity`
### What gets auto-provisioned
- A SPIFFE ID and matching X.509 certificate (rotated; valid 24 h).
- `roles/aiplatform.agentDefaultAccess` (basic project logging + model calls).
- `roles/aiplatform.agentContextEditor` (own sessions, memory, sandboxes).
- A workload access token bound to the X.509 cert; an authorization DPoP
proof; an entry in the agent identity pool.
> If `identity_type` is not configured, the runtime falls back to
> service-account mode — preserves backward compatibility for existing IaC
> deployments.
--------------------------------------------------------------------------------
## How to inspect / enumerate the identity at runtime
Source:
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-identity.md.txt>
### Read the effective identity (authoritative)
The `spec.effectiveIdentity` field on the ReasoningEngine GET response is the
single source of truth. Possible shapes (per the REST reference):
- `service-{project_number}@gcp-sa-aiplatform-re.iam.gserviceaccount.com` — `SERVICE_AGENT`
- `{name}@{project_id}.iam.gserviceaccount.com` — `SERVICE_ACCOUNT`
- `agents.global.{org-ORG_ID|proj-PROJECT_NUMBER}.system.id.goog/resources/aiplatform/projects/{project_number}/locations/{location}/reasoningEngines/{re}`
— `AGENT_IDENTITY`
Example REST response excerpt:
```json
{
"spec": {
"effectiveIdentity": "agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/AGENT_ENGINE_ID"
}
}
```
### Google Cloud console
Google Cloud console -> Agent Platform Deployments. The "Identity" column lists
the agent identity for each deployed agent.
### gcloud / curl
REST: `GET projects/PROJECT/locations/LOCATION/reasoningEngines/ID` against the
v1beta1 endpoint, then read `spec.effectiveIdentity`.
```bash
curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT/locations/LOCATION/reasoningEngines/ID" \
| jq '.spec.effectiveIdentity, .spec.identityType, .spec.serviceAccount'
```
### From inside the agent's container
ADC will already be wired up — confirm with a one-shot tool call:
```python
from google.auth import default
creds, project_id = default()
# creds.service_account_email when SA mode; for AGENT_IDENTITY the credential
# is system-attested and tied to the metadata server. Use ADC to call any
# Google API; identity comes from the bound token.
```
--------------------------------------------------------------------------------
## Token format / what shows up in logs
Source:
<https://docs.cloud.google.com/access-context-manager/docs/caa-agent-security.md.txt>
Source:
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-identity.md.txt>
Agent Identity uses two artifacts (not a plain bearer JWT):
1. **X.509 certificate** — issued under a Google-managed trust domain. Embeds
the agent's SPIFFE ID. Used for mTLS to Agent Gateway.
2. **Certificate-bound workload access token** — short-lived OAuth-style token
*cryptographically bound* to the X.509 cert; carries an encrypted
authorization DPoP proof.
Network/auth flow (when Agent Gateway is enabled):
- Agent -> Agent Gateway: mTLS, certificate-bound token.
- Agent Gateway -> Google Cloud API: DPoP (mTLS terminates at the gateway).
- CAA verifies the authorization DPoP proof and the resource DPoP proof were
signed with the same private key from the agent identity pool.
In Cloud Logging:
- Agent acting on its own authority -> entry shows the agent's SPIFFE identity
only.
- Agent acting on behalf of an end user (via auth manager) -> entry shows
*both* the agent identity and the end-user identity.
When grepping logs the SPIFFE identity will look like the
`agents.global.org-...system.id.goog/resources/aiplatform/...` form (no
`spiffe://` scheme on most log fields — it's the principal form).
--------------------------------------------------------------------------------
## Required roles for the identity to function
Source:
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-identity.md.txt>
### Granted automatically on create
- `roles/aiplatform.agentDefaultAccess` — project logging and core model
inference (`aiplatform.endpoints.predict`).
- `roles/aiplatform.agentContextEditor` — scoped access to the agent's own
sessions, memories, and sandboxes.
> **Warning:** **Least-Privilege Guardrail**: Do **NOT** grant project-level
> `roles/aiplatform.expressUser` or `roles/aiplatform.user` to an Agent Identity
> (`principal://` or `principalSet://`). Those roles grant
> `aiplatform.reasoningEngines.{create,delete,update}` across the entire project,
> allowing a compromised agent to overwrite or delete sibling agents and escalate
> privileges across A2A boundaries.
### Recommended baseline (grant manually before/after deploy)
| Role | Why |
| :--- | :--- |
| `roles/serviceusage.serviceUsageConsumer` | Consume project quota + Agent Platform SDK |
| `roles/browser` | Basic Google Cloud project/hierarchy metadata lookup |
| `roles/logging.logWriter` | Emit structured application logs |
| `roles/monitoring.metricWriter` | Emit metrics |
| `roles/cloudapiregistry.viewer` | Discover tools via Cloud API Registry |
### Least-Privilege Agent-to-Agent (A2A) Invocation (`agentInvoker` + IAM Deny)
When Agent A invokes Agent B on Agent Runtime, create a minimal custom role and
bind it **at resource scope on Agent B only** (never project-wide). Because
`gcloud` does not expose a `reasoning-engines` IAM subcommand, perform a
read-modify-write via the Vertex AI v1 REST `:getIamPolicy` and `:setIamPolicy`
methods (preserving existing `bindings` and `etag`):
```bash
gcloud iam roles create agentInvoker \
--project=PROJECT_ID \
--title="Agent Runtime Invoker" \
--permissions="aiplatform.reasoningEngines.query,aiplatform.reasoningEngines.get"
# 1. Fetch existing resource-level IAM policy & etag on Agent B
curl -s -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/TARGET_AGENT_B_ID:getIamPolicy" \
-d '{}'
# 2. Apply updated bindings + etag via REST :setIamPolicy (note: raw REST wraps "policy", unlike gcloud iap web)
curl -s -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/TARGET_AGENT_B_ID:setIamPolicy" \
-d '{
"policy": {
"etag": "ETAG_FROM_GET_IAM_POLICY",
"version": 3,
"bindings": [
{
"role": "projects/PROJECT_ID/roles/agentInvoker",
"members": [
"principal://agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/CALLER_AGENT_A_ID"
]
}
]
}
}'
```
For defense in depth, attach an Organization/Project **IAM Deny policy** denying
`aiplatform.googleapis.com/reasoningEngines.{create,delete,update}` to
`principalSet://agents.global.org-ORGANIZATION_ID.system.id.goog/*`.
### Tool, Gateway, & Cross-Project Roles (often missed)
- `roles/iamconnectors.user` on the `AuthProvider` resource — required for Auth
Manager 2LO/3LO token brokering.
- **IAP egress through Agent Gateway**:
- **Policy V1 (`gcloud iap web`)**: `roles/iap.egressor`
(`iap.webServiceVersions.egressViaIAP`) bound with
`--resource-type=agent-registry`.
- **UAP Policy V2 (`iapPolicyVersion: "V2"`)**:
`iap.googleapis.com/resources.egressViaIAP` in an `AccessPolicy` bound to
the governance project/folder/org.
- **Cross-project Agent Runtime → Central Agent Gateway**: In the central
gateway project, grant the deploying user `networkservices.agentGateways.use`
+ `networkservices.agentGateways.get` (`roles/networkservices.viewer`), and
grant the runtime project's AI Platform Service Agent
(`service-RUNTIME_PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com`)
`roles/networkservices.viewer` or a custom role (`ae_agw_cross_project_sa` /
`ar_agw_cross_project_sa` with
`networkservices.agentGateways.get,networkservices.operations.get`). Both
runtime and gateway must reside in the **same region**.
### Service-account mode (legacy default)
Default SA:
`service-<PROJECT_NUMBER>@gcp-sa-aiplatform-re.iam.gserviceaccount.com`
(`roles/aiplatform.reasoningEngineServiceAgent`). Custom SAs require explicit
least-privilege roles (e.g., `roles/storage.objectViewer` on staging buckets).
--------------------------------------------------------------------------------
## Granting roles — exact gcloud commands
Source:
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-identity.md.txt>
### Single agent
```bash
gcloud RESOURCE_TYPE add-iam-policy-binding RESOURCE_ID \
--member="principal://agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/AGENT_ENGINE_ID" \
--role="ROLE_NAME"
```
### All agents in a project (with org)
```bash
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="principalSet://agents.global.org-ORGANIZATION_ID.system.id.goog/attribute.platformContainer/aiplatform/projects/PROJECT_NUMBER" \
--role=roles/serviceusage.serviceUsageConsumer
# Repeat for browser, cloudapiregistry.viewer, logging.logWriter, monitoring.metricWriter.
```
### All agents in an orgless project (`proj-`, NOT `project-`)
```bash
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="principalSet://agents.global.proj-PROJECT_NUMBER.system.id.goog/attribute.platformContainer/aiplatform/projects/PROJECT_NUMBER" \
--role="ROLE_NAME"
```
### All agents across an org
```bash
gcloud RESOURCE_TYPE add-iam-policy-binding RESOURCE_ID \
--member="principalSet://agents.global.org-ORGANIZATION_ID.system.id.goog/attribute.platform/aiplatform" \
--role="ROLE_NAME"
```
### List the roles attached to a deployed (SA-mode) agent
```bash
gcloud projects get-iam-policy PROJECT_ID_OR_NUMBER \
--flatten="bindings[].members" \
--filter="bindings.members:serviceAccount:PRINCIPAL" \
--format="value(bindings.role)"
```
For Agent-Identity mode, filter against the principal string instead:
```bash
gcloud projects get-iam-policy PROJECT_ID \
--flatten="bindings[].members" \
--filter="bindings.members:principal://agents.global.org-ORG.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/AGENT_ID" \
--format="value(bindings.role)"
```
--------------------------------------------------------------------------------
## Common debugging scenarios
### "Who is this request from?" — start here
1. `GET` the ReasoningEngine, read `spec.identityType` and
`spec.effectiveIdentity`.
2. If `identityType` is `AGENT_IDENTITY`, the principal in IAM/audit logs will
be the SPIFFE-style `agents.global....`. If `SERVICE_ACCOUNT`, expect a
`service-...@gcp-sa-aiplatform-re.iam.gserviceaccount.com` (default) or
custom SA email.
3. Search audit logs for that exact string.
### `401 UNAUTHENTICATED` from a Google Cloud API
Source: <https://docs.cloud.google.com/iam/docs/troubleshoot-auth-manager.md.txt>
```
{ "error": { "code": 401, "status": "UNAUTHENTICATED",
"message": "Request had invalid authentication credentials..." } }
```
This is usually **Context-Aware Access** rejecting an unbound or shared token,
not a missing IAM role. Confirm:
- The call originates from the deployed runtime container (not local dev).
- mTLS / DPoP path is intact (see CAA flow in section 4).
- If you must work around (NOT recommended in production), set
`GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES=False` via
`env_vars` on `agent_engines.create(...)`. This disables token binding.
### `403 PERMISSION_DENIED` after switching to AGENT_IDENTITY
The Agent Runtime Service Agent's project-wide grants do **not** transfer to the
per-agent identity. The agent has only the two default roles. Add baseline roles
via the principalSet binding, then per-agent grants for sensitive resources.
### IAP / Agent Gateway egress denied
You need an `roles/iap.egressor` binding on the IAP/endpoint with the agent
principal as `members`. Per the policy assignment doc:
```json
{
"bindings": [
{
"role": "roles/iap.egressor",
"members": [
"principal://agents.global.org-123456789012.system.id.goog/resources/aiplatform/projects/9876543210/locations/us-central1/reasoningEngines/1234567890123456789"
]
}
],
"version": 3
}
```
> **Warning:** `gcloud iap web set-iam-policy` requires a top-level IAM `Policy`
> JSON object (`{"bindings": [...]}`). Do **NOT** wrap `"bindings"` inside
> `{"policy": ...}` (which is used only by raw REST `:setIamPolicy` calls) —
> passing `{"policy": ...}` to `gcloud iap web set-iam-policy` submits an empty
> policy and **silently wipes all existing IAP bindings**!
Apply with `gcloud iap web set-iam-policy policy.json --project=PROJECT_ID
--region=LOCATION --resource-type=agent-registry` (adding
`--endpoint=ENDPOINT_UUID`, `--mcp-server=MCP_UUID`, or `--agent=AGENT_UUID`
**alongside** `--resource-type=agent-registry` for per-resource scope; omitting
`--resource-type=agent-registry` targets `IAPWebLocation` `iap_web` and ignores
child flags).
### `403` Egress / Auth Error Calling an MCP Server on Cloud Run
Choose the pattern matching how the Cloud Run service is secured:
1. **Standard Cloud Run IAM (`roles/run.invoker`) — Service Account Impersonation Required**:
Direct Agent Identity (`principal://...`) to Cloud Run OIDC authentication is
**not natively supported**. Configure the agent code to use **Service Account
impersonation** (`google.auth.impersonated_credentials.IDTokenCredentials`) to
mint an OIDC ID token for the Cloud Run URL:
- Grant **`roles/iam.serviceAccountTokenCreator`** to the Agent Identity on
the target Service Account.
- Grant **`roles/run.invoker`** to that target Service Account on the Cloud
Run service, and authorize egress to the Cloud Run URL in Agent Registry +
IAP/UAP.
2. **Preview — Cloud Run Native IAP for MCP Servers (`--iap --functional-type=mcp-server`)**:
Deploy or update the Cloud Run MCP service with native IAP instead of
application-layer SA impersonation:
```bash
gcloud beta run deploy MCP_SERVICE_NAME \
--image=IMAGE_URL --region=REGION \
--allow-unauthenticated --iap --functional-type=mcp-server
```
Grant `roles/run.invoker` on the Cloud Run service to the IAP service agent
(`service-PROJECT_NUMBER@gcp-sa-iap.iam.gserviceaccount.com`), grant
`roles/iap.httpsResourceAccessor` on `--resource-type=cloud-run
--service=MCP_SERVICE_NAME`, and target the `.run.app` short URL
(`https://MCP_SERVICE_NAME-PROJECT_NUMBER.REGION.run.app`).
### Workforce Identity Federation (WIF) Console Errors or `gcloud` `error 13`
Federated workforce identities have limited Preview support across Agent Gateway
and Agent Registry control planes. Running `gcloud network-services
agent-gateways import` or `gcloud agent-registry` commands as a WIF user can fail
with `error 13: an internal error has occurred` or `403`, and granting broader
IAM roles to the federated principal does **not** fix it. Authenticate with a
standard Cloud Identity or Google Workspace account (see BKI #36).
### Agent can't use an auth provider (Auth Manager) & OIDC issuer reachability
Verify `roles/iamconnectors.user` is granted to the agent identity on the
`AuthProvider` resource, and confirm `.well-known/openid-configuration` and JWKS
endpoints are publicly reachable.
--------------------------------------------------------------------------------
## Code: pulling the bound token via ADC inside the agent
Source: <https://docs.cloud.google.com/iam/docs/auth-agent-own-identity.md.txt>
```python
from google.auth import default
from google.cloud import vision
# ADC automatically retrieves the Agent Identity token from the
# metadata server. No code changes vs. SA mode.
creds, project_id = default()
client = vision.ImageAnnotatorClient(credentials=creds, project=project_id)
```
If you opt out of CAA (token sharing), set on deploy:
```python
config={
"env_vars": {
"GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES": False,
},
}
```
--------------------------------------------------------------------------------
## Quick reference — useful URLs
- Agent identity overview (govern):
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/agent-identity-overview.md.txt>
- Agent identity overview (IAM mirror):
<https://docs.cloud.google.com/iam/docs/agent-identity-overview.md.txt>
- Agent identity in runtime (create / list / grant):
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-identity.md.txt>
- Setup identity & permissions:
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/runtime/setup.md.txt>
- Manage agent access (SA mode):
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/manage-agent-access.md.txt>
- Principal identifiers (table of all forms):
<https://docs.cloud.google.com/iam/docs/principal-identifiers.md.txt>
- ReasoningEngineSpec REST reference:
<https://docs.cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1beta1/projects.locations.reasoningEngines.md.txt>
- Context-Aware Access for agents (mTLS / DPoP):
<https://docs.cloud.google.com/access-context-manager/docs/caa-agent-security.md.txt>
- Auth manager troubleshooting (401 / connectors role):
<https://docs.cloud.google.com/iam/docs/troubleshoot-auth-manager.md.txt>
- Auth using agent's own identity (ADC sample):
<https://docs.cloud.google.com/iam/docs/auth-agent-own-identity.md.txt>
- Configure IAM policies (IAP egressor examples):
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/policies/configure-iam-policies.md.txt>
- Three-identity delegation architecture:
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/identity-delegation-architecture.md.txt>
- Secure Cloud Run MCP servers with IAP:
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/policies/iap-cloud-run-mcp.md.txt>
agent-registry.md 49.7 KB
# Agent Registry — Debugging Reference
Curated reference for diagnosing why agents, MCP servers, and endpoints
registered in Google Cloud Agent Registry are not accepting traffic through
Agent Gateway / IAP.
Scope: Gemini Enterprise Agent Platform — Agent Registry (`v1` GA). Core commands
use `gcloud agent-registry` (`gcloud beta agent-registry` does **not** exist, and
`endpoints` is read-only with no `create` subcommand; all manual writes go through
`gcloud agent-registry services`). Standalone skills use `gcloud agent-registry
skills` (`list` / `describe`).
## Table of Contents
- [TL;DR for Debugging](#tldr-for-debugging): Lines 29-149
- [1. The Data Model in One Picture](#1-the-data-model-in-one-picture): Lines 150-197
- [2. Default-Deny + Hostname Matching](#2-default-deny--hostname-matching): Lines 198-338
- [3. Resource Type — Agents](#3-resource-type--agents): Lines 339-472
- [4. Resource Type — MCP Servers](#4-resource-type--mcp-servers): Lines 473-561
- [5. Resource Type — Endpoints](#5-resource-type--endpoints): Lines 562-705
- [6. IAM Scope: Registry-Wide vs Per-Resource](#6-iam-scope-registry-wide-vs-per-resource): Lines 706-845
- [7. Common Registration Errors and Where to Look](#7-common-registration-errors-and-where-to-look): Lines 846-877
- [8. Discovery via the Agent Registry MCP Server](#8-discovery-via-the-agent-registry-mcp-server): Lines 878-906
- [9. Quick Reference — Every gcloud Subcommand](#9-quick-reference--every-gcloud-subcommand): Lines 907-971
- [Source Index](#source-index): Lines 972-998
--------------------------------------------------------------------------------
## TL;DR for Debugging
Read these first when something is broken.
1. **Agent Registry is default-deny at the gateway.** Agent Gateway uses
Identity-Aware Proxy (IAP) to enforce authorization:
- **UAP (Policy V2)**: When the gateway uses `iapPolicyVersion: "V2"`,
Gatekeeper queries the attached registries. If the destination matches,
Gatekeeper sets `destination.is_registered = true` and exposes rich CEL
metadata under `destination.agent_registry.*`. If not cataloged,
`destination.is_registered = false`.
- **Legacy IAM v1**: When using legacy v1, if a target hostname is not
registered as a `Service` (and a matching `roles/iap.egressor` binding
does not exist on the registry entry for the calling agent's principal),
egress is blocked. Source:
`docs.cloud.google.com/iap/docs/agent-overview`.
2. **There are exactly three discoverable resource types**, and they are
*projections* of the same writable `Service`:
- **Agent** (read-only `Agent`)
- **MCP server** (read-only `McpServer`)
- **Endpoint** (read-only `Endpoint`) You always create/update/delete via
`services`. You list/describe via `agents`, `mcp-servers`, `endpoints`,
or `services`. Source: `docs.cloud.google.com/agent-registry/concepts`.
3. **Hostname matching is exact.** A single Google API can be reached at five+
distinct hostnames (base, mTLS, locational, locational-mTLS, REP regional).
Each hostname is a *separate* `Service` registration. If your agent calls
`bigquery.us-central1.rep.googleapis.com` but you only registered
`bigquery.googleapis.com`, the call is denied. See the "Hostname Matrix"
section.
4. **Manual registration is not supported in `us` or `eu` multi-region
locations.** `us` and `eu` are read-only roll-up discovery locations for
automatically registered Gemini Enterprise components and standalone skills.
Always register `Service` entries and `Binding` resources in a specific
region (e.g., `us-central1`, `europe-west1`) or `global`.
5. **Two predefined IAM roles control the registry itself**:
- `roles/agentregistry.viewer` (`agentregistry.{agents,endpoints,mcpServers}.list`)
— discover entries **and** required by the caller importing an `AgentGateway`
referencing the registry.
- `roles/agentregistry.editor` — create/update/delete `Service` resources.
These are project-scoped catalog permissions, not runtime traffic permissions.
6. **Traffic permissions live on IAP (Policy V1 vs. UAP Policy V2):**
- **Policy V1 (`gcloud iap web`)**: Grant `roles/iap.egressor`
(`iap.webServiceVersions.egressViaIAP`) with **`--resource-type=agent-registry`
always set**, optionally scoped with `--agent=AGENT_UUID`,
`--mcp-server=MCP_UUID`, or `--endpoint=ENDPOINT_UUID` (using the
server-generated `registryResource` basename, never `SERVICE_NAME`).
- **UAP Policy V2 (`iapPolicyVersion: "V2"`)**: Grant
`iap.googleapis.com/resources.egressViaIAP` via `gcloud iam
access-policies` and `gcloud iam policy-bindings`.
7. **Identifiers matter:**
- `SERVICE_NAME` / `SERVICE_ID` — your chosen ID (4–63 chars `[a-z0-9-]`)
for `gcloud agent-registry services`.
- `registryResource` UUID — server-generated child ID under `/endpoints/`,
`/mcpServers/`, or `/agents/` required by `gcloud iap web`.
- **Agent / MCP server URN** — immutable identifier (`urn:mcp:...`,
`urn:agent:...`) used by discovery tools and `ExtensionBinding` matchers.
- **Resource URI** — runtime URI embedded in the SPIFFE principal.
8. **Specs have a hard 10 KB cap and use plain file paths (no `@`).** Pass
`--mcp-server-spec-content=toolspec.json` or
`--agent-spec-content=agent-card.json` (`<= 10 KB`; `gcloud` `arg_json`
rejects `curl`-style `@file.json`).
9. **Automatic registration vs. manual:** Agent Runtime (SDK), Google Workspace,
Gemini Enterprise, annotated GKE (`registry.gke.io/functional-type:
"MCP_SERVER"`), Cloud Run services with `--functional-type={agent|mcp-server}`,
and enabled Google/Google Cloud remote MCP servers (created in `global` only)
register *automatically* **within the governance project only**. Cross-project
workloads, standard Cloud Run services, on-prem, and third-party APIs require
manual `gcloud agent-registry services create`.
- **Cloud Run `.run.app` vs. `.a.run.app` trap**: Automatic registration
records the deterministic regional URL
(`https://<SERVICE>-<PROJECT_NUMBER>.<REGION>.run.app`). Calling the
legacy hash URL (`https://<SERVICE>-<HASH>-uc.a.run.app`) fails exact
hostname matching unless manually registered.
10. **First debug command**: confirm the exact target URL is registered (`gcloud
agent-registry endpoints list --project=$PROJECT_ID --location=$LOCATION` and
`gcloud agent-registry services list --filter="interfaces.url:FRAGMENT"`).
11. **Governance project scope (no automatic cross-project discovery).**
Automatic registration only discovers resources inside the governance project
where `agentregistry.googleapis.com` is enabled. Remote agents and MCP servers
in separate Google Cloud projects must be manually registered in the central
governance project's registry.
12. **Agent Gateway Dual-Registry & Jurisdiction Rules**: An `AgentGateway`
supports a **maximum of two** registries in `registries[]`. When two
registries are configured, **exactly one must be `global`** and the other
must be regional (e.g., `us-central1`) or multi-regional (`us`, `eu`).
- Binding **two regional registries** (e.g., `us-central1` and
`europe-west1`) is invalid and rejected with an **HTTP `400`** validation
error.
- **Jurisdiction alignment**: A regional gateway can only reference a
regional registry in the **same region** or a multi-region registry in
the **same data residency jurisdiction** (e.g., `us-central1` gateway +
`eu` registry is rejected with `InvalidArgument`).
- **Gateway import preflight**: If `agent-gateways import` fails with
`Config validation failed` and `missing permissions:
agentregistry.agents.list`, enable **`agentregistry.googleapis.com`** on
the registry project and ensure the deploying caller holds
`roles/agentregistry.viewer` (`agentregistry.{agents,endpoints,mcpServers}.list`).
13. **REST API Path Extensions & Explicit Forward Proxies**: SDK clients such as
Zendesk append `.json` (`/api/v2/tickets.json`) — account for `.json`, `/`
subpaths, and `?` query strings in UAP CEL rules. Note that an explicit
forward `HTTPS_PROXY` tunnel (`HTTP CONNECT`) requires a `v1beta1` L4
`AuthzPolicy` (`networkRules` matching SNIs), not an Agent Registry entry for
the proxy host (see `references/agent-gateway.md` and BKI #34).
--------------------------------------------------------------------------------
## 1. The Data Model in One Picture
```
WRITE side READ side (read-only projections)
+--------------+ +----------+
| | endpoint-spec --> | Endpoint |
| Service | mcp-server-spec ->| McpServer|
| (writable) | agent-spec -----> | Agent |
+--------------+ +----------+
^ ^
create/update/delete get/list/search
(services subcommand) (endpoints / mcp-servers /
agents subcommand)
```
- The `Service` resource is the only thing you write.
- Agent Registry **automatically generates** the corresponding `Agent`,
`McpServer`, or `Endpoint` projection based on the `*-spec-type` you passed
at create time.
- The mutually exclusive `*-spec-type` flag at creation determines the read-only
projection (spec types cannot be changed on `services update`):
| `services create` Spec Flag | Allowed `--interfaces` | Read-Only Projection |
| :--- | :--- | :--- |
| `--endpoint-spec-type=no-spec` | Required (1+ URLs) | `Endpoint` |
| `--mcp-server-spec-type={tool-spec\|no-spec}` | Required (`protocolBinding=JSONRPC`) | `McpServer` |
| `--agent-spec-type=a2a-agent-card` | **Must be omitted** (read from `agent-card.json`) | `Agent` (with A2A skills) |
| `--agent-spec-type=no-spec` | Required (REST URL) | `Agent` (non-A2A REST) |
*(Standalone `Skill` resources do not use `Service`; inspect via `gcloud agent-registry skills list --location=LOCATION --project=PROJECT_ID`.)*
Source: `docs.cloud.google.com/agent-registry/overview`,
`docs.cloud.google.com/agent-registry/concepts`.
### URN formats (memorize these)
- **Manually registered MCP server URN:**
`urn:mcp:projects-PROJECT_NUMBER:projects:PROJECT_NUMBER:locations:REGION:agentregistry:SERVICE_ID`
- **Google Cloud remote MCP server URN:**
`urn:mcp:googleapis.com:projects:PROJECT_NUMBER:locations:global:SERVICE_NAME`
If a discovery query returns no results for what you think is a registered
server, check the URN format vs the location you registered against.
Source: `docs.cloud.google.com/agent-registry/concepts`.
--------------------------------------------------------------------------------
## 2. Default-Deny + Hostname Matching
This is the single most common debugging failure mode. Read this whole section.
### Why default-deny
Agent Gateway is the egress proxy for agents. It is built on IAP. IAP only
forwards a request if there is an IAM allow policy granting `roles/iap.egressor`
to the calling agent's principal **on a registry resource that matches the
request**. If no `Service` matches the destination hostname, no policy can
match, and the request is denied.
Source: `docs.cloud.google.com/iap/docs/agent-overview`.
### Hostname Matrix — register every form an agent might call
A single Google Cloud API can be addressed via several distinct hostnames. Each
one is a separate registry entry. The canonical set includes the following; if
any are missing for an API your agent uses, expect denial.
Variant | Hostname pattern | Example (`bigquery`, `us-central1`)
----------------- | --------------------------------------- | -----------------------------------
Base / global | `SERVICE.googleapis.com` | `bigquery.googleapis.com`
mTLS | `SERVICE.mtls.googleapis.com` | `bigquery.mtls.googleapis.com`
Locational | `LOCATION-SERVICE.googleapis.com` | `us-central1-bigquery.googleapis.com`
Locational mTLS | `LOCATION-SERVICE.mtls.googleapis.com` | `us-central1-bigquery.mtls.googleapis.com`
REP (public) | `SERVICE.LOCATION.rep.googleapis.com` | `bigquery.us-central1.rep.googleapis.com`
REP (private/PSC) | `SERVICE.LOCATION.p.rep.googleapis.com` | `bigquery.us-central1.p.rep.googleapis.com`
- **Locational endpoints** specify the region/multi-region in the URL prefix.
Format: `LOCATION-SERVICE.googleapis.com`. Locational endpoints don't
support data-residency-compliant connections from on-premises and don't
support failure-domain isolation; **REP is replacing them**.
- **REP (Regional Endpoint)** confines TLS termination and traffic to the
specified region. Format: `SERVICE.REGION.rep.googleapis.com`. Private REP
via PSC adds `.p.`.
- The base/global hostname terminates TLS at the nearest edge and provides no
regional isolation.
Source:
`docs.cloud.google.com/docs/security/compliance/restrict-endpoint-usage`.
### Recommended Pattern: Consolidated Google APIs Service
> **Warning:** **MANDATORY GOOGLE APIS CONSOLIDATION RULE**: NEVER recommend or
> register separate `Service` resources for individual Google APIs (such as
> Agent Runtime, Cloud Resource Manager, IAM, or Telemetry). Do NOT register
> each Google API as a separate service entry, as separate service entries cause
> resource clutter, complicate IAM policy management, and risk hitting registry
> quota limits. ALL Google APIs MUST ALWAYS be consolidated under a single Agent
> Registry Service named `googleapis` using multiple interfaces.
Instead of registering dozens of separate `Service` resources for each Google
API and its regional/mTLS permutations, consolidate all Google APIs under a
single Agent Registry Service named `googleapis` using **multiple interfaces**.
This reduces resource clutter, simplifies IAM policy management (granting
`roles/iap.egressor` once), and avoids registry quota limits.
#### The 8 Mandatory Base Interfaces + Essential Platform Families
For every Agent Runtime deployment behind an `ALL_TRAFFIC` Egress Agent Gateway,
the consolidated `googleapis` service **must** include the **8 base FQDN
interfaces**:
1. `https://agentregistry.googleapis.com`
2. `https://aiplatform.mtls.googleapis.com`
3. `https://cloudresourcemanager.mtls.googleapis.com`
4. `https://iamcredentials.mtls.googleapis.com`
5. `https://telemetry.mtls.googleapis.com`
6. `https://{region}-aiplatform.mtls.googleapis.com` (e.g., `us-central1`)
7. `https://{region}-aiplatform.googleapis.com`
8. `https://aiplatform.{region}.rep.googleapis.com`
Depending on model availability and runtime features, include these additional
interfaces from the **9 essential Google Cloud API families** on the **same**
`googleapis` service:
- **Global & Multi-Region Foundation Models**: Many Gemini models only expose
`global` or multi-region (`us`, `eu`) endpoints. Add
`https://aiplatform.googleapis.com` (alongside `aiplatform.mtls.googleapis.com`)
and, if targeting `us`/`eu`, `https://us-aiplatform.googleapis.com`,
`https://us-aiplatform.mtls.googleapis.com`, and
`https://aiplatform.us.rep.googleapis.com`. Calling an unsupported regional
model returns `HTTP 404 NOT_FOUND`; calling `global` without registering
`aiplatform.googleapis.com` drops TLS at `240.0.0.2:443` (`UNEXPECTED_EOF`).
- **Tracing, Logging, Monitoring, Storage, & Artifact Registry**: Add
`https://cloudtrace.googleapis.com`, `https://cloudtrace.mtls.googleapis.com`,
`https://trace.googleapis.com`, `https://trace.mtls.googleapis.com`,
`https://monitoring.googleapis.com`, `https://monitoring.mtls.googleapis.com`,
`https://logging.googleapis.com`, `https://logging.mtls.googleapis.com`,
`https://storage.googleapis.com`, `https://storage.mtls.googleapis.com`,
`https://artifactregistry.googleapis.com`, and
`https://artifactregistry.mtls.googleapis.com`.
- **Multi-Region `.rep.mtls` `NXDOMAIN` Pitfall**: Google Cloud does **not**
publish DNS records for `aiplatform.us.rep.mtls.googleapis.com` or
`aiplatform.eu.rep.mtls.googleapis.com`. On older `google-genai` SDK versions
with `AGENT_IDENTITY` enabled and `location="us"` or `"eu"`, automatic mTLS
URL rewriting fails with `NXDOMAIN` (`Name or service not known`). Fix:
upgrade `google-genai`, target `global` or a single region, or set
`GOOGLE_API_USE_MTLS_ENDPOINT=never` and `GOOGLE_API_USE_CLIENT_CERTIFICATE=false`.
#### Creating Consolidated Service via gcloud
```bash
gcloud agent-registry services create googleapis \
--project=$PROJECT_ID --location=$LOCATION \
--display-name="Google APIs" \
--endpoint-spec-type=no-spec \
--interfaces=url=https://agentregistry.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://aiplatform.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://aiplatform.mtls.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://cloudresourcemanager.mtls.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://iamcredentials.mtls.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://telemetry.mtls.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://cloudtrace.mtls.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://trace.mtls.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://monitoring.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://$LOCATION-aiplatform.mtls.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://$LOCATION-aiplatform.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://aiplatform.$LOCATION.rep.googleapis.com,protocolBinding=JSONRPC
```
### Quick "is the hostname registered?" check
```bash
gcloud agent-registry services list \
--project=$PROJECT_ID \
--location=$LOCATION \
--format="table(name.basename(), interfaces.url)" \
--filter="interfaces.url:HOSTNAME_FRAGMENT"
```
Replace `HOSTNAME_FRAGMENT` with e.g. `bigquery.us-central1.rep`.
Source: hostname patterns derived from
`docs.cloud.google.com/docs/security/compliance/restrict-endpoint-usage`;
registration flow from
`docs.cloud.google.com/agent-registry/register-endpoints`.
--------------------------------------------------------------------------------
## 3. Resource Type — Agents
### Concept
> Agents: Autonomous actors that possess specific *skills*. Skills represent an
> agent's high-level capabilities and are a primary mechanism for discovery. --
> `docs.cloud.google.com/agent-registry/concepts`
Two kinds: - **A2A-compliant agents** -- implement Agent2Agent. Registry scans
their `agent-card.json` to extract skills. - **Standard REST agents** --
registered as `NO_SPEC` type when no A2A spec exists.
Automatic registration sources: Agent Runtime (via SDK), Google Workspace
built-ins, Gemini Enterprise built-ins, GKE deployments with the Agent Registry
functional-type annotation. Everything else is manual.
### List
```bash
gcloud agent-registry agents list \
--project=PROJECT_ID \
--location=REGION
```
Filter:
```bash
gcloud agent-registry agents list \
--project=PROJECT_ID \
--location=REGION \
--filter="displayName='DISPLAY_NAME'"
```
### Describe
```bash
gcloud agent-registry agents describe AGENT_NAME \
--project=PROJECT_ID \
--location=REGION
```
Output exposes core details, skills (if A2A), and `Resource URI` -- the runtime
location of the agent, which is what gets embedded in the agent principal for
IAM.
### Update (via `services`, not `agents`)
Display name / description:
```bash
gcloud agent-registry services update AGENT_NAME \
--project=PROJECT_ID \
--location=REGION \
--display-name="New name" \
--description="Updated description"
```
Endpoint URL:
```bash
gcloud agent-registry services update AGENT_NAME \
--project=PROJECT_ID \
--location=REGION \
--interfaces=url=ENDPOINT_URL,protocolBinding=PROTOCOL
```
Valid `protocolBinding`: `HTTP_JSON`, `GRPC`, `JSONRPC`.
Agent spec payload (max size 10 KB to satisfy gRPC control plane metadata header
limits):
```bash
gcloud agent-registry services update AGENT_NAME \
--project=PROJECT_ID \
--location=REGION \
--agent-spec-content=agent-card.json
```
### Delete
For automatically registered agents: delete from the source runtime. For manually
registered agents:
```bash
gcloud agent-registry services delete AGENT_NAME \
--project=PROJECT_ID \
--location=REGION
```
### IAM model for agents
- **Registry permission to manage**: `roles/agentregistry.editor` on the project.
- **Agent-to-agent egress (Policy V1)**: extract the generated `Agent` UUID
(`basename` of `registryResource`) and bind `roles/iap.egressor` with
**`--resource-type=agent-registry`**:
```bash
AGENT_UUID=$(basename "$(gcloud agent-registry services describe AGENT_NAME \
--project=PROJECT_ID --location=REGION --format='value(registryResource)')")
gcloud iap web set-iam-policy agents-iap-policy.json \
--project=PROJECT_ID \
--resource-type=agent-registry \
--agent="$AGENT_UUID" \
--region=REGION
```
The policy's `members` uses the calling agent's principal (`principal://agents.global.org-123456789012.system.id.goog/resources/aiplatform/projects/9876543210/locations/us-central1/reasoningEngines/12345`, orgless `agents.global.proj-9876543210.system.id.goog/...`, or WIF `principal://iam.googleapis.com/...`).
### Common pitfalls
- **Agent in another project missing from central registry**: automatic
registration only discovers workloads inside the governance project. Manually
register cross-project agents with `gcloud agent-registry services create` in
the governance project (never in `us` or `eu`).
- **Agent appears in `services list` but not `agents list`**: wrong spec type at
creation (`--agent-spec-type=a2a-agent-card` or `--agent-spec-type=no-spec`
required).
- **Cloud Run agent missing from registry**: standard Cloud Run services do not
auto-register unless deployed with `gcloud beta run deploy --functional-type=agent
--identity-type=agent-identity`.
- **Gemini Enterprise egress ignores Agent Gateway**: Gemini Enterprise requires
**two** toggles — (1) `PATCH` the `Engine` on the regional endpoint
(`https://{global-|us-|eu-}discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/GE_LOCATION/collections/default_collection/engines/ENGINE_ID?updateMask=agentGatewaySetting.defaultEgressAgentGateway.name`)
and (2) set `"use_agent_gateway_egress": true` on each imported MCP/A2A
`DataConnector` (see BKI #37).
- **A2A agent missing skills**: `agent-card.json` exceeds 10 KB, or `--interfaces`
was passed alongside `--agent-spec-type=a2a-agent-card` (forbidden).
Sources: `docs.cloud.google.com/agent-registry/manage-agents`,
`docs.cloud.google.com/agent-registry/register-agents`,
`docs.cloud.google.com/gemini-enterprise-agent-platform/govern/policies/configure-iam-policies`.
--------------------------------------------------------------------------------
## 4. Resource Type — MCP Servers
### Concept
> MCP servers: Providers of standardized data resources and *tools*. Tools are
> deterministic functions exposed by an MCP server that agents can invoke to
> perform specific actions. -- `docs.cloud.google.com/agent-registry/concepts`
Official Google and Google Cloud remote MCP servers are auto-registered on API
enable. External / custom MCP servers (e.g. Cloud Run-hosted FastMCP) need
manual registration with a tool spec.
### Register
```bash
gcloud agent-registry services create SERVER_NAME \
--project=PROJECT_ID \
--location=REGION \
--display-name="DISPLAY_NAME" \
--mcp-server-spec-type=tool-spec \
--mcp-server-spec-content=toolspec.json \
--interfaces=url=SERVER_URL,protocolBinding=JSONRPC
```
- `protocolBinding` for MCP must be `JSONRPC` (`jsonrpc`), and `toolspec.json`
must be `<= 10 KB` (do **not** prefix the path with `@`). Use
`--mcp-server-spec-type=no-spec` (without `--mcp-server-spec-content`) when
not uploading a static tool catalog.
### List & Describe
```bash
gcloud agent-registry mcp-servers list --project=PROJECT_ID --location=REGION
gcloud agent-registry mcp-servers describe MCP_SERVER_UUID --project=PROJECT_ID --location=REGION
```
### Update tool spec & Delete
```bash
gcloud agent-registry services update SERVER_NAME \
--project=PROJECT_ID --location=REGION \
--mcp-server-spec-content=toolspec.json
gcloud agent-registry services delete SERVER_NAME --project=PROJECT_ID --location=REGION
```
### IAM model for MCP servers
- **Discover / manage catalog**: `roles/agentregistry.viewer` / `roles/agentregistry.editor`.
- **Call Agent Registry remote MCP server**: `roles/mcp.toolUser` + `roles/agentregistry.viewer`.
- **Agent-to-MCP egress (Policy V1)**: pass `--resource-type=agent-registry`
and the server-generated `McpServer` UUID (`registryResource` basename):
```bash
gcloud iap web set-iam-policy agents-iap-policy.json \
--project=PROJECT_ID \
--resource-type=agent-registry \
--mcp-server=MCP_SERVER_UUID \
--region=REGION
```
Policy V1 CEL attributes: `iap.googleapis.com/mcp.toolName`,
`iap.googleapis.com/mcp.tool.isReadOnly`, `iap.googleapis.com/request.auth.type` (`'MCP'`).
### Common pitfalls
- **Google/Google Cloud remote MCP server returns `NOT_FOUND` in a region**:
auto-registered Google remote MCP servers exist **only in `global`** (even
when exposing regional `.rep.googleapis.com/mcp` URLs). Always query with
`--location=global` and bind IAP policies with `--region=global`.
- **Cloud Run MCP server `403` unregistered mismatch (`.a.run.app` vs. `.run.app`)**:
`gcloud beta run deploy --functional-type=mcp-server` registers
`https://<SERVICE>-<PROJECT_NUMBER>.<REGION>.run.app`. Configure the agent to
call that exact `.run.app` URL (not the legacy `*-uc.a.run.app` URL).
- **Native MCP `AuthzPolicy` blocks `initialize` / `ping`**: when attaching a
Network Security `AuthzPolicy` with `mcp` tool rules, set
`baseProtocolMethodsOption: MATCH_BASE_PROTOCOL_METHODS` on `ALLOW` rules
(see `references/policies.md` and BKI #39).
- **Tool spec rejected or stale**: re-run `services update
--mcp-server-spec-content=toolspec.json` (`<= 10 KB`, no `@`) after tool
changes; never register manually in `us` or `eu`.
Sources: `docs.cloud.google.com/agent-registry/register-mcp-servers`,
`docs.cloud.google.com/agent-registry/manage-mcp-tools`,
`docs.cloud.google.com/agent-registry/use-agentregistry-mcp`,
`docs.cloud.google.com/gemini-enterprise-agent-platform/govern/policies/configure-iam-policies`.
--------------------------------------------------------------------------------
## 5. Resource Type — Endpoints
### Concept
> Endpoints: Target URLs, typically REST APIs, accessed by an agent. By
> abstracting these destinations into manageable resources, Agent Registry lets
> you centrally govern which external services your agents can access. --
> `docs.cloud.google.com/agent-registry/concepts`
Endpoints are how you authorize an agent to reach **anything that isn't an agent
or an MCP server**: Google APIs (BigQuery, Agent Runtime, etc.), third-party
REST APIs, internal HTTP services. Always manually registered.
### Register
```bash
gcloud agent-registry services create SERVICE_NAME \
--project=PROJECT_ID \
--location=REGION \
--display-name="DISPLAY_NAME" \
--endpoint-spec-type=no-spec \
--interfaces=url=ENDPOINT_URL,protocolBinding=PROTOCOL
```
- `--endpoint-spec-type=no-spec` is mandatory -- this is what causes the
read-only `Endpoint` projection to appear.
- After creation, Agent Registry auto-generates the read-only `Endpoint`
resource that agents discover.
> **Hostname registration is exact-match.** You must register *every* hostname
> variant the agent might dial. See "Hostname Matrix" in section 2. The fix for
> "endpoint registered but traffic denied" is almost always: register the
> missing variant.
### List
```bash
gcloud agent-registry endpoints list \
--project=PROJECT_ID \
--location=REGION
```
Filter:
```bash
gcloud agent-registry endpoints list \
--project=PROJECT_ID \
--location=REGION \
--filter="displayName='NAME'"
```
For URL-substring search, list `services` instead and filter on
`interfaces.url`:
```bash
gcloud agent-registry services list \
--project=PROJECT_ID \
--location=REGION \
--format="table(name.basename(), interfaces.url, interfaces.protocolBinding)" \
--filter="interfaces.url:HOSTNAME_FRAGMENT"
```
### Describe
```bash
gcloud agent-registry endpoints describe ENDPOINT_NAME \
--project=PROJECT_ID \
--location=REGION
```
### Update
```bash
gcloud agent-registry services update SERVICE_NAME \
--project=PROJECT_ID \
--location=REGION \
--interfaces=url=ENDPOINT_URL,protocolBinding=PROTOCOL
```
### Delete
```bash
gcloud agent-registry services delete SERVICE_NAME \
--project=PROJECT_ID \
--location=REGION
```
> "This action immediately removes the endpoint from discovery search results."
> Google Cloud console UI requires typing `DELETE` to confirm.
### IAM model for endpoints
- **Discover endpoints**: `roles/agentregistry.viewer`.
- **Register / update / delete**: `roles/agentregistry.editor`.
- **Agent-to-endpoint traffic**: bind `roles/iap.egressor` to the source
agent's principal on the endpoint resource:
```bash
gcloud iap web set-iam-policy agents-iap-policy.json \
--project=PROJECT_ID \
--resource-type=agent-registry \
--endpoint=ENDPOINT_UUID \
--region=REGION
```
Per-endpoint policy bindings do not require a CEL condition; you can omit
`condition` to grant unconditional egress to that one endpoint, or add a CEL
condition for attribute-based scoping (e.g. by `Name`, `ReadOnly`,
`Destructive`, `Idempotent`, `OpenWorld` properties).
### Note on `roles/iap.tunnelResourceAccessor`
Some IAP-protected resources use `roles/iap.tunnelResourceAccessor`
(`iap.tunnelDestGroups.accessViaIAP`, `iap.tunnelInstances.accessViaIAP`) --
that role governs **classic IAP TCP tunnels** to GCE instances and dest groups.
**Agent Gateway egress to Agent Registry resources does NOT use this role**; it
uses `roles/iap.egressor` (`iap.webServiceVersions.egressViaIAP`). If you see a
tutorial suggesting `tunnelResourceAccessor` for agent egress, it's the wrong
role -- confirm against `docs.cloud.google.com/iam/docs/roles-permissions/iap`.
### Common pitfalls
- **`Test connection` fails in Google Cloud console for a private URL**:
expected. The Google Cloud console connection test only validates *public*
URLs; it does not support private endpoints (Agent Runtime, internal HTTPS,
etc.).
- **Agent gets denied on a Google API call**: the API has a hostname variant
you didn't register (commonly the REP regional form
`${id}.${LOCATION}.rep.googleapis.com`).
- **Endpoint registered in `global` but agent calls a regional URL**: registry
location doesn't have to match the destination URL location, but the IAM
binding's `--region` must match where the resource is registered. Check that
`--region=` on `gcloud iap web set-iam-policy` equals the location used at
creation.
- **Endpoint not appearing in `endpoints list`**: created with the wrong spec
type. Must use `--endpoint-spec-type=no-spec`.
Sources: `docs.cloud.google.com/agent-registry/register-endpoints`,
`docs.cloud.google.com/agent-registry/manage-endpoints`,
`docs.cloud.google.com/iam/docs/roles-permissions/iap`,
`docs.cloud.google.com/gemini-enterprise-agent-platform/govern/policies/configure-iam-policies`.
--------------------------------------------------------------------------------
## 6. IAM Scope: Registry-Wide vs Per-Resource
There are two layers. Don't conflate them.
### Layer A — Agent Registry permissions (manage the catalog)
Project-scoped, granted via standard IAM:
| Role | Use |
| ---------------------------- | -------------------------------------------- |
| `roles/agentregistry.viewer` | List / describe / search agents, MCP, |
: : endpoints :
| `roles/agentregistry.editor` | Create / update / delete `Service` resources |
| `roles/mcp.toolUser` | Call tools via the Agent Registry remote MCP |
: : server (`mcp.tools.call`) :
These let humans and CI register and inspect entries. They do **not** grant
runtime traffic.
### Layer B — Traffic Authorization (Legacy v1 vs. UAP Policy V2)
Depending on the gateway's `iapPolicyVersion` setting, registry resources
authorize traffic through one of two mechanisms:
#### Mechanism B1: Unified Access Policy (UAP / Policy V2)
When the attached IAP Authz Extension specifies `iapPolicyVersion: "V2"`,
policies are decoupled from individual registry resources:
- `AccessPolicy` and `PolicyBinding` (`iam.googleapis.com/v3`) attach to the
Resource Manager hierarchy (Organization, Folder, Project) targeting numeric
resource URIs (e.g.
`//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}`).
- Rules grant FQDN permission `iap.googleapis.com/resources.egressViaIAP`.
- Agent Registry entries dynamically populate the
`destination.agent_registry.*` CEL attributes evaluated at runtime:
- `destination.is_registered` (boolean): `true` if target matches a
registry service.
- `destination.agent_registry.resource_type`: `'ENDPOINT'`,
`'MCP_SERVER'`, `'AGENT'`, `'SKILL'`.
- `destination.agent_registry.location`: region of registry resource.
- `destination.agent_registry.mcp_server.name`: full MCP server resource
name.
- `destination.agent_registry.mcp_server.method`: `'tools'`, `'prompts'`,
`'resources'`.
- `destination.agent_registry.mcp_server.tool.name`: specific tool name
(e.g. `'updateTicket'`).
- `destination.agent_registry.mcp_server.tool.annotations.read_only_hint`:
boolean.
- **Mandatory CEL Guard**: Always guard tool annotations with:
`(destination.agent_registry.mcp_server.method == 'tools') &&
(destination.agent_registry.mcp_server.tool.annotations.read_only_hint ==
true)`.
#### Mechanism B2: Legacy IAM v1 (Per-Resource Bindings)
In legacy v1, permissions are bound directly on Agent Registry resources via
`gcloud iap web set-iam-policy`. The role is always `roles/iap.egressor`. The
scope of the binding determines which target resources the source agent can
reach:
| Scope | Required `gcloud iap web` Target Flags | Grants Egress To |
| :--- | :--- | :--- |
| Registry-wide | `--resource-type=agent-registry` | All agents, MCP servers, and endpoints in that project/region registry |
| Single agent | `--resource-type=agent-registry --agent=AGENT_UUID` | One target agent (`registryResource` basename) |
| Single MCP server | `--resource-type=agent-registry --mcp-server=MCP_SERVER_UUID` | One target MCP server (`registryResource` basename) |
| Single endpoint | `--resource-type=agent-registry --endpoint=ENDPOINT_UUID` | One target endpoint (`registryResource` basename) |
All four require `--project=PROJECT_ID` and `--region=LOCATION` (`global` or
region). **Never omit `--resource-type=agent-registry`**: when `--region` is set
without `--resource-type`, `gcloud iap web` targets `IAPWebLocation`
(`projects/PROJECT_NUMBER/locations/LOCATION/iap_web`) and **silently ignores
`--agent`, `--mcp-server`, and `--endpoint`** (mutating the regional `iap_web`
container policy or failing on `--region=global`); when both `--resource-type`
and `--region` are omitted, it targets project-wide `IAPWeb`
(`projects/PROJECT_NUMBER/iap_web`).
> **Warning:** **Top-Level `{"bindings": [...]}` Required for `gcloud iap web set-iam-policy`**:
> `gcloud iap web set-iam-policy` parses the file directly as an IAM `Policy`
> object (`bindings`, `etag`, `version`) and wraps `SetIamPolicyRequest`
> internally. Do **NOT** wrap `"bindings"` inside `"policy": { ... }` when using
> `gcloud` — `apitools` discards the outer `"policy"` key and submits an **empty
> policy that silently wipes all existing IAP IAM bindings**! (Only raw REST
> `POST ...:setIamPolicy` requests use the `{"policy": {"bindings": [...]}}`
> envelope.)
The Policy V1 JSON file for `gcloud iap web set-iam-policy` uses top-level `"bindings"`:
```json
{
"bindings": [
{
"role": "roles/iap.egressor",
"members": ["AGENT_PRINCIPAL"]
}
],
"version": 3
}
```
### Agent principal formats (`members` / `principals`)
- **Agent Runtime / Gemini Enterprise (org-backed — `ENGINE_ID` is numeric)**:
`principal://agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/REGION/reasoningEngines/ENGINE_ID`
- **Agent Runtime (orgless project — note `proj-`, NOT `project-`)**:
`principal://agents.global.proj-PROJECT_NUMBER.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/REGION/reasoningEngines/ENGINE_ID`
- **Workload Identity Pool (DIY / external)**:
`principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT`
- **Project-wide Agent PrincipalSet**:
`principalSet://agents.global.org-ORGANIZATION_ID.system.id.goog/attribute.platformContainer/aiplatform/projects/PROJECT_NUMBER`
When debugging "wrong principal" errors: the principal is built from the agent's
**resource URI**, not its display name and not its URN. View the resource URI
via `gcloud agent-registry agents describe`.
### Full IAP role reference (relevant subset)
| Role | Permission grants the role provides | When to use |
| ---------------------------------- | ------------------------------------- | ------------- |
| `roles/iap.egressor` (Beta) | `iap.webServiceVersions.egressViaIAP` | **Agent |
: : : egress :
: : : through Agent :
: : : Gateway** :
| `roles/iap.httpsResourceAccessor` | `iap.webServiceVersions.accessViaIAP` | Human/service |
: : : ingress to an :
: : : IAP-protected :
: : : web app :
| `roles/iap.tunnelResourceAccessor` | `iap.tunnelDestGroups.accessViaIAP`, | Classic IAP |
: : `iap.tunnelInstances.accessViaIAP` : TCP tunnels :
: : : to GCE -- :
: : : **not** for :
: : : agent gateway :
| `roles/iap.admin` | Full IAP admin (`iap.tunnel.*`, all | Manage IAP |
: : getIam/setIam) : policies :
| `roles/iap.viewer` | Read IAP settings | Audit |
Source: `docs.cloud.google.com/iam/docs/roles-permissions/iap`.
--------------------------------------------------------------------------------
## 7. Common Registration Errors and Where to Look
| Symptom | Likely cause | Where to check |
| ---------------------------------- | -------------------------------- | ------------------------------------ |
| `services create` fails: "manual | Used `--location=us` or | Switch to a region (e.g. |
: registration not supported" : `--location=eu` (multi-regions) : `us-central1`) or `global` :
| `services create` succeeds but | Wrong `*-spec-type`. | Re-create with the correct |
: resource missing from `endpoints : `--endpoint-spec-type=no-spec` : spec-type, or check `services list` :
: list` : produces an `Endpoint`. : :
| `services update | Spec > 10 KB | Trim the tool spec |
: --mcp-server-spec-content` rejects : : :
: file : : :
| Agent calls API X, IAP returns 403 | Hostname variant not registered | `services list |
: : (commonly REP : --filter="interfaces.url\:FRAGMENT"` :
: : `*.LOCATION.rep.googleapis.com`) : :
| Agent calls API X, IAP returns 403 even though hostname is registered | Missing `roles/iap.egressor` binding for the source agent's principal | `gcloud iap web get-iam-policy --project=P --region=L --resource-type=agent-registry [--endpoint=UUID \| --mcp-server=UUID \| --agent=UUID]` |
| MCP tool call succeeds for one tool, denied for another | IAP policy condition restricts `mcp.toolName` or `mcp.tool.isReadOnly` | Inspect the IAP policy on the MCP server resource |
| Auto-registered Agent Runtime agent missing from registry | Agent deployed via custom code, not Agent Runtime SDK | Re-deploy via Agent Runtime, or register manually as a `Service` |
| A2A agent has no skills in registry | `agent-card.json` unreachable from Google's crawler or `> 10 KB` | Curl the Agent Card URL from a public network; verify content type, schema, and `<= 10 KB` size |
| Agent principal mismatch in IAP policy | Principal built from wrong resource URI / project number / `project-` typo instead of `proj-` | `gcloud agent-registry agents describe` → use Resource URI and numeric `PROJECT_NUMBER` |
| `roles/iap.tunnelResourceAccessor` granted, still denied | Wrong role — agent egress requires `roles/iap.egressor` | Replace the binding with `roles/iap.egressor` |
| Endpoint Google Cloud console "Test connection" fails on private URL | Connection test only works for public URLs (by design) | Test via the agent itself or `curl` from a peered network |
| `agents-iap-policy.json` set, still denied | Wrong `--region` flag on `set-iam-policy`, omitted `--resource-type=agent-registry` (wrote to `IAPWebLocation` `iap_web`), or wrapped JSON in `{"policy": ...}` (wiped bindings) | Pass `--resource-type=agent-registry`, match `--region` (`global` for Google remote MCPs), and use top-level `{"bindings": [...]}` |
| Cannot find URN or child UUID | Run `services describe` for `registryResource` UUID; `mcp-servers`/`agents describe` for URN | See Section 1 URN & UUID rules |
| `agent-gateways import`: `Config validation failed` (`missing permissions: agentregistry.agents.list`) | `agentregistry.googleapis.com` API disabled on registry project, or caller lacks `roles/agentregistry.viewer` | Enable `agentregistry.googleapis.com` and grant `roles/agentregistry.viewer` (`agentregistry.{agents,endpoints,mcpServers}.list`) |
| `agent-gateways import` `400` / `InvalidArgument` on `registries` | Two regional registries (`us-central1` + `europe-west1`), `> 2` registries, or cross-jurisdiction (`us-central1` + `eu`) | Configure max 2 registries: `global` + 1 same-region or same-jurisdiction multi-region registry |
| `NXDOMAIN` on `aiplatform.{us,eu}.rep.mtls.googleapis.com` | `.rep.mtls` DNS does not exist for `us`/`eu` multi-regions | Upgrade `google-genai`, use `global`/regional endpoint, or set `GOOGLE_API_USE_MTLS_ENDPOINT=never` |
| `gcloud iap web` returns `NOT_FOUND` or ignores `--endpoint`/`--mcp-server`/`--agent` | Omitted `--resource-type=agent-registry` (targets `IAPWebLocation` `iap_web`), passed `SERVICE_NAME` instead of UUID, or queried remote MCP in region instead of `global` | Always pass `--resource-type=agent-registry`, use `registryResource` basename, and use `--region=global` for Google remote MCPs |
| Console loading error or `gcloud` `error 13` with Workforce Identity Federation (WIF) | Preview WIF limitation on Agent Registry & Agent Gateway control planes | Authenticate with a Cloud Identity or Google Workspace account (see BKI #36) |
--------------------------------------------------------------------------------
## 8. Discovery via the Agent Registry MCP Server
The registry itself is exposed as a remote MCP server at
`agentregistry.googleapis.com`. Useful when debugging from inside an agent or
via `mcp inspector`. Tools include:
Discovery: - `search_agents`, `search_mcp_servers` -- keyword/prefix search -
`get_agent`, `get_mcp_server`, `get_endpoint` -- by resource name -
`get_service` -- read the underlying writable spec - `list_agents`,
`list_mcp_servers`, `list_endpoints`, `list_services` - `list_bindings`,
`get_binding`, `fetch_available_bindings` - `get_operation`
Administrative: - `create_service`, `update_service`, `delete_service` -
`create_binding`, `update_binding`, `delete_binding`
`tools/list` over MCP does not require auth:
```text
POST /mcp HTTP/1.1
Host: agentregistry.googleapis.com
Content-Type: application/json
{ "jsonrpc": "2.0", "method": "tools/list" }
```
Source: `docs.cloud.google.com/agent-registry/use-agentregistry-mcp`.
--------------------------------------------------------------------------------
## 9. Quick Reference — Every gcloud Subcommand
```bash
# READ
gcloud agent-registry agents list --project=P --location=L
gcloud agent-registry agents describe NAME --project=P --location=L
gcloud agent-registry mcp-servers list --project=P --location=L
gcloud agent-registry mcp-servers describe NAME --project=P --location=L
gcloud agent-registry endpoints list --project=P --location=L
gcloud agent-registry endpoints describe NAME --project=P --location=L
gcloud agent-registry services list --project=P --location=L
gcloud agent-registry services describe NAME --project=P --location=L
gcloud agent-registry skills list --project=P --location=L
gcloud agent-registry skills describe NAME --project=P --location=L
# WRITE (always 'services'; 'endpoints' has no 'create' subcommand and there is no 'gcloud beta agent-registry')
gcloud agent-registry services create NAME \
--project=P --location=L --display-name="..." \
--endpoint-spec-type=no-spec \
--interfaces=url=URL,protocolBinding=HTTP_JSON|GRPC|JSONRPC
gcloud agent-registry services create NAME \
--project=P --location=L --display-name="..." \
--mcp-server-spec-type=tool-spec \
--mcp-server-spec-content=toolspec.json \
--interfaces=url=URL,protocolBinding=JSONRPC
# A2A agent: omit --interfaces (read from agent-card.json)
gcloud agent-registry services create NAME \
--project=P --location=L --display-name="..." \
--agent-spec-type=a2a-agent-card \
--agent-spec-content=agent-card.json
# Non-A2A REST agent: --agent-spec-type=no-spec + --interfaces
gcloud agent-registry services create NAME \
--project=P --location=L --display-name="..." \
--agent-spec-type=no-spec \
--interfaces=url=URL,protocolBinding=HTTP_JSON
gcloud agent-registry services update NAME \
--project=P --location=L \
[ --display-name="..." | --description="..." \
| --interfaces=url=URL,protocolBinding=... | --clear-interfaces \
| --mcp-server-spec-content=toolspec.json \
| --agent-spec-content=agent-card.json ]
gcloud agent-registry services delete NAME --project=P --location=L
# IAP Policy V1 egress bindings (--resource-type=agent-registry is ALWAYS required)
gcloud iap web set-iam-policy POLICY.json \
--project=P --region=L --resource-type=agent-registry \
[ --agent=AGENT_UUID | --mcp-server=MCP_SERVER_UUID | --endpoint=ENDPOINT_UUID ]
gcloud iap web get-iam-policy \
--project=P --region=L --resource-type=agent-registry \
[ --agent=AGENT_UUID | --mcp-server=MCP_SERVER_UUID | --endpoint=ENDPOINT_UUID ]
```
Spec size cap: **10 KB** for `--mcp-server-spec-content` and
`--agent-spec-content` (pass plain file path without `@`).
Manual registration locations: any region or `global`. **Not** `us` or `eu`.
--------------------------------------------------------------------------------
## Source Index
- Agent Registry overview:
<https://docs.cloud.google.com/agent-registry/overview.md.txt>
- Agent Registry concepts:
<https://docs.cloud.google.com/agent-registry/concepts.md.txt>
- Register agents (manual):
<https://docs.cloud.google.com/agent-registry/register-agents.md.txt>
- Manage agents: <https://docs.cloud.google.com/agent-registry/manage-agents.md.txt>
- Register MCP servers:
<https://docs.cloud.google.com/agent-registry/register-mcp-servers.md.txt>
- Manage MCP servers/tools:
<https://docs.cloud.google.com/agent-registry/manage-mcp-tools.md.txt>
- Register endpoints:
<https://docs.cloud.google.com/agent-registry/register-endpoints.md.txt>
- Manage endpoints:
<https://docs.cloud.google.com/agent-registry/manage-endpoints.md.txt>
- Agent Registry MCP server:
<https://docs.cloud.google.com/agent-registry/use-agentregistry-mcp.md.txt>
- Govern (Gemini Enterprise Agent Platform):
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/agent-registry.md.txt>
- IAP for agents: <https://docs.cloud.google.com/iap/docs/agent-overview.md.txt>
- IAP IAM roles: <https://docs.cloud.google.com/iam/docs/roles-permissions/iap.md.txt>
- Configure IAM policies (IAP egressor examples):
<https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/policies/configure-iam-policies.md.txt>
- Regional service endpoint hostname formats:
<https://docs.cloud.google.com/docs/security/compliance/restrict-endpoint-usage.md.txt>
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:agent-platform-troubleshooting)" \
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 HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:agent-platform-troubleshooting)`
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 any rewording breaks
attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:agent-platform-troubleshooting)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
field-manual.md 66.7 KB
# Field manual: Agent Gateway / Registry / Identity / IAP
Practical debugging knowledge for the Google Cloud Gemini Enterprise Agent
Platform, distilled from real incident triage. Read this *before* diving into
the official docs — it covers the gotchas that the docs don't surface.
> **Tip:** **Check Known Issues First**: If the symptom matches a known pattern
> (e.g., startup failure, VPC-SC block, Cloud Run egress 403, explicit proxy 404,
> or DNS 2-hop `NXDOMAIN`), jump straight to `references/known-issues.md` — it
> indexes recurring failure modes by symptom.
## Table of Contents
- [The mental model](#the-mental-model): Lines 26-121
- [The single biggest gotcha: hostname permutations](#the-single-biggest-gotcha-hostname-permutations): Lines 122-153
- [Recommended Registry Structure: Consolidated Google APIs](#recommended-registry-structure-consolidated-google-apis): Lines 154-191
- [Metric Queries & Visualization](#metric-queries--visualization): Lines 192-228
- [Diagnostic playbook](#diagnostic-playbook): Lines 229-1156
- [Steps 0–10: Core 403, Crash, PSC Exhaustion, ACT/NAT, UAP/IAM, Identity, Cross-Project, & Next-Hop SWP/PBR](#step-0--establish-context--disable-prompts): Lines 270-1074
- [Step 11: Explicit HTTPS Proxy Egress (`HTTPS_PROXY` + L4 `networkRules`)](#step-11--diagnose-explicit-https-proxy-egress-https_proxy--l4-networkrules): Lines 1075-1094
- [Step 12: Cloud DNS Peering (2-Hop Limit) & Cross-Project Shared VPC IAM](#step-12--diagnose-cloud-dns-peering-2-hop-limit--cross-project-shared-vpc-iam): Lines 1095-1122
- [Step 13: Private CA `TrustConfig` TLS Failures & ACT Immutability](#step-13--diagnose-private-ca-trustconfig-tls-failures--act-immutability): Lines 1123-1137
- [Step 14: SGP, Model Armor 60s Stream Timeouts, Native MCP Rules, & Cloud Trace](#step-14--diagnose-sgp-model-armor-60s-stream-timeouts-native-mcp-rules--cloud-trace): Lines 1138-1156
- [Quick reference: the checks in order](#quick-reference-the-checks-in-order): Lines 1157-1179
## The mental model
The Agent Platform runs as **default-deny egress**. An agent (typically an Agent
Runtime instance) cannot talk to *anything* outside itself unless every layer
permits it:
1. **Agent Registry** — the destination must be registered as an Endpoint, MCP
Server, or Agent.
2. **Agent Gateway** — intercepts the request (it sits in front of the agent's
egress). Note: an `authz_policy` must explicitly target the gateway
resource, otherwise the authz extension won't actually run.
3. **Service-extension (delegated authz)** — the gateway calls IAP to make an
allow/deny decision.
4. **IAP / IAM Policy Evaluation** — the agent's identity must be authorized by
IAP:
* **IAM v1 (Legacy Policy Model)**: Evaluated when `iapPolicyVersion:
"V1"` (or unset). The agent identity must have the **IAP egressor role**
(`roles/iap.egressor`, display name "IAP-secured Egressor") directly
bound on the registered resource shadow resource in IAP.
* **Unified Access Policy (UAP / Policy V2 / IAM v3)**: Evaluated when the
gateway's IAP Authz Extension metadata specifies `iapPolicyVersion:
"V2"`. Next-gen access control bound directly to Resource Manager
hierarchy nodes (Organizations, Folders, Projects) via `PolicyBinding`
(`iam.googleapis.com/v3`). Evaluates `AccessPolicy` rules with CEL
expressions on deep attributes (`destination.agent_registry.*` or
`destination.unregistered.*`). Follows strict evaluation invariants:
absolute DENY precedence (cannot be overridden by downstream projects),
and additive ALLOW aggregation across the CRM tree.
5. **Principal Access Boundary (PAB)** — even with the IAM/UAP binding correct,
a PAB policy on the principal set can restrict which resources it can reach.
**PAB takes precedence over IAM Allow** — a correct egressor binding does
nothing if a PAB scopes the principal away from the target.
**Implementation note.** Agent Gateway is built on a Google-managed Secure Web
Proxy instance that provides the egress-proxy capabilities. Customers don't
configure the proxy directly — its rules are derived from registry entries and
authz policies. Denials *can* originate at this proxy layer before IAP runs (no
IAP audit entry exists for those calls); those show up in load-balancer logs
(see Step 3b).
**Proxy Routing, TLS SNI & Agent Connectivity Templates (ACT):** Inside an Agent
Runtime container, outbound connections enter the gateway tunnel via synthetic
PSC VIP `CONNECT 240.0.0.2:443`. By default, Agent Gateway terminates or inspects
TLS, evaluates the inner SNI hostname against Agent Registry and `AuthzPolicy`
rules, and resolves public internet and standard non-VPC-SC Google API hostnames
using **public recursive DNS at the gateway proxy** (Cloud DNS peering via
`dnsPeeringConfig` is required **only** for private internal domains such as
`corp.internal.` or VPC-SC `googleapis.com.` mapped to `199.36.153.4/30`). If an
inner SNI hostname (e.g., `us-central1-aiplatform.googleapis.com`) is NOT
registered and no L4 `networkRules` policy matches, the proxy drops the request
with `default_denied` before IAP runs.
Under **VPC Service Controls (VPC-SC)**, Agent Gateway requires an **Agent
Connectivity Template (ACT)** configured with `vpcEgress: ALL_TRAFFIC`:
- Traffic destined for external public APIs (e.g., `api.ipify.org`,
`api.weather.gov`) traverses the gateway and egresses through the consumer
VPC PSC-I Network Attachment subnet via **Cloud NAT** using static IPs. If
Cloud NAT is missing or misconfigured, external traffic hangs or resets
silently.
- Traffic destined for Google APIs (e.g., Vertex AI, Cloud Run default domains
`*.run.app`) routes through Private Google Access / Restricted Google Access
without traversing public Cloud NAT.
### Don't confuse `roles/iap.egressor` with other IAP roles
The display name "IAP-secured Egressor" maps to **`roles/iap.egressor`** —
that's the role for Agent Gateway egress. Other IAP roles exist that are easy to
mistake for it but are unrelated:
| Role ID | Purpose | Use for Agent |
: : : Gateway? :
| :--------------------------------- | :----------------- | :----------------- |
| `roles/iap.egressor` | Agent egress | **Yes — this one** |
: : through Agent : :
: : Gateway : :
| `roles/iap.tunnelResourceAccessor` | TCP/SSH tunneling | No |
: : through IAP to a : :
: : VM : :
| `roles/iap.httpsResourceAccessor` | Access to | No |
: : IAP-protected web : :
: : apps (ingress) : :
| `roles/iap.tunnelDestGroupUser` | Member of an IAP | No |
: : tunnel destination : :
: : group : :
Don't substitute. The IAP authz check explicitly looks for
`iap.webServiceVersions.egressViaIAP`, which only `roles/iap.egressor` grants
for the Agent Gateway path.
If any layer says no, the agent gets back a 403:
```
{'code': 403, 'message': "403 Forbidden. {'message': 'Egress request is not authorized.', 'status': 'Forbidden'}"}
```
## The single biggest gotcha: hostname permutations
A Google API like `aiplatform.googleapis.com` is reachable through *many*
hostnames. The agent might call any of them depending on the SDK version,
regional client config, or whether mTLS is in play:
Form | Example
:------------------------- | :--------------------------------------------
Base | `aiplatform.googleapis.com`
Base + mTLS | `aiplatform.mtls.googleapis.com`
Locational | `us-central1-aiplatform.googleapis.com`
Locational + mTLS | `us-central1-aiplatform.mtls.googleapis.com`
Regional REP (public) | `aiplatform.us-central1.rep.googleapis.com`
Regional REP (private/PSC) | `aiplatform.us-central1.p.rep.googleapis.com`
**The gateway matches hostnames exactly.** If you registered only
`aiplatform.googleapis.com` but the SDK actually called
`us-central1-aiplatform.googleapis.com`, the request gets denied — even though
"the API is registered." When investigating a 403, *always* establish what
hostname the agent actually called, then verify that *exact* hostname is in the
registry.
A registration script typically looks like this (note all five permutations):
```bash
reg_svc "${id}" "${name}" "https://${id}.googleapis.com"
reg_svc "${id}-mtls" "${name} mTLS" "https://${id}.mtls.googleapis.com"
reg_svc "${LOCATION}-${id}" "${name} Locational" "https://${LOCATION}-${id}.googleapis.com"
reg_svc "${LOCATION}-${id}-mtls" "${name} Locational mTLS" "https://${LOCATION}-${id}.mtls.googleapis.com"
reg_svc "${id}-${LOCATION}-rep" "${name} Regional (REP)" "https://${id}.${LOCATION}.rep.googleapis.com"
```
## Recommended Registry Structure: Consolidated Google APIs
To simplify management and reduce resource overhead, it is recommended to
register all Google APIs under a single `googleapis` service entry in the Agent
Registry using **multiple interfaces** (one for each required API hostname).
### Recommended Base Interfaces (Consolidated `googleapis` Service)
Your base `googleapis` service should include the following interfaces:
- `https://agentregistry.googleapis.com`
- `https://aiplatform.mtls.googleapis.com`
- `https://cloudresourcemanager.mtls.googleapis.com`
- `https://iamcredentials.mtls.googleapis.com`
- `https://telemetry.mtls.googleapis.com`
- `https://{region}-aiplatform.mtls.googleapis.com`
- `https://{region}-aiplatform.googleapis.com`
- `https://aiplatform.{region}.rep.googleapis.com`
*(Replace `{region}` with your actual region, e.g., `us-central1`.)*
- **Global-only foundation models & `.rep.mtls` pitfall**: When calling global-only Gemini models, also add `https://aiplatform.googleapis.com` to the `googleapis` service. Never construct `aiplatform.{us,eu}.rep.mtls.googleapis.com` FQDNs (multi-region `.rep.mtls` DNS records do not exist and fail with `NXDOMAIN`).
### Other Services
If you are using additional Google Cloud APIs (or custom MCPs / separate engines), ensure their exact hostnames are included on the consolidated `googleapis` service (or registered as separate non-Google services):
- `discoveryengine`
- `logging`
- `monitoring`
- `oauth2`
- `cloudtrace` and `trace`
- `iap`
- `modelarmor`
Missing any required API hostnames is the most common "agent works in dev, fails
in prod" cause.
## Metric Queries & Visualization
When diagnosing performance issues, latency spikes, or intermittent failures,
query and visualize relevant time-series metrics if you have monitoring access.
Note that the Google Cloud Console **Agent Gateway Observability** tab requires
upgrading the project's `_Default` log bucket to **Log Analytics** (`_AllLogs` view).
If the user reports "slowness" or "intermittent errors", visualize the trend
using a Mermaid `xychart-beta` chart in your diagnostic report.
### 1. Agent Gateway Egress QPS, Latency, & Error Rate
Query native Agent Gateway and underlying Secure Web Proxy metrics:
- **Metrics**: `networkservices.googleapis.com/agentgateway/request_count`, `networkservices.googleapis.com/agentgateway/total_latencies`, `networkservices.googleapis.com/agentgateway/backend_latencies`, `networkservices.googleapis.com/agentgateway/iap_authz_request_count`, and `networkservices.googleapis.com/gateway/request_count`
- **Breakby**: `response_code_class`, `gateway_name`
### 2. Agent Runtime Latency (p50/p90/p99)
Query the Agent Runtime latency to identify performance degradation:
- **Metric**: `aiplatform.googleapis.com/reasoning_engine/query_latency`
- **Breakby**: `reasoning_engine_id`, `location`
### 3. Visualizing with Mermaid
When presenting latency or error trends in the report, format them as a Mermaid
chart:
```mermaid
xychart-beta
title "Gateway Latency (p90) last 24h"
x-axis [00:00, 04:00, 08:00, 12:00, 16:00, 20:00]
y-axis "Latency (ms)" 0 --> 1000
line [120, 150, 850, 900, 140, 130]
```
## Diagnostic playbook
```
┌──────────────────────────────────────────────────────┐
│ 0. Establish context & Verify access │
└──────────────────────────┬───────────────────────────┘
▼
┌──────────────────────────────────────────────────────┐
│ 1. Pull agent logs — classify primary symptom: │
│ • Timeout / Reset → 3c (PSC) & 3d (ACT / NAT) │
│ • Crash / Traceback → 1b (Runtime stderr / OOM) │
│ • 404 on HTTPS_PROXY → 11 (L4 networkRules SNI) │
│ • NXDOMAIN / Shared VPC → 12 (DNS 2-hop & Host IAM) │
│ • Private CA TLS Error → 13 (TrustConfig & Rebind) │
│ • 60s Cutoff / SGP /429 → 14 (SGP / MA / Trace) │
│ • 403 Forbidden → Continue to Step 2 │
└──────────────────────────┬───────────────────────────┘
▼
┌──────────────────────────────────────────────────────┐
│ 2. Pull gateway logs — find EXACT hostname called │
└──────────────────────────┬───────────────────────────┘
▼
┌──────────────────────────────────────────────────────┐
│ 3. Pull IAP logs — Check V1 vs V2, DRY_RUN, decision │
│ (If no IAP entry, check 3b proxy LB log) │
└──────────────────────────┬───────────────────────────┘
▼
┌──────────────────────────────────────────────────────┐
│ 4. Is the EXACT hostname registered in Agent Registry│
│ (agents / mcp-servers / endpoints)? │
└────────────┬─────────────────────────────┬───────────┘
no │ yes │
▼ ▼
┌──────────────────────────┐ ┌──────────────────────────────┐
│ Unregistered hostname │ │ 5. Check IAM / UAP Policies │
│ permutation: register on │ │ 6. Authz extension & dual-reg│
│ consolidated googleapis │ │ 7. Agent Identity & PAB / CR │
│ or custom Service entry. │ │ 8–10. Principal, X-Proj, SWP │
└──────────────────────────┘ └──────────────────────────────┘
```
### Step 0 — Establish context & Disable prompts
Before running any diagnostics, ensure the gcloud CLI is installed (see
[Google Cloud SDK Installation](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)),
your environment is configured correctly, and prompts are disabled to prevent
commands from hanging:
1. **Disable CLI Prompts**:
```bash
gcloud config set core/disable_prompts True
```
2. **Verify Project Access**:
```bash
gcloud projects describe $PROJECT_ID
```
If this fails, you cannot proceed with log gathering. Prompt the user for
correct permissions or coordinates.
3. **Discover the Correct Project (if resources are missing)**: If the active
project (configured in `gcloud`) does not contain the expected Agent
Gateways, Agent Runtime instances, or Registry entries, it may be the wrong
project.
> **Important:** **Check Active Project First**: Always check the active
> project first before checking any other user-supplied project:
>
> ```bash
> ACTIVE_PROJ=$(gcloud config get-value project)
> gcloud network-services agent-gateways list --location=us-central1 --project=$ACTIVE_PROJ
> gcloud agent-registry agents list --location=us-central1 --project=$ACTIVE_PROJ
> ```
>
> If you find the target resources in the active project, **proceed
> immediately** and do NOT check other projects.
If you cannot find the target resource (for example, the stuck gateway or
the failing agent) in the active project:
1. **Never write or execute custom Python or bash discovery scripts** (or
multi-project/multi-region `for` loops) to scan across projects or
regions. Use individual `gcloud` CLI commands (or `curl` REST API calls
authenticated with `gcloud auth application-default print-access-token`).
2. Check at most **1–2 explicit candidate projects** provided by the user
in the target region (default `us-central1` if unspecified):
```bash
gcloud network-services agent-gateways list --location=us-central1 --project=$CANDIDATE_PROJECT_ID
gcloud agent-registry agents list --location=us-central1 --project=$CANDIDATE_PROJECT_ID
```
3. If you cannot locate any candidate resource within 2 turns, **stop
searching** and write the diagnostic report using clear placeholders
for resource names while providing the complete verification commands
and PSC subnet IP calculation formulas.
Once the project containing the resources is identified, use that
`PROJECT_ID` for all subsequent steps.
### Step 0.4 — Special Handling for Telemetry (telemetry.mtls.googleapis.com) Issues
If the symptom or error logs involve **telemetry.mtls.googleapis.com** (e.g.,
connection reset, handshake error, or `certificate verify failed` during
startup/`set_up()`):
1. This is a known issue that can be caused by Egress Gateway blocking (BKI 23)
OR SSL CA trust issues (BKI 17).
2. In your diagnostic report, **you MUST address both possibilities and
unconditionally recommend the following actions (even if resources appear to
be already configured in the dirty environment)**:
* **Verify/Perform Endpoint Registration**: Explain that
`telemetry.mtls.googleapis.com` must be registered in the Agent
Registry. **You MUST also explicitly suggest checking whether other
required monitoring/tracing endpoints (such as
`monitoring.googleapis.com` or `trace.mtls.googleapis.com`) are
registered as Endpoints** (`gcloud agent-registry endpoints list --location=$LOCATION --project=$PROJECT_ID`),
and provide the `gcloud agent-registry services create` command (using
`--endpoint-spec-type=no-spec` and `--interfaces=url=https://...,protocolBinding=JSONRPC`)
to register any missing endpoints.
* **Verify/Create Authorization Policy**: Explain that an
`AuthorizationPolicy` must allow the agent's principal set to access the
telemetry endpoint (by binding a `REQUEST_AUTHZ` policy with the IAP
extension to the gateway). **You MUST recommend creating or updating
this policy and provide the exact gcloud/Terraform configuration for
it**, even if you see a policy already bound in the project.
* **Verify CA Trust**: Recommend configuring the agent's environment
variables (`REQUESTS_CA_BUNDLE`, `SSL_CERT_FILE`, and
`GRPC_DEFAULT_SSL_ROOTS_FILE_PATH` pointing to
`/etc/ssl/certs/ca-certificates.crt`) to ensure the Python/gRPC runtime
trusts the gateway's TLS inspection CA.
### Step 0.5 — Mismatched Symptoms (Dirty Environments)
In shared evaluation or development projects, the logs you retrieve might
contain errors from previous, unrelated runs (e.g., finding an SSL `certificate
verify failed` error when the user is asking about IAP 403 errors).
If the logs you find do **not** match the symptom described in the user's prompt
(e.g., the user complains about "403 errors... logs mention IAP" but you find
"SSLError" and "no IAP logs"):
1. **Do not ignore the user's prompt.** Do not assume your log findings are the
only issue.
2. In your diagnostic report, you MUST address the user's described symptom.
3. Explain that while you found a different error in the active logs (and
diagnose it), for any logs or findings where the agent is getting a 403 to
an MCP server or endpoint, you must **check the IAP Egressor bindings on the
matching resource in the registry first**:
* If there is no registry entry for the MCP server or endpoint, ensure
there is one created.
* Ensure that the agent has the `roles/iap.egressor` role bound to the
registry entry. If there are no permissions matching, tell the user to
grant `roles/iap.egressor` against the registry entry.
* Verify that an `AuthorizationPolicy` is correctly bound to the Gateway.
4. Include these prioritized troubleshooting steps for IAP denials (checking
registry entries and `roles/iap.egressor` bindings first, checking IAP audit
logs, and verifying Gateway policies) as recommended fixes, even if you
couldn't verify them in the current log state.
### Step 1 — Confirm the symptom in agent logs
Check the Agent Runtime logs for the error (403, SSL Handshake Timeout, or
Connection Reset):
```
resource.type="aiplatform.googleapis.com/ReasoningEngine"
resource.labels.location=$LOCATION
resource.labels.reasoning_engine_id=$AGENT_ID
(textPayload:"403" OR textPayload:"handshake operation timed out" OR textPayload:"Connection reset by peer" OR textPayload:"Network is unreachable")
```
**Alternative (CLI Fallback):**
```bash
# Note: --limit=10 limits output volume to capture recent error logs while preventing context overflow and command timeouts.
gcloud logging read 'resource.type="aiplatform.googleapis.com/ReasoningEngine" AND resource.labels.location="'$LOCATION'" AND resource.labels.reasoning_engine_id="'$AGENT_ID'" AND (textPayload:"403" OR textPayload:"handshake operation timed out" OR textPayload:"Connection reset by peer" OR textPayload:"Network is unreachable")' --project=$PROJECT_ID --limit=10
```
The error payload tells you *that* it failed.
- If it is a **403**, continue with the standard Gateway/IAP flow (Step 2).
- If it is an **SSL Handshake Timeout** or **Connection Reset/Network
Unreachable**, suspect a PSC provisioning issue or subnet exhaustion. Skip
to **Step 3c**.
- If it is a **container crash**, **startup error**, or **Python exception**,
proceed to **Step 1b**.
### Step 1b — Debugging Agent Runtime Crashes (Container Crashes & Python Exceptions)
If the agent logs (Step 1) show that the Agent Runtime container failed to start
or crashed during execution (instead of a 403 or network timeout), follow this
checklist:
#### 1. Pull stderr logs for Python exceptions
Query the stderr logs specifically to find traceback info:
```
resource.type="aiplatform.googleapis.com/ReasoningEngine"
resource.labels.location=$LOCATION
resource.labels.reasoning_engine_id=$AGENT_ID
logName="projects/$PROJECT_ID/logs/aiplatform.googleapis.com%2Freasoning_engine_stderr"
```
**Alternative (CLI Fallback):**
```bash
# Note: --limit=20 fetches a sufficient recent log sample to identify startup stack traces without flooding output or timing out.
gcloud logging read 'resource.type="aiplatform.googleapis.com/ReasoningEngine" AND resource.labels.location="'$LOCATION'" AND resource.labels.reasoning_engine_id="'$AGENT_ID'" AND logName="projects/'$PROJECT_ID'/logs/aiplatform.googleapis.com%2Freasoning_engine_stderr"' --project=$PROJECT_ID --limit=20
```
Look for common Python startup failures:
- `ModuleNotFoundError` or `ImportError`: The uploaded agent code requires a
package that was not specified in the deployment requirements.
- `SyntaxError`: Syntax error in the uploaded Python files.
- Initialization crashes in the `__init__` method of the agent class.
#### 2. Check for Resource Limit Exceeded (OOM)
If the container dies silently without a Python traceback, it may have been
killed by the runtime due to Out of Memory (OOM) or CPU limits.
- Check if the requested resource limits (CPU/Memory) in `DeploymentSpec` are
sufficient.
- Look for container termination status if visible in the logs (e.g., exit
code `137` usually indicates OOMKilled).
### Step 2 — Find the failing hostname in gateway logs
```
resource.type="networkservices.googleapis.com/Gateway"
resource.labels.location="REGION"
resource.labels.gateway_name="AGENT_GATEWAY_NAME"
```
**Alternative (CLI Fallback):**
```bash
# Retrieve recent gateway entries (exclude synthetic 240.0.0.2:443 CONNECT wrapper when inspecting inner L7 calls;
# omit the NOT clause if empty so pre-IAP default_denied routing drops remain visible):
gcloud logging read 'resource.type="networkservices.googleapis.com/Gateway" AND resource.labels.location="REGION" AND resource.labels.gateway_name="AGENT_GATEWAY_NAME" AND NOT jsonPayload.enforcedGatewaySecurityPolicy.hostname="240.0.0.2:443"' --project=PROJECT_ID --limit=50
```
The gateway log entry shows the actual hostname the request targeted. Write it
down — you will need it in Step 4.
**Model Armor & SGP Special Cases (High-Confidence Indicators):**
- **Model Armor `PERMISSION_DENIED` (BKI 13)**: If `serviceExtensionInfo` shows `grpcStatus: "PERMISSION_DENIED"` on `modelarmor.*`, check gateway direction — Client-to-Agent ingress uses `service-${AGENT_PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com` whereas Agent-to-Anywhere egress uses `service-${GATEWAY_PROJECT_NUMBER}@gcp-sa-dep.iam.gserviceaccount.com` (see `references/known-issues.md` BKI #13).
- **Model Armor 60s Stream Cutoff (BKI 13 / Step 14)**: If `grpcStatus` reports `UNKNOWN` / `DEADLINE_EXCEEDED` or `Stream removed` right at **60 seconds**, Envoy hit the non-configurable 60s `CONTENT_AUTHZ` stream deadline.
- **Semantic Governance Policy Denial (BKI 38 / Step 14)**: Query `logName="projects/PROJECT_ID/logs/semantic-governance-policy"` for SGP `jsonPayload.verdict` and `jsonPayload.evaluations[].rationale` (note: streamed model calls return no verdict or an error).
### Step 3 — Check IAP allow/deny decision
> **Important:** **Data Access Logs & API Prerequisite**: IAP data-plane decisions are written to **Data Access audit logs** (`DATA_READ` type, disabled by default), and `iap.googleapis.com` must be enabled in the gateway project (`gcloud services list --enabled --filter="config.name:iap.googleapis.com" --project=$PROJECT_ID`). Verify audit config with:
>
> ```bash
> gcloud projects get-iam-policy $PROJECT_ID \
> --filter="auditConfigs.service:iap.googleapis.com" \
> --format="yaml(auditConfigs)"
> ```
>
> If empty or missing `DATA_READ` for `iap.googleapis.com`, enable it in **IAM → Audit Logs**.
Query both UAP Policy V2 (`iap.resources.egressViaIAP`) and legacy IAM v1
(`iap.webServiceVersions.egressViaIAP`) while excluding MCP base-protocol noise:
```text
protoPayload.serviceName="iap.googleapis.com"
(protoPayload.authorizationInfo.permission="iap.resources.egressViaIAP" OR protoPayload.authorizationInfo.permission="iap.webServiceVersions.egressViaIAP")
-protoPayload.metadata.mcp_attributes.base_protocol_method="true"
```
**Alternative (CLI Fallback):**
```bash
gcloud logging read 'protoPayload.serviceName="iap.googleapis.com" AND (protoPayload.authorizationInfo.permission="iap.resources.egressViaIAP" OR protoPayload.authorizationInfo.permission="iap.webServiceVersions.egressViaIAP") AND -protoPayload.metadata.mcp_attributes.base_protocol_method="true"' --project=PROJECT_ID --limit=50
```
What to read out of each entry:
- **`protoPayload.authorizationInfo[].granted`** — `true` or `false`.
- **`protoPayload.authenticationInfo.principalSubject`** — the SPIFFE /
`principal://...` URI of the caller.
- **`protoPayload.authorizationInfo[].resource`** — the registered resource
the call resolved to.
- **`labels."iap.googleapis.com/audited_resource_name"`** — if this is
`unregisteredResource`, the destination hostname isn't in the registry. Go
to Step 4.
- **The policy version & enforcement mode** — in `AuthzExtension` (`name`,
`service`, and `timeout` are all required on `import`), `iapPolicyVersion`
is uppercase `"V2"` (logged lowercase `"v2"` in audit logs):
```yaml
name: projects/PROJECT_ID/locations/LOCATION/authzExtensions/iap-authz-ext
service: iap.googleapis.com
failOpen: false
timeout: 1s
metadata:
iamEnforcementMode: "DRY_RUN" # omit (or set "ENFORCE", never "ENFORCED") for active blocking
iapPolicyVersion: "V2" # "V2" for UAP Policy V2; "V1" (or omit) for legacy IAM v1
```
* **In `DRY_RUN` mode**, denials are logged but the request proceeds. If
your agent fails with a real `403` while IAP is in dry-run, check the
gateway proxy load-balancer log (Step 3b) or the destination backend.
* **Under UAP (`iapPolicyVersion: "v2"`)**, check
`protoPayload.metadata.policyEvaluationResults[]` and audit log entries.
UAP logs will display the evaluation outcomes across the Resource
Manager hierarchy (Organization, Folder, Project).
* If an **explicit DENY** matched anywhere in the hierarchy (e.g., at
Org or Folder level), the request is rejected immediately, even if a
project-level policy allows it.
* If **no ALLOW matched**, the request is denied by default-deny.
* Check for CEL attribute mismatches (e.g., calling an unregistered
host when policies only allow `destination.agent_registry.*`, or
path mismatches like missing `.json` extensions in REST API paths).
### Step 3b — If there's no IAP audit entry for the failing call, pull the gateway proxy load-balancer log
The gateway's underlying egress proxy can deny a request before IAP runs. The
denial is in the proxy's load-balancer log. The `SECURE_WEB_GATEWAY` label here
refers to the proxy implementation under the hood:
```
jsonPayload.@type="type.googleapis.com/google.cloud.loadbalancing.type.LoadBalancerLogEntry"
resource.labels.gateway_type="SECURE_WEB_GATEWAY"
```
**Alternative (CLI Fallback):**
```bash
# Note: --limit=50 limits output volume when querying load balancer log entries.
gcloud logging read 'jsonPayload.@type="type.googleapis.com/google.cloud.loadbalancing.type.LoadBalancerLogEntry" AND resource.labels.gateway_type="SECURE_WEB_GATEWAY"' --project=PROJECT_ID --limit=50
```
Key fields to inspect:
- `httpRequest.status`: Look for `403`.
- `jsonPayload.enforcedGatewaySecurityPolicy.hostname`: Look for
`240.0.0.2:443` (expected under PSC).
- `jsonPayload.enforcedGatewaySecurityPolicy.matchedRules`: Look for
`default_denied`.
- `jsonPayload.mtls.clientCertChainVerified`: Often `false` if connection
dropped early.
If you see `240.0.0.2:443` under `hostname` and `default_denied` under
`matchedRules`, this is a routing drop. The proxy decrypted the tunnel but
failed to match the *inner* SNI hostname against the Agent Registry. Make sure
all required hostname permutations are registered.
### Step 3c — Diagnosing PSC Subnet Exhaustion
If you observe **SSL Handshake Timeouts** or **Connection Reset** in the agent
logs, or if the Agent Gateway deployment is failing/stuck, the Private Service
Connect (PSC) subnet might be out of IP addresses.
> **Note:** **CLIENT_TO_AGENT Gateways**: Both ingress (`CLIENT_TO_AGENT`) and
> egress (`AGENT_TO_ANYWHERE`) gateways can be stuck in provisioning. Ingress
> gateways do NOT populate the `agentGatewayCard` even when active, so check
> whether they are stuck by describing their network attachment and calculating
> subnet IPs.
1. **Find the Agent Gateway Name** (if not provided): List the gateways in the
project to find the one that is stuck or relevant:
```bash
gcloud network-services agent-gateways list --location=$LOCATION --project=$PROJECT_ID
```
2. **Identify the Network Attachment**: Describe the Agent Gateway to find the
Network Attachment in use:
```bash
gcloud network-services agent-gateways describe AGENT_GATEWAY_NAME --location=$LOCATION --project=$PROJECT_ID
```
Look for `networkConfig.egress.networkAttachment` or
`networkConfig.ingress.networkAttachment` (depending on gateway type).
3. **Describe the Network Attachment**:
```bash
gcloud compute network-attachments describe NETWORK_ATTACHMENT_NAME --region=$LOCATION --project=$PROJECT_ID
```
Note the `subnetwork` field.
4. **Inspect the Subnet**: Describe the subnet to check its IP range:
```bash
gcloud compute networks subnets describe SUBNET_NAME --region=$LOCATION --project=$PROJECT_ID
```
Check the `ipCidrRange` (e.g., a `/28` subnet only has 16 IP addresses, and
Google Cloud reserves 4, leaving only 12 for resources).
5. **Check IP Usage and Calculate Free IPs**:
* Find the number of allocated IPs by looking at the `connectionEndpoints`
list in the network attachment description from Step 2. Each endpoint in
that list consumes one IP address.
* Calculate the number of usable IPs in the subnet based on its
`ipCidrRange` (e.g., a `/28` subnet has 16 IPs, minus 4 reserved by
Google Cloud = 12 usable IPs; a `/16` has 65536 IPs, minus 4 = 65532
usable).
* Explicitly state the calculation in your report: `Usable IPs - Allocated
IPs = Free IPs`.
* **Flag `/28` Exhaustion Risk**: Even if the current subnet has free IPs
(or is larger, like `/16`), if you are diagnosing a stuck/failing
gateway deployment, you **MUST** explicitly mention in your report that
a `/28` subnet is too small and easily exhausted, and recommend
expanding the CIDR range to at least `/26` as a best practice.
### Step 3d — Diagnosing Agent Connectivity Template (ACT) & Network Routing
Under VPC Service Controls (VPC-SC), Agent Gateway relies on an **Agent
Connectivity Template (ACT)**. If the agent experiences timeouts, silent
connection hangs, or connection drops when attempting to reach public internet
endpoints or internal services, check the ACT and consumer network
configuration:
1. **Inspect the Agent Connectivity Template**:
```bash
gcloud network-services agent-connectivity-templates describe ACT_NAME \
--location=$LOCATION --project=$PROJECT_ID
```
Verify the `egressNetworkConfig.vpcEgress` mode:
- `vpcEgress: ALL_TRAFFIC`: Routes **all** outbound traffic (public
internet, SaaS APIs, internal RFC 1918, and Google APIs) through the
consumer VPC Network Attachment. **Mandatory for VPC Service Controls
(VPC-SC).**
- `vpcEgress: PRIVATE_RANGES_ONLY`: Routes only private/restricted ranges
(RFC 1918, RFC 6598 `100.64.0.0/10`, Class E `240.0.0.0/4`,
`private.googleapis.com` `199.36.153.8/30`, and
`restricted.googleapis.com` `199.36.153.4/30`) into the consumer VPC;
standard Google APIs use Private Google Access and public internet
traffic egresses directly from Agent Gateway.
2. **Verify Consumer Cloud NAT for External Endpoints (BKI 28)**: When
`vpcEgress: ALL_TRAFFIC` is enabled, external internet traffic (e.g.,
`api.ipify.org`, `api.weather.gov`, third-party SaaS) traverses the gateway
and exits through the consumer VPC PSC-I Network Attachment subnet.
- **Cloud NAT Requirement**: The consumer VPC **MUST** have a Cloud NAT
gateway covering the PSC-I subnet range (with Private Google Access
enabled on the subnet).
- If Cloud NAT is missing or does not cover the PSC-I subnet, TCP
connections to external internet endpoints **hang silently or reset**
without a proxy error log.
- Verify NAT status:
```bash
gcloud compute routers nats list --router=$ROUTER_NAME --region=$LOCATION --project=$PROJECT_ID
```
3. **Verify Cloud DNS Peering Scope (See Step 12)**: Agent Gateway resolves
public internet domains and non-VPC-SC Google APIs via public recursive DNS
at the gateway proxy **without** Cloud DNS peering. `dnsPeeringConfig` is
required **only** for private internal domains (e.g., `corp.internal.`) or
when enforcing VPC-SC (`googleapis.com.` mapped to
`restricted.googleapis.com` `199.36.153.4/30` or internal PSC endpoints).
4. **Ordered 7-Step Teardown & Dangling ACT References (BKI 30)**: Always
delete resources in strict dependency order, polling each async operation
to `404` before proceeding:
1. Delete or unbind `ReasoningEngine` instances (`?force=true` on REST `DELETE` if active sessions/memories exist).
2. Delete UAP `PolicyBinding` then `AccessPolicy` (`gcloud iam policy-bindings delete` → poll `404` → `gcloud iam access-policies delete`).
3. Delete `AuthzPolicy`, `TelemetryPolicy`, and `ExtensionBinding` resources targeting the gateway.
4. Delete `AuthzExtension` resources.
5. Delete `AgentGateway` and poll `gcloud network-services agent-gateways describe` until `NOT_FOUND` (`404`).
6. Delete `AgentConnectivityTemplate` (`gcloud network-services agent-connectivity-templates delete`), `TrustConfig`, and `NetworkAttachment`.
7. Delete consumer Cloud NAT, subnets, and VPC.
- If `AgentConnectivityTemplate` deletion still fails with
`FAILED_PRECONDITION: Resource ... is already being used by resource(s) .../agentGateways/...`
after Step 5 confirmed `404` and async producer cleanup has settled,
unblock deployments immediately by creating a newly named
`AgentConnectivityTemplate` and open a Google Cloud Support case citing
the stuck `agentConnectivityTemplates` URI to purge the orphaned
producer reference.
### Step 4 — Verify the hostname is registered (in the form the agent used)
List registry entries — pick the right resource type for the destination:
```bash
gcloud agent-registry endpoints list --project=$PROJECT_ID --location=$LOCATION
gcloud agent-registry mcp-servers list --project=$PROJECT_ID --location=$LOCATION
gcloud agent-registry agents list --project=$PROJECT_ID --location=$LOCATION
```
Grep the output for the exact hostname from step 2. If it's missing, that's the
root cause.
### Step 5 — Verify IAM / UAP bindings on the registered resource
Depending on whether your gateway uses **IAM v1** or **Unified Access Policy
(UAP / Policy V2)** (determined by `iapPolicyVersion` in the Authz Extension),
verify the corresponding authorization bindings:
#### Option A: Unified Access Policy (UAP / Policy V2 / IAM v3)
In UAP, access policies are bound directly to the **Google Cloud Resource
Manager (CRM) hierarchy** (Project, Folder, or Organization) rather than IAP
shadow resources.
1. **Search Policy Bindings Attached to the Target Project**:
```bash
# List bindings owned by the project (note: `list` has NO --target flag)
gcloud iam policy-bindings list --project="${PROJECT_ID}" --location=global
# Search bindings targeting the project's CRM node
gcloud iam policy-bindings search-target-policy-bindings \
--target="//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}" \
--project="${PROJECT_ID}" \
--location=global
```
2. **Search Policy Bindings on Parent Folders / Organization**:
```bash
# Folder level
gcloud iam policy-bindings search-target-policy-bindings \
--target="//cloudresourcemanager.googleapis.com/folders/${FOLDER_ID}" \
--project="${PROJECT_ID}" \
--location=global
# Organization level
gcloud iam policy-bindings search-target-policy-bindings \
--target="//cloudresourcemanager.googleapis.com/organizations/${ORGANIZATION_ID}" \
--project="${PROJECT_ID}" \
--location=global
```
3. **Inspect the Referenced AccessPolicy**:
```bash
gcloud iam access-policies describe ACCESS_POLICY_ID \
--project="${PROJECT_ID}" \
--location=global
```
* Verify the rule uses the full FQDN permission:
`iap.googleapis.com/resources.egressViaIAP`.
* Verify the agent's principal or principal set matches
`rules[].principals` (watch for orgless `proj-${PROJECT_NUMBER}`, never `project-`).
* Inspect CEL conditions: check for null dereferences (`mcp_server.method == 'tools'`), unsupported `.startsWith()`/`.matches()` on `agent_registry.*`, missing `.json` extensions in unregistered REST API paths, or blanket `destination.is_registered == false` `DENY` rules that crash container boot.
4. **Check for Org Policy Constraint Blockers (BKI 24)**: If `gcloud iam
policy-bindings create` failed with `CUSTOM_ORG_POLICY_VIOLATION`, check
whether `constraints/iam.managed.disableAccessPolicyBinding` is enforced:
```bash
gcloud org-policies describe constraints/iam.managed.disableAccessPolicyBinding --project=$PROJECT_ID
```
To unblock, apply an override disabling the constraint (`enforce: false`).
Note: IAM access policies, bindings, and Org Policy overrides take **~30 to
60 seconds** to propagate.
5. **REST API Fallback for UAP Bindings**:
```bash
curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
"https://iam.googleapis.com/v3/projects/${PROJECT_ID}/locations/global/policyBindings"
```
#### Option B: IAM v1 (Legacy Policy Model)
In IAM v1, `roles/iap.egressor` is bound directly to the IAP shadow resource at
the registry or endpoint level:
##### Registry-level IAM policy
```bash
curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-d '{}' \
-X POST "https://iap.googleapis.com/v1/projects/${PROJECT_NUMBER}/locations/${LOCATION}/iap_web/agentRegistry:getIamPolicy" \
-H "Content-Type: application/json"
```
##### Per-endpoint IAM policy
```bash
curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-d '{}' \
-X POST "https://iap.googleapis.com/v1/projects/${PROJECT_NUMBER}/locations/${LOCATION}/iap_web/agentRegistry/endpoints/${ENDPOINT_ID}:getIamPolicy" \
-H "Content-Type: application/json"
```
##### Same call, but for global registry:
```bash
curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-d '{"options": {"requestedPolicyVersion": 3}}' \
-X POST "https://iap.googleapis.com/v1/projects/${PROJECT_NUMBER}/locations/global/iap_web/agentRegistry:getIamPolicy" \
-H "Content-Type: application/json"
```
When reading the returned policy, look for a binding that matches the agent's
service account or principal set with role `roles/iap.egressor`.
### Step 6 — Inspect the gateway / authz extension wiring
#### List authz extensions
```bash
gcloud service-extensions authz-extensions list \
--location=$LOCATION --project=$PROJECT_ID
gcloud service-extensions authz-extensions describe RESOURCE_NAME \
--location=$LOCATION --project=$PROJECT_ID
```
#### Verify AuthorizationPolicy & AuthzExtension Wiring
1. **Check `iapPolicyVersion` in Authz Extension**: Describe the Authz
Extension and inspect the `metadata` map:
```bash
gcloud service-extensions authz-extensions describe RESOURCE_NAME \
--location=$LOCATION --project=$PROJECT_ID --format="yaml(metadata)"
```
- If using **UAP (Policy V2)**: `iapPolicyVersion` MUST be explicitly set
to `"V2"`.
- If using **IAM v1**: `iapPolicyVersion` is `"V1"` or unset.
- Check `iamEnforcementMode`: `"DRY_RUN"` logs evaluations without
blocking; omitting `iamEnforcementMode` (or setting `"ENFORCE"`, never
`"ENFORCED"`) actively blocks.
2. **Verify AuthorizationPolicy Binding**: Verify that the
`AuthorizationPolicy` is correctly bound to your `Gateway` (and **omits
`target.loadBalancingScheme`** when targeting `agentGateways/*`). If it is
not bound, the authorization logic will not run on gateway traffic.
- Inspect the `AuthorizationPolicy` resource.
- Ensure the policy's target matches the gateway's name and location.
3. **Verify Multi-Registry Gateway Constraints (BKI 26)**: Inspect the Agent
Gateway description:
```bash
gcloud network-services agent-gateways describe AGENT_GATEWAY_NAME \
--location=$LOCATION --project=$PROJECT_ID --format="yaml(registries)"
```
- Network Services permits at most **2 registries** bound to an Agent
Gateway.
- When 2 registries are configured, **exactly ONE must be `global`** and
the second must be **`regional` (same region as gateway) or
`multi-regional` (same jurisdiction, e.g., `us-central1` + `us`)**.
- Configuring two regional, two multi-regional, two global, or
cross-jurisdiction registries is rejected with HTTP `400` /
`InvalidArgument`.
#### List authz policies, agent gateways, and authz extensions via raw API
```bash
# authzPolicies (use v1beta1 if inspecting L4 networkRules; v1 for GA httpRules/CUSTOM)
curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
"https://networksecurity.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/authzPolicies"
# agentGateways
curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
"https://networkservices.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/agentGateways"
# authzExtensions (hosted under networkservices.googleapis.com, NOT serviceextensions.googleapis.com)
curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
"https://networkservices.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/authzExtensions"
```
### Step 7 — Verify the agent identity has the baseline roles
The agent identity itself needs least-privilege baseline permissions on the
source side:
- **Least-privilege check (`agentDefaultAccess` & `agentInvoker`)**: Deployed
Agent Identities automatically receive `roles/aiplatform.agentDefaultAccess`
and `roles/aiplatform.agentContextEditor`. Do **NOT** grant project-level
`roles/aiplatform.user` or `roles/aiplatform.expressUser` to an Agent
Identity (they allow modifying/deleting sibling `ReasoningEngine` instances);
for A2A calls, bind a custom `agentInvoker` role
(`aiplatform.reasoningEngines.{query,get}`) on the target engine only.
- `roles/agentregistry.viewer` — to discover registered catalog entries and
validate gateway bindings
- `roles/logging.logWriter`, `roles/monitoring.metricWriter`, telemetry roles
— observability
- `roles/browser` — needed for `resourcemanager.projects.get` during SDK init.
Without it, the ReasoningEngine fails startup with `Failed to convert
project number to project ID` (see known-issues §1).
- `roles/iap.httpsGatewayUser` (IAP-secured Web App User) and
`roles/iap.egressor` (IAP-secured Egressor) — to ensure the agent is
authorized to egress through IAP. **You MUST recommend verifying both roles
and the AuthorizationPolicy binding in your report's fix/debugging
section**:
1. `roles/iap.httpsGatewayUser` is typically required on the Gateway
resource.
2. `roles/iap.egressor` is required on the target Registry/Endpoint.
3. Verify that the `AuthorizationPolicy` is correctly bound to the Gateway
(ensure the policy targets the gateway resource). Do NOT omit these
recommendations even if you believe they are already correctly
configured, as they are essential verification steps for the user.
### Step 7b — Check Principal Access Boundary (PAB) policies
A PAB policy can override IAM Allow and restrict the resources the principal set
can reach.
```bash
# List org-wide PAB policies
gcloud iam principal-access-boundary-policies list \
--organization="${ORGANIZATION_ID}" --location=global
# Inspect policy bindings attached to the project resource
gcloud iam policy-bindings search-target-policy-bindings \
--location=global \
--project="${PROJECT_ID}" \
--target="//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}"
```
### Step 7c — Cloud Run / Functions Egress Authentication
If the destination is Cloud Run or Cloud Functions, direct OIDC authentication
using the default Agent Identity (`principalSet://...`) is not natively
supported by Cloud Run. The agent must use Service Account impersonation.
**You MUST recommend the following in your report if the destination is Cloud
Run:**
1. Explain that direct Agent Identity to Cloud Run OIDC auth is unsupported.
2. Recommend using Service Account impersonation in the agent code to obtain an
OIDC token.
3. Specify that the Agent Identity needs `roles/iam.serviceAccountTokenCreator`
on the target Service Account (which in turn needs `roles/run.invoker` on
the Cloud Run service). Refer to `references/known-issues.md` BKI 21 for
details and code examples.
### Step 8 — PrincipalSet vs Principal
If permissions seem flaky, suspect the **PrincipalSet** binding. Move to a **1:1
Principal binding** (bind the specific service account directly) to verify.
### Step 9 — Cross-Project Runtime-to-Gateway Binding Verification
When an Agent Runtime (Reasoning Engine) in Project A (`AE_PROJECT_NUMBER`)
binds to an Agent Gateway in Centralized Governance Project B
(`AGW_PROJECT_ID`):
1. **Check Deployer Caller Permissions:** Verify the deploying identity has
`roles/networkservices.viewer` (or `networkservices.agentGateways.get` and
`networkservices.agentGateways.use`) on the gateway in Project B:
```bash
gcloud network-services agent-gateways describe GATEWAY_NAME \
--project=AGW_PROJECT_ID \
--location=REGION
```
2. **Check Vertex AI Service Agent IAM in Gateway Project:** Ensure Project A's
service agent is authorized in Project B:
```bash
gcloud projects get-iam-policy AGW_PROJECT_ID \
--flatten="bindings[].members" \
--filter="bindings.members:service-AE_PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com" \
--format="table(bindings.role)"
```
Must have `roles/networkservices.viewer` or custom role
`ae_agw_cross_project_sa`
(`networkservices.agentGateways.get,networkservices.operations.get`).
3. **Validate Regional Colocation Invariant:** Both the runtime and the gateway
**MUST** be deployed in the exact same region (e.g. `us-central1`).
Cross-region bindings fail control plane validation with `INVALID_ARGUMENT`.
4. **Verify Context-Aware Access (CAA) Token Sharing Opt-Out:** Verify that the
agent runtime was deployed with:
`"GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES": False` Without
this, bound token enforcement drops credentials during cross-project egress,
returning `401 Context-Aware Access requirements are not met`.
5. **Validate IAP Policy Target (Server-Generated Resource ID vs. Friendly
Name):** Ensure IAP policies (`gcloud iap web add-iam-policy-binding --resource-type=agent-registry`)
target the server-generated resource ID (`agentregistry-00000000-...`
extracted via `registryResource`), NOT the friendly service name:
```bash
gcloud agent-registry services describe MCP_SERVICE_NAME \
--project=AGW_PROJECT_ID \
--location=REGION \
--format='value(registryResource)'
```
6. **Verify Cross-Project VPC Service Controls (VPC-SC):** If Project A and
Project B are in separate perimeters, ensure a perimeter bridge or
ingress/egress rules cover `aiplatform.googleapis.com`,
`networkservices.googleapis.com`, and `agentregistry.googleapis.com`.
### Step 10 — Diagnose Secure Web Proxy (SWP) and Policy-Based Routing (PBR) Egress
> **Note:** **Pattern A (Transparent Next-Hop SWP + PBR — This Step)** preserves full Agent Gateway L7 governance (IAP/UAP, Model Armor, SGP) before VPC next-hop inspection. If your Agent Runtime container instead sets `HTTPS_PROXY=https://proxy.corp.internal:443` to tunnel through an explicit forward proxy via L4 `networkRules`, jump to **Step 11**.
If the consumer VPC employs a downstream Secure Web Proxy (SWP) behind an Agent
Gateway Network Attachment for Layer 7 inspection:
1. **Verify Next-Hop SWP Deployment Mode**: Confirm SWP is deployed directly in
the consumer VPC with `type: SECURE_WEB_GATEWAY` and
`routingMode: NEXT_HOP_ROUTING_MODE`. Do NOT attempt to use PSC Service
Attachments (which only support explicit `HTTP CONNECT` proxies) or static
routes (which fail because Network Attachments cannot bear VM instance tags).
2. **Verify Policy-Based Routing (PBR) Matching**:
Ensure a PBR exists with priority 200 matching source CIDR of the PSC-I subnet
(`10.20.1.0/24`) and destination `0.0.0.0/0` routing to `--next-hop-ilb-ip=<SWP_IP>`:
```bash
gcloud network-connectivity policy-based-routes create agw-psci-to-swp-pbr \
--network=projects/PROJECT_ID/global/networks/VPC_NAME \
--source-range=10.20.1.0/24 \
--destination-range=0.0.0.0/0 \
--next-hop-ilb-ip=10.20.1.250 \
--priority=200 \
--project=PROJECT_ID
```
Ensure a default fallback PBR exists with priority 1000 routing to `DEFAULT_ROUTING`.
3. **Verify Cloud NAT `ENDPOINT_TYPE_SWG` on Proxy Subnet**:
Ensure the Cloud NAT covering the proxy-only subnet (`REGIONAL_MANAGED_PROXY`)
includes `--endpoint-types=ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG`. Without this,
SWP proxy backends cannot establish outbound connections to the internet.
4. **Verify GatewaySecurityPolicy CEL Allowlist**:
Check SWP logs for `DENIED` decisions under `networkservices.googleapis.com/Gateway`.
Verify that both external target domains and the regional AI Platform session
endpoint (`<region>-aiplatform.mtls.googleapis.com`) are allowed in CEL rules:
```cel
inUrlList(host(), ['api.weather.gov', 'api.ipify.org', 'REGION-aiplatform.mtls.googleapis.com'])
```
Omission of the regional AI Platform endpoint breaks ADK streaming queries
with HTTP 503 (`remote connection failure`).
### Step 11 — Diagnose Explicit HTTPS Proxy Egress (`HTTPS_PROXY` + L4 `networkRules`)
When an Agent Runtime container is configured with `HTTPS_PROXY=https://proxy.corp.internal:443` (explicit forward proxy over TLS) instead of transparent Next-Hop SWP:
1. **Diagnose `HTTP 404 Not Found` (`CONNECT tunnel failed, response 404`)**:
- **Cause**: Agent Gateway's default L7 listener terminates outer TLS and rejects nested `HTTP CONNECT` requests with `404` when no L4 `networkRules` policy matches the proxy's SNI (or when the proxy listens on plaintext HTTP instead of TLS `:443`, or `:443` was omitted from `HTTPS_PROXY`).
- **Verify L4 `AuthzPolicy` (`v1beta1`) & Consumer Proxy ACLs**: Confirm an `AuthzPolicy` with `action: ALLOW` and `networkRules` matching the proxy's exact SNI is imported via **`gcloud beta`** (GA `gcloud` rejects `networkRules`), **omits `target.loadBalancingScheme`**, omits `ports`, and either omits `from` or includes `7.0.0.0/8` + PSC-I CIDR in `from.sources[].ipBlocks` (while consumer VPC firewall/Squid ACLs allow only the consumer PSC-I subnet CIDR, never `7.0.0.0/8`):
```bash
gcloud beta network-security authz-policies describe ALLOW_PROXY_POLICY_NAME \
--location=$LOCATION --project=$PROJECT_ID
```
2. **Verify `NO_PROXY` / `no_proxy` Exclusions (Prevent Control-Plane Hair-Pinning)**:
- Inspect the Reasoning Engine's `deploymentSpec.env` and verify `NO_PROXY` and `no_proxy` exclude metadata and (where direct Google API routing is desired) Google APIs:
`169.254.169.254,metadata.google.internal,localhost,127.0.0.1,.googleapis.com,googleapis.com`
- Missing `NO_PROXY` routes metadata or Vertex AI session/telemetry calls into the external corporate proxy, causing boot hangs or `403` authentication failures.
3. **Verify Container-Side Private CA Trust**:
- ACT `tlsConfig.trustConfig` does **not** apply to L4-bypassed `loopback_tls_network_authz` tunnels. If the explicit proxy uses a private CA or performs TLS inspection, bundle both the proxy CA and system roots inside the agent container (`SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`, `GRPC_DEFAULT_SSL_ROOTS_FILE_PATH`).
4. **Account for the L7 Governance Trade-Off**:
- Matching an L4 `networkRules` `ALLOW` rule bypasses L7 TLS termination at Agent Gateway, skipping IAP/UAP, Model Armor, SGP, and L7 `httpRules` on traffic inside that proxy tunnel. Use **Step 10 (Next-Hop SWP + PBR)** if both Agent Gateway L7 governance and downstream VPC proxy inspection are required.
### Step 12 — Diagnose Cloud DNS Peering (2-Hop Limit) & Cross-Project Shared VPC IAM
When private hostnames fail with `NXDOMAIN` / `503` or gateway/ACT creation fails with `PERMISSION_DENIED`, `INVALID_ARGUMENT`, or `Code 13`:
1. **Inspect `AgentConnectivityTemplate` `dnsPeeringConfig`**:
```bash
gcloud network-services agent-connectivity-templates describe $ACT_NAME \
--location=$LOCATION --project=$PROJECT_ID --format="yaml(egressNetworkConfig)"
```
- Every entry in `dnsPeeringConfig.domains[]` must end with a trailing dot (e.g., `corp.internal.`, `googleapis.com.`).
- `dnsPeeringConfig.targetNetwork` is a single string URI (`projects/TARGET_VPC_PROJECT_ID/global/networks/VPC_NAME`) using the **Project ID** (not project number). Verify `networkAttachment`'s subnet belongs to the expected VPC (or a region supporting decoupled hub `targetNetwork`).
2. **Check the 2-Hop Transitive DNS Peering Limit & Root `"."` Zone Trap**:
```bash
gcloud dns managed-zones list --project=$TARGET_VPC_PROJECT_ID \
--format="table(name,dnsName,visibility,peeringConfig.targetNetwork.networkUrl,forwardingConfig)"
```
- **2-Hop Limit**: Agent Gateway's tenant peering zone consumes **Hop 1** (`Tenant VPC → Attached Spoke VPC`). If the Attached Spoke VPC uses a Cloud DNS Peering Zone (**Hop 2**) pointing to a Central Hub VPC, **the Central Hub VPC MUST host an Authoritative Private Zone** (or resolve locally). Chaining to a *third* DNS Peering Zone returns `NXDOMAIN` / `SERVFAIL` (`503`).
- **Root `"."` Domain Trap**: Peering `"."` works **only** with a Cloud DNS **Private Forwarding Zone** pointing to an upstream recursive resolver. Configuring an **Authoritative** Private Zone for `"."` breaks all public internet and `*.googleapis.com` resolution with `NXDOMAIN`.
3. **Verify Dual-Principal Cross-Project / Shared VPC IAM on `TARGET_VPC_PROJECT_ID`**:
- **Caller / Provisioning Identity**: Needs `roles/compute.networkViewer`, `roles/dns.reader`, `roles/networkconnectivity.regionalEndpointAdmin`, and `roles/networkconnectivity.consumerNetworkAdmin` (or `roles/viewer`) on the host project, plus `compute.networkAttachments.use` (`roles/compute.networkUser`) when referencing a host-project attachment.
- **Agent Gateway Service Agent (`service-${AGW_PROJECT_NUMBER}@gcp-sa-agentgateway.iam.gserviceaccount.com`)**: Needs `roles/dns.peer`, `roles/dns.reader`, and `roles/compute.networkViewer` plus `roles/compute.networkUser` (when Network Attachment is in the service project, recommended) OR `roles/compute.networkAdmin` (when Network Attachment is in the host project):
```bash
gcloud projects get-iam-policy $TARGET_VPC_PROJECT_ID \
--flatten="bindings[].members" \
--filter="bindings.members:service-${AGW_PROJECT_NUMBER}@gcp-sa-agentgateway.iam.gserviceaccount.com" \
--format="table(bindings.role)"
```
### Step 13 — Diagnose Private CA `TrustConfig` TLS Failures & ACT Immutability
When private HTTPS destinations or `*.googleapis.com` calls fail TLS verification after attaching a Certificate Manager `TrustConfig`:
1. **Inspect `TrustConfig` & `additionalRoots`**:
```bash
gcloud certificate-manager trust-configs describe $TRUST_CONFIG_NAME \
--location=$LOCATION --project=$PROJECT_ID
```
- Confirm the `TrustConfig` is in the **exact same project and region** as the Agent Gateway and `AgentConnectivityTemplate`, and that target server certificates include a **Subject Alternative Name (SAN)** matching the hostname.
- **`*.googleapis.com` Breakage (`PUBLICLY_TRUSTED_ROOTS`)**: Check `egressNetworkConfig.tlsConfig.additionalRoots` on the ACT. If set to `NO_ADDITIONAL_ROOTS`, Agent Gateway rejects Google-signed certificates for `*.googleapis.com` and all public HTTPS APIs! Set `additionalRoots: PUBLICLY_TRUSTED_ROOTS`.
2. **Apply Updates via New ACT + Gateway Rebind (Immutability Rule)**:
- `tlsConfig.trustConfig` is **immutable** on an existing `AgentConnectivityTemplate`, and attached Agent Gateways **do not pick up in-place `tlsConfig` edits**.
- **Fix**: Create a **new** `AgentConnectivityTemplate` (e.g., `act-v2`) referencing the **same** `networkAttachment` with the corrected `tlsConfig`, then re-import/update the `AgentGateway` YAML to point `agentConnectivityTemplate` to `act-v2`.
### Step 14 — Diagnose SGP, Model Armor 60s Stream Timeouts, Native MCP Rules, & Cloud Trace
1. **Semantic Governance Policies (SGP)**:
- Query SGP data-plane evaluation logs (`verdict`, `evaluations[].rationale`, `token_usage`):
```bash
gcloud logging read 'logName="projects/'$PROJECT_ID'/logs/semantic-governance-policy"' \
--project=$PROJECT_ID --limit=20
```
- If streamed model calls (`:streamGenerateContent`, `:streamRawPredict`) return **no verdict or an error** (or produce zero entries in `logs/semantic-governance-policy`), invoke models **without streaming** and verify the `CONTENT_AUTHZ` `AuthzPolicy` includes the non-streaming `when` CEL filter using `.contains()` (`:generateContent`, `:rawPredict`, `/v1/messages`, `/chat/completions`) while excluding `application/grpc` (unexcluded gRPC crashes startup).
- If SGP unexpectedly began blocking in staging, inspect `gcloud service-extensions authz-extensions describe $EXT_NAME --location=$LOCATION --project=$PROJECT_ID --format="yaml(metadata)"` — updating `sgpUserIntentMatching` replaces the entire `metadata` map and wipes `sgpEnforcementMode: "DRY_RUN"` if omitted.
- If SGP policy/engine CLI commands return `SEMANTIC_GOVERNANCE_POLICY_AGENT_NOT_CONFIGURED` or `SEMANTIC_GOVERNANCE_POLICY_ENGINE_NOT_ENABLED_IN_REGION`, confirm the Reasoning Engine was created with `AGENT_IDENTITY` + `agent_gateway_config`, `service-${PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com` has `roles/compute.networkAdmin` and `roles/dns.admin`, consumer VPC subnets avoid `10.0.0.0/24`–`10.0.2.0/24`, and the engine is `ACTIVE` (with ACT DNS peering resolving `dnsRecord`).
2. **Model Armor (`CONTENT_AUTHZ`) `PERMISSION_DENIED` vs. 60s `Stream removed`**:
- **`PERMISSION_DENIED` (BKI 13)**: Check gateway direction! **Client-to-Agent (ingress)** requires `roles/modelarmor.calloutUser` (agent project) + `roles/modelarmor.user` (template project) on `service-${AGENT_PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com` (and sanitizes **only** ADK `streamQuery`). **Agent-to-Anywhere (egress)** requires `roles/modelarmor.calloutUser` + `roles/serviceusage.serviceUsageConsumer` (gateway project) + `roles/modelarmor.user` (template project) on `service-${GATEWAY_PROJECT_NUMBER}@gcp-sa-dep.iam.gserviceaccount.com`.
- **`500`/`504` or gRPC `UNKNOWN: Stream removed` at ~60s**: Envoy enforces a hard 60-second total stream deadline on `CONTENT_AUTHZ`. Narrow `AuthzPolicy.httpRules` to exclude long-running streams or gRPC channels.
3. **Native MCP `AuthzPolicy` Handshake `403`**:
- If `AuthzPolicy` uses `httpRules[].to.operations[].mcp` with `action: ALLOW` and MCP clients fail on `initialize` or `ping`, set `baseProtocolMethodsOption: MATCH_BASE_PROTOCOL_METHODS` (default is `SKIP_BASE_PROTOCOL_METHODS`).
4. **Missing Spans in Cloud Trace (`TelemetryPolicy` Preview)**:
- Verify `cloudtrace.googleapis.com` is enabled, `gcloud beta network-services telemetry-policies describe $POLICY_NAME --location=$LOCATION --project=$PROJECT_ID` targets the gateway with non-zero `samplingRate`, and **`roles/cloudtrace.agent`** is granted on the project to all three gateway service agents (`service-${PROJECT_NUMBER}@compute-system.iam.gserviceaccount.com`, `service-${PROJECT_NUMBER}@gcp-sa-networksecurity.iam.gserviceaccount.com`, `service-${PROJECT_NUMBER}@gcp-sa-agentgateway.iam.gserviceaccount.com`) plus the calling agent's workload SA (for parent spans).
## Quick reference: the checks in order
When triaging a `403` or connection failure, walk these in order:
1. Confirm the error in the agent log (`403` vs. SSL Handshake Timeout vs. Connection Reset vs. Crash).
2. Find the *exact hostname* in the gateway log (if `403`).
3. Check IAP audit log: decision, principal, policy version (`iapPolicyVersion="v2"` vs. `"V1"`), `iamEnforcementMode`, and watch for `unregisteredResource`.
- 3b. If no IAP audit entry, pull gateway proxy load-balancer log.
- 3c. If SSL Handshake Timeout or Connection Reset, run the PSC Subnet Exhaustion Check (`subnets describe`, `/28` → `/26`).
- 3d. If timeouts or silent connection drops to public internet under VPC-SC, verify Agent Connectivity Template (`vpcEgress: ALL_TRAFFIC` vs. `PRIVATE_RANGES_ONLY`) and Consumer Cloud NAT routing.
4. Confirm exact hostname permutation is registered in Agent Registry (`googleapis` consolidated service + custom entries).
5. Check IAM / UAP Policies on the target:
- IAM v1: Check `roles/iap.egressor` (`--resource-type=agent-registry`).
- UAP (Policy V2): Check CRM `PolicyBinding` (`search-target-policy-bindings`) and `AccessPolicy` across Project, Folder, and Org; check `constraints/iam.managed.disableAccessPolicyBinding` (~30–60s propagation).
6. Check `AuthzExtension` (`iapPolicyVersion: "V2"` vs. `"V1"`), `AuthzPolicy` targets (omit `loadBalancingScheme`), and multi-registry constraints (max 2: 1 `global` + 1 same-region or same-jurisdiction multi-regional).
7. Confirm least-privilege Agent Identity roles (no `expressUser` / `aiplatform.user`; use `agentInvoker` for A2A). 7b. Check PAB policies. 7c. Check Cloud Run egress auth (SA impersonation or `--iap --functional-type=mcp-server`).
8. If behavior is flaky, test with a 1:1 `principal://` binding.
9. If cross-project runtime binding (Project A → Gateway in Project B), verify deployer and service agent viewer permissions on Project B, regional colocation, CAA opt-out (`GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES: False`), and server-generated resource UUID in IAP bindings.
10. If routing egress through a transparent downstream Secure Web Proxy (SWP), verify `NEXT_HOP_ROUTING_MODE`, PBR priority 200 on PSC-I subnet to `--next-hop-ilb-ip`, Cloud NAT `ENDPOINT_TYPE_SWG`, and `GatewaySecurityPolicy` CEL allowlist.
11. If routing egress through an explicit corporate proxy (`HTTPS_PROXY=https://...:443` returning `404`), verify `gcloud beta` L4 `AuthzPolicy` (`networkRules` matching `snis`), `NO_PROXY`, container Private CA trust, and L7 bypass trade-offs.
12. If private DNS returns `NXDOMAIN` or Shared VPC setup fails, verify `dnsPeeringConfig` trailing dots, the **2-hop transitive DNS peering limit** (authoritative zone at Hop 2), root `"."` forwarding-only rule, and dual-principal Host Project IAM.
13. If Private CA `TrustConfig` breaks `*.googleapis.com` or edits fail to apply, set `additionalRoots: PUBLICLY_TRUSTED_ROOTS` on a **new** ACT and rebind the `AgentGateway`.
14. If requests fail at 60s (`Stream removed`), return no SGP verdict or error on streaming, block MCP `initialize`, or drop Cloud Trace spans, verify Model Armor `httpRules` scoping & ingress/egress SAs, SGP non-streaming invocation + `.contains()` CEL filter & full `metadata` map, MCP `MATCH_BASE_PROTOCOL_METHODS`, and `TelemetryPolicy` `roles/cloudtrace.agent` grants.
known-issues.md 87.6 KB
# Best Known Issues (BKIs) and limitations
Concrete failure modes that come up repeatedly with the Agent Platform —
symptoms and fixes. Read this when the symptom in front of you matches one of
these patterns; it's faster than walking the full diagnostic flow.
## Table of Contents
- [1. ReasoningEngine startup: project ID conversion](#1-reasoningengine-startup-failed-to-convert-project-number-to-project-id): Lines 50-72
- [2. ReasoningEngine startup: Assembly Service init](#2-reasoningengine-startup-assembly-service-failed-to-initialize): Lines 73-85
- [3. Reasoning Engine Gateway Sharing Constraints, Pre-April 29, 2026 Instances, & SCC Threat Detection](#3-reasoning-engine-gateway-sharing-constraints-pre-april-29-2026-instances--scc-threat-detection): Lines 86-115
- [4. 403 / Egress not authorized — missing authz_policy or UAP binding](#4-403--egress-request-is-not-authorized--missing-authz_policy-or-uap-binding): Lines 116-150
- [5. IAP ENFORCE / Blanket DENY blocks Agent Runtime startup](#5-iap-enforce-mode--blanket-deny-blocks-agent-runtime-startup): Lines 151-180
- [6. Private CA & Self-Signed TLS Destinations (TrustConfig, PUBLICLY_TRUSTED_ROOTS, & ACT Rebind)](#6-private-ca--self-signed-tls-destinations-fail-handshake-missing-trustconfig-or-publicly_trusted_roots): Lines 181-233
- [7. Principal Access Boundary (PAB) override](#7-principal-access-boundary-pab-policies-overriding-iam-allow): Lines 234-269
- [8. Gateway proxy denies before IAP](#8-gateway-proxy-denies-the-request-before-iap-runs): Lines 270-320
- [9. Cross-Project / VPC Agent Gateway & ACT Import Failures (PERMISSION_DENIED, INVALID_ARGUMENT, or Code 13)](#9-cross-project--vpc-agent-gateway--act-import-failures-permission_denied-invalid_argument-or-code-13): Lines 321-396
- [10. Cross-Project Runtime-to-Gateway Binding Failures](#10-cross-project-runtime-to-gateway-binding-failures-permission_denied-invalid_argument-or-caa-token-suppression): Lines 397-609
- [11. RE Container Crash: Dependency Mismatch](#11-reasoning-engine-container-crash-python-dependency-mismatch--startup-exceptions): Lines 610-632
- [12. mTLS Egress Failure: Expired Cert](#12-mtls-egress-failure-invalid-or-expired-client-certificate): Lines 633-654
- [13. Model Armor Integration Fails with 500, PERMISSION_DENIED, or 60s Stream Termination](#13-model-armor-integration-fails-with-500-permission_denied-or-60-second-stream-termination-stream-removed): Lines 655-721
- [15. Egress Blocked: Empty Registry IAM Policy](#15-egress-blocked-empty-agent-registry-iam-policy-403-forbidden): Lines 722-758
- [16. RE deployment fails with Code 13](#16-reasoning-engine-deployment-fails-with-code-13-internal-error): Lines 759-807
- [17. RE outbound SSL handshake failure (Egress Gateway)](#17-reasoning-engine-outbound-ssl-handshake-failure-certificate_verify_failed-with-egress-agent-gateway): Lines 808-862
- [18. VPC-SC Perimeter Blocks Provisioning](#18-vpc-service-controls-vpc-sc-perimeter-blocks-agent-gateway-provisioning): Lines 863-964
- [19. PSC Subnet Exhaustion Fails Deployment](#19-psc-subnet-exhaustion-fails-agent-gateway-deployment): Lines 965-1013
- [20. Config Validation Failure: Missing Agent Registry API / Caller Permissions](#20-config-validation-failure-missing-agent-registry-api-enablement): Lines 1014-1052
- [21. Agent Identity Egress to Cloud Run/Funcs (JWT issue)](#21-agent-identity-egress-to-cloud-run--functions-fails-with-401403-jwt-auth-issue): Lines 1053-1104
- [22. Cross-Project Agent Not Visible in Central Registry](#22-cross-project-agent-or-mcp-server-not-visible-in-central-governance-registry): Lines 1105-1130
- [23. Telemetry Egress Blocked by Egress Gateway](#23-telemetry-egress-blocked-by-egress-agent-gateway-startup-failure): Lines 1131-1178
- [24. UAP Org Policy Blocker (disableAccessPolicyBinding)](#24-uap-org-policy-blocker-constraintsiammanageddisableaccesspolicybinding): Lines 1179-1213
- [25. UAP Policy Binding Destruction Race Condition](#25-uap-policy-binding-destruction-race-condition-400-failed_precondition): Lines 1214-1234
- [26. Agent Gateway Multi-Registry & Jurisdiction Validation Errors](#26-agent-gateway-multi-registry--jurisdiction-validation-errors): Lines 1235-1262
- [27. CEL Null Dereference Crash on Non-Tool MCP Methods](#27-cel-null-dereference-crash-on-non-tool-mcp-methods): Lines 1263-1282
- [28. ACT ALL_TRAFFIC Silent Outbound Hang (Missing Cloud NAT)](#28-act-all_traffic-silent-outbound-hang-missing-cloud-nat): Lines 1283-1307
- [29. Agent Gateway Control-Plane Mutation Concurrency Lock (HTTP 409 ABORTED)](#29-agent-gateway-control-plane-mutation-concurrency-lock-http-409-aborted): Lines 1308-1325
- [30. ACT Deletion Fails with 400 FAILED_PRECONDITION (already being used)](#30-act-deletion-fails-with-400-failed_precondition-already-being-used): Lines 1326-1358
- [31. Reasoning Engine Deletion Preconditions (Active Sessions)](#31-reasoning-engine-deletion-preconditions-active-sessions-require-forcetrue): Lines 1359-1374
- [32. REST API Path Matching Gotcha (.json and Query Strings)](#32-rest-api-path-matching-gotcha-json-extensions-and-query-strings): Lines 1375-1398
- [33. Secure Web Proxy (SWP) & Policy-Based Routing (PBR) Egress Failures](#33-secure-web-proxy-swp--policy-based-routing-pbr-egress-failures): Lines 1399-1474
- [34. Explicit Forward HTTPS Proxy (HTTP CONNECT) Fails with HTTP 404 or 403](#34-explicit-forward-https-proxy-http-connect-fails-with-http-404-or-403-through-agent-gateway): Lines 1475-1557
- [35. Cloud DNS Transitive Peering Chain Exceeded (>2 Hops) or Authoritative Root Zone (".")](#35-cloud-dns-transitive-peering-chain-exceeded-2-hops-or-authoritative-root-zone--causing-servfail--nxdomain): Lines 1558-1603
- [36. Consumer VPC Packet Intercept (HTTP 503) & Workforce/Workload Identity Federation Limits](#36-consumer-vpc-packet-intercept-http-503--workforce--workload-identity-federation-code-13--403-limits): Lines 1604-1639
- [37. Immediate HTTP 498 After Binding Agent Runtime, or Gemini Enterprise UpdateEngine Failures](#37-immediate-http-498-after-binding-agent-runtime-to-gateway-or-gemini-enterprise-regional-updateengine-failures): Lines 1640-1673
- [38. Semantic Governance Policy (SGP) Failures](#38-semantic-governance-policy-sgp-failures-startup-grpc-crash-streaming-bypass-missing-agent-in-picker-or-metadata-overwrite): Lines 1674-1727
- [39. Native MCP AuthzPolicy Blocks Session Handshake (MATCH_BASE_PROTOCOL_METHODS)](#39-native-mcp-authzpolicy-blocks-session-handshake-initialize--ping-due-to-missing-match_base_protocol_methods--extensionbinding-double-invocation): Lines 1728-1785
--------------------------------------------------------------------------------
## 1. ReasoningEngine startup: "Failed to convert project number to project ID"
**Symptom:**
- Log name: `aiplatform.googleapis.com/reasoning_engine_stderr`
- Error text: `google.api_core.exceptions.Unknown: None` or `Failed to convert
project number to project ID.`
- Happens during ReasoningEngine startup, before any user code runs.
**Cause:** The ReasoningEngine's system identity (the principal set it runs
under) lacks `resourcemanager.projects.get`, which the Agent Runtime SDK needs
to resolve the project name during init.
**Fix:** Grant `roles/browser` to the ReasoningEngine principal set:
```bash
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
--member="principalSet://agents.global.org-${ORG_ID}.system.id.goog/attribute.platformContainer/aiplatform/projects/${PROJECT_NUMBER}" \
--role="roles/browser"
```
--------------------------------------------------------------------------------
## 2. ReasoningEngine startup: "Assembly Service failed to initialize"
**Symptom:** `[1099] ERROR: Assembly Service failed to initialize.` in
`reasoning_engine_stderr`.
**Cause:** Generic "init failed" — usually a downstream symptom of either #1
(project-number resolution) or a runtime error in the agent's `set_up()` method.
**Investigation:** Pull all `severity=ERROR` from `reasoning_engine_stderr`
around the same timestamp; the actual root cause is in the same window.
--------------------------------------------------------------------------------
## 3. Reasoning Engine Gateway Sharing Constraints, Pre-April 29, 2026 Instances, & SCC Threat Detection
**Symptom:** Binding or updating a Reasoning Engine (Agent Runtime) to use an
Agent Gateway fails with `INVALID_ARGUMENT`, `FAILED_PRECONDITION`, or `Internal
error encountered` (`Code 13`).
**Causes & Platform Limits:**
1. **Shared Gateway Per `(project, region)` Invariant**: Multiple Reasoning
Engines in the same project and region **can** share an Agent Gateway,
provided **every** bound Reasoning Engine in that `(project, region)` binds
to the **exact same** egress and/or ingress gateway instance. Attempting to
bind a second engine in the same region to a *different* gateway (`gateway-B`
while `gateway-A` is active) fails.
2. **Creation Date Cutoff (April 29, 2026)**: Reasoning Engines created before
April 29, 2026 cannot be updated in-place to bind to an Agent Gateway and
must be redeployed as new instances.
3. **SCC Agent Engine Threat Detection Conflict**: Agent Gateway binding is
incompatible with Security Command Center (SCC) Agent Engine Threat
Detection in the same project.
4. **Revision Traffic Requirement**: Updating `agent_gateway_config` on an
existing Reasoning Engine requires 100% of traffic on the latest revision
and archives prior revisions.
**Fix:** Bind all Reasoning Engines in a given `(project, region)` to the same
Agent Gateway, redeploy any pre-April 29, 2026 engines, and disable SCC Agent
Engine Threat Detection before attaching an Agent Gateway.
--------------------------------------------------------------------------------
## 4. 403 / "Egress request is not authorized" — missing `authz_policy` or UAP binding
**Symptom:** Audit logs show `GatekeeperAuthorizer.AuthorizeUser` returning
`Permission Denied` for `iap.webServiceVersions.egressViaIAP` or
`iap.googleapis.com/resources.egressViaIAP`.
**Cause:**
1. **Missing AuthzPolicy Attachment**: The IAP authz extension exists, but no
`authz_policy` targets the specific Agent Gateway (`target.resources[]`).
2. **Missing or Misconfigured UAP Binding (Policy V2)**: When the gateway uses
`iapPolicyVersion: "V2"`, no `PolicyBinding` binds an `AccessPolicy` to the
target CRM node
(`//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}`), or the
target resource was specified using the string project ID instead of the
numeric project number.
**Fix:**
1. Verify the `authz_policy` targets the gateway:
```bash
gcloud network-security authz-policies list --location=${LOCATION}
```
2. If using UAP, verify the policy binding targets the numeric project number:
```bash
gcloud iam policy-bindings search-target-policy-bindings \
--target="//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}" \
--project="${PROJECT_ID}" \
--location=global
```
--------------------------------------------------------------------------------
## 5. IAP `ENFORCE` mode / Blanket DENY blocks Agent Runtime startup
**Symptom:** Agent Runtime instances fail to deploy or start, with 403s or
connection resets in startup logs (`reasoning_engine_stderr`).
**Cause:**
1. **Default-Deny without Bootstrap Endpoints**: With IAP in `ENFORCE` mode on
the Agent Gateway, all egress is denied by default — including bootstrap
calls the agent runtime makes to `telemetry.mtls.googleapis.com`,
`cloudresourcemanager`, `aiplatform`, `logging`, `monitoring`, etc.
2. **Blanket Unregistered DENY in UAP**: An Org or Folder Admin created an
explicit `effect: DENY` rule on `(destination.is_registered == false)`.
Because DENY has absolute precedence and cannot be overridden by
project-level rules, Reasoning Engine boot traffic to
`telemetry.mtls.googleapis.com` is dropped immediately.
**Fix:**
- Ensure all required monitoring/telemetry endpoints
(`telemetry.mtls.googleapis.com`, `monitoring.googleapis.com`,
`trace.mtls.googleapis.com`, `cloudtrace.googleapis.com`) are registered in
the Agent Registry and permitted by policy.
- **Never create a blanket DENY on `destination.is_registered == false`**.
Rely on gateway default-deny instead.
- Set IAP to `DRY_RUN` (`iamEnforcementMode: "DRY_RUN"`) to observe failing
destinations without blocking container initialization.
--------------------------------------------------------------------------------
## 6. Private CA & Self-Signed TLS Destinations Fail Handshake (Missing `TrustConfig` or `PUBLICLY_TRUSTED_ROOTS`)
**Symptom:**
- **Symptom A**: Outbound calls through Agent Gateway to internal MCP servers
or private endpoints using Private CA or self-signed certificates fail TLS
handshake verification.
- **Symptom B**: After attaching a Certificate Manager `TrustConfig` to an
Agent Connectivity Template (ACT), private endpoints succeed, **but all
calls to `*.googleapis.com` and public HTTPS APIs suddenly fail TLS
verification**.
- **Symptom C**: Updating `tlsConfig` in-place on an existing ACT fails with
an immutability error or does not take effect on the running gateway.
**Cause:**
1. Private CA roots (via `trustStores`) or self-signed leaf certificates (via
`allowlistedCertificates`) must be configured in a Certificate Manager
`TrustConfig` in the **same project and region** and attached to
`egressNetworkConfig.tlsConfig.trustConfig` on the ACT.
2. When `trustConfig` is set without `additionalRoots: PUBLICLY_TRUSTED_ROOTS`,
`additionalRoots` defaults to `NO_ADDITIONAL_ROOTS`, stripping Mozilla/Google
public root CAs from the gateway proxy's trust store.
3. `egressNetworkConfig.tlsConfig.trustConfig` is **immutable** on an existing
ACT resource.
**Fix:**
1. Create a regional Certificate Manager `TrustConfig` (`trustStores` for
Private CA chains or `allowlistedCertificates` for self-signed leaf certs;
target certs must contain a valid SAN).
2. Create a **new** ACT (`act-v2.yaml`) referencing the `TrustConfig` **and**
explicitly setting `additionalRoots: PUBLICLY_TRUSTED_ROOTS`:
```yaml
name: projects/PROJECT_ID/locations/REGION/agentConnectivityTemplates/agw-act-v2
accessPath: AGENT_TO_ANYWHERE
deploymentModel: CENTRALIZED
egressNetworkConfig:
networkAttachment: projects/PROJECT_ID/regions/REGION/networkAttachments/agw-na
vpcEgress: ALL_TRAFFIC
tlsConfig:
trustConfig: projects/PROJECT_NUMBER/locations/REGION/trustConfigs/private-ca-trust
additionalRoots: PUBLICLY_TRUSTED_ROOTS
```
3. Import the new ACT (`gcloud network-services agent-connectivity-templates
import agw-act-v2 --source=act-v2.yaml --location=REGION`) and rebind the
Agent Gateway (`agentConnectivityTemplate: .../agentConnectivityTemplates/agw-act-v2`)
via `gcloud network-services agent-gateways import`.
--------------------------------------------------------------------------------
## 7. Principal Access Boundary (PAB) policies overriding IAM Allow
**Symptom:** Agent identity has the right egress permissions bound
(`roles/iap.egressor` under Policy V1 or `iap.googleapis.com/resources.egressViaIAP`
under UAP Policy V2) and the destination is registered, but calls still return `403`.
**Cause:** A Principal Access Boundary policy is restricting the scope of
resources the principal can access. **PAB policies take precedence over IAM
Allow and UAP policies** — even a valid egress grant does nothing if a PAB
blocks the target resource.
**Investigation:** List PAB policies and inspect policy bindings attached to the
target project resource (`--location=global` and a full CRM resource URI are
required):
```bash
# List org-wide PAB policies
gcloud iam principal-access-boundary-policies list \
--organization="${ORGANIZATION_ID}" --location=global
# Inspect policy bindings attached to the project resource
gcloud iam policy-bindings search-target-policy-bindings \
--location=global \
--project="${PROJECT_ID}" \
--target="//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}"
# Inspect a specific PAB
gcloud iam principal-access-boundary-policies search-policy-bindings "${PAB_POLICY_ID}" \
--organization="${ORGANIZATION_ID}" --location=global
```
**Fix:** Either widen the PAB to include the destination resource, or remove the
PAB binding from the agent's principal set if it shouldn't apply.
--------------------------------------------------------------------------------
## 8. Gateway proxy denies the request before IAP runs
**Symptom:** Requests fail with no IAP audit log entry — IAP never saw them.
**Cause:** The gateway's underlying egress proxy (a Google-managed Secure Web
Proxy instance) enforces a deny-by-default posture *before* IAP authz runs. When
the proxy itself denies a call, IAP doesn't get a chance to evaluate, so no IAP
audit-log entry is produced for that call.
**Specific Case: CONNECT to PSC VIP (`240.0.0.2:443`) with Default Denied** In
environments using Private Service Connect (PSC), clients resolve Google APIs to
internal VIPs (e.g., `240.0.0.2:443`). Consequently, the outer tunnel request is
logged as `CONNECT 240.0.0.2:443` in the proxy logs. **This is expected
behavior.** Because TLS inspection is enabled on the Secure Web Proxy (SWP), the
proxy intercepts this CONNECT tunnel and inspects the TLS handshake to extract
the actual SNI hostname (e.g., `us-central1-aiplatform.googleapis.com`) for
routing and policy evaluation. If the extracted SNI hostname is **not**
registered in the Agent Registry, the proxy cannot match the route. The proxy
then denies the connection, logging a `403` on the `CONNECT` request with
`hostname: 240.0.0.2:443` and matching the `default_denied` rule.
**Investigation:** Pull the gateway proxy load-balancer logs:
```
jsonPayload.@type="type.googleapis.com/google.cloud.loadbalancing.type.LoadBalancerLogEntry"
resource.labels.gateway_type="SECURE_WEB_GATEWAY"
```
**Alternative (CLI Fallback):**
```bash
gcloud logging read 'jsonPayload.@type="type.googleapis.com/google.cloud.loadbalancing.type.LoadBalancerLogEntry" AND resource.labels.gateway_type="SECURE_WEB_GATEWAY"' --project=PROJECT_ID --limit=50
```
Key fields to inspect in the match:
- `httpRequest.status`: Look for `403`.
- `jsonPayload.enforcedGatewaySecurityPolicy.hostname`: Look for
`240.0.0.2:443` (expected PSC CONNECT target).
- `jsonPayload.enforcedGatewaySecurityPolicy.matchedRules`: Look for
`default_denied`.
- `jsonPayload.mtls.clientCertChainVerified`: Often `false` because the
handshake was interrupted on route match failure.
**Fix:** Identify the inner hostname the agent was attempting to reach (e.g.
`us-central1-aiplatform.googleapis.com`) and ensure ALL required hostname
permutations are registered in the Agent Registry. The proxy relies on these
registry entries to dynamically build its routing table.
--------------------------------------------------------------------------------
## 9. Cross-Project / VPC Agent Gateway & ACT Import Failures (`PERMISSION_DENIED`, `INVALID_ARGUMENT`, or `Code 13`)
**Symptom:**
- During `gcloud network-services agent-connectivity-templates import` or
`gcloud network-services agent-gateways import`, the command fails with:
- Structured preflight `PERMISSION_DENIED` or `INVALID_ARGUMENT` naming
either **the caller** or **`service-GATEWAY_PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com`**, OR
- Synchronous `{"code": 13, "message": "an internal error has occurred"}`
on unexpected downstream actuation failures.
**Cause:**
1. **Dual-Principal Validation**: Cross-project Network Attachment and Cloud DNS
peering validation checks **both** the caller identity (EUC / CI pipeline)
**and** the Agent Gateway Control Plane Service Agent
(`service-GATEWAY_PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com`).
2. **Malformed `NetworkAttachment` URI**: Using `/locations/REGION/` instead of
`/regions/REGION/` fails validation with `invalid network attachment URI`.
3. **DNS `targetNetwork` & Zone Rules**: Every entry in `dnsPeeringConfig.domains[]`
must end with a trailing dot (e.g., `corp.internal.`). Progressive regional
rollout supports decoupling `dnsPeeringConfig.targetNetwork` from the
`NetworkAttachment` VPC (pointing directly at a DNS Hub VPC); in regions not
yet enabled, `targetNetwork` must match the `NetworkAttachment` VPC (with at
most 1 customer Cloud DNS Peering Zone hop to the Hub VPC — see BKI #35).
**Fix:**
1. **Grant Caller / Provisioning Permissions on the Host Network/DNS Project**:
Grant `roles/compute.networkViewer`, `roles/dns.reader`,
`roles/networkconnectivity.regionalEndpointAdmin`, and
`roles/networkconnectivity.consumerNetworkAdmin` (or `roles/viewer`), plus
`compute.networkAttachments.use` (`roles/compute.networkUser`) if the
`NetworkAttachment` resides in the host project:
```bash
gcloud projects add-iam-policy-binding TARGET_NETWORK_PROJECT_ID \
--member="user:OPERATOR_EMAIL" \
--role="roles/compute.networkViewer"
gcloud projects add-iam-policy-binding TARGET_NETWORK_PROJECT_ID \
--member="user:OPERATOR_EMAIL" \
--role="roles/dns.reader"
```
2. **Grant Agent Gateway Service Agent Permissions on the Host Network/DNS Project**
(ensure `dns.googleapis.com` is enabled):
```bash
# Grant roles/compute.networkUser (if NA is in service project, recommended)
# or roles/compute.networkAdmin (if NA is in host project) + networkViewer:
gcloud projects add-iam-policy-binding TARGET_NETWORK_PROJECT_ID \
--member="serviceAccount:service-GATEWAY_PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com" \
--role="roles/compute.networkUser"
gcloud projects add-iam-policy-binding TARGET_NETWORK_PROJECT_ID \
--member="serviceAccount:service-GATEWAY_PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com" \
--role="roles/compute.networkViewer"
# Grant DNS peer + reader on the target DNS project:
gcloud projects add-iam-policy-binding TARGET_DNS_PROJECT_ID \
--member="serviceAccount:service-GATEWAY_PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com" \
--role="roles/dns.peer"
gcloud projects add-iam-policy-binding TARGET_DNS_PROJECT_ID \
--member="serviceAccount:service-GATEWAY_PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com" \
--role="roles/dns.reader"
```
3. Verify `connectionPreference: ACCEPT_AUTOMATIC` (or explicit project
acceptance) on `projects/PROJECT_ID/regions/REGION/networkAttachments/NAME`,
and verify `service-GATEWAY_PROJECT_NUMBER@gcp-sa-dep.iam.gserviceaccount.com`
holds `roles/compute.networkUser` on the consumer PSC-I subnet.
--------------------------------------------------------------------------------
## 10. Cross-Project Runtime-to-Gateway Binding Failures: PERMISSION_DENIED, INVALID_ARGUMENT, or CAA Token Suppression
**Symptom:**
- **Symptom A (Deployer PERMISSION_DENIED):** Calling Vertex AI
`client.agent_engines.create(...)` or REST API in Project 1
(`AE_PROJECT_ID`) referencing an Agent Gateway in Project 2
(`AGW_PROJECT_ID`) fails synchronously with: `ERROR:
(gcloud.ai.reasoning-engines.create) PERMISSION_DENIED: Permission
'networkservices.agentGateways.use' denied on resource
'//networkservices.googleapis.com/projects/AGW_PROJECT_ID/locations/REGION/agentGateways/GATEWAY_NAME'`
- **Symptom B (Control-Plane INVALID_ARGUMENT):** Deployment fails with:
`INVALID_ARGUMENT: Agent Gateway project in
spec.deployment_spec.agent_gateway_config.agent_to_anywhere_config.agent_gateway
must match the Vertex AI project.` or region mismatch `INVALID_ARGUMENT:
Agent Gateway location in spec... must match the Vertex AI location.`
- **Symptom C (CAA 401 Unauthenticated Egress):** Runtime container deploys
successfully, but egress requests to external endpoints or MCP tools fail
immediately with: `Error Code: "401", Error Details: "Context-Aware Access
requirements are not met"` or `Request had invalid authentication
credentials.`
- **Symptom D (Proxy 403 PERMISSION_DENIED on MCP Tool / Service Name):**
Egress through the gateway fails with HTTP 403 `PERMISSION_DENIED`, even
though `roles/iap.egressor` was granted to the friendly service name in
Agent Registry.
- **Symptom E (Unsupported Folder-Level principalSet):** Policy binding using
`principalSet://TRUST_DOMAIN/attribute.platformContainer/aiplatform/folders/FOLDER_NUMBER`
fails silently or is rejected as an invalid principal identifier.
- **Symptom F (VPC-SC Perimeter Block):** Egress calls fail with
`VPC_SERVICE_CONTROLS_VIOLATION` across project boundaries.
**Cause:**
1. **Regional Colocation & Shared-Gateway Invariants:** Cross-project binding
(`spec.deploymentSpec.agentGatewayConfig.agentToAnywhereConfig.agentGateway`)
is supported across Google Cloud projects, provided **both the runtime and
the gateway reside in the exact same Google Cloud region** (e.g.,
`us-central1`). Cross-region bindings are rejected with `INVALID_ARGUMENT`,
and all bound runtimes in a given `(project, region)` must share the same
gateway instance.
2. **Missing Deployer and Service Agent IAM Permissions:**
- The **deploying principal** (user EUC, Cloud Build SA, or pipeline
identity) must have `networkservices.agentGateways.use` and
`networkservices.agentGateways.get` on the gateway in `AGW_PROJECT_ID`.
- The runtime project's **Vertex AI Service Agent**
(`service-AE_PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com`)
must hold `roles/networkservices.viewer` (or custom role
`ae_agw_cross_project_sa` — also documented as `ar_agw_cross_project_sa`
— with `networkservices.agentGateways.get` and
`networkservices.operations.get`) on `AGW_PROJECT_ID`.
3. **Context-Aware Access (CAA) Token Suppression:** By default, Google Cloud
SDKs and `google-auth` enforce bound token protection. In cross-project
egress, bound token requirements reject requests unless the runtime
explicitly sets the environment variable
`GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES: False`.
4. **Friendly Service Name vs. Server-Generated Resource ID Trap:** In Agent
Registry, services, endpoints, and mcp-servers are written via `gcloud
agent-registry services create`. However, IAP authorization (`gcloud iap web
add-iam-policy-binding`) must bind to the **server-generated resource ID**
(`agentregistry-00000000-...`, extracted from the `registryResource` field),
NOT the friendly service name (`[MCP_SERVICE_NAME]`). Binding to the
friendly service name attaches the policy to a non-existent IAP resource.
5. **SPIFFE principalSet Syntax Limitation:**
`attribute.platformContainer/aiplatform/folders/FOLDER_NUMBER` is **not** an
indexed attribute in IAM SPIFFE URI evaluation. Scoping must strictly use
project-level syntax
(`attribute.platformContainer/aiplatform/projects/PROJECT_NUMBER`) or
trust-domain-wide syntax (`principalSet://TRUST_DOMAIN/*`), or use Principal
Access Boundary (PAB) policies.
6. **VPC Service Controls Perimeter Boundary:** If Project 1 (`AE_PROJECT_ID`)
and Project 2 (`AGW_PROJECT_ID`) reside in different perimeters, perimeter
bridging or bidirectional ingress/egress rules covering
`aiplatform.googleapis.com`, `networkservices.googleapis.com`, and
`agentregistry.googleapis.com` are required.
**Investigation:**
1. **Check Deployer Permissions on Gateway:**
```bash
gcloud network-services agent-gateways describe GATEWAY_NAME \
--project=AGW_PROJECT_ID \
--location=REGION
```
If this fails with `PERMISSION_DENIED`, the deployer lacks read/use
permissions.
2. **Check Vertex AI Service Agent IAM on Gateway Project:**
```bash
gcloud projects get-iam-policy AGW_PROJECT_ID \
--flatten="bindings[].members" \
--filter="bindings.members:service-AE_PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com" \
--format="table(bindings.role)"
```
Verify that `roles/networkservices.viewer` or custom role
`ae_agw_cross_project_sa` is present.
3. **Verify Runtime Region vs. Gateway Region:** Ensure both the Reasoning
Engine runtime and the Agent Gateway are deployed in the same region.
4. **Inspect Runtime CAA Environment Variable:** Inspect the Reasoning Engine
deployment spec or Python definition. Verify that `env_vars` contains
`"GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES": False`.
5. **Verify IAP Binding Target Resource ID:**
```bash
# Fetch the server-generated registryResource identifier
gcloud agent-registry services describe MCP_SERVICE_NAME \
--project=AGW_PROJECT_ID \
--location=REGION \
--format='value(registryResource)'
```
Confirm that `gcloud iap web add-iam-policy-binding` used the trailing UUID
(`agentregistry-00000000-...`) as `--mcp-server` or `--agent`, not the
friendly name.
6. **Check VPC-SC Status:** Confirm whether `AE_PROJECT_ID` and
`AGW_PROJECT_ID` reside in the same VPC-SC perimeter or have perimeter
ingress/egress rules allowing communication.
**Fix:**
1. **Grant Deployer Permissions:** Grant `roles/networkservices.viewer` (or
permissions `networkservices.agentGateways.use` and
`networkservices.agentGateways.get`) to the deploying identity on
`AGW_PROJECT_ID`:
```bash
gcloud projects add-iam-policy-binding AGW_PROJECT_ID \
--member="user:DEPLOYER_EMAIL" \
--role="roles/networkservices.viewer"
```
2. **Grant Vertex AI Service Agent Permissions:** Grant the Agent Runtime's
service agent access to the governance project: *Option A (Standard Viewer
Role):*
```bash
gcloud projects add-iam-policy-binding AGW_PROJECT_ID \
--member="serviceAccount:service-AE_PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com" \
--role="roles/networkservices.viewer"
```
*Option B (Least-Privilege Custom Role):*
```bash
gcloud iam roles create ae_agw_cross_project_sa \
--project="AGW_PROJECT_ID" \
--title="AE AGW Cross Project SA" \
--description="Custom role for cross-project service agent to access Agent Gateways and Operations" \
--permissions="networkservices.agentGateways.get,networkservices.operations.get" \
--stage="GA"
gcloud projects add-iam-policy-binding AGW_PROJECT_ID \
--member="serviceAccount:service-AE_PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com" \
--role="projects/AGW_PROJECT_ID/roles/ae_agw_cross_project_sa"
```
3. **Configure Runtime with CAA Opt-Out:** In the agent runtime deployment
configuration:
```python
remote_agent = client.agent_engines.create(
agent=local_agent,
config={
"agent_gateway_config": {
"agent_to_anywhere_config": {
"agent_gateway": (
"projects/AGW_PROJECT_ID/locations/REGION/agentGateways/AGENT_GATEWAY_TO_ANYWHERE_NAME"
)
},
},
"identity_type": types.IdentityType.AGENT_IDENTITY,
"env_vars": {
"GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES": (
False
),
},
},
)
```
4. **Bind IAP Role to the Server-Generated Resource ID:**
```bash
REGISTRY_RESOURCE=$(gcloud agent-registry services describe MCP_SERVICE_NAME \
--project=AGW_PROJECT_ID \
--location=REGION \
--format='value(registryResource)')
RESOURCE_ID=$(basename "$REGISTRY_RESOURCE")
AGENT_PRINCIPAL="principal://agents.global.org-ORG_ID.system.id.goog/resources/aiplatform/projects/AE_PROJECT_NUMBER/locations/REGION/reasoningEngines/ENGINE_ID"
gcloud iap web add-iam-policy-binding \
--project=AGW_PROJECT_ID \
--region=REGION \
--resource-type=agent-registry \
--mcp-server="${RESOURCE_ID}" \
--member="$AGENT_PRINCIPAL" \
--role="roles/iap.egressor"
```
5. **Use Valid principalSet Syntax:** For baseline Google APIs access, avoid
folder-level scoping. Use project-level scoping:
```
principalSet://agents.global.org-ORG_ID.system.id.goog/attribute.platformContainer/aiplatform/projects/AE_PROJECT_NUMBER
```
or trust-domain-wide scoping:
```
principalSet://agents.global.org-ORG_ID.system.id.goog/*
```
--------------------------------------------------------------------------------
## 11. Reasoning Engine Container Crash: Python Dependency Mismatch / Startup Exceptions
**Symptom:**
- Log name: `aiplatform.googleapis.com/reasoning_engine_stderr`
- Error text: `ModuleNotFoundError: No module named '...'` or `ImportError:
cannot import name '...'` or Python tracebacks.
- The Reasoning Engine fails to deploy or dies immediately after creation.
**Cause:** The Python code uploaded for the Reasoning Engine depends on external
packages that were not specified or incorrectly specified during deployment.
**Fix:**
1. Identify the missing or mismatched package from the traceback in
`reasoning_engine_stderr`.
2. Update your `requirements.txt` file or the `requirements` parameter in your
deployment script (e.g. `deploy_agent.py`) to include the correct package
and version constraint.
3. Re-deploy the Reasoning Engine.
--------------------------------------------------------------------------------
## 12. mTLS Egress Failure: Invalid or Expired Client Certificate
**Symptom:**
- Gateway proxy load-balancer logs show connection drops or `403` errors.
- Logs contain `jsonPayload.mtls.clientCertChainVerified: false` or handshake
failures.
- The agent fails to reach the destination MCP server when using mTLS.
**Cause:** The client certificate used by the Agent Gateway is expired, not yet
valid, or not trusted by the destination server (CA mismatch).
**Fix:**
1. Verify the certificate validity dates and CA chain.
2. If expired or invalid, upload a new certificate to Certificate Manager and
update the corresponding `ClientTlsPolicy` resource.
3. Ensure the destination server trusts the CA that signed the gateway's client
certificate.
--------------------------------------------------------------------------------
## 13. Model Armor Integration Fails with 500, `PERMISSION_DENIED`, or 60-Second Stream Termination (`Stream removed`)
**Symptom:**
- **Symptom A (`PERMISSION_DENIED`)**: Calling the agent returns `500 Internal
Server Error`; gateway logs show `grpcStatus: "PERMISSION_DENIED"` on
`modelarmor.*` and `authzPolicyInfo.result: DENIED`.
- **Symptom B (`Stream removed` at 60 Seconds)**: Long-running streaming
responses or outbound HTTP/2 gRPC channels cut off right at **60 seconds**
with HTTP `500`/`504` or gRPC `UNKNOWN: Stream removed`.
**How to Identify:**
```text
resource.type="networkservices.googleapis.com/Gateway"
jsonPayload.serviceExtensionInfo.backendTargetName : "modelarmor"
jsonPayload.serviceExtensionInfo.backendTargetType="BACKEND_SERVICE"
```
**Cause:**
1. **Distinct Ingress vs. Egress Service Agents**:
- **Agent-to-Anywhere (Egress, max 4 `CONTENT_AUTHZ` policies)** executes
callouts under the **Service Extensions Service Agent**:
`service-GATEWAY_PROJECT_NUMBER@gcp-sa-dep.iam.gserviceaccount.com`.
- **Client-to-Agent (Ingress, max 1 `CONTENT_AUTHZ` policy, sanitizes ADK
`streamQuery` only)** executes callouts under the **AI Platform Reasoning
Engine Service Agent**:
`service-AGENT_PROJECT_NUMBER@gcp-sa-aiplatform-re.iam.gserviceaccount.com`.
> **Warning:** Basic `roles/owner` or `roles/editor` grants do **not** satisfy Model Armor data-plane callout checks.
2. **Non-Configurable 60-Second Stream Deadline**: Envoy enforces a hard
**60-second total stream lifetime** on `CONTENT_AUTHZ` callouts (independent
of per-callout `AuthzExtension.timeout` `1s–10s`), and file/PDF sanitization
is unsupported in gateway integration.
**Fix:**
1. **For Agent-to-Anywhere (Egress)**: Grant `roles/modelarmor.calloutUser` and
`roles/serviceusage.serviceUsageConsumer` on the **gateway project**, plus
`roles/modelarmor.user` on the **Model Armor template project**, to
`service-GATEWAY_PROJECT_NUMBER@gcp-sa-dep.iam.gserviceaccount.com`:
```bash
gcloud projects add-iam-policy-binding GATEWAY_PROJECT_ID \
--member="serviceAccount:service-GATEWAY_PROJECT_NUMBER@gcp-sa-dep.iam.gserviceaccount.com" \
--role="roles/modelarmor.calloutUser"
gcloud projects add-iam-policy-binding GATEWAY_PROJECT_ID \
--member="serviceAccount:service-GATEWAY_PROJECT_NUMBER@gcp-sa-dep.iam.gserviceaccount.com" \
--role="roles/serviceusage.serviceUsageConsumer"
gcloud projects add-iam-policy-binding TEMPLATE_PROJECT_ID \
--member="serviceAccount:service-GATEWAY_PROJECT_NUMBER@gcp-sa-dep.iam.gserviceaccount.com" \
--role="roles/modelarmor.user"
```
2. **For Client-to-Agent (Ingress)**: Grant `roles/modelarmor.calloutUser` on
the **agent runtime project** and `roles/modelarmor.user` on the **template
project** to
`service-AGENT_PROJECT_NUMBER@gcp-sa-aiplatform-re.iam.gserviceaccount.com`.
3. **Scope `AuthzPolicy.httpRules` to Exclude Long-Lived Streams & gRPC**:
Restrict `CONTENT_AUTHZ` `httpRules` (e.g., `!request.headers['content-type'].startsWith('application/grpc')`
and targeted non-streaming tool/model hosts) so `>60s` streams bypass inline
`CONTENT_AUTHZ` buffering.
--------------------------------------------------------------------------------
## 15. Egress Blocked: Empty Agent Registry IAM Policy (403 Forbidden)
**Symptom:** All egress attempts through the gateway fail with a `403 Permission
Denied` (logged as `Egress request is not authorized`).
**Cause:** The IAM policy on the `agent-registry` resource in the consumer
project is empty or lacks bindings for the agent. The agent's service account
must be explicitly granted the `roles/iap.egressor` role.
**Fix:** Grant the `roles/iap.egressor` role to the agent's service account at
the registry level.
1. Create a `policy.json` file:
```json
{
"bindings": [
{
"role": "roles/iap.egressor",
"members": [
"serviceAccount:YOUR_AGENT_SERVICE_ACCOUNT_EMAIL"
]
}
]
}
```
2. Apply the policy to the Agent Registry:
```bash
gcloud iap web set-iam-policy policy.json \
--resource-type=agent-registry \
--project=YOUR_PROJECT_ID
```
--------------------------------------------------------------------------------
## 16. Reasoning Engine deployment fails with Code 13 (Internal Error)
**Symptom:**
- Agent Runtime deployment fails with generic Code 13: `Failed to deploy to
Agent Platform: Failed to update Agent Runtime: {'code': 13, 'message':
'Please refer to our troubleshooting pages...'}`.
- The instance is immediately cleaned up.
### Root Cause A: Conflicting Second Gateway in Shared Tenant Project (`gateway-A` vs. `gateway-B`)
- **Underlying Cause:** Agent Runtime allocates one shared tenant project per
customer `(project, region)`. Multiple Reasoning Engines in that `(project,
region)` **can** share the same `gateway-A`, **but** attempting to bind a
Reasoning Engine to a *different* gateway (`gateway-B`) while `gateway-A` is
active fails due to wildcard route conflict (also triggered on pre-April 29,
2026 engines or projects with SCC Agent Engine Threat Detection enabled — see
BKI #3).
- **Fix:** Reuse the existing `gateway-A` across all Reasoning Engines in that
`(project, region)`, or migrate cleanly:
1. Delete any active Reasoning Engines in the region bonded to the old
gateway.
```bash
curl -X DELETE -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" "https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/reasoningEngines/${REASONING_ENGINE_ID}?force=true"
```
2. If the old Reasoning Engines are already deleted but routes are stuck,
delete the old gateway resource to force cleanup:
```bash
gcloud network-services agent-gateways delete OLD_GATEWAY_NAME --location=LOCATION --project=PROJECT_ID
```
3. Retry deployment bonded to the new gateway.
### Root Cause B: Container Startup Timeout or Initialization Failure
- **Underlying Cause:** The container fails to complete initialization within
the startup timeout limit (due to syntax errors, missing dependencies, slow
network calls, or permission denials).
- **Fix:**
1. Verify the container can start locally.
2. Check Cloud Logging at the time of deployment for Python tracebacks.
3. De-risk initialization code by lazy loading heavy dependencies.
--------------------------------------------------------------------------------
## 17. Reasoning Engine outbound SSL handshake failure (CERTIFICATE_VERIFY_FAILED) with Egress Agent Gateway
**Symptom:**
- Log show: `CERTIFICATE_VERIFY_FAILED: self signed certificate in certificate
chain`
- Occurs when a Reasoning Engine makes outbound calls while bound to an Egress
Agent Gateway with `AGENT_IDENTITY` enabled.
**Cause:** When outgoing connections pass through Secure Web Proxy (SWG) on the
Agent Gateway, SWG performs TLS decryption and inspection using a dynamic
certificate signed by its custom root CA. If the Reasoning Engine trust store
does not contain these root certificates, outbound handshakes fail.
For custom container or prebuilt image deployments, the automated trust
certificate injection is skipped, so the gateway's root certificates are not
baked into the container.
**Fix / Workaround:**
- **For Source/Config-based Deployments (Agent Runtime SDK):** Create the
Agent Gateway first and wait until provisioning completes. Verify root
certificates are ready:
```bash
gcloud network-services agent-gateways describe GATEWAY_NAME \
--location=LOCATION \
--format="value(agentGatewayCard.rootCertificates)"
```
Once this returns PEM certificates, deploy/update the Reasoning Engine. The
pipeline will automatically bake them in.
- **For Custom Container / Prebuilt Image Deployments:** Extract the gateway's
PEM root certificates using `gcloud network-services agent-gateways describe`
(note: `gcloud network-services` has **no** `export-cacerts` subcommand) and bake them into your container image:
```bash
gcloud network-services agent-gateways describe GATEWAY_NAME \
--location=LOCATION \
--project=PROJECT_ID \
--format="value[delimiter=\n](agentGatewayCard.rootCertificates)" > agw_root.crt
```
```dockerfile
COPY agw_root.crt /usr/local/share/ca-certificates/agw-gateway.crt
RUN chmod 644 /usr/local/share/ca-certificates/agw-gateway.crt && update-ca-certificates
ENV GRPC_DEFAULT_SSL_ROOTS_FILE_PATH=/etc/ssl/certs/ca-certificates.crt
ENV REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
ENV AGENT_GATEWAY_ROOT_CERT_302034098528=/etc/ssl/certs/ca-certificates.crt
```
--------------------------------------------------------------------------------
## 18. VPC Service Controls (VPC-SC) Perimeter Blocks Agent Gateway Provisioning
> **Note:** **Native VPC-SC Creation Support:** As of September 8, 2026, Agent
> Gateway creation inside a VPC-SC perimeter **works natively out of the box**
> without requiring manual control-plane ingress policies, provided the Agent
> Connectivity Template (ACT) specifies `vpcEgress: ALL_TRAFFIC` and consumer
> DNS resolves `googleapis.com.` to `restricted.googleapis.com` (`199.36.153.4/30`).
**Symptom:**
- Deployment of Agent Gateway fails or runtime egress is blocked when the
project is inside a VPC-SC perimeter.
- Violation logs show `NETWORK_NOT_IN_SAME_SERVICE_PERIMETER` or similar
VPC-SC blocks for calls between the consumer project and Google-managed
infrastructure.
**Cause:**
1. **ACT Egress Mode Misconfiguration (Primary Cause):** The Agent Connectivity
Template is configured with `vpcEgress: PRIVATE_RANGES_ONLY` or the gateway is
deployed in Standalone mode (without an ACT). In these modes, traffic bypasses
the customer's VPC perimeter boundaries, causing VPC-SC to reject the
deployment or egress calls.
2. **Legacy or Strict Custom Perimeters (Historical):** Prior to September 8, 2026,
control plane provisioning workflows required explicit ingress policies for
Google-managed service agents. In legacy or custom perimeters that block
Google-managed actuation identities, explicit ingress policies may still be
required.
**Fix:**
1. **Verify ACT `ALL_TRAFFIC`, `restricted.googleapis.com` DNS, & Shared VPC Co-Membership:**
Ensure the ACT uses `vpcEgress: ALL_TRAFFIC` on a consumer PSC-I Network
Attachment with Cloud NAT, configure a consumer Cloud DNS private zone for
`googleapis.com.` (`*.googleapis.com` CNAME → `restricted.googleapis.com.` →
`199.36.153.4/30`) peered via `dnsPeeringConfig`, and ensure any Shared VPC
host project resides inside the **same** VPC-SC perimeter as the gateway and
runtime projects.
2. **Configure Ingress Policies (Legacy / Restrictive Perimeters Fallback):** If
operating in a strict perimeter where Google-managed actuation identities are
blocked, configure ingress policies in your VPC-SC perimeter to allow the
actuation identities. Two ingress rules are required:
### Rule 1: Gateway Control Plane Actuation
Allows the control plane service agent to manage gateway resources.
- **From**:
- Identities:
`serviceAccount:actuation-a@networkservices-prod.iam.gserviceaccount.com`
- Sources: Access Level `*`
- **To**:
- Operations:
- Service: `compute.googleapis.com`
- Methods:
- `FirewallsService.Delete`, `FirewallsService.Get`
- `GlobalOperationsService.Get`
- `HealthChecksService.Delete`, `HealthChecksService.Get`
- `InstanceTemplatesService.Delete`,
`InstanceTemplatesService.Get`
- `NetworksService.Delete`, `NetworksService.Get`
- `RegionAddressesService.Delete`
- `RegionBackendServicesService.Delete`,
`RegionBackendServicesService.Get`
- `RegionForwardingRulesService.Delete`,
`RegionForwardingRulesService.Get`
- `RegionInstanceGroupManagersService.Delete`,
`RegionInstanceGroupManagersService.Get`
- `RegionOperationsService.Get`
- `RegionRoutersService.Delete`, `RegionRoutersService.Get`
- `RoutesService.Delete`, `RoutesService.Get`
- `ServiceAttachmentsService.Delete`,
`ServiceAttachmentsService.Get`
- `SubnetworksService.Delete`, `SubnetworksService.Get`,
`SubnetworksService.List`
- `ZonesService.List`
- Service: `cloudresourcemanager.googleapis.com`
- Methods: `Projects.SetIamPolicy`
- Service: `networkservices.googleapis.com` (Methods: `*`)
- Service: `networksecurity.googleapis.com` (Methods: `*`)
- Service: `serviceusage.googleapis.com` (Methods: `*`)
- Service: `certificatemanager.googleapis.com` (Methods: `*`)
- Service: `privateca.googleapis.com` (Methods: `*`)
- Resources: `projects/CUSTOMER_PROJECT_NUMBER`
### Rule 2: Agent Runtime
Allows the Agent Runtime pipeline agent to access security resources.
- **From**:
- Identities:
`serviceAccount:cloud-aiplatform-pipeline-robot-prod@system.gserviceaccount.com`
- Sources: Access Level `*`
- **To**:
- Operations:
- Service: `networksecurity.googleapis.com` (Methods: `*`)
- Resources: `projects/CUSTOMER_PROJECT_NUMBER`
Replace `CUSTOMER_PROJECT_NUMBER` with your actual project number.
--------------------------------------------------------------------------------
## 19. PSC Subnet Exhaustion Fails Agent Gateway Deployment
**Symptom:**
- Agent Gateway deployment fails or gets stuck during provisioning.
- Resource allocation errors related to IP addresses in GCE logs.
**Cause:** The Private Service Connect (PSC) Network Attachment requires free IP
addresses in its allocated subnet to establish connections. If the subnet
(especially if it is small, like `/28`) runs out of free IP addresses, the
gateway cannot allocate the necessary interfaces and deployment fails.
**Fix:** Verify and expand the PSC subnet.
1. **Find the Agent Gateway Name** (if not provided): List the gateways in the
project:
```bash
gcloud network-services agent-gateways list --location=$LOCATION --project=$PROJECT_ID
```
2. **Identify the subnetwork used by the gateway's Network Attachment**:
Describe the gateway:
```bash
gcloud network-services agent-gateways describe AGENT_GATEWAY_NAME --location=$LOCATION --project=$PROJECT_ID
```
Look for `networkConfig.egress.networkAttachment` or
`networkConfig.ingress.networkAttachment`.
3. **Describe the Network Attachment to find the subnet name**:
```bash
gcloud compute network-attachments describe <ATTACHMENT_NAME> --region=$LOCATION --project=$PROJECT_ID
```
4. **Describe the subnetwork to check the CIDR range**:
```bash
gcloud compute networks subnets describe <SUBNET_NAME> --region=$LOCATION --project=$PROJECT_ID
```
5. If the subnet is small (e.g. `/28` or `/29`), it may be exhausted. Allocate
a larger subnet (minimum `/26` recommended) or expand the existing one, and
recreate the network attachment and gateway if necessary.
--------------------------------------------------------------------------------
## 20. Config Validation Failure: Missing Agent Registry API enablement
**Symptom:** During `gcloud network-services agent-gateways import`, the command
fails with:
```text
ERROR: (gcloud.network-services.agent-gateways.import) {
"code": 3,
"details": [
{
"@type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "most likely missing permissions in project <PROJECT_NUMBER>, location <LOCATION>: agentregistry.agents.list, agentregistry.endpoints.list, and agentregistry.mcpServers.list",
"field": "resource.registries"
}
]
}
],
"message": "Config validation failed"
}
```
**Cause:** Primary cause: the Agent Registry API (`agentregistry.googleapis.com`)
is not enabled in the target registry project (even though the error message
suggests missing permissions). Secondary cause (when the API is already enabled):
the caller running `agent-gateways import` lacks `roles/agentregistry.viewer`
(`agentregistry.agents.list`, `agentregistry.endpoints.list`,
`agentregistry.mcpServers.list`) on the registry project.
**Fix:** Enable the Agent Registry API in the project (and ensure the deploying
caller holds `roles/agentregistry.viewer`):
```bash
gcloud services enable agentregistry.googleapis.com --project=YOUR_PROJECT_ID
```
--------------------------------------------------------------------------------
## 21. Agent Identity Egress to Cloud Run / Functions fails with 401/403 (JWT Auth issue)
**Symptom:** The agent is registered in the Agent Registry with an Agent
Gateway. When attempting to call an MCP server or tool hosted on Cloud Run or
Cloud Functions, the request fails with an egress error or HTTP 401 Unauthorized
/ 403 Forbidden.
**Cause:** Direct Agent Identity (using `principalSet`) to Cloud Run OIDC
authentication is not supported natively. Cloud Run requires a standard OIDC ID
token, which the default agent identity cannot obtain directly.
**Fix / Workaround:** The agent must use Service Account impersonation to obtain
an OIDC ID token to authenticate with Cloud Run.
1. **Configure IAM Permissions:**
* The Agent Identity (`principalSet://...`) must have the
`roles/iam.serviceAccountTokenCreator` role on a target Service Account
(e.g. `mcp-invoker-sa`).
* The target Service Account must have `roles/run.invoker` on the Cloud
Run service.
2. **Enable Service Account Token Creator API:** Ensure
`iamcredentials.googleapis.com` is enabled in the project.
3. **Impersonate in Code:** Use the Google Auth SDK to impersonate the Service
Account and generate ID tokens for the Cloud Run audience. Example Python
(ADK):
```python
from google.auth import impersonated_credentials
import google.auth
source_creds, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
impersonated = impersonated_credentials.Credentials(
source_credentials=source_creds,
target_principal="YOUR_TARGET_SA_EMAIL",
target_scopes=["https://www.googleapis.com/auth/cloud-platform"],
)
id_token_creds = impersonated_credentials.IDTokenCredentials(
target_credentials=impersonated,
target_audience="YOUR_CLOUD_RUN_URL_ORIGIN",
include_email=True,
)
# Use id_token_creds to authenticate requests to Cloud Run.
```
4. **Alternative (Preview — Cloud Run MCP Servers Only):** Deploy the Cloud Run
MCP server with native IAP (`gcloud beta run deploy SERVICE --allow-unauthenticated
--iap --functional-type=mcp-server`), grant `roles/run.invoker` to
`service-PROJECT_NUMBER@gcp-sa-iap.iam.gserviceaccount.com`, and target the
deterministic `https://SERVICE-PROJECT_NUMBER.REGION.run.app` short URL.
--------------------------------------------------------------------------------
## 22. Cross-Project Agent or MCP Server Not Visible in Central Governance Registry
**Symptom:** You deployed an agent or MCP server in Workload Project A, but
`gcloud agent-registry agents list` or `mcp-servers list` in Central Governance
Project B does not show it.
**Cause:** Automatic registration discovers resources **only within the same
project** where `agentregistry.googleapis.com` is enabled (there is no automatic
cross-project discovery or `gcloud agent-registry boundary` CLI command).
**Fix:** Manually register cross-project agents, MCP servers, and endpoints in
the Central Governance Project's registry using `gcloud agent-registry services
create` in a specific region or `global` (never `us` or `eu`):
```bash
# Example: Register a cross-project A2A agent (omit --interfaces with a2a-agent-card)
gcloud agent-registry services create cross-proj-agent \
--project=GOVERNANCE_PROJECT_ID \
--location=REGION \
--display-name="Cross-Project Agent" \
--agent-spec-type=a2a-agent-card \
--agent-spec-content=agent-card.json
```
--------------------------------------------------------------------------------
## 23. Telemetry Egress Blocked by Egress Agent Gateway (Startup Failure)
**Symptom:** Reasoning Engine deployment fails to start up (container crashes
during `set_up()`). Logs show connection reset or handshake errors to
`telemetry.mtls.googleapis.com`.
**Cause:** Your project is using an **Egress Agent Gateway** (default-deny). The
agent runtime connects to Google telemetry services during startup. Because
these endpoints are not registered in the Agent Registry and allowed via policy,
the gateway blocks the connection, causing the startup probe to fail.
**Fix:** Register the required telemetry endpoints in the Agent Registry and
allow access via policy.
1. **Verify & Register Telemetry and Tracing Endpoints:** You MUST explicitly
check and verify whether all required monitoring and tracing endpoints
(`telemetry.mtls.googleapis.com`, `monitoring.googleapis.com`,
`trace.mtls.googleapis.com`, `cloudtrace.googleapis.com`) are registered as
Endpoints in the Agent Registry:
```bash
gcloud agent-registry endpoints list --location=us-central1 --project=$PROJECT_ID
```
In Agent Registry, read-only `Endpoint` entries are projected automatically
from writable `Service` entries (`gcloud agent-registry endpoints` is read-only
with no `create` subcommand). Register or update your consolidated `googleapis` service
with `--endpoint-spec-type=no-spec` so all required telemetry/tracing FQDNs
are projected as Endpoints:
```bash
gcloud agent-registry services create googleapis \
--location=us-central1 \
--project=$PROJECT_ID \
--display-name="Google APIs" \
--endpoint-spec-type=no-spec \
--interfaces=url=https://telemetry.mtls.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://monitoring.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://trace.mtls.googleapis.com,protocolBinding=JSONRPC \
--interfaces=url=https://cloudtrace.googleapis.com,protocolBinding=JSONRPC
```
2. **Authorize the Egress:** Ensure your `AuthorizationPolicy` (`AuthzPolicy` +
IAP `roles/iap.egressor` / UAP policy) is bound to the Gateway and allows
the agent's principal set to egress to these registered telemetry endpoints.
--------------------------------------------------------------------------------
## 24. UAP Org Policy Blocker (constraints/iam.managed.disableAccessPolicyBinding)
**Symptom:** Creating an IAM Policy Binding (`gcloud iam policy-bindings create`
or Terraform `google_iam_{organizations,folders,projects}_policy_binding`) fails with:
```text
ERROR: (gcloud.iam.policy-bindings.create) CUSTOM_ORG_POLICY_VIOLATION: Operation violates organization policy constraint 'constraints/iam.managed.disableAccessPolicyBinding'.
```
**Cause:** Enterprise Google Cloud organizations often enforce
`constraints/iam.managed.disableAccessPolicyBinding` by default to prevent
unauthorized IAM v3 bindings. (Note: always use the singular constraint name
`disableAccessPolicyBinding`; some documentation pages contain a plural typo
`disableAccessPolicyBindings` that `gcloud org-policies` rejects.)
**Fix:** An Organization or Folder Administrator must apply an Org Policy V2
override setting `enforce: false` at the target resource level:
```bash
gcloud org-policies set-policy --project=${PROJECT_ID} override.yaml
```
Where `override.yaml` defines:
```yaml
name: projects/PROJECT_ID/policies/iam.managed.disableAccessPolicyBinding
spec:
rules:
- enforce: false
```
Allow 30–60 seconds for IAM policy control plane propagation before retrying.
--------------------------------------------------------------------------------
## 25. UAP Policy Binding Destruction Race Condition (400 FAILED_PRECONDITION)
**Symptom:** During automated teardown or `terraform destroy`, destroying
`google_iam_{organization,folder,project}_access_policy` (after `google_iam_{organizations,folders,projects}_policy_binding`) fails with:
```text
HTTP 400 FAILED_PRECONDITION: Access policy is referenced by active policy binding(s).
```
**Cause:** Deleting a `PolicyBinding` is subject to a 10–30 second replication
delay in the IAM control plane. If an orchestrator deletes the binding and
immediately issues a deletion for the parent `AccessPolicy`, IAM rejects the
call because the binding is still visible in eventual consistency.
**Fix:** Ensure teardown workflows poll `GET` on the `PolicyBinding` resource
URL until an HTTP 404 is confirmed before deleting the referenced
`AccessPolicy`. In Terraform scripts or destroy provisioners, never exit 0 on
timeout.
--------------------------------------------------------------------------------
## 26. Agent Gateway Multi-Registry & Jurisdiction Validation Errors
**Symptom:** `gcloud network-services agent-gateways import` or Terraform apply
fails with HTTP `400` / `InvalidArgument`:
```text
Invalid argument: maximum of two registries are supported. When it's two registries, one of them must be global, the other one can be either regional or multi-regional.
```
**Cause:** Either (a) more than two registries were specified, (b) two
registries were configured without `global` (e.g., two regional registries like
`us-central1` and `europe-west1`, or two `global` registries), or (c) the
regional/multi-regional registry violates jurisdiction alignment (a regional
gateway in `us-central1` can only attach `us-central1` or `us`, never
`europe-west1` or `eu`).
**Fix:** Configure **at most two registries**, ensuring **exactly one is `global`**
and the second matches the gateway's exact region or data-residency
multi-region:
```yaml
registries:
- //agentregistry.googleapis.com/projects/PROJECT_NUMBER/locations/global
- //agentregistry.googleapis.com/projects/PROJECT_NUMBER/locations/us-central1
```
--------------------------------------------------------------------------------
## 27. CEL Null Dereference Crash on Non-Tool MCP Methods
**Symptom:** Gatekeeper returns HTTP 500 or `PERMISSION_DENIED` with internal
evaluation error logs when an agent invokes MCP lifecycle or non-tool methods
(`prompts/list`, `resources/read`).
**Cause:** When invoking non-tool MCP operations, the `tool` message inside
`mcp_server` is `null`. A CEL rule that dereferences
`destination.agent_registry.mcp_server.tool.annotations.*` or `tool.name`
without first checking the method throws an unhandled null-dereference exception
in the CEL evaluator.
**Fix:** Guard all tool attribute dereferences with a method check:
```cel
(destination.agent_registry.mcp_server.method == 'tools') && (destination.agent_registry.mcp_server.tool.annotations.read_only_hint == true)
```
--------------------------------------------------------------------------------
## 28. ACT ALL_TRAFFIC Silent Outbound Hang (Missing Cloud NAT)
**Symptom:** When an Agent Gateway uses an Agent Connectivity Template with
`vpcEgress: ALL_TRAFFIC`, Reasoning Engine calls to public external APIs
(`api.weather.gov`, `api.ipify.org`, SaaS tools) hang and eventually fail with
connection timeouts. Egress to Google APIs continues to function normally.
**Cause:** In `ALL_TRAFFIC` mode, all non-Google outbound packets exit the PSC-I
Network Attachment into the consumer VPC subnet (`agw-psci-subnet`). If that
subnet does not have an active Cloud NAT gateway, public traffic is dropped.
(Google APIs bypass Cloud NAT via Andromeda Private Google Access).
**Fix:** Configure Cloud Router and Cloud NAT on the consumer VPC covering the
PSC-I subnet:
```bash
gcloud compute routers nats create agw-cloud-nat \
--router=agw-nat-router \
--region=LOCATION \
--nat-custom-subnet-ip-ranges=agw-psci-subnet \
--auto-allocate-nat-external-ips
```
--------------------------------------------------------------------------------
## 29. Agent Gateway Control-Plane Mutation Concurrency Lock (HTTP 409 ABORTED)
**Symptom:** Submitting a PATCH, update, or import command against an Agent
Gateway returns:
```text
HTTP 409 ABORTED: unable to queue the operation
```
**Cause:** The Network Services control plane enforces a strict per-resource
concurrency mutex lock on each Agent Gateway resource. Concurrent mutations are
aborted while an asynchronous update or delete operation is already active.
**Fix:** Wait ~1.5 to 2 minutes for the in-flight Long-Running Operation (LRO)
to reach `done: true` before initiating another mutation.
--------------------------------------------------------------------------------
## 30. ACT Deletion Fails with `400 FAILED_PRECONDITION` (`already being used`)
**Symptom:** Attempting to delete an Agent Connectivity Template fails with:
```text
HTTP 400 FAILED_PRECONDITION: Resource projects/.../agentConnectivityTemplates/... is already being used by resource(s) projects/.../agentGateways/...
```
**Cause:** Either an Agent Gateway deletion Long-Running Operation (LRO) is
still in flight, another Agent Gateway in the project still references the ACT,
or an asynchronous gateway cleanup left a backend cross-reference pending.
**Fix:**
1. Verify that all referencing `AgentGateway` resources in the region have
finished deleting (`done: true`):
```bash
gcloud network-services agent-gateways list --location=${REGION} --project=${PROJECT_ID}
gcloud network-services operations list --location=${REGION} --project=${PROJECT_ID}
```
2. Always delete dependent resources in strict reverse order (`AuthzPolicy` →
`AuthzExtension` → `AgentGateway` → `AgentConnectivityTemplate`), waiting
for each LRO to complete before issuing the next delete.
3. If `agent-gateways list` is empty and all operations show `done: true` for
more than 10 minutes while the ACT still reports `already being used`,
create a newly named ACT to unblock deployments immediately and open a
Google Cloud Support case referencing the stuck ACT URI so support can clear
the orphaned backend reference.
--------------------------------------------------------------------------------
## 31. Reasoning Engine Deletion Preconditions (Active Sessions Require ?force=true)
**Symptom:** Deleting a Vertex AI Reasoning Engine instance fails with:
```text
HTTP 400 FAILED_PRECONDITION: Cannot delete ReasoningEngine with active sessions.
```
**Cause:** Active agent sessions or conversations remain attached to the engine
runtime.
**Fix:** Append `?force=true` to the delete API call or use the force flag in
the CLI/REST client to cascade session cleanup.
--------------------------------------------------------------------------------
## 32. REST API Path Matching Gotcha (.json Extensions and Query Strings)
**Symptom:** An agent calling an external REST API (e.g. Zendesk) receives HTTP
403 `Egress request is not authorized`, even though a UAP rule allows
`/api/v2/tickets`.
**Cause:** SDK clients typically append `.json` (e.g. `/api/v2/tickets.json`) or
query strings (`?page=1`). Strict equality checks reject these variations, while
naive `.startsWith('/api/v2/tickets')` introduces security escapes to
`/api/v2/tickets_delete_all`.
**Fix:** Construct explicit boundary-aware CEL path conditions:
```cel
((destination.unregistered.path == '/api/v2/tickets') ||
(destination.unregistered.path == '/api/v2/tickets.json') ||
(destination.unregistered.path.startsWith('/api/v2/tickets/')) ||
(destination.unregistered.path.startsWith('/api/v2/tickets?')) ||
(destination.unregistered.path.startsWith('/api/v2/tickets.json?')))
```
--------------------------------------------------------------------------------
## 33. Secure Web Proxy (SWP) & Policy-Based Routing (PBR) Egress Failures
**Symptom:** When attempting to route egress traffic from an Agent Gateway
Network Attachment through a downstream Secure Web Proxy (SWP) for Layer 7 URL
filtering, packets drop silently, connections time out, or requests fail with
`HTTP 403 Forbidden`, `HTTP 503 Service Unavailable: remote connection failure`,
or `INVALID_ARGUMENT`.
**Causes & Platform Constraints:**
1. **PSC Endpoints Cannot Be Route Next-Hops**: Google Cloud route tables (both
static routes and Policy-Based Routes) do **not** allow Private Service
Connect (PSC) forwarding rules (`--load-balancing-scheme=""`) or service
attachments as next hops.
2. **SWP via PSC Service Attachment Lacks Next-Hop Mode**: Publishing Secure
Web Proxy behind a PSC Service Attachment operates strictly in **Explicit
Proxy Mode** (`HTTP CONNECT`). Packets emerging from an Agent Gateway
Network Attachment are Layer 3/Layer 4 transparent IP packets; they cannot
reach an explicit proxy without client-side proxy configuration (unless the
container is explicitly configured with `HTTPS_PROXY` on `:443` and a
`v1beta1` L4 `AuthzPolicy` — see BKI #34).
3. **Static Route Tag Defect**: Next-hop routing mode with static routes
requires VM network tags (`--tags`). Network Attachments
(`compute network-attachments`) are consumer network interfaces, not VM
instances, and cannot bear network tags. Static routes cannot match or steer
traffic originating from an Agent Gateway Network Attachment.
4. **SWP Gateway Resource Definition Syntax Error**: Creating an SWP gateway
with `type: SECURE_WEB_PROXY` fails validation. The Network Services
API requires `type: SECURE_WEB_GATEWAY` and
`routingMode: NEXT_HOP_ROUTING_MODE`.
5. **Cloud NAT Missing `ENDPOINT_TYPE_SWG`**: SWP Envoy proxy instances reside
on the private proxy-only subnet and lack external IPs. Outbound internet
egress requires Cloud NAT configured with
`--endpoint-types=ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG`. If
`ENDPOINT_TYPE_SWG` is omitted, proxy outbound traffic hangs silently.
6. **ADK Streaming Session Allowlist Omission**: In `ALL_TRAFFIC` ACT mode,
Agent Development Kit (ADK) streaming queries initialize sessions via
`POST https://<region>-aiplatform.mtls.googleapis.com/.../sessions`. Because
`ALL_TRAFFIC` forces all runtime egress to the Network Attachment, PBR
steers this session call to SWP. If `<region>-aiplatform.mtls.googleapis.com`
is omitted from the GatewaySecurityPolicy allowlist, SWP drops it
(`default_denied`), causing ADK streaming queries to fail with HTTP 503
(`remote connection failure`), while direct `query()` calls succeed.
**Fix:**
1. **Deploy Next-Hop SWP directly in the consumer VPC**:
Create an Envoy proxy-only subnet (`purpose: REGIONAL_MANAGED_PROXY`, `role: ACTIVE`,
minimum `/26`) and deploy SWP listening on an internal IP on the PSC-I
subnet (e.g. `10.20.1.250`) with `type: SECURE_WEB_GATEWAY` and
`routingMode: NEXT_HOP_ROUTING_MODE`.
2. **Configure Policy-Based Routing (PBR)**:
Create a PBR matching source CIDR `10.20.1.0/24` (the Network Attachment
subnet) and destination `0.0.0.0/0` with `--next-hop-ilb-ip=10.20.1.250`
(priority 200). Add a default fallback PBR with priority 1000:
```bash
gcloud network-connectivity policy-based-routes create agw-psci-to-swp-pbr \
--network=projects/PROJECT_ID/global/networks/VPC_NAME \
--source-range=10.20.1.0/24 \
--destination-range=0.0.0.0/0 \
--next-hop-ilb-ip=10.20.1.250 \
--priority=200 \
--project=PROJECT_ID
```
3. **Configure Cloud NAT with `ENDPOINT_TYPE_SWG`**:
Create (or recreate) Cloud NAT on the Cloud Router via `gcloud compute routers nats create`
with `--endpoint-types=ENDPOINT_TYPE_VM,ENDPOINT_TYPE_SWG` (`--endpoint-types` is immutable and not supported on `nats update`).
4. **Allowlist External Domains and Regional AI Platform in GatewaySecurityPolicy**:
Ensure the CEL policy rule permits both external target domains and the
regional AI platform session endpoint:
`inUrlList(host(), ['api.weather.gov', 'api.ipify.org', '<region>-aiplatform.mtls.googleapis.com'])`.
--------------------------------------------------------------------------------
## 34. Explicit Forward HTTPS Proxy (`HTTP CONNECT`) Fails with `HTTP 404` or `403` Through Agent Gateway
**Symptom:**
- **Symptom A (`HTTP 404` on `CONNECT`)**: An Agent Runtime container or tool
configured with `HTTPS_PROXY=https://proxy.corp.internal:443` fails on every
proxied request with `HTTP 404 Not Found` (`curl: (56) CONNECT tunnel
failed, response 404`).
- **Symptom B (`gcloud` Schema / Validation Error)**: Importing an
`AuthzPolicy` containing `networkRules` fails under GA `gcloud`, or fails
with `INVALID_ARGUMENT` when `target.loadBalancingScheme` or `ports` is set.
- **Symptom C (`HTTP 403` from Downstream Proxy or ADC Metadata Hang)**: The
tunnel reaches Squid / Explicit SWP, which rejects the client with `403
Access Denied`, or Vertex AI SDK / `google-auth` hangs trying to reach
`169.254.169.254` or `*.googleapis.com` through the proxy.
**Cause:**
1. By default, Agent Gateway terminates TLS and routes decrypted streams
through an L7 HTTP connection manager, which rejects nested `HTTP CONNECT`
methods with `404`.
2. `networkRules` (L4 SNI pass-through) is available only in the **`v1beta1`**
API (`gcloud beta`), prohibits `target.loadBalancingScheme` when targeting
`agentGateways`, and does not support `ports` in public schemas.
3. **Two-Plane Source IP Split**: Inside Agent Gateway's Envoy listener,
Agent Runtime connections arrive from Google's internal managed runtime
egress CIDR `7.0.0.0/8` (while consumer VPC workloads arrive from their VPC
CIDR), whereas packets exiting Agent Gateway's PSC-I NIC into your **consumer
VPC** are sourced from your **consumer PSC-I Network Attachment subnet CIDR**
(e.g., `10.20.0.0/24` — never `7.0.0.0/8`). In addition, L4 pass-through
bypasses ACT `tlsConfig.trustConfig` certificate validation and breaks GCE
metadata / Google API mTLS if `NO_PROXY` is omitted.
**Fix:**
1. **Import a `v1beta1` L4 `AuthzPolicy` matching the proxy SNI** (omit
`loadBalancingScheme` and `ports`; max 5 `networkRules`, max 10 `snis`,
mutually exclusive with `httpRules`; either omit `from` or include **both**
`7.0.0.0/8` and your PSC-I CIDR in `from.sources[].ipBlocks`):
```yaml
# proxy-l4-authz-policy.yaml
name: allow-explicit-proxy-l4
action: ALLOW
policyProfile: REQUEST_AUTHZ
target:
resources:
- projects/PROJECT_ID/locations/REGION/agentGateways/AGENT_GATEWAY_NAME
networkRules:
- to:
operations:
- snis:
- exact: "proxy.corp.internal"
```
```bash
gcloud beta network-security authz-policies import allow-explicit-proxy-l4 \
--source=proxy-l4-authz-policy.yaml \
--location=REGION \
--project=PROJECT_ID
```
2. **Configure TLS on `:443` & Allow the Consumer PSC-I Subnet CIDR on the Proxy**:
Listen on `:443` with TLS (e.g., `HTTPS_PROXY=https://proxy.corp.internal:443`),
ensure `proxy.corp.internal.` resolves via `dnsPeeringConfig`, and allow
your **consumer PSC-I Network Attachment subnet CIDR** (e.g., `10.20.0.0/24` /
`10.0.0.0/8` RFC 1918) in consumer VPC GCE ingress firewall rules and Squid
`acl localnet src` — do **not** allow `7.0.0.0/8` on consumer VPC firewalls
or Squid ACLs (`7.0.0.0/8` is used **only** inside `AuthzPolicy`
`networkRules[].from.sources[].ipBlocks` when `from` is configured).
3. **Set `NO_PROXY` and Container CA Trust**: Set both `NO_PROXY` and `no_proxy`
to `"169.254.169.254,metadata.google.internal,localhost,127.0.0.1,.googleapis.com,googleapis.com"`,
and bundle both `agentGatewayCard.rootCertificates` and your Private CA root
into `SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`, and
`GRPC_DEFAULT_SSL_ROOTS_FILE_PATH`.
4. **Security Trade-Off**: L4 `networkRules` bypasses L7 Agent Gateway policies
(IAP/UAP, Model Armor, SGP, and `httpRules`) for traffic inside the
`proxy.corp.internal` tunnel; enforce domain/URL policies on the downstream
proxy or use BKI #33 (Next-Hop SWP + PBR) when L7 Agent Gateway inspection
is required.
--------------------------------------------------------------------------------
## 35. Cloud DNS Transitive Peering Chain Exceeded (>2 Hops) or Authoritative Root Zone (`"."`) Causing `SERVFAIL` / `NXDOMAIN`
**Symptom:**
- **Symptom A (`INVALID_ARGUMENT` or `HTTP 503` / `SERVFAIL` on Private Host)**:
ACT or Gateway import fails preflight validation on a multi-hop peered DNS
zone, or runtime calls to internal FQDNs fail with `HTTP 503` / `NXDOMAIN`
even though VMs in the Spoke VPC resolve them.
- **Symptom B (`NXDOMAIN` on All `*.googleapis.com` & Public Domains)**: After
configuring `dnsPeeringConfig.domains: ["."]`, every Google API and public
internet request fails DNS resolution.
**Cause:**
1. **Cloud DNS 2-Hop Transitive Limit**: Agent Gateway supports transitive
Cloud DNS peering up to **at most 2 hops** (3 VPC networks: `Gateway Tenant
VPC → Attached Spoke VPC → Target Hub VPC`). Agent Gateway's internal tenant
peering consumes **Hop 1**, leaving at most **1** customer DNS peering hop.
If the 2nd-hop VPC chains to another Cloud DNS Peering Zone (a 3rd hop),
preflight validation or runtime DNS resolution fails.
2. **Authoritative `"."` Zone Trap**: Peering `domains: ["."]` to an
**Authoritative** private zone for `"."` makes that zone authoritative for
the entire DNS root, returning `NXDOMAIN` for all unrecorded domains.
3. **Schema Split**: `AgentConnectivityTemplate` `dnsPeeringConfig` accepts
only `domains` (array) and `targetNetwork` (string URI with **Project ID**;
passing `targetProject` fails schema validation), whereas inline
`AgentGateway.networkConfig.dnsPeeringConfig` requires `domains`,
`targetNetwork`, and `targetProject`.
**Fix:**
1. Keep DNS peering to **at most 1 customer peering hop** (`<= 2` hops total),
ensuring the 2nd-hop Hub VPC hosts an **Authoritative Private Zone** or uses
**Cloud DNS Forwarding** (inbound/outbound forwarding IPs) rather than
another Peering Zone. Where supported in your region, you can point
`dnsPeeringConfig.targetNetwork` directly at the central DNS Hub VPC
(granting `roles/dns.peer` and `roles/dns.reader` to
`service-GATEWAY_PROJECT_NUMBER@gcp-sa-agentgateway.iam.gserviceaccount.com`
and `roles/dns.reader` + `roles/compute.networkViewer` to the caller on the
Hub project).
2. Use `domains: ["."]` **only** with a **Cloud DNS Private Forwarding Zone**,
never an Authoritative private root zone; prefer specific suffixes with
trailing dots (e.g., `["corp.internal."]`).
--------------------------------------------------------------------------------
## 36. Consumer VPC Packet Intercept (`HTTP 503`) & Workforce / Workload Identity Federation (`Code 13` / `403`) Limits
**Symptom:**
- **Symptom A (`HTTP 503` on PSC-I Egress)**: All private or internet egress
through an ACT Network Attachment fails with `HTTP 503` or TLS connection
resets despite valid Cloud NAT, firewall rules, and Agent Registry entries.
- **Symptom B (`Code 13` or `403` with WIF Principals)**: Provisioning Agent
Gateway / Registry resources from a Workforce Identity Federation session
returns `Code 13` (`Internal error`), or cross-cloud (AWS / Azure) Workload
Identity Federation (WIF — Preview) runtime requests fail with `Code 13` or
`403 Forbidden`.
**Cause:**
1. **Network Security Packet Intercept Conflict**: Consumer VPCs with Network
Security Packet Intercept (`InterceptDeploymentGroup`) or inline third-party
NGFW packet interception matching the PSC-I Network Attachment subnet
disrupt Agent Gateway's egress flows.
2. **Preview WIF Caller & Claim Limits**: Workforce Identity Federation human
principals hit `Code 13` during Preview gateway/registry management
operations (adding broader IAM roles to the WIF user does **not** bypass
this Preview limitation), and referencing unsupported custom WIF attribute
expressions in IAP / UAP policies fails runtime evaluation.
**Fix:**
1. Exclude the Agent Gateway PSC-I Network Attachment subnet (or use a
dedicated egress VPC/subnet) from Network Security Packet Intercept rules.
2. Execute gateway/registry provisioning using a standard Cloud Identity /
Google Workspace user or Google Cloud Service Account, and bind exact
supported `principal://iam.googleapis.com/locations/global/workforcePools/...`
or `workloadIdentityPools/...` identifiers in runtime policies.
--------------------------------------------------------------------------------
## 37. Immediate `HTTP 498` After Binding Agent Runtime to Gateway, or Gemini Enterprise Regional `UpdateEngine` Failures
**Symptom:**
- **Symptom A (`HTTP 498`)**: Immediately after binding an Agent Runtime
(Reasoning Engine) to an Agent Gateway, agent invocations fail with HTTP
status **`498`**.
- **Symptom B (Gemini Enterprise `404`/`400` or Bypassed Egress)**: Attaching
an Agent Gateway to a Gemini Enterprise engine in `us` or `eu` via
`discoveryengine.googleapis.com` fails, or registered connectors/MCP tools
bypass the gateway.
**Cause:**
1. Binding an Agent Runtime to an Agent Gateway in enforcing mode *before*
registering and authorizing essential platform APIs (Vertex AI, Cloud
Resource Manager, IAM Credentials, Telemetry, Sessions / Memory Bank) blocks
mandatory runtime platform calls, surfacing as `HTTP 498`.
2. Gemini Enterprise engines require regional endpoint host prefixes
(`global-`, `us-`, or `eu-discoveryengine.googleapis.com`) on `UpdateEngine`
`PATCH` **and** per-connector opt-in (`"use_agent_gateway_egress": true`).
**Fix:**
1. Deploy the IAP extension in `iamEnforcementMode: "DRY_RUN"` first or
register the consolidated `googleapis` service entry and grant
`roles/iap.egressor` / UAP allow rules **before** binding the Agent Runtime
to the gateway.
2. For Gemini Enterprise, call
`PATCH https://{global-|us-|eu-}discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/GE_LOCATION/collections/default_collection/engines/ENGINE_ID?updateMask=agentGatewaySetting.defaultEgressAgentGateway.name`
and set `"use_agent_gateway_egress": true` on each `DataConnector`.
--------------------------------------------------------------------------------
## 38. Semantic Governance Policy (SGP) Failures: Startup gRPC Crash, Streaming Bypass, Missing Agent in Picker, or `metadata` Overwrite
**Symptom:**
- **Symptom A (Startup gRPC Crash)**: Agent Runtime crashes on startup after
attaching an SGP `AuthzPolicy`.
- **Symptom B (Streamed Model Call Returns No Verdict or an Error)**:
Streamed model calls (`:streamGenerateContent`, `:streamRawPredict`) return
no verdict or an error, or produce zero evaluation entries in
`projects/PROJECT_ID/logs/semantic-governance-policy`.
- **Symptom C (Missing Agent)**: Expected Reasoning Engine is missing from the
Console SGP agent selector, or CLI fails with
`SEMANTIC_GOVERNANCE_POLICY_AGENT_NOT_CONFIGURED`.
- **Symptom D (Unexpected Enforcement After `metadata` Update)**: Updating
`sgpUserIntentMatching: "ENABLED"` or `"DISABLED"` unexpectedly activates
blocking enforcement (wiping `sgpEnforcementMode: "DRY_RUN"`), or sessions
fail with `FAILED_PRECONDITION` when calling `SGP_DNS_HOSTNAME`.
**Cause & Fixes:**
1. **Mandatory gRPC Exclusion, Non-Streaming Invocation, & `.contains()` `when` Filter**:
The LLM in the semantic governance policy engine does **not** support
streamed model responses (`:streamGenerateContent`, `:streamRawPredict`
return no verdict or an error), and omitting gRPC exclusion intercepts
internal `application/grpc` startup calls. Invoke models **without
streaming** and configure `httpRules[].when` on the `CONTENT_AUTHZ`
`AuthzPolicy` using `.contains()` (because `request.path` includes query
strings):
`"!request.headers['content-type'].startsWith('application/grpc') && (request.path.contains(':generateContent') || request.path.contains(':rawPredict') || request.path.contains('/v1/messages') || request.path.contains('/chat/completions'))"`.
2. **Agent Eligibility (`AGENT_IDENTITY` + `agent_gateway_config`)**: Both
fields must be set **at Reasoning Engine creation time**
(`spec.effectiveIdentity` starting with `agents.global.`); redeploy
ineligible engines.
3. **VPC Connectivity, Reserved Subnets, & Service Agent IAM**: Ensure consumer
VPC subnets do **not** overlap SGP's reserved internal ranges
(`10.0.0.0/24`, `10.0.1.0/24`, `10.0.2.0/24`), configure `dnsPeeringConfig`
so `SGP_DNS_HOSTNAME` (`dnsRecord`) resolves, and grant
`roles/compute.networkAdmin`, `roles/dns.admin`, and `roles/cloudtrace.agent`
to `service-PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com`.
4. **Wholesale `updateMask=metadata` Replacement**: Importing or patching
`AuthzExtension` `metadata` replaces the **entire** `metadata` map. Always
include **both** keys together (e.g., `sgpEnforcementMode: "DRY_RUN"` and
`sgpUserIntentMatching: "ENABLED"` or `"DISABLED"`), and verify verdicts in
`projects/PROJECT_ID/logs/semantic-governance-policy`.
5. **SGP Control-Plane Error Reference (`gcloud beta ai semantic-governance-policies` / `semantic-governance-policy-engine`)**:
- `SEMANTIC_GOVERNANCE_POLICY_ALREADY_EXISTS` / `SEMANTIC_GOVERNANCE_POLICY_ETAG_MISMATCH`: Use `update` with the latest `etag` from `describe`.
- `SEMANTIC_GOVERNANCE_POLICY_AGENT_REQUIRED` / `SEMANTIC_GOVERNANCE_POLICY_CONSTRAINT_REQUIRED`: Supply `--agent` and `--natural-language-constraint`.
- `SEMANTIC_GOVERNANCE_POLICY_AGENT_INVALID_NAME` / `SEMANTIC_GOVERNANCE_POLICY_MCP_SERVER_INVALID_NAME` / `SEMANTIC_GOVERNANCE_POLICY_AGENT_REGISTRY_INVALID_NAME` / `SEMANTIC_GOVERNANCE_POLICY_AGENT_NOT_FOUND` / `SEMANTIC_GOVERNANCE_POLICY_MCP_SERVER_NOT_FOUND`: Pass full `projects/PROJECT_ID/locations/LOCATION/{agents|mcpServers}/agentregistry-...` resource paths registered in the same location.
- `SEMANTIC_GOVERNANCE_POLICY_AGENT_NOT_CONFIGURED`: Redeploy agent with `AGENT_IDENTITY` + `agent_gateway_config` set at creation time.
- `SEMANTIC_GOVERNANCE_POLICY_REGISTRY_DENIED`: Enable `agentregistry.googleapis.com` and grant `roles/agentregistry.viewer`.
- `SEMANTIC_GOVERNANCE_POLICY_AGENT_UNSUPPORTED_REGION` / `SEMANTIC_GOVERNANCE_POLICY_MCP_SERVER_UNSUPPORTED_REGION` / `SEMANTIC_GOVERNANCE_POLICY_ENGINE_SERVICE_NOT_AVAILABLE_IN_LOCATION` / `SEMANTIC_GOVERNANCE_POLICY_ENGINE_NOT_ENABLED_IN_REGION`: Use a supported SGP region (`us-central1`, `us-east1`, `us-east4`, `us-west1`, `europe-southwest1`, `europe-west1`, `europe-west4`, `europe-west8`), set `api_endpoint_overrides/aiplatform`, and provision the engine via `gcloud beta ai semantic-governance-policy-engine update` until `state: ACTIVE`.
--------------------------------------------------------------------------------
## 39. Native MCP `AuthzPolicy` Blocks Session Handshake (`initialize` / `ping`) Due to Missing `MATCH_BASE_PROTOCOL_METHODS` & `ExtensionBinding` Double-Invocation
**Symptom:**
- **Symptom A (`403` on MCP Session Startup)**: After attaching a native MCP
Layer 7 `AuthzPolicy` (`httpRules[].to.operations[].mcp`, `action: ALLOW`)
paired with `DENY_BY_DEFAULT`, MCP clients and ADK agents fail immediately
during session startup with `HTTP 403 Forbidden` before calling `tools/list`
or `tools/call`.
- **Symptom B (Duplicate Extension Calls / Double Latency)**: Requests routed
through an Agent Gateway invoke the same `AuthzExtension` or
`ProducerExtension` twice.
**Cause:**
1. MCP clients execute JSON-RPC base lifecycle methods (`initialize`, `ping`,
`notifications/initialized`) before calling tools. In
`httpRules[].to.operations[].mcp`, `baseProtocolMethodsOption` defaults to
**`SKIP_BASE_PROTOCOL_METHODS`**, which prevents `initialize` and `ping`
from matching an `ALLOW` rule when `DENY_BY_DEFAULT` is active.
2. **`ExtensionBinding` Hierarchy & Coexistence Double-Invocation**: When
`ExtensionBinding` resources (Preview) attach the **same** extension at
**both** project scope (`target.scope.parent: "projects/PROJECT_NUMBER"`,
`resourceTypes: "AGENT_GATEWAY"`) **and** gateway resource scope
(`target.resources`), both bindings execute on matching requests. Combining
a project-scope `ExtensionBinding` with a gateway-bound `AuthzPolicy`
(`action: CUSTOM`) for the same extension likewise invokes it twice (double
latency and double billing).
**Fix:**
1. Set `baseProtocolMethodsOption: MATCH_BASE_PROTOCOL_METHODS` on `ALLOW`
rules (keep `SKIP_BASE_PROTOCOL_METHODS` on `DENY` rules so denying one tool
does not block the MCP session), omit `target.loadBalancingScheme`, and
re-import with `gcloud network-security authz-policies import`:
```yaml
name: allow-approved-mcp-tools
action: ALLOW
policyProfile: REQUEST_AUTHZ
target:
resources:
- projects/PROJECT_ID/locations/REGION/agentGateways/AGENT_GATEWAY_NAME
httpRules:
- to:
operations:
- mcp:
baseProtocolMethodsOption: MATCH_BASE_PROTOCOL_METHODS
methods:
- name: "tools/list"
- name: "tools/call"
params:
- exact: "get_order_status"
```
2. Attach each extension at **either** project scope (`target.scope`) **or**
gateway resource scope (`target.resources` / `AuthzPolicy`), never both on
the same traffic path.
policies.md 73.7 KB
# Agent Platform Policies — Debugging Reference
Reference for diagnosing IAM, IAP, and Agent Gateway policy denials in the
**Google Cloud Gemini Enterprise Agent Platform**. Read this when an agent gets
a 403, when an MCP/agent/endpoint call is silently dropped, or when a freshly
applied policy "doesn't take."
Agent Gateway enforces governance across five complementary policy layers:
1. **Network Security `AuthzPolicy` (`networksecurity.googleapis.com` `v1` / `v1beta1`)**:
Gateway attachment and traffic-phase dispatcher supporting L7 `httpRules`
(including native MCP method/tool matching), L4 SNI `networkRules` (`gcloud beta`),
delegated `CUSTOM` service extensions (`REQUEST_AUTHZ` and `CONTENT_AUTHZ`),
and `DENY_BY_DEFAULT` fallback enforcement.
2. **IAM Unified Access Policy (UAP / Policy V2, `iam.googleapis.com/v3`) & Legacy IAM v1**:
Agent-to-Anywhere (egress) identity and destination authorization evaluated
by IAP (`service: iap.googleapis.com`, `iapPolicyVersion: "V2"` vs. legacy
`"V1"` `roles/iap.egressor`).
3. **Model Armor Content Security (`CONTENT_AUTHZ`)**: Inline prompt/response
screening and Sensitive Data Protection (SDP) redaction across Client-to-Agent
(ingress) and Agent-to-Anywhere (egress) flows.
4. **Semantic Governance Policies (SGP)**: Context-aware natural-language
constraints and user-intent alignment evaluated by the LLM in the semantic
governance policy engine on non-streaming LLM requests.
5. **Extensible Policies (`ExtensionBinding` / `ProducerExtension`, Preview) &
Token Management Policies (Preview)**: Simplified 1P/2P/3P `ext_proc`
bindings and shared LLM token quota enforcement returning HTTP `429`.
## Table of Contents
- [TL;DR for debugging](#tldr-for-debugging): Lines 50-157
- [1. UAP (Policy V2) vs. Legacy IAM v1 Architecture](#1-uap-policy-v2-vs-legacy-iam-v1-architecture): Lines 158-223
- [2. UAP Core Architectural Constructs](#2-uap-core-architectural-constructs): Lines 224-310
- [3. Runtime Evaluation Pipeline & Mathematical Invariants](#3-runtime-evaluation-pipeline--mathematical-invariants): Lines 311-378
- [4. Deep CEL Attribute Reference](#4-deep-cel-attribute-reference): Lines 379-489
- [5. The 3-Tier Organizational Security Model](#5-the-3-tier-organizational-security-model): Lines 490-697
- [6. Legacy IAM v1 Reference (Backward Compatibility)](#6-legacy-iam-v1-reference-backward-compatibility): Lines 698-729
- [7. Observability, Auditing, & Dry-Run Operations](#7-observability-auditing--dry-run-operations): Lines 730-784
- [8. Production Edge Cases & Architectural Gotchas](#8-production-edge-cases--architectural-gotchas): Lines 785-885
- [9. Quick Command Cheat Sheet](#9-quick-command-cheat-sheet): Lines 886-927
- [10. Debugging Flowchart](#10-debugging-flowchart): Lines 928-962
- [11. Network Security AuthzPolicy: L7 HTTP/MCP Rules, L4 networkRules, & DENY_BY_DEFAULT](#11-network-security-authzpolicy-l7-httpmcp-rules-l4-networkrules--deny_by_default): Lines 963-1073
- [12. Model Armor Content Security Policies (CONTENT_AUTHZ)](#12-model-armor-content-security-policies-content_authz): Lines 1074-1102
- [13. Semantic Governance Policies (SGP)](#13-semantic-governance-policies-sgp): Lines 1103-1173
- [14. Extensible Policies: ExtensionBinding & ProducerExtension (Preview)](#14-extensible-policies-extensionbinding--producerextension-preview): Lines 1174-1207
- [15. Token Management Policies (Preview — HTTP 429)](#15-token-management-policies-preview--http-429): Lines 1208-1222
--------------------------------------------------------------------------------
## TL;DR for debugging
1. **Check Policy Architecture First (`V1` vs `V2`)**:
- In Gateway metadata: Check if the attached IAP `AuthzExtension` specifies
`iapPolicyVersion: "V2"`. Without this key, the gateway defaults to
legacy V1 shadow-resource evaluation. Active blocking is enabled by
omitting `iamEnforcementMode` (or setting `iamEnforcementMode: "ENFORCE"`,
never `"ENFORCED"`).
- In Cloud Audit Logs (`protoPayload.serviceName="iap.googleapis.com"`):
Check `protoPayload.metadata.iapPolicyVersion`. If lowercase `"v2"`,
diagnose UAP `AccessPolicy` and `PolicyBinding` resources. If absent or
`"v1"`, diagnose legacy IAM v1 bindings on Agent Registry entries.
2. **The UAP Permission MUST be FQDN**: In UAP access policy rules
(`operation.permissions`), the permission MUST be specified in full FQDN
format: **`iap.googleapis.com/resources.egressViaIAP`** (Agent-to-Anywhere
egress). Using the short form `iap.resources.egressViaIAP` causes the IAM
policy compiler to reject the policy, even though Cloud Audit Logs record
`protoPayload.authorizationInfo.permission="iap.resources.egressViaIAP"`
(V2) or `"iap.webServiceVersions.egressViaIAP"` (V1).
3. **UAP Policy Bindings Target Resource Manager Nodes**: `PolicyBinding`
targets must be canonical Resource Manager URIs using numeric IDs (e.g.
`//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}` or
`//cloudresourcemanager.googleapis.com/folders/${FOLDER_ID}`). Passing
gateway or registry resource names causes
`INVALID_TARGET_FULL_RESOURCE_NAME`.
4. **UAP Invariants: Absolute DENY Precedence & Additive ALLOW Aggregation**:
- **Absolute DENY Precedence**: If ANY matching rule across Org, Folder,
or Project evaluates to DENY, the request is immediately rejected (HTTP
403). There are NO deny exceptions.
- **Additive ALLOW Aggregation**: Permissions granted at Org/Folder level
cannot be narrowed or revoked by Project developers.
5. **Mandatory CEL Null-Dereference Guard**: When an agent calls non-tool MCP
methods (`prompts/list`, `resources/read`), the `tool` object inside
`mcp_server` is `null`. A CEL condition dereferencing `.tool.name` or
`.tool.annotations.*` without verifying the method crashes Gatekeeper with a
CEL evaluation error. Always prepend:
`(destination.agent_registry.mcp_server.method == 'tools')`.
6. **Avoid Blanket Unregistered DENY (Container Boot Crash)**: Never configure
an Org or Folder-level rule with `(destination.is_registered == false)` and
`effect: DENY`. Reasoning Engine containers boot by contacting public
endpoints (`telemetry.mtls.googleapis.com`). An absolute DENY causes
container boot crashes. Rely instead on Gateway default-deny.
7. **Zendesk / REST Path Extensions (`.json`)**: Strict prefix matching in
unregistered UAP rules (e.g. `.startsWith('/api/v2/tickets')`) leaves
vulnerabilities to sibling paths (e.g. `/api/v2/tickets_export`), while
exact matching on `/api/v2/tickets` breaks SDK clients that append `.json`
(`/api/v2/tickets.json`). Match exact paths, `/` subpaths, `.json`, and `?`
query strings explicitly.
8. **Org Policy Blocker
(`constraints/iam.managed.disableAccessPolicyBinding`)**: If creating a
policy binding fails with `CUSTOM_ORG_POLICY_VIOLATION`, an Org Admin must
set an Org Policy V2 override setting `enforce: false` at the target CRM
level using the exact singular constraint name
`constraints/iam.managed.disableAccessPolicyBinding` (some documentation
pages contain a plural typo `disableAccessPolicyBindings` that `gcloud org-policies`
rejects). Allow **~30–60 seconds** for IAM policy/binding propagation.
9. **Terraform Binding Destruction Race**: Simultaneous destruction of
`PolicyBinding` and `AccessPolicy` fails with `400 FAILED_PRECONDITION:
Access policy is referenced by active policy binding(s)` due to IAM
replication latency (10–30 s). Destroy scripts must poll GET the binding URL
until HTTP 404 is confirmed before deleting the policy.
10. **Legacy IAM v1 Fallback**: In legacy v1, outbound agent traffic is
authorized by granting `roles/iap.egressor` directly on the Agent Registry
resource (`gcloud iap web set-iam-policy --resource-type=agent-registry`).
Do NOT use `roles/iap.tunnelResourceAccessor` or web ingress roles.
11. **Omit `loadBalancingScheme` & Use `gcloud beta` for L4 `networkRules`**:
Never set `target.loadBalancingScheme` on `AuthzPolicy` resources targeting
`agentGateways/*` (causes `INVALID_ARGUMENT`). L4 `networkRules` require
`gcloud beta network-security authz-policies import`, allow `snis` only (no
`ports` or HTTP fields), and bypass L7 IAP/UAP, Model Armor, and SGP
inspection on matched TLS tunnels.
12. **Native MCP `AuthzPolicy` `ALLOW` Rules Require `MATCH_BASE_PROTOCOL_METHODS`**:
`httpRules[].to.operations[].mcp` defaults `baseProtocolMethodsOption` to
`SKIP_BASE_PROTOCOL_METHODS`. Every MCP `ALLOW` rule must explicitly set
`baseProtocolMethodsOption: MATCH_BASE_PROTOCOL_METHODS` so `initialize` and
`ping` handshakes succeed.
13. **Model Armor Distinct Service Agents & 60s Stream Deadline**: Ingress
(`CLIENT_TO_AGENT`, ADK `streamQuery` only) runs as
`service-${AGENT_PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com`;
egress (`AGENT_TO_ANYWHERE`) runs as
`service-${GATEWAY_PROJECT_NUMBER}@gcp-sa-dep.iam.gserviceaccount.com`.
Envoy enforces a hard 60-second total stream deadline on `CONTENT_AUTHZ`
callouts — exclude `>60s` streams or gRPC channels via `httpRules` to avoid
`Stream removed` errors.
14. **SGP Non-Streaming CEL Filter & Metadata Map Overwrite**: Scope SGP
`CONTENT_AUTHZ` policies with a `when` CEL filter using `.contains()` on
non-streaming LLM paths (`:generateContent`, `:rawPredict`, `/v1/messages`,
`/chat/completions`). Updating `AuthzExtension` metadata (`import` or
`updateMask=metadata`) replaces the entire map — always pass all active keys
(`sgpEnforcementMode`, `sgpUserIntentMatching`) together.
--------------------------------------------------------------------------------
## 1. UAP (Policy V2) vs. Legacy IAM v1 Architecture
```
+-------------------------------------------------------------------------------+
| Legacy IAM v1 Model (Monolithic & Per-Resource) |
| |
| Resource (e.g. Storage Bucket, IAP Web Backend Shadow Resource) |
| └── IAM Policy |
| └── Bindings: [Role: roles/iap.egressor, Members: [principal://...]] |
| |
| Limitations: |
| - Policy is physically glued to the target resource / shadow resource. |
| - Zero reusability across projects or folders. |
| - Synthetic shadow resources: projects/123/iap_web/compute/services/... |
| - Coarse-grained network/L7 attributes. |
+-------------------------------------------------------------------------------+
│
▼
+-------------------------------------------------------------------------------+
| Unified Access Policy (UAP / Policy V2) Model (Decoupled & Hierarchical) |
| |
| +──────────────────────────+ +───────────────────────────+ |
| │ CRM Hierarchy Node │ │ AccessPolicy │ |
| │ (Org, Folder, Project) │ │ (Reusable Rule Definition)│ |
| +─────────────┬────────────+ +─────────────┬─────────────+ |
| │ │ |
| │ binds to │ |
| └──────────────► ◄────────────────────┘ |
| │ |
| +──────────┴──────────+ |
| │ PolicyBinding │ |
| │ target: CRM Node │ |
| │ policy: AccessPolicy│ |
| +─────────────────────+ |
+-------------------------------------------------------------------------------+
```
### Architectural Comparison Matrix
| Feature | Legacy IAM v1 | Unified Access Policy (UAP / Policy V2) |
: Dimension : : :
| :------------- | :------------------------- | :----------------------------------------------------------------------------- |
| **Coupling** | **Tightly Coupled**: | **Decoupled**: Standalone first-class objects referenced by multiple bindings. |
: : Policies live inside : :
: : individual resource : :
: : metadata. : :
| **Attachment | Concrete service resources | Canonical Resource Manager nodes: |
: Target** : or synthetic shadow : `//cloudresourcemanager.googleapis.com/{organizations|folders|projects}/{ID}`. :
: : resources (`iap_web`). : :
| **Rule | Primitive | Explicit `effect: ALLOW` or `effect: DENY`, target FQDN permissions, and deep |
: Capabilities** : Role-to-Principal bindings : L7 CEL conditions. :
: : with basic contextual : :
: : conditions. : :
| **Evaluation | Unordered role evaluation; | Unified evaluation pipeline: Org → Folder → Project |
: Order** : Deny policies exist as a : with **strict absolute DENY precedence** and **additive ALLOW aggregation**. :
: : separate API : :
: : (`iam.googleapis.com/v2`). : :
| **Enforcement | Binary (always enforced). | Dual-mode: **`DRY_RUN`** (audit log simulation) or **`ENFORCE`** / omitted |
: Modes** : : (active blocking). :
| **Workload | Static service accounts | Extends natively to ephemeral **Workload Identity Federation for Agents** |
: Targets** : and human users. : (`principal\://agents.global.org-...`). :
--------------------------------------------------------------------------------
## 2. UAP Core Architectural Constructs
UAP is comprised of two core resources in the `iam.googleapis.com/v3` (`v3beta`) API:
### 2.1 AccessPolicy (`iam.googleapis.com/v3/.../accessPolicies`)
An `AccessPolicy` is a versioned container of authorization rules defining
*what* is permitted or forbidden, *for whom*, and *under what conditions*.
**`gcloud` Rules Array File (`rules.json` passed to `--details-rules=rules.json`)**:
```json
[
{
"description": "Permit access to registered corporate tools",
"effect": "ALLOW",
"principals": [
"principalSet://agents.global.org-112233445566.system.id.goog/attribute.platform/aiplatform"
],
"operation": {
"permissions": [
"iap.googleapis.com/resources.egressViaIAP"
]
},
"conditions": {
"iap.googleapis.com": {
"title": "allow_registered_mcp",
"description": "Matches registered corporate MCP servers",
"expression": "(destination.is_registered == true) && (destination.agent_registry.resource_type == 'MCP_SERVER')"
}
}
}
]
```
```bash
gcloud iam access-policies create platform-egress-policy \
--details-rules=rules.json \
--project="${PROJECT_ID}" \
--location=global \
--display-name="Platform Egress Policy"
```
> **Note:** **REST API vs. `gcloud` vs. Terraform Schema Differences**:
> - **`gcloud iam access-policies create --details-rules=`**: Expects a top-level JSON array `[ { ... } ]` of rule objects (there is no `--file` flag).
> - **REST API (`POST https://iam.googleapis.com/v3beta/{parent}/locations/global/accessPolicies?accessPolicyId={id}`)**: Wraps the rules array inside `{"displayName": "...", "details": {"rules": [ ... ]}}`. Both `gcloud` JSON and REST JSON use **singular** `"operation": {"permissions": [...]}` and **plural service-keyed map** `"conditions": {"iap.googleapis.com": { ... }}`.
> - **Terraform (`google_iam_{organization,folder,project}_access_policy` in `google` / `google-beta`)**: Uses HCL blocks `details { rules { operation { permissions = [...] } conditions { service = "iap.googleapis.com" expression = "..." } } }` (singular `operation`, plural `conditions`; `title` is not supported), paired with plural `google_iam_{organizations,folders,projects}_policy_binding`.
#### Key Properties:
- **`effect`**: Either `ALLOW` or `DENY` (an `AccessPolicy` must contain at least one rule).
- **`principals`**: SPIFFE agent identity strings (`principal://...`) or principal sets (`principalSet://...`). Never pass `urn:agent:...` catalog URNs here.
- **`operation.permissions`**: Fully Qualified Domain Name (FQDN) format: `iap.googleapis.com/resources.egressViaIAP` (Agent-to-Anywhere egress).
- **`conditions["iap.googleapis.com"].expression`**: Common Expression Language (CEL) boolean predicate.
### 2.2 PolicyBinding (`iam.googleapis.com/v3/.../policyBindings`)
A `PolicyBinding` attaches an `AccessPolicy` to a specific Resource Manager node. Allow **~30–60 seconds** after creating or updating a binding or policy for IAM control-plane propagation.
```json
{
"displayName": "Bind Platform Egress to Engineering Folder",
"target": {
"resource": "//cloudresourcemanager.googleapis.com/folders/123456789012"
},
"policy": "folders/123456789012/locations/global/accessPolicies/platform-egress-policy",
"policyKind": "ACCESS"
}
```
```bash
gcloud iam policy-bindings create bind-platform-egress \
--location=global \
--project="${PROJECT_ID}" \
--policy-kind=access \
--policy="projects/${PROJECT_ID}/locations/global/accessPolicies/platform-egress-policy" \
--target-resource="//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}"
```
- **`target.resource` (`--target-resource`)**: Canonical Resource Manager URI:
- Org: `//cloudresourcemanager.googleapis.com/organizations/${ORG_ID}`
- Folder: `//cloudresourcemanager.googleapis.com/folders/${FOLDER_ID}`
- Project: `//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}` (numeric project number).
- **`policyKind` (`--policy-kind`)**: `ACCESS` in JSON/REST (`access` in `gcloud`).
--------------------------------------------------------------------------------
## 3. Runtime Evaluation Pipeline & Mathematical Invariants
```
+-----------------------------------------------------------------------------------+
| 1. Workload Egress |
| Agent container issues outbound request (e.g. HTTP GET /api/v2/tickets.json) |
| Injected proxy environment directs traffic to Envoy / Agent Gateway. |
+------------------------------------------┬----------------------------------------+
│
▼
+-----------------------------------------------------------------------------------+
| 2. PEP Interception & Gatekeeper Resolution |
| - IAP Authz Extension intercepts the request (Envoy ext_authz). |
| - Gatekeeper verifies caller's SPIFFE/OIDC Agent Identity token. |
| - Gatekeeper queries Agent Registry: |
| * If target matches registry: sets destination.is_registered = true |
| * If target not cataloged: sets destination.is_registered = false |
| - Populates request attributes into the destination CEL context. |
+------------------------------------------┬----------------------------------------+
│
▼
+-----------------------------------------------------------------------------------+
| 3. PDP Traversal: IAM CheckPolicy() |
| IAM traverses the CRM hierarchy top-down or bottom-up: |
| Organization (organizations/112233445566) |
| │ |
| ▼ |
| Folder (folders/123456789012) |
| │ |
| ▼ |
| Project (projects/9876543210) |
| - Evaluates all active PolicyBindings attached to all nodes in the path. |
+------------------------------------------┬----------------------------------------+
│
▼
+-----------------------------------------------------------------------------------+
| 4. Evaluation Logic Engine |
| [Step A: Check for Absolute DENY] |
| Did ANY matching rule across Org, Folder, or Project evaluate to DENY? |
| ├── YES ──► REJECT IMMEDIATELY (HTTP 403 Forbidden / PERMISSION_DENIED) |
| └── NO |
| │ |
| ▼ |
| [Step B: Aggregate Additive ALLOWs] |
| ALLOW_effective = ALLOW_project ∪ ALLOW_folder ∪ ALLOW_org |
| Did AT LEAST ONE rule match with effect: ALLOW? |
| ├── YES ──► PERMIT REQUEST (Forward to backend target) |
| └── NO ──► DEFAULT-DENY (HTTP 403 Forbidden) |
+-----------------------------------------------------------------------------------+
```
### The Two Mathematical Invariants of UAP
1. **Absolute DENY Precedence**:
`Decision = DENY` if `∃ r ∈ (Rules_org ∪ Rules_folder ∪ Rules_project)` such that `Match(r) ∧ r.effect == DENY`.
There are **no deny exceptions** in UAP. If an Org-level rule denies a
destination, no project developer or platform admin can override or bypass
that denial.
2. **Additive ALLOW Aggregation**:
`ALLOW_effective = ALLOW_org ∪ ALLOW_folder ∪ ALLOW_project`.
Permissions granted at higher levels cannot be narrowed, scoped down, or
revoked by lower tiers. If a Platform Admin allows a domain at the Folder
level, an individual Project Developer cannot block an agent from accessing
it unless an explicit `DENY` rule is added.
--------------------------------------------------------------------------------
## 4. Deep CEL Attribute Reference
UAP evaluates CEL expressions within the `iap.googleapis.com` namespace rooted
at the `destination` object.
```
destination
│
┌─────────────────────────┴─────────────────────────┐
▼ ▼
is_registered == true is_registered == false
│ │
agent_registry unregistered
├── resource_type ├── host
├── location ├── path
├── project_id └── method
├── endpoint.name
├── mcp_server.name
├── mcp_server.method
├── mcp_server.tool.name
├── mcp_server.tool.annotations.read_only_hint
├── mcp_server.tool.annotations.destructive_hint
├── mcp_server.tool.annotations.idempotent_hint
├── mcp_server.tool.annotations.open_world_hint
├── mcp_server.prompt.name
├── mcp_server.resource.name
└── agent.name
```
### 4.1 Registered Destinations (`destination.is_registered == true`)
Populated when the target is cataloged in the Gemini Enterprise **Agent
Registry**.
> **Important:** String functions (`.startsWith()`, `.endsWith()`, `.contains()`) are **NOT** supported on any `destination.agent_registry.*` attribute, and regex `.matches()` is **NOT** supported on any UAP CEL attribute. Registered string attributes support **only `==`, `!=`, and `in`**.
| Attribute | Type | Supported Operators | Purpose / Example |
| :--- | :--- | :--- | :--- |
| `destination.is_registered` | bool | `==`, `!=` | Root guard. Must be verified before accessing sub-attributes. |
| `destination.agent_registry.resource_type` | string | `==`, `!=`, `in` | Resource type: `'ENDPOINT'`, `'MCP_SERVER'`, `'AGENT'`, `'SKILL'`. |
| `destination.agent_registry.location` | string | `==`, `!=`, `in` | Region of the registry resource (`'global'`, `'us-central1'`). |
| `destination.agent_registry.project_id` | string | `==`, `!=`, `in` | Host project ID of the registry entry (`'prod-agent-hub'`). |
| `destination.agent_registry.endpoint.name` | string | `==`, `!=`, `in` | Full resource name: `'projects/{p}/locations/{l}/endpoints/{name}'`. |
| `destination.agent_registry.mcp_server.name` | string | `==`, `!=`, `in` | Full resource name: `'projects/{p}/locations/{l}/mcpServers/{name}'`. |
| `destination.agent_registry.mcp_server.method` | string | `==`, `!=`, `in` | MCP protocol method family: `'tools'`, `'prompts'`, `'resources'`. |
| `destination.agent_registry.mcp_server.tool.name` | string | `==`, `!=`, `in` | Specific tool name being executed (e.g., `'updateTicket'`). |
| `destination.agent_registry.mcp_server.tool.annotations.read_only_hint` | bool | `==`, `!=` | `true` if tool is declared read-only by tool author. |
| `destination.agent_registry.mcp_server.tool.annotations.destructive_hint` | bool | `==`, `!=` | `true` if tool performs irreversible mutations. |
| `destination.agent_registry.mcp_server.tool.annotations.idempotent_hint` | bool | `==`, `!=` | `true` if repeated identical calls have no additional effect. |
| `destination.agent_registry.mcp_server.tool.annotations.open_world_hint` | bool | `==`, `!=` | `true` if tool interacts with external open-world entities. |
| `destination.agent_registry.mcp_server.prompt.name` | string | `==`, `!=`, `in` | MCP prompt name (must guard with `mcp_server.method == 'prompts'`). |
| `destination.agent_registry.mcp_server.resource.name` | string | `==`, `!=`, `in` | MCP resource name/URI (must guard with `mcp_server.method == 'resources'`). |
| `destination.agent_registry.agent.name` | string | `==`, `!=`, `in` | Full resource name of target agent for Agent-to-Agent egress. |
> **Warning:** **Null Dereference Guard Pattern**: When an agent calls a non-tool MCP method (such as `prompts/list` or `resources/read`), the `tool` message inside `mcp_server` is `null` (and similarly `prompt` or `resource` is `null` on `tools/*` calls). Dereferencing `.tool.*`, `.prompt.name`, or `.resource.name` without checking `mcp_server.method` first crashes Gatekeeper with a CEL evaluation error.
>
> **Mandatory pattern**:
>
> ```cel
> (destination.agent_registry.mcp_server.method == 'tools') && (destination.agent_registry.mcp_server.tool.annotations.read_only_hint == true)
> ```
### 4.2 Unregistered Destinations (`destination.is_registered == false`)
Populated when an agent calls an external IP, public URL, SaaS endpoint, or
uncataloged GCP service.
| Attribute | Type | Supported Operators | Purpose / Example |
| :--- | :--- | :--- | :--- |
| `destination.unregistered.host` | string | `==`, `!=`, `in`, `.startsWith()`, `.endsWith()`, `.contains()` | Target host FQDN: `'acme.zendesk.com'`, `'api.github.com'`. (No `.matches()` regex.) |
| `destination.unregistered.path` | string | `==`, `!=`, `in`, `.startsWith()`, `.endsWith()`, `.contains()` | Request URI path: `'/api/v2/tickets.json'`. |
| `destination.unregistered.method` | string | `==`, `!=`, `in` | HTTP verb: `'GET'`, `'POST'`, `'PUT'`, `'DELETE'`. |
> **Important:** **Tool Annotations Unavailable on Unregistered Endpoints**: Unregistered endpoints do NOT possess semantic annotations (`read_only_hint`, `destructive_hint`). The proxy only sees raw L7 wire data (host, path, method). Restricting read-only behavior on unregistered endpoints must be enforced via HTTP methods (`destination.unregistered.method == 'GET'`).
### 4.3 Cloud Console Parenthesization Rule
To ensure the Google Cloud Console UI parses and renders UAP rules as standard
interactive resources (Endpoint, MCP Server, Agent) rather than raw CEL text
fallbacks, **each CEL clause MUST be wrapped in parentheses**:
```cel
(destination.agent_registry.endpoint.name == 'projects/123/locations/us-central1/endpoints/my-ep') && (destination.agent_registry.location == 'us-central1')
```
### 4.4 Principal Identity Grammar
```cel
// 1. Single Agent Runtime Agent (Organization-backed project):
principal://agents.global.org-${ORG_ID}.system.id.goog/resources/aiplatform/projects/${PROJECT_NUMBER}/locations/${LOCATION}/reasoningEngines/${ENGINE_ID}
// 2. Single Agent Runtime Agent (Orgless project — uses proj-${PROJECT_NUMBER}):
principal://agents.global.proj-${PROJECT_NUMBER}.system.id.goog/resources/aiplatform/projects/${PROJECT_NUMBER}/locations/${LOCATION}/reasoningEngines/${ENGINE_ID}
// 3. Single Gemini Enterprise App Agent:
principal://agents.global.org-${ORG_ID}.system.id.goog/resources/discoveryengine/projects/${PROJECT_NUMBER}/locations/${LOCATION}/collections/default_collection/engines/${APP_ID}/assistants/default_assistant/agents/${AGENT_ID}
// 4. All Agents across the entire Organization:
principalSet://agents.global.org-${ORG_ID}.system.id.goog/*
// 5. All Agent Runtime (aiplatform) Agents in the Organization:
principalSet://agents.global.org-${ORG_ID}.system.id.goog/attribute.platform/aiplatform
// 6. All Agents scoped to a specific consumer Project:
principalSet://agents.global.org-${ORG_ID}.system.id.goog/attribute.platformContainer/aiplatform/projects/${PROJECT_NUMBER}
```
> **Note:** Never use `urn:agent:...` catalog URNs in IAM UAP `principals` — URN strings are used only in Agent Registry metadata and `ExtensionBinding.matchConditions`.
--------------------------------------------------------------------------------
## 5. The 3-Tier Organizational Security Model
```
=================================================================================
TIER 1: SECURITY ADMIN (ORGANIZATION SCOPE)
Scope: organizations/${ORG_ID}
Goal: Enterprise Perimeter Guardrails & Telemetry Survival
---------------------------------------------------------------------------------
Rules:
[ALLOW] Essential Container Telemetry (telemetry.mtls.googleapis.com)
[DENY] Unapproved Commercial LLMs (api.openai.com, api.anthropic.com)
=================================================================================
│
▼
=================================================================================
TIER 2: PLATFORM ADMIN (FOLDER SCOPE)
Scope: folders/${FOLDER_ID}
Goal: Shared Corporate Defaults & Developer Autonomy Baselines
---------------------------------------------------------------------------------
Rules:
[ALLOW] Registered Google Cloud APIs (.../endpoints/googleapis)
[ALLOW] Corporate Intranet Apex & Subdomains (*.corp.example.com)
[ALLOW] Central Read-Only MCP Tools (read_only_hint == true)
=================================================================================
│
▼
=================================================================================
TIER 3: AGENT DEVELOPER (PROJECT SCOPE)
Scope: projects/${PROJECT_NUMBER}
Goal: Granular, Least-Privilege Workload Authorizations
---------------------------------------------------------------------------------
Rules:
[ALLOW] Mutating Tool updateTicket on Registered Jira MCP Server
[ALLOW] Strict Zendesk Ticket API (/api/v2/tickets.json, GET/POST/PUT)
[ALLOW] Scoped GitHub Org Query (/repos/my-org/, GET/POST)
=================================================================================
```
### Concrete Terraform Implementation (`google-beta` provider)
> **Important:** In the `google-beta` Terraform provider (`iam3`), `AccessPolicy`
> resources use **singular** hierarchy nouns (`google_iam_{organization,folder,project}_access_policy`)
> with `details { rules { effect, operation { ... }, conditions { service, expression } } }`
> (`title` is not supported in `conditions`), whereas CRM `PolicyBinding`
> resources use **plural** hierarchy nouns (`google_iam_{organizations,folders,projects}_policy_binding`)
> with `policy_kind = "ACCESS"` and `target { resource = "..." }`. Both the
> `AccessPolicy` **and** its `PolicyBinding` are required for enforcement (and
> `constraints/iam.managed.disableAccessPolicyBinding` must not be enforced on
> the target hierarchy node).
```hcl
# ------------------------------------------------------------------------------
# TIER 1: Organization Guardrails + Organization PolicyBinding
# ------------------------------------------------------------------------------
resource "google_iam_organization_access_policy" "org_guardrails" {
provider = google-beta
organization = var.org_id
location = "global"
access_policy_id = "org-security-guardrails"
display_name = "Organization Security Guardrails"
details {
rules {
description = "ALLOW: Essential telemetry for Reasoning Engine boot"
effect = "ALLOW"
principals = ["principalSet://agents.global.org-${var.org_id}.system.id.goog/attribute.platform/aiplatform"]
operation {
permissions = ["iap.googleapis.com/resources.egressViaIAP"]
}
conditions {
service = "iap.googleapis.com"
expression = "(destination.is_registered == false) && (destination.unregistered.host in ['telemetry.mtls.googleapis.com', 'cloudlogging.googleapis.com', 'monitoring.googleapis.com'])"
}
}
rules {
description = "DENY: Prevent data exfiltration to unauthorized commercial LLMs"
effect = "DENY"
principals = ["principalSet://agents.global.org-${var.org_id}.system.id.goog/*"]
operation {
permissions = ["iap.googleapis.com/resources.egressViaIAP"]
}
conditions {
service = "iap.googleapis.com"
expression = "(destination.is_registered == false) && (destination.unregistered.host in ['api.openai.com', 'api.anthropic.com', 'api.cohere.ai'])"
}
}
}
}
resource "time_sleep" "wait_org_access_policy" {
create_duration = "60s"
depends_on = [google_iam_organization_access_policy.org_guardrails]
}
resource "google_iam_organizations_policy_binding" "org_guardrails_binding" {
provider = google-beta
depends_on = [time_sleep.wait_org_access_policy]
organization = var.org_id
location = "global"
policy_binding_id = "org-security-guardrails-binding"
display_name = "Bind Organization Security Guardrails"
policy_kind = "ACCESS"
policy = "organizations/${var.org_id}/locations/global/accessPolicies/${google_iam_organization_access_policy.org_guardrails.access_policy_id}"
target {
resource = "//cloudresourcemanager.googleapis.com/organizations/${var.org_id}"
}
}
# ------------------------------------------------------------------------------
# TIER 2: Folder Platform Defaults + Folder PolicyBinding
# ------------------------------------------------------------------------------
resource "google_iam_folder_access_policy" "folder_defaults" {
provider = google-beta
folder = var.folder_id
location = "global"
access_policy_id = "folder-platform-defaults"
display_name = "Folder Platform Defaults"
details {
rules {
description = "ALLOW: Read-only tools on registered corporate MCP servers"
effect = "ALLOW"
principals = ["principalSet://agents.global.org-${var.org_id}.system.id.goog/attribute.platform/aiplatform"]
operation {
permissions = ["iap.googleapis.com/resources.egressViaIAP"]
}
conditions {
service = "iap.googleapis.com"
expression = "(destination.is_registered == true) && (destination.agent_registry.resource_type == 'MCP_SERVER') && (destination.agent_registry.project_id == 'corp-tools-hub') && (destination.agent_registry.mcp_server.method == 'tools') && (destination.agent_registry.mcp_server.tool.annotations.read_only_hint == true)"
}
}
}
}
resource "time_sleep" "wait_folder_access_policy" {
create_duration = "60s"
depends_on = [google_iam_folder_access_policy.folder_defaults]
}
resource "google_iam_folders_policy_binding" "folder_defaults_binding" {
provider = google-beta
depends_on = [time_sleep.wait_folder_access_policy]
folder = var.folder_id
location = "global"
policy_binding_id = "folder-platform-defaults-binding"
display_name = "Bind Folder Platform Defaults"
policy_kind = "ACCESS"
policy = "folders/${var.folder_id}/locations/global/accessPolicies/${google_iam_folder_access_policy.folder_defaults.access_policy_id}"
target {
resource = "//cloudresourcemanager.googleapis.com/folders/${var.folder_id}"
}
}
# ------------------------------------------------------------------------------
# TIER 3: Project Agent-Specific Workload Policy + Project PolicyBinding
# ------------------------------------------------------------------------------
resource "google_iam_project_access_policy" "project_workload_egress" {
provider = google-beta
project = var.project_id
location = "global"
access_policy_id = "support-bot-egress"
display_name = "Support Bot Workload Egress Policy"
details {
rules {
description = "ALLOW: Specific ticket operations with verb constraints"
effect = "ALLOW"
# var.reasoning_engine_id MUST be the numeric ReasoningEngine resource ID
principals = [
"principal://agents.global.org-${var.org_id}.system.id.goog/resources/aiplatform/projects/${var.project_number}/locations/us-central1/reasoningEngines/${var.reasoning_engine_id}"
]
operation {
permissions = ["iap.googleapis.com/resources.egressViaIAP"]
}
conditions {
service = "iap.googleapis.com"
expression = "(destination.is_registered == false) && (destination.unregistered.host == 'acme.zendesk.com') && ((destination.unregistered.path == '/api/v2/tickets') || (destination.unregistered.path == '/api/v2/tickets.json') || (destination.unregistered.path.startsWith('/api/v2/tickets/')) || (destination.unregistered.path.startsWith('/api/v2/tickets?')) || (destination.unregistered.path.startsWith('/api/v2/tickets.json?'))) && (destination.unregistered.method in ['GET', 'POST', 'PUT'])"
}
}
}
}
resource "time_sleep" "wait_project_access_policy" {
create_duration = "60s"
depends_on = [google_iam_project_access_policy.project_workload_egress]
}
resource "google_iam_projects_policy_binding" "project_workload_egress_binding" {
provider = google-beta
depends_on = [time_sleep.wait_project_access_policy]
project = var.project_id
location = "global"
policy_binding_id = "support-bot-egress-binding"
display_name = "Bind Support Bot Workload Egress Policy"
policy_kind = "ACCESS"
policy = "projects/${var.project_id}/locations/global/accessPolicies/${google_iam_project_access_policy.project_workload_egress.access_policy_id}"
target {
resource = "//cloudresourcemanager.googleapis.com/projects/${var.project_number}"
}
}
```
--------------------------------------------------------------------------------
## 6. Legacy IAM v1 Reference (Backward Compatibility)
In deployments where the Gateway AuthzExtension does NOT specify
`iapPolicyVersion: "V2"`, IAP operates in legacy V1 mode:
### 6.1 Assigning `roles/iap.egressor`
Apply bindings using `gcloud iap web set-iam-policy`:
```bash
# Registry-wide scope (top-level {"bindings": [...]} JSON without a "policy" wrapper)
gcloud iap web set-iam-policy agents-iap-policy.json \
--project=PROJECT_ID \
--resource-type=agent-registry \
--region=REGION
# Specific MCP Server scope (--resource-type=agent-registry is still mandatory; pass catalog UUID)
gcloud iap web set-iam-policy mcp-iap-policy.json \
--project=PROJECT_ID \
--resource-type=agent-registry \
--region=REGION \
--mcp-server=MCP_SERVER_UUID
```
### 6.2 Inspecting Legacy Policies
```bash
gcloud iap web get-iam-policy --project=PROJECT_ID --resource-type=agent-registry --region=REGION
```
--------------------------------------------------------------------------------
## 7. Observability, Auditing, & Dry-Run Operations
### 7.1 Gateway AuthzExtension Configuration
In the Agent Gateway's IAP `AuthzExtension` metadata:
- `iapPolicyVersion: "V2"`: **Mandatory** to activate UAP policy evaluation.
- `iamEnforcementMode: "DRY_RUN"`: Evaluates complete hierarchy, logs
decisions to Cloud Audit Logs, and permits traffic.
- Omit `iamEnforcementMode` (or set `iamEnforcementMode: "ENFORCE"`, never
`"ENFORCED"`): Actively blocks unapproved traffic with HTTP `403` / gRPC
`PERMISSION_DENIED`.
### 7.2 Cloud Audit Log Schema (UAP)
Enable **Data Access (`DATA_READ`)** audit logs for `iap.googleapis.com` to record runtime UAP policy evaluations and denials:
```text
protoPayload.serviceName="iap.googleapis.com"
(protoPayload.authorizationInfo.permission="iap.resources.egressViaIAP" OR protoPayload.metadata.iapPolicyVersion="v2")
```
Example audit log payload:
```json
{
"protoPayload": {
"@type": "type.googleapis.com/google.cloud.audit.AuditLog",
"serviceName": "iap.googleapis.com",
"methodName": "CheckPolicy",
"metadata": {
"iapPolicyVersion": "v2",
"iamEnforcementMode": "DRY_RUN",
"policyEvaluationResults": [
{
"policy": "organizations/112233445566/locations/global/accessPolicies/org-security-guardrails",
"evaluationResult": "ALLOWED"
},
{
"policy": "folders/123456789012/locations/global/accessPolicies/folder-platform-defaults",
"evaluationResult": "ALLOWED"
},
{
"policy": "projects/9876543210/locations/global/accessPolicies/support-bot-egress",
"evaluationResult": "ALLOWED"
}
],
"finalDecision": "ALLOWED"
}
}
}
```
--------------------------------------------------------------------------------
## 8. Production Edge Cases & Architectural Gotchas
### 1. The Blanket Unregistered DENY Boot Crash
- **Trap**: An Org Admin configures:
```cel
(destination.is_registered == false) // effect: DENY
```
- **Consequence**: All Reasoning Engine containers crash during startup.
Reasoning Engines emit container boot telemetry to
`telemetry.mtls.googleapis.com`, which is an unregistered public endpoint.
Because DENY is absolute, the agent fails to initialize.
- **Fix**: Rely on the Agent Gateway's built-in default-deny architecture.
Never write a generic DENY on `destination.is_registered == false`.
### 2. Sibling Path Prefix Escapes vs. Query Strings
- **Trap**: Restricting an external API with `.startsWith('/api/v2/tickets')`.
- **Consequence**: An attacker or compromised agent can access
`/api/v2/tickets_export` or `/api/v2/tickets_delete_all` because both
strings start with that prefix.
- **Fix**: Enforce strict boundary delimiters and query parameters:
```cel
((destination.unregistered.path == '/api/v2/tickets') ||
(destination.unregistered.path == '/api/v2/tickets.json') ||
(destination.unregistered.path.startsWith('/api/v2/tickets/')) ||
(destination.unregistered.path.startsWith('/api/v2/tickets?')) ||
(destination.unregistered.path.startsWith('/api/v2/tickets.json?')))
```
### 3. Confused Deputy via Unanchored `project_id` Sets
- **Trap**: Allowing `destination.agent_registry.resource_type == 'MCP_SERVER'` across an overly broad `project_id in [...]` list without anchoring the exact `mcp_server.name`.
- **Consequence**: Any developer who registers a new MCP server inside one of those projects automatically satisfies the policy. (Note also that `mcp_server.name` does **not** support `.startsWith()` or `.endsWith()` — only `==`, `!=`, and `in`.)
- **Fix**: Anchor both `project_id` and the exact canonical `mcp_server.name`:
```cel
(destination.agent_registry.project_id == 'corp-tools-hub') &&
(destination.agent_registry.mcp_server.name == 'projects/corp-tools-hub/locations/us-central1/mcpServers/jira-service')
```
### 4. Intranet Subdomain Wildcard Masking
- **Trap**: A Platform Admin allows `*.corp.example.com` (unregistered
intranet) at the Folder tier, and creates an MCP server named
`tools.corp.example.com`.
- **Consequence**: If a developer forgets to catalog `tools.corp.example.com`
in Agent Registry, Gatekeeper flags `destination.is_registered = false`. The
request falls through to the unregistered intranet ALLOW rule, completely
bypassing all tool-level semantic checks (`read_only_hint`) and granting
ambient access!
- **Fix**: Host corporate MCP servers on a distinct domain namespace outside
the intranet wildcard, or ensure registration is verified before deployment.
### 5. IAM Policy Binding Destruction Race Condition
- **Trap**: Deleting a `PolicyBinding` and its `AccessPolicy` in Terraform at
the same time.
- **Consequence**: IAM Policy Control Plane has a 10–30 second replication
delay. Terraform issues `DELETE AccessPolicy` while the binding deletion is
still replicating, returning `400 FAILED_PRECONDITION: Access policy is
referenced by active policy binding(s)`.
- **Fix**: Destroy provisioners must poll GET the binding URL until HTTP 404
is confirmed before deleting the AccessPolicy.
### 6. Organization Policy Constraint Blocker
- **Trap**: `gcloud iam policy-bindings create` fails with
`CUSTOM_ORG_POLICY_VIOLATION`.
- **Root Cause**: Many Google Cloud organizations enforce
`constraints/iam.managed.disableAccessPolicyBinding` by default. (Beware:
some documentation pages misspell this in the plural as
`disableAccessPolicyBindings`, which `gcloud org-policies` rejects.)
- **Fix**: Apply an Org Policy V2 override setting `enforce: false` at the
target CRM level, then wait **~30–60 seconds** for propagation before
retrying `policy-bindings create`:
```bash
gcloud org-policies set-policy --project=${PROJECT_ID} override.yaml
# override.yaml:
# name: projects/${PROJECT_ID}/policies/iam.managed.disableAccessPolicyBinding
# spec:
# rules:
# - enforce: false
```
### 7. UAP Control-Plane & Console Error Reference
| Error Code / Symptom | Root Cause | Remediation |
| :--- | :--- | :--- |
| `POLICY_NOT_FOUND` (`HTTP 404`) | Policy ID missing in `--location=global` or wrong parent project/folder/org. | Run `gcloud iam access-policies list --project=${PROJECT_ID} --location=global` to confirm canonical policy name. |
| `TOO_MANY_ACCESS_POLICY_BINDINGS_PER_TARGET` | Target CRM node exceeded per-target policy binding quota. | Consolidate rules into a single `AccessPolicy` and delete redundant bindings on that target. |
| `TOO_MANY_ACCESS_POLICY_BINDINGS_TO_POLICY` | Single `AccessPolicy` bound to too many separate CRM targets. | Bind once at a higher Folder/Org node and discriminate workloads/destinations via `principals` and CEL conditions. |
| `TOO_MANY_CONDITIONS` | Rule exceeded Fine-Grained Access Control (FGAC) CEL condition complexity. | Combine host/method checks using `in [...]` lists or split logic across multiple rules inside the same `AccessPolicy`. |
| `HTTP 412 Precondition Failed` / `ABORTED` | Concurrent edit invalidated the `AccessPolicy` `etag`. | Re-run `gcloud iam access-policies describe` (`GET`) to obtain the latest `etag` before `update` / `PATCH`. |
| **Cannot delete the last rule in a policy** | An `AccessPolicy` must contain at least one rule. | Delete all referencing `PolicyBinding` resources first (poll `GET` until HTTP `404`), then delete the `AccessPolicy`. |
--------------------------------------------------------------------------------
## 9. Quick Command Cheat Sheet
### UAP (Policy V2) Commands
```bash
# List all policy bindings in a project (parent scope — note: `list` has NO --target/--target-resource flag)
gcloud iam policy-bindings list --project="${PROJECT_ID}" --location=global
# Search policy bindings attached to a specific CRM target resource URI
gcloud iam policy-bindings search-target-policy-bindings \
--target="//cloudresourcemanager.googleapis.com/projects/${PROJECT_NUMBER}" \
--project="${PROJECT_ID}" \
--location=global
# Describe an Access Policy
gcloud iam access-policies describe "${POLICY_ID}" \
--project="${PROJECT_ID}" \
--location=global
# Tail UAP Audit Logs in Cloud Logging (Data Access + Policy Evaluation)
gcloud logging read \
'protoPayload.serviceName="iap.googleapis.com" AND (protoPayload.authorizationInfo.permission="iap.resources.egressViaIAP" OR protoPayload.metadata.iapPolicyVersion="v2")' \
--project="${PROJECT_ID}" --limit=20 --order=desc
```
### Legacy IAM v1 Commands
```bash
# Get IAM policy on Agent Registry
gcloud iap web get-iam-policy \
--project="${PROJECT_ID}" \
--resource-type=agent-registry \
--region="${LOCATION}"
# Tail Legacy IAP Audit Logs
gcloud logging read \
'protoPayload.serviceName="iap.googleapis.com"' \
--project="${PROJECT_ID}" --limit=20 --order=desc
```
--------------------------------------------------------------------------------
## 10. Debugging Flowchart
```
┌─────────────────────────────┐
│ Agent request denied (403) │
└──────────────┬──────────────┘
│
▼
┌─────────────────────────────┐
│ Check IAP Audit Logs: │
│ iapPolicyVersion == "v2"? │
└───────┬─────────────┬───────┘
yes │ │ no (legacy v1)
│ ▼
│ ┌─────────────────────────────┐
│ │ Check roles/iap.egressor │
│ │ on Agent Registry entry │
│ └─────────────────────────────┘
▼
┌─────────────────────────────────────────────────────────────┐
│ Check policyEvaluationResults across Org, Folder, Project │
└──────────────────────────────┬──────────────────────────────┘
│
┌──────────────┴──────────────┐
▼ ▼
Any rule evaluated to DENY? No rules matched ALLOW?
│ │
▼ ▼
Identify denying rule Verify destination.is_registered
(Check for blanket DENY and check CEL conditions
or denylisted domain) (Check null guard on .tool.*)
```
--------------------------------------------------------------------------------
## 11. Network Security AuthzPolicy: L7 HTTP/MCP Rules, L4 networkRules, & DENY_BY_DEFAULT
`AuthzPolicy` (`networksecurity.googleapis.com`) binds authorization rules and
delegated extensions directly to `agentGateways/*` resources.
### 11.1 Policy Evaluation Order & Mandatory Target Invariant
When multiple `AuthzPolicy` resources target the same Agent Gateway in
`REQUEST_AUTHZ`, Envoy evaluates them in strict priority order:
1. **`CUSTOM`** (delegated `AuthzExtension`, such as IAP or custom `ext_proc`)
2. **`DENY`** (explicit L7 `httpRules` or L4 `networkRules` deny)
3. **`ALLOW`** (explicit L7 `httpRules` or L4 `networkRules` allow)
4. **`DENY_BY_DEFAULT`** (flips fallback behavior from default-allow to default-deny; **cannot** contain `httpRules` or `networkRules`)
5. Fallback default-allow (only if no `DENY_BY_DEFAULT` policy is attached; note Google-managed egress Agent Gateways already enforce registry/IAP default-deny).
> **Warning:** **Never Set `target.loadBalancingScheme` on Agent Gateways**:
> When `target.resources` references `projects/*/locations/*/agentGateways/*`,
> **omit `target.loadBalancingScheme`** (or leave it `LOAD_BALANCING_SCHEME_UNSPECIFIED`).
> Setting `loadBalancingScheme: INTERNAL_MANAGED` fails validation with
> `INVALID_ARGUMENT: Unsupported load balancing scheme: INTERNAL_MANAGED`.
### 11.2 Native MCP Attribute Rules (`baseProtocolMethodsOption`)
In `GA` (`gcloud network-security authz-policies import`), `httpRules[].to.operations[].mcp`
matches MCP JSON-RPC calls without external extensions.
- **Critical Default Trap (`SKIP_BASE_PROTOCOL_METHODS`)**: By default,
`baseProtocolMethodsOption` is `SKIP_BASE_PROTOCOL_METHODS` (which skips
matching `initialize`, `completion/*`, `logging/*`, `notifications/*`, and
`ping`). In a `DENY` policy this is safe, **but in an `ALLOW` policy coupled
with `DENY_BY_DEFAULT`, leaving the default blocks the MCP `initialize`
handshake with HTTP `403`!**
- **Mandatory Fix for `ALLOW` Policies**: Explicitly set
`baseProtocolMethodsOption: MATCH_BASE_PROTOCOL_METHODS`:
```yaml
name: allow-readonly-mcp-tools
target:
resources:
- "projects/${PROJECT_ID}/locations/${LOCATION}/agentGateways/${GATEWAY_NAME}"
policyProfile: REQUEST_AUTHZ
action: ALLOW
httpRules:
- to:
operations:
- mcp:
baseProtocolMethodsOption: MATCH_BASE_PROTOCOL_METHODS
methods:
- name: "tools/list"
- name: "tools/call"
params:
- exact: "get_ticket"
```
```bash
gcloud network-security authz-policies import allow-readonly-mcp-tools \
--source=allow-readonly-mcp-tools.yaml \
--location="${LOCATION}" \
--project="${PROJECT_ID}"
```
### 11.3 L4 `networkRules` (SNI Passthrough & Explicit HTTPS Proxy Support)
When an Agent Runtime workload routes outbound traffic through an **explicit
corporate HTTPS forward proxy** (`HTTPS_PROXY=https://proxy.corp.internal:443`,
with explicit port `:443` and `NO_PROXY=.googleapis.com,googleapis.com,169.254.169.254,metadata.google.internal,localhost,127.0.0.1`),
the client sends an inner `HTTP CONNECT` tunnel over TLS to the proxy's SNI.
Without an L4 `networkRules` policy, Agent Gateway's L7 HTTP connection manager
terminates TLS and rejects nested `CONNECT` requests with **HTTP `404 Not Found`**.
Attaching an L4 `AuthzPolicy` with `networkRules` dispatches matching SNIs to
the gateway's `loopback_tls_network_authz` TCP/SNI listener:
```yaml
name: allow-explicit-proxy-sni
target:
resources:
- "projects/${PROJECT_ID}/locations/${LOCATION}/agentGateways/${GATEWAY_NAME}"
policyProfile: REQUEST_AUTHZ
action: ALLOW
networkRules:
- from:
sources:
- ipBlocks:
- prefix: "7.0.0.0"
length: 8
- prefix: "10.20.1.0"
length: 24
to:
operations:
- snis:
- exact: "proxy.corp.internal"
```
```bash
# MUST use `gcloud beta` (v1beta1 schema); GA `v1` rejects `networkRules`
gcloud beta network-security authz-policies import allow-explicit-proxy-sni \
--source=allow-explicit-proxy-sni.yaml \
--location="${LOCATION}" \
--project="${PROJECT_ID}"
```
**Strict L4 `networkRules` Schema & Security Trade-offs**:
- **`gcloud beta` Required**: `networkRules` exists only in `v1beta1` (`gcloud beta network-security authz-policies import`).
- **`snis` Only**: `networkRules[].to.operations[]` supports **only `snis`** (`exact`, `prefix`, `suffix`, `contains`, `ignoreCase`; max 10 SNIs per operation, max 5 `networkRules` per policy). Do **not** specify `ports` or any HTTP fields (`hosts`, `paths`, `methods`, `headerSet`, `mcp`), and never mix `httpRules` and `networkRules` in the same policy.
- **Two-Plane Source IP Rule (`7.0.0.0/8` vs. Consumer PSC-I CIDR)**: `from.sources[].resources` is disallowed on Agent Gateway targets. Inside Agent Gateway's Envoy (`AuthzPolicy` `networkRules[].from.sources[].ipBlocks`), either **omit `from`** or include **both** `7.0.0.0/8` (the internal Agent Runtime → Gateway Envoy source range) and your consumer PSC-I subnet CIDR. Inside your **consumer VPC** (GCE ingress firewall rules and Squid `acl localnet src`), allow **only your consumer PSC-I Network Attachment subnet CIDR** (e.g., `10.20.1.0/24`) — packets entering your VPC via PSC-I are sourced from the PSC-I subnet, never `7.0.0.0/8`.
- **L7 Governance Bypass Trade-off**: Traffic matching an L4 `networkRules` `ALLOW` rule bypasses L7 TLS termination at Agent Gateway — meaning **IAP/UAP, Model Armor, Semantic Governance Policies, and L7 `httpRules` are NOT evaluated** on traffic encapsulated inside that proxy tunnel (your downstream corporate proxy assumes L7 policy responsibility). Also note ACT `tlsConfig.trustConfig` is not applied to L4-bypassed tunnels; configure proxy CA trust inside the agent container (`SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE`).
--------------------------------------------------------------------------------
## 12. Model Armor Content Security Policies (`CONTENT_AUTHZ`)
Model Armor attaches to Agent Gateway via a `ServiceExtensions` `AuthzExtension`
(`service: modelarmor.${LOCATION}.rep.googleapis.com`) and a `NetworkSecurity`
`AuthzPolicy` with `policyProfile: CONTENT_AUTHZ` and `action: CUSTOM`.
### 12.1 Ingress vs. Egress Capabilities, Limits, & Distinct Service Agents
| Dimension | Client-to-Agent (Ingress) | Agent-to-Anywhere (Egress) |
| :--- | :--- | :--- |
| **Max `CONTENT_AUTHZ` Policies** | **1** per ingress gateway | **4** per egress gateway |
| **Service Agent Executing Callout** | **AI Platform Reasoning Engine SA**:<br>`service-${AGENT_PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com` | **Service Extensions SA**:<br>`service-${GATEWAY_PROJECT_NUMBER}@gcp-sa-dep.iam.gserviceaccount.com` |
| **Required IAM Roles** | • `roles/modelarmor.calloutUser` on **agent runtime project**<br>• `roles/modelarmor.user` on **Model Armor template project** | • `roles/modelarmor.calloutUser` + `roles/serviceusage.serviceUsageConsumer` on **gateway project**<br>• `roles/modelarmor.user` on **Model Armor template project** |
| **Sanitized Payloads** | **Only ADK `reasoningEngines.streamQuery`** requests & responses on Agent Runtime | • **MCP**: `tools/call`, `prompts/get`, MCP tool execution errors<br>• **A2A v1**: `SendMessage`, `AgentCard`, `GetExtendedAgentCard` (JSON-RPC & HTTP+JSON/REST)<br>• **OpenAI-compatible LLM**: non-streaming Chat Completions, Get chat messages, non-streaming Responses, Embeddings, Legacy Assistants/Threads/Messages, API errors |
| **Bypassed Without Sanitization** | Non-ADK payloads (e.g., LangChain), `query`, and `ReasoningEngine` error responses | • **MCP**: `tools/list`, `resources/*`, `notifications/*`, Streamable HTTP/SSE, protocol errors<br>• **A2A**: `<v1`, `SendStreamingMessage`, `GetTask`/`ListTasks`/`CancelTask`/`SubscribeToTask`, gRPC protobuf<br>• **OpenAI**: streaming SSE responses<br>• **Documents/PDFs**: unsupported in gateway integration (call Model Armor REST `sanitizeUserPrompt` directly) |
### 12.2 Sensitive Data Protection (SDP) Redaction Semantics
- In-flight payload redaction requires template enforcement type **`INSPECT_AND_BLOCK`** plus advanced SDP settings with a de-identify template.
- **Single- vs. Multi-Detector Rule**: If a payload violates **only** the SDP detector, Model Armor redacts the sensitive spans in-flight and forwards the request/response. If a payload violates **multiple detectors** (e.g., SDP + Prompt Injection), Model Armor **blocks the entire payload** without performing redaction.
- Under `INSPECT_ONLY`, payloads pass unmodified (redaction applies only to Model Armor's own logs).
### 12.3 Hard 60-Second Stream Deadline & Runtime Gotchas
- **Non-Configurable 60s Stream Deadline (`Stream removed`)**: While `AuthzExtension.timeout` configures individual callout RPC deadlines (`1s`–`10s`), Envoy enforces a **hard 60-second total stream lifetime** on `CONTENT_AUTHZ` processing. Long-running LLM generations, SSE streams, or outbound HTTP/2 gRPC channels routed through a `CONTENT_AUTHZ` policy terminate at 60 seconds with HTTP `500`/`504` or gRPC `UNKNOWN: Stream removed`. **Fix**: Scope `AuthzPolicy.httpRules` (hosts/paths/headers) so `CONTENT_AUTHZ` intercepts only targeted non-streaming tool/model endpoints and excludes long-lived gRPC/SSE streams.
- **Body-Shape Inspection & Streaming Log Volume**: Model Armor matches protocol payloads by **JSON body structure**, not URL path alone. On ADK `streamQuery` responses, seeing multiple `CONTENT_MODIFIED` / per-chunk callout entries in gateway logs is expected frame-by-frame inspection behavior.
--------------------------------------------------------------------------------
## 13. Semantic Governance Policies (SGP)
Semantic Governance Policies evaluate proposed tool calls and model interactions
against **Natural Language Constraints (NLC)** and optional **User Intent
Alignment** using **the LLM in the semantic governance policy engine**.
### 13.1 Provisioning Prerequisites & Reserved Subnets
1. **API, Supported Locations, & Regional Endpoint Override**: SGP is available in `us-central1`, `us-east1`, `us-east4`, `us-west1`, `europe-southwest1`, `europe-west1`, `europe-west4`, and `europe-west8`. Enable `aiplatform.googleapis.com` and point `gcloud` at the regional endpoint before running SGP engine/policy commands:
```bash
gcloud config set api_endpoint_overrides/aiplatform "https://${LOCATION}-aiplatform.googleapis.com/"
```
2. **Vertex AI Service Agent IAM**: Grant `service-${PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com` `roles/compute.networkAdmin` and `roles/dns.admin` (plus `roles/cloudtrace.agent` when Cloud Trace is enabled) on the project.
3. **Reserved CIDR Ranges**: The SGP engine reserves **`10.0.0.0/24`, `10.0.1.0/24`, and `10.0.2.0/24`** internally. Overlapping subnets in the peered VPC cause engine provisioning or connectivity failures.
4. **Engine & Policy CLI**: Manage via `gcloud beta ai semantic-governance-policy-engine {update,describe,deprovision}` and `gcloud beta ai semantic-governance-policies {create,update,list,describe,delete}`.
### 13.2 Data-Plane `AuthzExtension` Metadata & Non-Streaming CEL `when` Filter
1. **Mandatory Non-Streaming `when` CEL Filter**: SGP supports **non-streaming** JSON LLM calls across Gemini (`:generateContent`), Vertex AI (`:rawPredict`), Anthropic Messages (`/v1/messages`), and OpenAI Chat Completions (`/chat/completions`). The policy engine **does not support streamed model responses** (`:streamGenerateContent`, `:streamRawPredict`) — streamed calls return **no verdict or an error** (and produce zero evaluation entries in `logs/semantic-governance-policy`), so agents must invoke models **without streaming**. Excluding `application/grpc` is also mandatory so internal gRPC bootstrap calls (e.g., Cloud Resource Manager) do not crash agent startup. Because Envoy populates `request.path` **including query parameters** (e.g., `?alt=json`), always use `.contains()` rather than `.endsWith()`:
```yaml
name: sgp-content-authz-policy
target:
resources:
- "projects/${PROJECT_ID}/locations/${LOCATION}/agentGateways/${GATEWAY_NAME}"
policyProfile: CONTENT_AUTHZ
action: CUSTOM
httpRules:
- when: "!request.headers['content-type'].startsWith('application/grpc') && (request.path.contains(':generateContent') || request.path.contains(':rawPredict') || request.path.contains('/v1/messages') || request.path.contains('/chat/completions'))"
customProvider:
authzExtension:
resources:
- "projects/${PROJECT_ID}/locations/${LOCATION}/authzExtensions/${SGP_EXTENSION_NAME}"
```
2. **`AuthzExtension.metadata` Keys & Wholesale Map Overwrite Trap**:
- `sgpEnforcementMode: "DRY_RUN"` (audit-only; omit key to enforce blocking).
- `sgpUserIntentMatching: "ENABLED"` or `"DISABLED"` (logs `sgpUserIntentMatchingMode` as `CONSTRAINTS_AND_INTENT`, `CONSTRAINTS_ONLY`, or `INTENT_ONLY`).
- **Trap**: Updating `AuthzExtension` via `gcloud service-extensions authz-extensions import` or REST `PATCH ...?updateMask=metadata` **replaces the entire `metadata` map**. Updating `sgpUserIntentMatching` without repeating `sgpEnforcementMode: "DRY_RUN"` immediately flips the gateway into active enforcement!
### 13.3 SGP Cloud Logging, Runtime Failure Modes, & Control-Plane Error Catalog
Query SGP data-plane evaluation logs in Cloud Logging:
```text
logName="projects/${PROJECT_ID}/logs/semantic-governance-policy"
```
- **Runtime Log Fields & Failure Symptoms**: Inspect `jsonPayload.verdict`, `jsonPayload.evaluations[].rationale`, `jsonPayload.sgpUserIntentMatchingMode`, and `jsonPayload.token_usage`. If `logs/semantic-governance-policy` has **zero entries** or streamed LLM calls fail, verify the agent invokes models **without streaming** (`:generateContent` rather than `:streamGenerateContent`) and that `httpRules[].when` uses `.contains()`. If agent sessions fail with `FAILED_PRECONDITION`, verify `dnsPeeringConfig` on your ACT resolves the engine's private `dnsRecord` (`SGP_DNS_HOSTNAME`).
- **Control-Plane Error Catalog (`aiplatform.googleapis.com` `ErrorInfo.reason`)**: Returned when running `gcloud beta ai semantic-governance-policies` or `semantic-governance-policy-engine`:
| Control-Plane Error Code (`Status`) | Root Cause & Action |
| :--- | :--- |
| `SEMANTIC_GOVERNANCE_POLICY_ALREADY_EXISTS` (`ALREADY_EXISTS`) | Policy ID already exists in project/location → choose a unique ID or use `semantic-governance-policies update`. |
| `SEMANTIC_GOVERNANCE_POLICY_ETAG_MISMATCH` (`ABORTED`) | Concurrent update invalidated `etag` → run `describe` to fetch the latest `etag` and retry `update`. |
| `SEMANTIC_GOVERNANCE_POLICY_AGENT_REQUIRED` (`INVALID_ARGUMENT`) | Missing `--agent` target → supply the full Agent Registry agent resource name. |
| `SEMANTIC_GOVERNANCE_POLICY_CONSTRAINT_REQUIRED` (`INVALID_ARGUMENT`) | Missing `--natural-language-constraint` → provide a non-empty natural-language constraint. |
| `SEMANTIC_GOVERNANCE_POLICY_AGENT_INVALID_NAME` (`INVALID_ARGUMENT`) | Malformed `--agent` path → use `projects/PROJECT_ID/locations/LOCATION/agents/agentregistry-...`. |
| `SEMANTIC_GOVERNANCE_POLICY_AGENT_UNSUPPORTED_REGION` (`INVALID_ARGUMENT`) | Agent resource location does not match policy location → register/deploy in the same supported SGP region. |
| `SEMANTIC_GOVERNANCE_POLICY_AGENT_NOT_FOUND` (`FAILED_PRECONDITION`) | Target agent not found in Agent Registry → verify with `gcloud agent-registry agents list --location=${LOCATION}`. |
| `SEMANTIC_GOVERNANCE_POLICY_AGENT_NOT_CONFIGURED` (`FAILED_PRECONDITION`) | Agent was not created with both `AGENT_IDENTITY` (`agents.global.*`) and `agent_gateway_config` → redeploy a new Reasoning Engine with both set at creation time. |
| `SEMANTIC_GOVERNANCE_POLICY_MCP_SERVER_NOT_FOUND` (`FAILED_PRECONDITION`) | Referenced MCP server missing in Agent Registry → verify with `gcloud agent-registry mcp-servers list --location=${LOCATION}`. |
| `SEMANTIC_GOVERNANCE_POLICY_MCP_SERVER_INVALID_NAME` (`INVALID_ARGUMENT`) | Malformed MCP server path → use `projects/PROJECT_ID/locations/LOCATION/mcpServers/agentregistry-...`. |
| `SEMANTIC_GOVERNANCE_POLICY_MCP_SERVER_UNSUPPORTED_REGION` (`INVALID_ARGUMENT`) | MCP server location does not match policy location (or is in an unsupported region) → align locations. |
| `SEMANTIC_GOVERNANCE_POLICY_REGISTRY_DENIED` (`PERMISSION_DENIED`) | Caller lacks Agent Registry read access or API is disabled → enable `agentregistry.googleapis.com` and grant `roles/agentregistry.viewer`. |
| `SEMANTIC_GOVERNANCE_POLICY_AGENT_REGISTRY_INVALID_NAME` (`INVALID_ARGUMENT`) | Malformed Agent Registry resource identifier in policy target/tool scope → verify exact `name` from `agent-registry {agents,mcp-servers} describe`. |
| `SEMANTIC_GOVERNANCE_POLICY_ENGINE_NOT_ENABLED_IN_REGION` (`FAILED_PRECONDITION`) | SGP engine not provisioned or not yet `ACTIVE` in `${LOCATION}` → run `gcloud beta ai semantic-governance-policy-engine update --location=${LOCATION}` and poll `describe` until `state: ACTIVE`. |
| `SEMANTIC_GOVERNANCE_POLICY_ENGINE_SERVICE_NOT_AVAILABLE_IN_LOCATION` (`FAILED_PRECONDITION`) | SGP is unavailable in the requested location → deploy in a supported SGP region (`us-central1`, `us-east1`, `us-east4`, `us-west1`, `europe-southwest1`, `europe-west1`, `europe-west4`, `europe-west8`) with `api_endpoint_overrides/aiplatform` set. |
--------------------------------------------------------------------------------
## 14. Extensible Policies: ExtensionBinding & ProducerExtension (Preview)
`ExtensionBinding` (`gcloud beta service-extensions extension-bindings import`)
provides a streamlined consumer attachment model replacing manual
`AuthzExtension` + `AuthzPolicy` pairs:
- **1P Built-in Extensions**: Reference Google-managed endpoints directly via
`producerExtension: "iap.googleapis.com"` or
`producerExtension: "modelarmor.us.rep.googleapis.com"` (passing templates in
`producerMetadata.model_armor_settings`) without creating a `ProducerExtension`.
- **2P/3P Custom `ext_proc` Extensions**: Producers host an Envoy `ext_proc`
gRPC service (e.g., Cloud Run with HTTP/2 + plaintext gRPC + unauthenticated
ingress → Serverless NEG → Regional Internal ALB → PSC Service Attachment)
and publish a `ProducerExtension` using the separate `--extension-settings-*` flags:
```bash
gcloud beta service-extensions producer-extensions create PRODUCER_EXTENSION_NAME \
--location="${LOCATION}" \
--project="${PRODUCER_PROJECT}" \
--phase=authz \
--extension-settings-service="projects/${PRODUCER_PROJECT}/regions/${LOCATION}/serviceAttachments/${PSC_ATTACHMENT_NAME}" \
--extension-settings-supported-events=request-headers,request-body,response-headers,response-body \
--extension-settings-authority="ext.producer.example.com"
```
Consumers then bind `producerExtension: "projects/${PRODUCER_PROJECT}/locations/${LOCATION}/producerExtensions/PRODUCER_EXTENSION_NAME"` after PSC project allowlisting.
- **Match Conditions & Metadata Context**: `matchConditions` filter on
`to.destination.resources` (`prefix: "urn:mcp"`, `prefix: "urn:agent"`) or
`to.destination.hosts`. Custom `ext_proc` servers receive gateway/registry
context in `ProcessingRequest.metadata_context` under
`com.google.serviceextensions.invocation_info` (`binding_selector.{target, project_number, to_resource}`).
- **Double-Invocation Gotcha**: `ExtensionBinding` can attach at either the
gateway resource level (`target.resources`) or project scope (`target.scope.parent: "projects/${PROJECT_NUMBER}"`, `resourceTypes: "AGENT_GATEWAY"`). Attaching the **same** extension via both a project-scope `ExtensionBinding` and a gateway-level `ExtensionBinding` (or combining a project-scope `ExtensionBinding` with a gateway-bound `AuthzPolicy`) executes the extension **twice** on every matching request (see BKI #39).
--------------------------------------------------------------------------------
## 15. Token Management Policies (Preview — HTTP 429)
Token management policies enforce shared LLM token budgets (`input`, `output`,
and `cached` tokens) across Gemini, Anthropic, and OpenAI-compatible models on
self-managed Secure Web Proxy Agent Gateway deployments (for GKE and Cloud Run
agents).
- **Strict Dependency & Teardown Order** (max **1** of each per project target scope):
1. Create `TokenAggregationPolicy` first (up to 10 first-match `rules` grouping traffic into a `tokenGroup`; unmatched traffic logs as `unmatched`).
2. Create `TokenBudgetPolicy` second (up to 10 `TokenPool` entries with `maxTokens`, `HOURLY` or `DAILY` midnight PT reset, `alertThreshold` e.g. `0.8`; non-targeted models log pool `undefined`).
3. Create `CostPerTokenPolicy` third (optional custom USD rates or discount for `gcp.token_management.token.estimated_cost`).
- **Teardown**: Delete in **strict reverse order**: `CostPerTokenPolicy` → `TokenBudgetPolicy` → `TokenAggregationPolicy`.
- **Diagnosing Unexpected HTTP `429 Too Many Requests` vs. Quota Overshoot**:
- **Pre-flight block (`429`)**: When a pool's reconciled consumption reaches `maxTokens` and strict enforcement is active, pre-flight checks reject new LLM requests immediately with **HTTP `429`**. Distinguish gateway token-pool `429` from upstream Vertex AI/model quota `429` by checking `token_management_alert_logs` in Cloud Logging and `gen_ai.client.token.usage` in Cloud Monitoring.
- **Concurrent overshoot**: Because output tokens are reconciled *after* an LLM response completes, concurrent in-flight requests admitted just below `maxTokens` can temporarily exceed the budget before subsequent requests are throttled. Validate new budgets with `validateOnly: true` and `alertThreshold: 0.6`–`0.8` before enabling strict blocking.
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