From 219036561af5981f02cacd70ed154ca22dfeea9c Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Fri, 27 Nov 2026 16:17:25 +0000 Subject: [PATCH] envoy, node, docs: support GCP Agent Gateway FULL_DUPLEX_STREAMED ext_proc and host-first MCP resolution Add full compatibility with Google Cloud Agent Gateway (AuthzExtension EXT_PROC_GRPC + AuthzPolicy CONTENT_AUTHZ) and Envoy BUFFERED / FULL_DUPLEX_STREAMED ext_proc proxies for unmodified HTTP, Git Smart HTTP, and MCP traffic: - internal/envoy: - Read ProcessingRequest.ProtocolConfig and FlowControlInit to detect FULL_DUPLEX_STREAMED request/response body modes and SendBodyWithoutWaitingForHeaderResponse. - In FULL_DUPLEX_STREAMED mode, buffer MCP POST request body chunks silently until EndOfStream (or RequestTrailers) before authorizing tools/call against TaskAuthorizationRule allowed_tools, echoing allowed bodies via BodyMutation.StreamedResponse and failing closed with 403 ImmediateResponse (or 413 on overflow > MaxHTTPBodyBytes) before any disallowed bytes leave Envoy. - Reject partial half-duplex STREAMED MCP RequestBody chunks (EndOfStream=false when not in FULL_DUPLEX_STREAMED mode) fail-closed with 403 ImmediateResponse on the first chunk so zero unverified body bytes can be released upstream. - Add CheckInput.HeadersOnly and CheckResult.NeedsRequestBody so host-resolved MCP services mounted on arbitrary paths (such as "/" or "/mcp/v1") trigger body inspection without relying on a /mcp path prefix or custom headers, while non-MCP POST traffic (such as Git Smart HTTP git-upload-pack) is decided at RequestHeaders without body buffering. - Emit RFC 9113 lowercase, deterministically sorted HTTP/2 header names in both gRPC ext_authz Check and ext_proc HeaderMutation responses. - internal/node: - Add ResolveMCPByHostPath (longest segment-boundary path prefix with fail-closed ambiguity rejection) and strip explicit :port from :authority. - Resolve ext_authz / ext_proc targets host-first for unmodified gateway traffic (X-Mesh-Target-Service -> /mesh/... -> MCP host+path -> Egress host -> bare //). - Return verified X-Mesh-* provenance headers (never backend secrets) on HeadersOnly MCP pre-checks for FULL_DUPLEX_STREAMED gateways, and enforce TrustedTransport (--socket-path or --tls-ca) before injecting MCP target_auth_path Authorization headers alongside egress credential brokering. - Add structured audit logging for ExtAuthz denials and ExtProc protocol mode. - site & development/examples/gcp-agent-gateway: - Add the Google Cloud Agent Gateway integration guide and runnable deployment and verification bundle (Managed Agent Gateway + Vertex AI Agent Runtime AGENT_IDENTITY, plus Edge ALB Service Extensions topology). --- .../examples/gcp-agent-gateway/README.md | 96 +++ .../agent_runtime/deploy_agent.py | 172 +++++ .../gcp-agent-gateway/agent_runtime/main.py | 214 ++++++ .../agent_runtime/requirements.txt | 5 + .../examples/gcp-agent-gateway/cleanup.sh | 72 ++ .../gcp-agent-gateway/deploy_edge_alb.sh | 266 +++++++ .../gcp-agent-gateway/deploy_managed_agw.sh | 283 +++++++ .../github-mcp-live/Dockerfile | 29 + .../gcp-agent-gateway/github-mcp-live/main.go | 312 ++++++++ .../examples/gcp-agent-gateway/pep/Dockerfile | 45 ++ .../gcp-agent-gateway/pep/entrypoint.sh | 142 ++++ .../gcp-agent-gateway/pep/node.yaml.tmpl | 14 + .../gcp-agent-gateway/pep/policy.json.tmpl | 53 ++ .../gcp-agent-gateway/verify_edge_alb.sh | 183 +++++ internal/envoy/envoy_test.go | 717 +++++++++++++++++- internal/envoy/server.go | 331 ++++++-- internal/node/egress_inspect_test.go | 367 +++++++++ internal/node/ext_authz.go | 225 ++++-- internal/node/service.go | 14 + internal/node/service_registry.go | 53 ++ internal/node/service_registry_test.go | 61 ++ site/content/docs/guides/_index.md | 11 +- site/content/docs/guides/gcp-agent-gateway.md | 291 +++++++ tests/integration/posture_isolation_test.go | 22 +- 24 files changed, 3861 insertions(+), 117 deletions(-) create mode 100644 development/examples/gcp-agent-gateway/README.md create mode 100755 development/examples/gcp-agent-gateway/agent_runtime/deploy_agent.py create mode 100644 development/examples/gcp-agent-gateway/agent_runtime/main.py create mode 100644 development/examples/gcp-agent-gateway/agent_runtime/requirements.txt create mode 100755 development/examples/gcp-agent-gateway/cleanup.sh create mode 100755 development/examples/gcp-agent-gateway/deploy_edge_alb.sh create mode 100755 development/examples/gcp-agent-gateway/deploy_managed_agw.sh create mode 100644 development/examples/gcp-agent-gateway/github-mcp-live/Dockerfile create mode 100644 development/examples/gcp-agent-gateway/github-mcp-live/main.go create mode 100644 development/examples/gcp-agent-gateway/pep/Dockerfile create mode 100755 development/examples/gcp-agent-gateway/pep/entrypoint.sh create mode 100644 development/examples/gcp-agent-gateway/pep/node.yaml.tmpl create mode 100644 development/examples/gcp-agent-gateway/pep/policy.json.tmpl create mode 100755 development/examples/gcp-agent-gateway/verify_edge_alb.sh create mode 100644 site/content/docs/guides/gcp-agent-gateway.md diff --git a/development/examples/gcp-agent-gateway/README.md b/development/examples/gcp-agent-gateway/README.md new file mode 100644 index 000000000..ad6b6ad3f --- /dev/null +++ b/development/examples/gcp-agent-gateway/README.md @@ -0,0 +1,96 @@ +# Agent Mesh as a Google Cloud Agent Gateway Service Extension (`EXT_PROC_GRPC`) + +This example deploys `agentmesh-node` on Google Cloud Run as an Envoy gRPC v3 +**Service Extension** (`AuthzExtension` with `wireFormat: EXT_PROC_GRPC` + +`AuthzPolicy` with `policyProfile: CONTENT_AUTHZ`, `action: CUSTOM`) plugged +directly into **Google Cloud Agent Gateway** — keeping Agent Gateway in the L7 +data path for TLS inspection, Agent Registry, Model Armor, and Cloud Logging +while Agent Mesh enforces short-lived, cryptographically sealed +**Task Authorization Rules (`tar_block`)** and verified IdP `claim()` facts. + +## What This Qualifies With 100% Real Traffic + +A single 10-minute sealed Biscuit minted via RFC 8693 `POST /oauth/token` +grants an isolated agent strictly: + +1. **Read-only Git Smart HTTP `git clone`** of `github.com/google/agentmesh.git` + (`GET /google/agentmesh.git/info/refs` + `POST /google/agentmesh.git/git-upload-pack`), + while blocking `git push` (`POST /git-receive-pack`), unapproved repositories + (`kubernetes/kubernetes.git`), and raw `HTTP CONNECT` tunnels with HTTP `403`. +2. **Read-only GitHub MCP tools** (`list_issues`, `issue_read`, `search_issues`) + against live `https://api.github.com` via `ext_proc` JSON-RPC body inspection + (with **no** custom `X-Mesh-Target-Service` header required — resolved by + `:authority` + path), stripping spoofed `X-Mesh-*` / `X-Peer-Id` headers and + blocking all mutating tools (`issue_write`, `create_pull_request`, + `push_files`, `delete_repository`) with HTTP `403` before reaching the backend. +3. **Fail-closed task scoping:** standing unattenuated Biscuits (no `tar_block`) + and expired mandates (> 15m `max_task_ttl`) are rejected with HTTP `403`. + +## Two Topologies Included + +| Topology | Script | Data Path | Best For | +| :--- | :--- | :--- | :--- | +| **A: Managed Agent Gateway (`AGENT_TO_ANYWHERE`)** | [`deploy_managed_agw.sh`](deploy_managed_agw.sh) + [`agent_runtime/deploy_agent.py`](agent_runtime/deploy_agent.py) | Vertex AI Agent Runtime (`AGENT_IDENTITY`) → Managed `AgentGateway` → `AuthzExtension` (`EXT_PROC_GRPC`) → `agentmesh-node` on Cloud Run → live `github.com` & `github-mcp-live` | Exact Google Cloud Agent Gateway product architecture | +| **B: Edge Agent Gateway (External ALB Fallback)** | [`deploy_edge_alb.sh`](deploy_edge_alb.sh) + [`verify_edge_alb.sh`](verify_edge_alb.sh) | Any HTTPS/HTTP client (workstation, CI runner, sandbox) → Regional External ALB (`EXTERNAL_MANAGED`) → `AuthzExtension` (`EXT_PROC_GRPC`) → `agentmesh-node` on Cloud Run → live `github.com` & `github-mcp-live` | Fast end-to-end real `git clone`/`git push` + live MCP verification from any terminal | + +## Prerequisites + +- A Google Cloud project with billing enabled where you have IAM permissions + to enable APIs and manage Cloud Run, Service Extensions, and Agent Gateway. +- `gcloud` CLI (`>= 588.0.0`) authenticated with `gcloud auth login` and + `gcloud auth application-default login`. +- `curl`, `jq`, `git`, and `python3`. + +## Quickstart — Topology B (Edge ALB, ~5 minutes) + +```bash +export PROJECT_ID="" +export REGION="us-central1" + +chmod +x deploy_edge_alb.sh verify_edge_alb.sh cleanup.sh +./deploy_edge_alb.sh + +# Wait ~60s for AuthzPolicy propagation, then run all 7 live probes (including real git clone): +./verify_edge_alb.sh +``` + +## Quickstart — Topology A (Managed Agent Gateway + Vertex AI Agent Runtime) + +```bash +export PROJECT_ID="" +export REGION="us-central1" + +chmod +x deploy_managed_agw.sh +./deploy_managed_agw.sh + +# Deploy and invoke the Vertex AI Agent Runtime ADK qualification agent: +python3 -m venv /tmp/agw-venv +/tmp/agw-venv/bin/pip install -r agent_runtime/requirements.txt +PROJECT_ID="${PROJECT_ID}" REGION="${REGION}" AGW_NAME="agentmesh-egress-gw" \ + PEP_URL="$(gcloud run services describe agentmesh-agw-pep --region="${REGION}" --project="${PROJECT_ID}" --format='value(status.url)')" \ + MCP_URL="$(gcloud run services describe agentmesh-github-mcp-live --region="${REGION}" --project="${PROJECT_ID}" --format='value(status.url)')" \ + /tmp/agw-venv/bin/python agent_runtime/deploy_agent.py +``` + +### Production Hardening Notes + +- **Lock down `ALLOWED_AUDIENCE` and `ALLOWED_MEMBER`:** The sandbox scripts + include gcloud's default client ID in `ALLOWED_AUDIENCE` so + `gcloud auth print-identity-token` works immediately from a developer + terminal. In production, set `ALLOWED_AUDIENCE` strictly to your dedicated + workload audience and narrow `ALLOWED_MEMBER` to your agent service account + or principal prefix. +- **Brokered GitHub credentials:** Mount a Secret Manager read-only GitHub token + into `agentmesh-agw-pep` and set `MCP_GITHUB_AUTH_PATH=/secrets/github-token`. + `agentmesh-node` injects `Authorization` via `ext_proc` `HeaderMutation` only + after Phase 2 JSON-RPC `tools/call` authorization succeeds. +- **Private VPC callout:** For private-only Cloud Run (`--ingress=internal-and-cloud-load-balancing`), + front `agentmesh-agw-pep` with a Regional Internal ALB, attach a VPC + `networkAttachment` + `dnsPeeringConfig` to the `AgentGateway`, and point + `AuthzExtension.service` / `authority` at the private DNS hostname. + +## Cleanup + +```bash +PROJECT_ID="" REGION="us-central1" ./cleanup.sh +``` diff --git a/development/examples/gcp-agent-gateway/agent_runtime/deploy_agent.py b/development/examples/gcp-agent-gateway/agent_runtime/deploy_agent.py new file mode 100755 index 000000000..f27514570 --- /dev/null +++ b/development/examples/gcp-agent-gateway/agent_runtime/deploy_agent.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Idempotently deploys the qualification ADK agent to Vertex AI Agent Runtime +bound to a Managed Google Cloud Agent Gateway (AGENT_TO_ANYWHERE) and runs the +live allow/deny probe matrix via reasoningEngines/:streamQuery. + +Usage: + PROJECT_ID= REGION=us-central1 AGW_NAME=agentmesh-egress-gw \ + PEP_URL=https://... MCP_URL=https://... /tmp/agw-venv/bin/python deploy_agent.py +""" + +import json +import os +import sys +import time + +import google.auth +import google.auth.transport.requests +import requests +import vertexai +from google.genai import types as genai_types +from vertexai import types + +DISPLAY_NAME = "agentmesh-agw-qualifier" + + +def _adc_headers(project_id: str) -> dict[str, str]: + creds, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"]) + creds.refresh(google.auth.transport.requests.Request()) + return { + "Authorization": f"Bearer {creds.token}", + "Content-Type": "application/json", + "x-goog-user-project": project_id, + } + + +def _find_existing_engine(project_id: str, region: str) -> str: + url = f"https://{region}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{region}/reasoningEngines" + r = requests.get(url, headers=_adc_headers(project_id), timeout=30) + r.raise_for_status() + for re_obj in r.json().get("reasoningEngines", []): + if re_obj.get("displayName") == DISPLAY_NAME: + return re_obj["name"] + return "" + + +def main() -> int: + project_id = os.environ["PROJECT_ID"] + region = os.environ.get("REGION", "us-central1") + agw_name = os.environ.get("AGW_NAME", "agentmesh-egress-gw") + pep_url = os.environ["PEP_URL"] + mcp_url = os.environ["MCP_URL"] + audience = os.environ.get("AGENTMESH_AUDIENCE", "agentmesh-gcp-agw") + agw_resource = f"projects/{project_id}/locations/{region}/agentGateways/{agw_name}" + + re_name = _find_existing_engine(project_id, region) + if re_name and os.environ.get("RECREATE_AGENT", "").lower() in ("1", "true", "yes"): + print(f"==> RECREATE_AGENT=true: deleting existing Reasoning Engine {re_name}") + del_url = f"https://{region}-aiplatform.googleapis.com/v1/{re_name}?force=true" + del_resp = requests.delete(del_url, headers=_adc_headers(project_id), timeout=60) + del_resp.raise_for_status() + for _ in range(30): + if not _find_existing_engine(project_id, region): + break + time.sleep(2) + re_name = "" + if re_name: + print(f"==> Reusing existing Reasoning Engine: {re_name}") + else: + agent_dir = os.path.dirname(os.path.abspath(__file__)) + vertexai.init(project=project_id, location=region) + client = vertexai.Client( + project=project_id, + location=region, + http_options=genai_types.HttpOptions(api_version="v1beta1"), + ) + + print(f"==> Deploying ADK agent to Vertex AI Agent Runtime bound to {agw_resource}") + prev_cwd = os.getcwd() + os.chdir(agent_dir) + try: + remote = client.agent_engines.create( + config={ + "display_name": DISPLAY_NAME, + "description": "Qualifies Agent Mesh AuthzExtension on Managed Agent Gateway", + "identity_type": types.IdentityType.AGENT_IDENTITY, + "source_packages": ["main.py", "requirements.txt"], + "entrypoint_module": "main", + "entrypoint_object": "agent_instance", + "requirements_file": "requirements.txt", + "agent_framework": "google-adk", + "class_methods": [], + "max_instances": 1, + "env_vars": { + "GOOGLE_CLOUD_LOCATION": region, + "NUM_WORKERS": "2", + # Required for Agent Gateway-attached Agent Runtime engines so + # internal sessions.create calls succeed cleanly. + "GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES": "False", + "AGENTMESH_PEP_URL": pep_url, + "AGENTMESH_MCP_URL": mcp_url, + "AGENTMESH_AUDIENCE": audience, + }, + "agent_gateway_config": { + "agent_to_anywhere_config": {"agent_gateway": agw_resource}, + }, + } + ) + finally: + os.chdir(prev_cwd) + re_name = remote.api_resource.name + print(f"==> Deployed Reasoning Engine: {re_name}") + print("==> Waiting 30s for AuthzPolicy & gateway attachment propagation...") + time.sleep(30) + + re_id = re_name.split("/")[-1] + headers = _adc_headers(project_id) + base_url = f"https://{region}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{region}/reasoningEngines/{re_id}" + + print("==> Creating session and running live qualification matrix through Managed Agent Gateway...") + sess_resp = requests.post( + f"{base_url}/sessions", + headers=headers, + json={"userId": "qualifier"}, + timeout=30, + ) + sess_resp.raise_for_status() + sess_json = sess_resp.json() + sess_full = sess_json.get("response", {}).get("name") or sess_json.get("name", "") + session_id = sess_full.split("/sessions/")[-1].split("/")[0] + + q_resp = requests.post( + f"{base_url}:streamQuery", + headers=headers, + json={ + "classMethod": "async_stream_query", + "input": { + "user_id": "qualifier", + "session_id": session_id, + "message": "Run run_agw_qualification_matrix and return the exact JSON result.", + }, + }, + timeout=180, + ) + q_resp.raise_for_status() + for line in q_resp.text.splitlines(): + line = line.strip() + if not line: + continue + try: + evt = json.loads(line) + print(json.dumps(evt, indent=2)) + except json.JSONDecodeError: + print(line) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/development/examples/gcp-agent-gateway/agent_runtime/main.py b/development/examples/gcp-agent-gateway/agent_runtime/main.py new file mode 100644 index 000000000..cc9e6acb5 --- /dev/null +++ b/development/examples/gcp-agent-gateway/agent_runtime/main.py @@ -0,0 +1,214 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Minimal ADK agent deployed to Vertex AI Agent Runtime with AGENT_IDENTITY +and attached to a Managed Google Cloud Agent Gateway (AGENT_TO_ANYWHERE). + +Its tools mint a 10-minute sealed Agent Mesh TAR Biscuit from the PEP's +/oauth/token endpoint using the runtime's Google OIDC identity token and then +issue real HTTPS requests to github.com and the live GitHub MCP backend so +Agent Gateway's CONTENT_AUTHZ AuthzExtension (agentmesh-node ext_proc) can +enforce task-scoped read-only clone and read-only issue access. +""" + +import base64 +import datetime +import json +import os + +import google.auth.transport.requests +import google.oauth2.id_token +import requests +from google.adk.agents import LlmAgent +from vertexai.agent_engines import AdkApp + +PEP_URL = os.environ["AGENTMESH_PEP_URL"].rstrip("/") +MCP_URL = os.environ["AGENTMESH_MCP_URL"].rstrip("/") +ALLOWED_AUDIENCE = os.environ.get("AGENTMESH_AUDIENCE", "agentmesh-gcp-agw") + + +def _peek_jwt_claims(token: str) -> dict: + try: + parts = token.split(".") + if len(parts) < 2: + return {"raw_len": len(token)} + pad = "=" * (-len(parts[1]) % 4) + payload = json.loads(base64.urlsafe_b64decode(parts[1] + pad)) + return {k: payload.get(k) for k in ("iss", "aud", "sub", "email", "azp") if k in payload} + except Exception as exc: + return {"decode_error": str(exc)} + + +def _mint_sealed_tar_biscuit() -> str: + req = google.auth.transport.requests.Request() + id_token = google.oauth2.id_token.fetch_id_token(req, ALLOWED_AUDIENCE) + exp = ( + datetime.datetime.now(datetime.timezone.utc) + + datetime.timedelta(minutes=10) + ).strftime("%Y-%m-%dT%H:%M:%SZ") + tar_spec = { + "name": "tasks/agw-runtime-github-readonly", + "display_name": "Agent Runtime: Clone google/agentmesh + Read GitHub Issues Only", + "expire_time": exp, + "rules": [ + { + "description": "Allow read-only Git Smart HTTP clone of google/agentmesh.git", + "allowed_services": ["egress://github.com"], + "operation": { + "allowed_methods": ["GET", "POST"], + "allowed_paths": [ + "/google/agentmesh.git/info/refs", + "/google/agentmesh.git/git-upload-pack", + ], + }, + }, + { + "description": "Allow read-only GitHub MCP issue tools only", + "allowed_services": ["mcp://github"], + "operation": { + "allowed_tools": ["list_issues", "issue_read", "search_issues"], + }, + }, + ], + } + resp = requests.post( + f"{PEP_URL}/oauth/token", + data={ + "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", + "subject_token": id_token, + "subject_token_type": "urn:ietf:params:oauth:token-type:id_token", + "options": json.dumps(tar_spec), + "seal": "true", + }, + timeout=15, + ) + if not resp.ok: + raise RuntimeError( + f"/oauth/token returned HTTP {resp.status_code}: {resp.text.strip()} " + f"(subject_jwt_claims={_peek_jwt_claims(id_token)})" + ) + return resp.json()["access_token"] + + +def run_agw_qualification_matrix() -> dict: + """Runs all allow/deny GitHub Smart HTTP and MCP probes through the real + Managed Google Cloud Agent Gateway + agentmesh-node ext_proc extension.""" + biscuit = _mint_sealed_tar_biscuit() + results = {} + + # 1. Allowed Git Smart HTTP discovery (GET github.com/google/agentmesh.git/info/refs) + r_clone_refs = requests.get( + "https://github.com/google/agentmesh.git/info/refs?service=git-upload-pack", + headers={"X-Mesh-Biscuit": biscuit}, + timeout=15, + ) + results["git_clone_info_refs_allowed"] = { + "status": r_clone_refs.status_code, + "passed": r_clone_refs.status_code == 200, + } + + # 2. Denied Git Smart HTTP push (POST github.com/google/agentmesh.git/git-receive-pack) + r_push = requests.post( + "https://github.com/google/agentmesh.git/git-receive-pack", + headers={"X-Mesh-Biscuit": biscuit}, + data=b"0000", + timeout=15, + ) + results["git_push_denied"] = { + "status": r_push.status_code, + "passed": r_push.status_code == 403, + } + + # 3. Denied unapproved repository (GET github.com/kubernetes/kubernetes.git/info/refs) + r_other = requests.get( + "https://github.com/kubernetes/kubernetes.git/info/refs?service=git-upload-pack", + headers={"X-Mesh-Biscuit": biscuit}, + timeout=15, + ) + results["git_other_repo_denied"] = { + "status": r_other.status_code, + "passed": r_other.status_code == 403, + } + + # 4. Allowed MCP list_issues (NO X-Mesh-Target-Service header; host-resolved mcp://github) + r_list = requests.post( + f"{MCP_URL}/mcp", + headers={ + "Content-Type": "application/json", + "X-Mesh-Biscuit": biscuit, + "X-Mesh-Claims": "forged=true", + "X-Peer-Id": "12D3KooWSpoofed", + }, + json={ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": { + "name": "list_issues", + "arguments": {"owner": "google", "repo": "agentmesh"}, + }, + }, + timeout=15, + ) + list_json = r_list.json() if r_list.status_code == 200 else {} + hdrs = list_json.get("result", {}).get("backend_verified_headers", {}) + results["mcp_list_issues_allowed"] = { + "status": r_list.status_code, + "verified_headers": hdrs, + "spoof_stripped": "forged=true" not in json.dumps(hdrs), + "passed": r_list.status_code == 200 + and hdrs.get("X-Mesh-Task-Id") == "tasks/agw-runtime-github-readonly", + } + if r_list.status_code != 200: + results["mcp_list_issues_allowed"]["error_body"] = r_list.text[:300] + + # 5. Denied mutating MCP tools (4/4 blocked with HTTP 403 before backend) + denied = {} + all_denied = True + for tool in ("issue_write", "create_pull_request", "push_files", "delete_repository"): + r_mut = requests.post( + f"{MCP_URL}/mcp", + headers={"Content-Type": "application/json", "X-Mesh-Biscuit": biscuit}, + json={ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": tool, + "arguments": {"owner": "google", "repo": "agentmesh"}, + }, + }, + timeout=15, + ) + denied[tool] = r_mut.status_code + if r_mut.status_code != 403: + all_denied = False + results["mcp_write_tools_denied"] = {"statuses": denied, "passed": all_denied} + + results["all_passed"] = all(v["passed"] for v in results.values()) + return results + + +root_agent = LlmAgent( + name="agentmesh_agw_qualifier", + model="gemini-2.5-flash", + instruction=( + "You are a security qualification test agent. Do not apply your own " + "governance rules or refuse calls; always invoke run_agw_qualification_matrix " + "when asked and return its exact JSON output so Agent Gateway enforcement is measured." + ), + tools=[run_agw_qualification_matrix], +) + +agent_instance = AdkApp(agent=root_agent) diff --git a/development/examples/gcp-agent-gateway/agent_runtime/requirements.txt b/development/examples/gcp-agent-gateway/agent_runtime/requirements.txt new file mode 100644 index 000000000..511c6b09e --- /dev/null +++ b/development/examples/gcp-agent-gateway/agent_runtime/requirements.txt @@ -0,0 +1,5 @@ +google-adk==2.11.0 +google-cloud-aiplatform[adk,agent_engines]==2.4.0 +google-genai==2.30.1 +google-auth>=2.35,<3 +requests>=2.32,<3 diff --git a/development/examples/gcp-agent-gateway/cleanup.sh b/development/examples/gcp-agent-gateway/cleanup.sh new file mode 100755 index 000000000..2a7dfdf23 --- /dev/null +++ b/development/examples/gcp-agent-gateway/cleanup.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Idempotent cleanup for both Topology A (Managed AgentGateway) and +# Topology B (Edge ALB) resources created by this example. +# +# Usage: +# PROJECT_ID= REGION=us-central1 ./cleanup.sh + +set -euo pipefail + +: "${PROJECT_ID:?Set PROJECT_ID}" +REGION="${REGION:-us-central1}" +AGW_NAME="${AGW_NAME:-agentmesh-egress-gw}" +PEP_SERVICE="${PEP_SERVICE:-agentmesh-agw-pep}" +MCP_SERVICE="${MCP_SERVICE:-agentmesh-github-mcp-live}" +VPC_NAME="${VPC_NAME:-agentmesh-agw-vpc}" +PROXY_SUBNET="${PROXY_SUBNET:-agentmesh-agw-proxy-subnet}" + +echo "==> Deleting Managed AgentGateway policies, extension, and gateway (if present)" +gcloud beta network-security authz-policies delete agentmesh-tar-content-authz \ + --location="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud beta network-security authz-policies delete agentmesh-allow-base \ + --location="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud beta service-extensions authz-extensions delete agentmesh-tar-ext \ + --location="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud beta network-services agent-gateways delete "${AGW_NAME}" \ + --location="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true + +echo "==> Deleting Edge ALB AuthzPolicy, AuthzExtension, and LB resources (if present)" +gcloud beta network-security authz-policies delete agentmesh-edge-content-authz \ + --location="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud beta service-extensions authz-extensions delete agentmesh-edge-ext \ + --location="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud compute forwarding-rules delete agentmesh-edge-alb-fr \ + --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud compute target-http-proxies delete agentmesh-edge-alb-proxy \ + --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud compute url-maps delete agentmesh-edge-alb-map \ + --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud compute backend-services delete agentmesh-pep-bs \ + --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud compute backend-services delete agentmesh-mcp-bs \ + --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud compute network-endpoint-groups delete agentmesh-pep-neg \ + --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud compute network-endpoint-groups delete agentmesh-mcp-neg \ + --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud compute addresses delete agentmesh-edge-alb-ip \ + --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true + +echo "==> Deleting Cloud Run services" +gcloud run services delete "${PEP_SERVICE}" --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud run services delete "${MCP_SERVICE}" --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true + +echo "==> Deleting VPC subnet and network (best-effort)" +gcloud compute networks subnets delete "${PROXY_SUBNET}" --region="${REGION}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true +gcloud compute networks delete "${VPC_NAME}" --project="${PROJECT_ID}" --quiet >/dev/null 2>&1 || true + +echo "Cleanup commands submitted. Delete any deployed Vertex AI Agent Runtime instances separately if created." diff --git a/development/examples/gcp-agent-gateway/deploy_edge_alb.sh b/development/examples/gcp-agent-gateway/deploy_edge_alb.sh new file mode 100755 index 000000000..35c971083 --- /dev/null +++ b/development/examples/gcp-agent-gateway/deploy_edge_alb.sh @@ -0,0 +1,266 @@ +#!/usr/bin/env bash +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Idempotent deployment for Topology B: +# Google Cloud External ALB (Edge Agent Gateway) + Service Extensions +# AuthzExtension (EXT_PROC_GRPC) + AuthzPolicy (CONTENT_AUTHZ) -> +# agentmesh-node on Cloud Run -> live GitHub Smart HTTP & GitHub MCP backend. +# +# Usage: +# PROJECT_ID= REGION=us-central1 ./deploy_edge_alb.sh + +set -euo pipefail + +: "${PROJECT_ID:?Set PROJECT_ID to a GCP project with billing enabled}" +REGION="${REGION:-us-central1}" +AR_REPO="${AR_REPO:-agentmesh-agw}" +VPC_NAME="${VPC_NAME:-agentmesh-agw-vpc}" +PROXY_SUBNET="${PROXY_SUBNET:-agentmesh-agw-proxy-subnet}" +PEP_SERVICE="${PEP_SERVICE:-agentmesh-agw-pep}" +MCP_SERVICE="${MCP_SERVICE:-agentmesh-github-mcp-live}" +ALLOWED_MEMBER="${ALLOWED_MEMBER:-mesh:system:authenticated}" +# Include gcloud's default client ID so `gcloud auth print-identity-token` works +# in sandbox verification alongside workload tokens targeting `agentmesh-gcp-agw`. +# In production, restrict ALLOWED_AUDIENCE strictly to your dedicated audience. +ALLOWED_AUDIENCE="${ALLOWED_AUDIENCE:-agentmesh-gcp-agw,32555940559.apps.googleusercontent.com}" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)" +IMAGE_PREFIX="${REGION}-docker.pkg.dev/${PROJECT_ID}/${AR_REPO}" +PEP_IMAGE="${IMAGE_PREFIX}/${PEP_SERVICE}:latest" +MCP_IMAGE="${IMAGE_PREFIX}/${MCP_SERVICE}:latest" + +echo "==> [1/6] Enabling required GCP APIs on ${PROJECT_ID}" +gcloud services enable \ + artifactregistry.googleapis.com \ + cloudbuild.googleapis.com \ + compute.googleapis.com \ + networksecurity.googleapis.com \ + networkservices.googleapis.com \ + run.googleapis.com \ + --project="${PROJECT_ID}" + +echo "==> [2/6] Ensuring Artifact Registry repository ${AR_REPO}" +gcloud artifacts repositories describe "${AR_REPO}" \ + --location="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || gcloud artifacts repositories create "${AR_REPO}" \ + --repository-format=docker --location="${REGION}" \ + --description="Agent Mesh + Agent Gateway qualification images" \ + --project="${PROJECT_ID}" + +echo "==> [3/6] Building container images with Cloud Build" +TMP_CB="$(mktemp -d)" +trap 'rm -rf "${TMP_CB}"' EXIT + +if [ "${SKIP_BUILD:-false}" != "true" ]; then + cat >"${TMP_CB}/cloudbuild-pep.yaml" <"${TMP_CB}/cloudbuild-mcp.yaml" < [4/6] Deploying Cloud Run services (${MCP_SERVICE} and ${PEP_SERVICE})" +gcloud run deploy "${MCP_SERVICE}" \ + --image="${MCP_IMAGE}" \ + --region="${REGION}" \ + --platform=managed \ + --allow-unauthenticated \ + --ingress=all \ + --min-instances=1 \ + --max-instances=2 \ + --project="${PROJECT_ID}" + +MCP_URL="$(gcloud run services describe "${MCP_SERVICE}" \ + --region="${REGION}" --project="${PROJECT_ID}" --format='value(status.url)')" + +# Reserve the Edge ALB static external IP first so we can register it as the +# host-resolved MCP target URL on agentmesh-node (zero X-Mesh-Target-Service needed for /mcp). +gcloud compute networks describe "${VPC_NAME}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || gcloud compute networks create "${VPC_NAME}" --subnet-mode=auto --project="${PROJECT_ID}" + +gcloud compute networks subnets describe "${PROXY_SUBNET}" \ + --region="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || gcloud compute networks subnets create "${PROXY_SUBNET}" \ + --network="${VPC_NAME}" --region="${REGION}" \ + --range=10.12.13.0/24 --purpose=REGIONAL_MANAGED_PROXY --role=ACTIVE \ + --project="${PROJECT_ID}" + +gcloud compute addresses describe agentmesh-edge-alb-ip \ + --region="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || gcloud compute addresses create agentmesh-edge-alb-ip \ + --region="${REGION}" --network-tier=STANDARD --project="${PROJECT_ID}" + +ALB_IP="$(gcloud compute addresses describe agentmesh-edge-alb-ip \ + --region="${REGION}" --project="${PROJECT_ID}" --format='value(address)')" + +cat >"${TMP_CB}/pep-env.yaml" < [5/6] Provisioning Regional External ALB (EXTERNAL_MANAGED)" +gcloud compute network-endpoint-groups describe agentmesh-pep-neg \ + --region="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || gcloud compute network-endpoint-groups create agentmesh-pep-neg \ + --region="${REGION}" --network-endpoint-type=serverless \ + --cloud-run-service="${PEP_SERVICE}" --project="${PROJECT_ID}" + +gcloud compute network-endpoint-groups describe agentmesh-mcp-neg \ + --region="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || gcloud compute network-endpoint-groups create agentmesh-mcp-neg \ + --region="${REGION}" --network-endpoint-type=serverless \ + --cloud-run-service="${MCP_SERVICE}" --project="${PROJECT_ID}" + +gcloud compute backend-services describe agentmesh-pep-bs \ + --region="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || { + gcloud compute backend-services create agentmesh-pep-bs \ + --region="${REGION}" --load-balancing-scheme=EXTERNAL_MANAGED \ + --protocol=HTTP2 --project="${PROJECT_ID}" + gcloud compute backend-services add-backend agentmesh-pep-bs \ + --region="${REGION}" --network-endpoint-group=agentmesh-pep-neg \ + --network-endpoint-group-region="${REGION}" --project="${PROJECT_ID}" + } + +gcloud compute backend-services describe agentmesh-mcp-bs \ + --region="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || { + gcloud compute backend-services create agentmesh-mcp-bs \ + --region="${REGION}" --load-balancing-scheme=EXTERNAL_MANAGED \ + --protocol=HTTP --project="${PROJECT_ID}" + gcloud compute backend-services add-backend agentmesh-mcp-bs \ + --region="${REGION}" --network-endpoint-group=agentmesh-mcp-neg \ + --network-endpoint-group-region="${REGION}" --project="${PROJECT_ID}" + } + +gcloud compute url-maps describe agentmesh-edge-alb-map \ + --region="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || gcloud compute url-maps create agentmesh-edge-alb-map \ + --region="${REGION}" --default-service=agentmesh-mcp-bs \ + --project="${PROJECT_ID}" + +gcloud compute target-http-proxies describe agentmesh-edge-alb-proxy \ + --region="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || gcloud compute target-http-proxies create agentmesh-edge-alb-proxy \ + --region="${REGION}" --url-map=agentmesh-edge-alb-map \ + --project="${PROJECT_ID}" + +gcloud compute forwarding-rules describe agentmesh-edge-alb-fr \ + --region="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || gcloud compute forwarding-rules create agentmesh-edge-alb-fr \ + --region="${REGION}" --load-balancing-scheme=EXTERNAL_MANAGED \ + --network="${VPC_NAME}" --network-tier=STANDARD \ + --address=agentmesh-edge-alb-ip --target-http-proxy=agentmesh-edge-alb-proxy \ + --target-http-proxy-region="${REGION}" --ports=80 \ + --project="${PROJECT_ID}" + +echo "==> [6/6] Importing Service Extensions AuthzExtension (EXT_PROC_GRPC) and AuthzPolicy (CONTENT_AUTHZ)" +PEP_HOST="${PEP_URL#https://}" +# Omit forwardHeaders so all client headers (including :authority, :method, +# :path, Content-Type, Authorization, and X-Mesh-Biscuit) reach ext_proc. +cat >"${TMP_CB}/authz-extension.yaml" <"${TMP_CB}/authz-policy.yaml" < +# agentmesh-node on Cloud Run -> real GitHub + live GitHub MCP backend, +# verified from a Vertex AI Agent Runtime agent with AGENT_IDENTITY. +# +# Targets a personal or sandbox GCP project with billing enabled. +# +# Usage: +# PROJECT_ID= REGION=us-central1 ./deploy_managed_agw.sh + +set -euo pipefail + +: "${PROJECT_ID:?Set PROJECT_ID to a GCP project with billing enabled}" +REGION="${REGION:-us-central1}" +AR_REPO="${AR_REPO:-agentmesh-agw}" +AGW_NAME="${AGW_NAME:-agentmesh-egress-gw}" +PEP_SERVICE="${PEP_SERVICE:-agentmesh-agw-pep}" +MCP_SERVICE="${MCP_SERVICE:-agentmesh-github-mcp-live}" +ALLOWED_MEMBER="${ALLOWED_MEMBER:-mesh:system:authenticated}" +ALLOWED_AUDIENCE="${ALLOWED_AUDIENCE:-agentmesh-gcp-agw,32555940559.apps.googleusercontent.com}" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)" +PROJECT_NUM="$(gcloud projects describe "${PROJECT_ID}" --format='value(projectNumber)')" +IMAGE_PREFIX="${REGION}-docker.pkg.dev/${PROJECT_ID}/${AR_REPO}" +PEP_IMAGE="${IMAGE_PREFIX}/${PEP_SERVICE}:latest" +MCP_IMAGE="${IMAGE_PREFIX}/${MCP_SERVICE}:latest" +AGW_RESOURCE="projects/${PROJECT_ID}/locations/${REGION}/agentGateways/${AGW_NAME}" + +echo "==> [1/7] Enabling required GCP APIs on ${PROJECT_ID} (${PROJECT_NUM})" +gcloud services enable \ + agentregistry.googleapis.com \ + aiplatform.googleapis.com \ + artifactregistry.googleapis.com \ + cloudbuild.googleapis.com \ + compute.googleapis.com \ + dns.googleapis.com \ + iam.googleapis.com \ + iap.googleapis.com \ + logging.googleapis.com \ + modelarmor.googleapis.com \ + networksecurity.googleapis.com \ + networkservices.googleapis.com \ + run.googleapis.com \ + storage.googleapis.com \ + --project="${PROJECT_ID}" + +echo "==> [2/7] Materializing service identities and applying least-privilege IAM" +for svc in aiplatform.googleapis.com networkservices.googleapis.com; do + gcloud beta services identity create --service="${svc}" --project="${PROJECT_ID}" >/dev/null 2>&1 || true +done + +AI_SA="service-${PROJECT_NUM}@gcp-sa-aiplatform.iam.gserviceaccount.com" +AGW_SA="service-${PROJECT_NUM}@gcp-sa-agentgateway.iam.gserviceaccount.com" +COMPUTE_SA="${PROJECT_NUM}-compute@developer.gserviceaccount.com" + +# roles/networkservices.viewer is the narrowest predefined role carrying +# networkservices.agentGateways.get needed when Vertex AI Agent Runtime binds to AGW. +for role in roles/networkservices.viewer roles/aiplatform.serviceAgent roles/compute.networkAdmin roles/dns.admin; do + gcloud projects add-iam-policy-binding "${PROJECT_ID}" \ + --member="serviceAccount:${AI_SA}" --role="${role}" --condition=None --quiet >/dev/null +done + +for role in roles/agentgateway.serviceAgent roles/aiplatform.user roles/modelarmor.user; do + gcloud projects add-iam-policy-binding "${PROJECT_ID}" \ + --member="serviceAccount:${AGW_SA}" --role="${role}" --condition=None --quiet >/dev/null 2>&1 || true +done + +for role in roles/aiplatform.user roles/storage.objectViewer roles/artifactregistry.writer roles/agentregistry.viewer; do + gcloud projects add-iam-policy-binding "${PROJECT_ID}" \ + --member="serviceAccount:${COMPUTE_SA}" --role="${role}" --condition=None --quiet >/dev/null +done + +echo "==> [3/7] Building & deploying Cloud Run services (${MCP_SERVICE} and ${PEP_SERVICE})" +gcloud artifacts repositories describe "${AR_REPO}" \ + --location="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1 \ + || gcloud artifacts repositories create "${AR_REPO}" \ + --repository-format=docker --location="${REGION}" \ + --description="Agent Mesh + Agent Gateway qualification images" \ + --project="${PROJECT_ID}" + +TMP_DIR="$(mktemp -d)" +trap 'rm -rf "${TMP_DIR}"' EXIT + +if [ "${SKIP_BUILD:-false}" != "true" ]; then + cat >"${TMP_DIR}/cloudbuild-pep.yaml" <"${TMP_DIR}/cloudbuild-mcp.yaml" </dev/null | awk '$2=="organization"{print $1; exit}' || true)" + if [ -n "${ORG_ID}" ]; then + AGENT_IDENTITY_ISSUER="https://sts.googleapis.com/v1/organizations/${ORG_ID}/locations/global/workloadIdentityPools/agents.global.org-${ORG_ID}.system.id.goog" + else + AGENT_IDENTITY_ISSUER="https://sts.googleapis.com/v1/projects/${PROJECT_NUM}/locations/global/workloadIdentityPools/agents.global.project-${PROJECT_NUM}.system.id.goog" + fi +fi +echo " Agent Identity OIDC issuer: ${AGENT_IDENTITY_ISSUER}" + +# Configure agentmesh-node with MCP_GITHUB_URL pointing at MCP_URL/mcp so +# unmodified Agent Runtime requests to https:///mcp resolve by :authority +# with zero X-Mesh-Target-Service header. +cat >"${TMP_DIR}/pep-env.yaml" < [4/7] Creating Managed AgentGateway (${AGW_NAME}, AGENT_TO_ANYWHERE)" +if gcloud beta network-services agent-gateways describe "${AGW_NAME}" \ + --location="${REGION}" --project="${PROJECT_ID}" >/dev/null 2>&1; then + echo " AgentGateway ${AGW_NAME} already exists, skipping import." +else + cat >"${TMP_DIR}/agent-gateway.yaml" < [5/7] Importing baseline REQUEST_AUTHZ allow policy on AgentGateway" +cat >"${TMP_DIR}/allow-base-policy.yaml" < [6/7] Importing AuthzExtension (EXT_PROC_GRPC) pointing to ${PEP_HOST}" +# Omit forwardHeaders so Google Cloud Service Extensions forwards all client +# headers including :authority/:method/:path, Content-Type, Authorization, and +# X-Mesh-Biscuit (setting a partial allowlist drops :authority/Host and breaks +# host-based target resolution). +cat >"${TMP_DIR}/authz-extension.yaml" < [7/7] Importing CONTENT_AUTHZ AuthzPolicy scoping GitHub & MCP egress to agentmesh-tar-ext" +# Scope the extension to github.com and the MCP backend host so internal +# Vertex AI session/telemetry calls pass untouched. +cat >"${TMP_DIR}/content-authz-policy.yaml" </.git/...: reverse-proxies Git Smart HTTP traffic +// to real https://github.com for Edge ALB qualification. +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "net/http/httputil" + "net/url" + "os" + "strings" + "time" +) + +const ( + maxJSONRPCBytes = 1 << 20 + githubAPIBase = "https://api.github.com" + githubGitBase = "https://github.com" +) + +type jsonRPCRequest struct { + JSONRPC string `json:"jsonrpc"` + ID any `json:"id"` + Method string `json:"method"` + Params struct { + Name string `json:"name"` + Arguments map[string]any `json:"arguments"` + } `json:"params"` +} + +func main() { + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + + gitUpstream, err := url.Parse(githubGitBase) + if err != nil { + log.Fatalf("parse github url: %v", err) + } + gitProxy := &httputil.ReverseProxy{ + Rewrite: func(pr *httputil.ProxyRequest) { + pr.SetURL(gitUpstream) + pr.Out.Host = gitUpstream.Host + // Strip internal mesh headers before forwarding to public github.com. + for k := range pr.Out.Header { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-mesh-") || lk == "x-peer-id" { + pr.Out.Header.Del(k) + } + } + }, + } + + httpClient := &http.Client{Timeout: 15 * time.Second} + mux := http.NewServeMux() + mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok\n")) + }) + mux.HandleFunc("/mcp", func(w http.ResponseWriter, r *http.Request) { + handleMCP(w, r, httpClient) + }) + mux.HandleFunc("/mcp/", func(w http.ResponseWriter, r *http.Request) { + handleMCP(w, r, httpClient) + }) + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.URL.Path, ".git/") || strings.HasSuffix(r.URL.Path, ".git") { + gitProxy.ServeHTTP(w, r) + return + } + if r.Method == http.MethodPost { + handleMCP(w, r, httpClient) + return + } + http.NotFound(w, r) + }) + + srv := &http.Server{ + Addr: ":" + port, + Handler: mux, + ReadHeaderTimeout: 10 * time.Second, + IdleTimeout: 120 * time.Second, + } + log.Printf("github-mcp-live listening on :%s", port) + if err := srv.ListenAndServe(); err != nil { + log.Fatalf("listen: %v", err) + } +} + +func handleMCP(w http.ResponseWriter, r *http.Request, client *http.Client) { + if r.Method != http.MethodPost { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, maxJSONRPCBytes)) + if err != nil { + log.Printf("handleMCP 400: read body failed: %v", err) + http.Error(w, "read body failed", http.StatusBadRequest) + return + } + var rpc jsonRPCRequest + if err := json.Unmarshal(body, &rpc); err != nil { + log.Printf("handleMCP 400: invalid json-rpc body (len=%d): %v", len(body), err) + http.Error(w, "invalid json-rpc body", http.StatusBadRequest) + return + } + + verifiedHeaders := make(map[string]string) + for k, vals := range r.Header { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-mesh-") || lk == "x-peer-id" { + verifiedHeaders[k] = strings.Join(vals, ",") + } + } + if r.Header.Get("Authorization") != "" { + verifiedHeaders["Authorization"] = "" + } + + var result any + switch rpc.Method { + case "initialize": + result = map[string]any{ + "protocolVersion": "2024-11-05", + "serverInfo": map[string]any{"name": "github-mcp-live", "version": "1.0.0"}, + "capabilities": map[string]any{"tools": map[string]any{}}, + } + case "notifications/initialized": + w.WriteHeader(http.StatusAccepted) + return + case "tools/list": + result = map[string]any{ + "tools": []map[string]any{ + {"name": "list_issues", "description": "List live issues from a GitHub repository"}, + {"name": "issue_read", "description": "Read a live GitHub issue by number"}, + {"name": "search_issues", "description": "Search live GitHub issues"}, + {"name": "issue_write", "description": "Create or edit an issue (must be blocked by TAR)"}, + {"name": "create_pull_request", "description": "Open a pull request (must be blocked by TAR)"}, + {"name": "push_files", "description": "Push files to a repository (must be blocked by TAR)"}, + {"name": "delete_repository", "description": "Delete a repository (must be blocked by TAR)"}, + }, + } + case "tools/call": + toolRes, callErr := executeReadOnlyTool(r.Context(), client, r.Header.Get("Authorization"), rpc.Params.Name, rpc.Params.Arguments) + if callErr != nil { + writeJSON(w, http.StatusOK, map[string]any{ + "jsonrpc": "2.0", + "id": rpc.ID, + "error": map[string]any{ + "code": -32000, + "message": callErr.Error(), + }, + }) + return + } + result = map[string]any{ + "tool": rpc.Params.Name, + "live_github_data": toolRes, + "backend_verified_headers": verifiedHeaders, + } + default: + http.Error(w, "unsupported json-rpc method", http.StatusBadRequest) + return + } + + writeJSON(w, http.StatusOK, map[string]any{ + "jsonrpc": "2.0", + "id": rpc.ID, + "result": result, + }) +} + +func executeReadOnlyTool(ctx context.Context, client *http.Client, authHeader, tool string, args map[string]any) (any, error) { + owner := stringArg(args, "owner", "google") + repo := stringArg(args, "repo", "agentmesh") + if !isSafeSlug(owner) || !isSafeSlug(repo) { + return nil, fmt.Errorf("invalid owner or repo") + } + + var target string + switch tool { + case "list_issues": + target = fmt.Sprintf("%s/repos/%s/%s/issues?per_page=3&state=all", githubAPIBase, owner, repo) + case "issue_read": + num := 1 + if raw, ok := args["issue_number"].(float64); ok && raw > 0 { + num = int(raw) + } + target = fmt.Sprintf("%s/repos/%s/%s/issues/%d", githubAPIBase, owner, repo, num) + case "search_issues": + q := stringArg(args, "query", fmt.Sprintf("repo:%s/%s", owner, repo)) + target = fmt.Sprintf("%s/search/issues?per_page=3&q=%s", githubAPIBase, url.QueryEscape(q)) + default: + return nil, fmt.Errorf("MUTATING_TOOL_REACHED_BACKEND: %s (ext_proc should have blocked this)", tool) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("User-Agent", "agentmesh-gcp-agw-demo") + if authHeader != "" { + req.Header.Set("Authorization", authHeader) + } + + resp, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("github api request failed: %w", err) + } + defer func() { _ = resp.Body.Close() }() + + rawBody, err := io.ReadAll(io.LimitReader(resp.Body, maxJSONRPCBytes)) + if err != nil { + return nil, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, fmt.Errorf("github api returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(rawBody))) + } + var parsed any + if err := json.Unmarshal(rawBody, &parsed); err != nil { + return nil, err + } + return summarizeGitHubResponse(tool, parsed), nil +} + +func summarizeGitHubResponse(tool string, parsed any) any { + switch tool { + case "list_issues": + items, ok := parsed.([]any) + if !ok { + return parsed + } + out := make([]map[string]any, 0, len(items)) + for _, item := range items { + if m, ok := item.(map[string]any); ok { + out = append(out, map[string]any{ + "number": m["number"], + "state": m["state"], + "title": m["title"], + "url": m["html_url"], + }) + } + } + return out + case "issue_read": + if m, ok := parsed.(map[string]any); ok { + return map[string]any{ + "number": m["number"], + "state": m["state"], + "title": m["title"], + "url": m["html_url"], + } + } + } + return parsed +} + +func stringArg(args map[string]any, key, fallback string) string { + if args == nil { + return fallback + } + if v, ok := args[key].(string); ok && strings.TrimSpace(v) != "" { + return strings.TrimSpace(v) + } + return fallback +} + +func isSafeSlug(s string) bool { + if s == "" || len(s) > 100 { + return false + } + for _, r := range s { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' { + continue + } + return false + } + return true +} + +func writeJSON(w http.ResponseWriter, status int, payload any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(payload) +} diff --git a/development/examples/gcp-agent-gateway/pep/Dockerfile b/development/examples/gcp-agent-gateway/pep/Dockerfile new file mode 100644 index 000000000..386deca2a --- /dev/null +++ b/development/examples/gcp-agent-gateway/pep/Dockerfile @@ -0,0 +1,45 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Build context must be the repository root: +# docker build -f development/examples/gcp-agent-gateway/pep/Dockerfile . + +FROM golang:1.27.4@sha256:205c7636d74e0ffbe3d007162df7d74f859f5a8c8322dfb9f907977686c126cf AS builder +WORKDIR /app +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +ARG TARGETOS=linux +ARG TARGETARCH=amd64 +RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -buildvcs=false -o /out/agentmesh-one ./cmd/agentmesh-one && \ + CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -buildvcs=false -o /out/agentmesh-node ./cmd/agentmesh-node + +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl jq && \ + rm -rf /var/lib/apt/lists/* && \ + useradd -u 65532 -r -s /usr/sbin/nologin nonroot && \ + mkdir -p /data /etc/agentmesh && \ + chown -R 65532:65532 /data /etc/agentmesh + +COPY --from=builder /out/agentmesh-one /usr/local/bin/agentmesh-one +COPY --from=builder /out/agentmesh-node /usr/local/bin/agentmesh-node +COPY development/examples/gcp-agent-gateway/pep/policy.json.tmpl /etc/agentmesh/policy.json.tmpl +COPY development/examples/gcp-agent-gateway/pep/node.yaml.tmpl /etc/agentmesh/node.yaml.tmpl +COPY development/examples/gcp-agent-gateway/pep/entrypoint.sh /usr/local/bin/entrypoint.sh +RUN chmod +x /usr/local/bin/entrypoint.sh + +USER nonroot +ENV PORT=8080 +EXPOSE 8080 +ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] diff --git a/development/examples/gcp-agent-gateway/pep/entrypoint.sh b/development/examples/gcp-agent-gateway/pep/entrypoint.sh new file mode 100755 index 000000000..58766376b --- /dev/null +++ b/development/examples/gcp-agent-gateway/pep/entrypoint.sh @@ -0,0 +1,142 @@ +#!/usr/bin/env bash +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Starts a self-contained Agent Mesh control plane + enrolled agentmesh-node +# Service Extension PEP inside one Cloud Run container. +# +# Exposes HTTP/2 (h2c) on 0.0.0.0:${PORT:-8080} for: +# - /envoy.service.ext_proc.v3.ExternalProcessor/Process (Google Cloud Agent Gateway CONTENT_AUTHZ) +# - /envoy.service.auth.v3.Authorization/Check (Envoy gRPC ext_authz) +# - /ext_authz (Envoy HTTP ext_authz) +# - /oauth/token (RFC 8693 OIDC -> sealed TAR Biscuit) +# - /healthz and /readyz + +set -euo pipefail + +PORT="${PORT:-8080}" +CP_PORT="18082" +DATA_DIR="${DATA_DIR:-/data}" +OIDC_ISSUER="${OIDC_ISSUER:-https://accounts.google.com}" +WORKLOAD_ISSUER="${WORKLOAD_ISSUER:-https://accounts.google.com}" +ALLOWED_AUDIENCE="${ALLOWED_AUDIENCE:-agentmesh-gcp-agw}" +ALLOWED_MEMBER="${ALLOWED_MEMBER:-mesh:system:authenticated}" +MCP_GITHUB_URL="${MCP_GITHUB_URL:-https://api.githubcopilot.com/mcp}" +MCP_GITHUB_AUTH_PATH="${MCP_GITHUB_AUTH_PATH:-}" +EXTRA_EGRESS_HOST="${EXTRA_EGRESS_HOST:-}" + +mkdir -p "${DATA_DIR}/one" "${DATA_DIR}/node" "${DATA_DIR}/run" + +# Deduplicate every configured OIDC / Workload / Agent Identity issuer so both +# PolicyConfig bindings and node.yaml attenuation checks accept tokens from +# standard Google OIDC as well as Vertex AI Agent Identity pools. +ISSUERS_JSON="$(jq -cn \ + --arg oidc "${OIDC_ISSUER}" \ + --arg workload "${WORKLOAD_ISSUER}" \ + '([$oidc, $workload] | map(split(",")) | flatten | map(split("=")[0] | gsub("^\\s+|\\s+$"; "")) | map(select(length > 0)) | unique)')" +ISSUER_CHECK="$(printf '%s' "${ISSUERS_JSON}" | jq -r 'map("claim(\"iss\", " + tojson + ")") | join(" or ")')" + +# Render PolicyConfig from template (fail-closed if any required var is empty). +jq -n \ + --arg member "${ALLOWED_MEMBER}" \ + --argjson issuers "${ISSUERS_JSON}" \ + --arg extra_host "${EXTRA_EGRESS_HOST}" \ + --slurpfile tmpl /etc/agentmesh/policy.json.tmpl \ + '$tmpl[0] + | .bindings = ( + (.bindings | map(select(.role != "agw-github-agent"))) + + ($issuers | map({"role": "agw-github-agent", "members": [$member], "claims": {"iss": .}})) + ) + | if $extra_host != "" then .egress += [{"name": $extra_host, "served_by": ["role=agent-gateway-pep"]}] else . end' \ + >"${DATA_DIR}/run/policy.json" + +# Render node.yaml from template. +{ + while IFS= read -r line || [ -n "${line}" ]; do + line="${line//__ISSUER_CHECK__/${ISSUER_CHECK}}" + line="${line//__MCP_GITHUB_URL__/${MCP_GITHUB_URL}}" + printf '%s\n' "${line}" + done "${DATA_DIR}/run/node.yaml" + +# Generate ephemeral loopback-only admin & sidecar tokens (never passed as CLI flags). +head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' >"${DATA_DIR}/run/admin.token" +head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' >"${DATA_DIR}/run/node.token" +chmod 600 "${DATA_DIR}/run/admin.token" "${DATA_DIR}/run/node.token" + +cleanup() { + if [ -n "${ONE_PID:-}" ]; then + kill "${ONE_PID}" 2>/dev/null || true + fi +} +trap cleanup EXIT INT TERM + +echo "[entrypoint] Starting agentmesh-one on 127.0.0.1:${CP_PORT} (issuer=${OIDC_ISSUER}, aud=${ALLOWED_AUDIENCE})" +agentmesh-one \ + --bind-address="127.0.0.1" \ + --port="${CP_PORT}" \ + --external-url="http://127.0.0.1:${CP_PORT}" \ + --data-dir="${DATA_DIR}/one" \ + --admin-token-path="${DATA_DIR}/run/admin.token" \ + --issuer="${OIDC_ISSUER}" \ + --workload-issuer="${WORKLOAD_ISSUER}" \ + --allowed-audiences="${ALLOWED_AUDIENCE}" \ + --control-plane-biscuit-ttl=15m \ + --no-join-token \ + --policy-file="${DATA_DIR}/run/policy.json" \ + --router-allow-loopback=true & +ONE_PID=$! + +for _ in $(seq 1 80); do + if ! kill -0 "${ONE_PID}" 2>/dev/null; then + echo "[entrypoint] ERROR: agentmesh-one exited unexpectedly" >&2 + exit 1 + fi + if curl --noproxy '*' -sf "http://127.0.0.1:${CP_PORT}/readyz" >/dev/null 2>&1; then + break + fi + sleep 0.25 +done +curl --noproxy '*' -sf "http://127.0.0.1:${CP_PORT}/readyz" >/dev/null + +# Enroll the PEP node on first start (or reuse persisted identity if mounted). +if [ ! -f "${DATA_DIR}/node/identity.bin" ]; then + ADMIN_TOKEN="$(cat "${DATA_DIR}/run/admin.token")" + BT_JSON="$(curl --noproxy '*' -sf -X POST "http://127.0.0.1:${CP_PORT}/admin/bootstrap-tokens" \ + -H "Authorization: Bearer ${ADMIN_TOKEN}" \ + -H "Content-Type: application/json" \ + -d '{"role":"mesh:role:node","ttl_hours":1,"max_usages":1,"description":"gcp-agent-gateway-pep"}')" + printf '%s' "${BT_JSON}" | jq -r '.token' >"${DATA_DIR}/run/node.bootstrap" + chmod 600 "${DATA_DIR}/run/node.bootstrap" + + echo "[entrypoint] Enrolling agentmesh-node PEP into local control plane" + agentmesh-node join "http://127.0.0.1:${CP_PORT}" \ + --bootstrap-token-path="${DATA_DIR}/run/node.bootstrap" \ + --config="${DATA_DIR}/run/node.yaml" \ + --data-dir="${DATA_DIR}/node" \ + --allow-loopback + rm -f "${DATA_DIR}/run/node.bootstrap" +fi + +echo "[entrypoint] Starting agentmesh-node Service Extension PEP on 0.0.0.0:${PORT}" +exec agentmesh-node run \ + --bind-addr="0.0.0.0:${PORT}" \ + --socket-path="${DATA_DIR}/node/agentmesh.sock" \ + --api-token-path="${DATA_DIR}/run/node.token" \ + --config="${DATA_DIR}/run/node.yaml" \ + --data-dir="${DATA_DIR}/node" \ + --allow-loopback diff --git a/development/examples/gcp-agent-gateway/pep/node.yaml.tmpl b/development/examples/gcp-agent-gateway/pep/node.yaml.tmpl new file mode 100644 index 000000000..a2509ca68 --- /dev/null +++ b/development/examples/gcp-agent-gateway/pep/node.yaml.tmpl @@ -0,0 +1,14 @@ +version: "v1alpha1" +labels: + role: agent-gateway-pep +attenuation: + checks: + - 'check if __ISSUER_CHECK__;' + # Refuse blanket standing credentials; require sealed short-lived TAR mandates. + require_task_scope: true + max_task_ttl: 15m +services: + - type: mcp + name: github + description: "GitHub MCP server governed by Google Cloud Agent Gateway ext_proc + TAR" + target_url: "__MCP_GITHUB_URL__" diff --git a/development/examples/gcp-agent-gateway/pep/policy.json.tmpl b/development/examples/gcp-agent-gateway/pep/policy.json.tmpl new file mode 100644 index 000000000..dedb38e5a --- /dev/null +++ b/development/examples/gcp-agent-gateway/pep/policy.json.tmpl @@ -0,0 +1,53 @@ +{ + "attested_claims": [ + "azp", + "email_verified", + "google.compute_engine.project_id" + ], + "roles": [ + { + "name": "mesh:role:router", + "allowed_services": ["*"], + "allowed_targets": ["*"] + }, + { + "name": "mesh:role:node", + "allowed_labels": ["role=*"], + "allowed_publish": ["mcp://github"], + "allowed_services": ["system://mesh.catalog"], + "allowed_targets": ["*"] + }, + { + "name": "agw-github-agent", + "allowed_services": [ + "egress://github.com", + "egress://api.github.com", + "mcp://github" + ], + "allowed_targets": ["*"] + } + ], + "bindings": [ + { + "role": "mesh:role:node", + "members": ["mesh:system:authenticated"] + }, + { + "role": "agw-github-agent", + "members": ["mesh:system:authenticated"], + "claims": { + "iss": "https://accounts.google.com" + } + } + ], + "egress": [ + { + "name": "github.com", + "served_by": ["role=agent-gateway-pep"] + }, + { + "name": "api.github.com", + "served_by": ["role=agent-gateway-pep"] + } + ] +} diff --git a/development/examples/gcp-agent-gateway/verify_edge_alb.sh b/development/examples/gcp-agent-gateway/verify_edge_alb.sh new file mode 100755 index 000000000..9b898d090 --- /dev/null +++ b/development/examples/gcp-agent-gateway/verify_edge_alb.sh @@ -0,0 +1,183 @@ +#!/usr/bin/env bash +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Live end-to-end verification against Topology B (Google Cloud External ALB + +# Service Extensions AuthzExtension EXT_PROC_GRPC -> agentmesh-node -> real GitHub). +# +# Usage: +# PROJECT_ID= REGION=us-central1 ./verify_edge_alb.sh + +set -euo pipefail + +: "${PROJECT_ID:?Set PROJECT_ID}" +REGION="${REGION:-us-central1}" +PEP_SERVICE="${PEP_SERVICE:-agentmesh-agw-pep}" + +ALB_IP="$(gcloud compute addresses describe agentmesh-edge-alb-ip \ + --region="${REGION}" --project="${PROJECT_ID}" --format='value(address)')" +PEP_URL="$(gcloud run services describe "${PEP_SERVICE}" \ + --region="${REGION}" --project="${PROJECT_ID}" --format='value(status.url)')" + +echo "==> Obtaining real Google OIDC ID token" +ID_TOKEN="$(gcloud auth print-identity-token)" + +EXP_RFC3339="$(python3 -c 'import datetime; print((datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(minutes=10)).strftime("%Y-%m-%dT%H:%M:%SZ"))')" +TAR_JSON="$(cat < Exchanging Google OIDC JWT at ${PEP_URL}/oauth/token for sealed 10m TAR Biscuit" +SEALED_RESP="$(curl -sf -X POST "${PEP_URL}/oauth/token" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \ + --data-urlencode "subject_token=${ID_TOKEN}" \ + --data-urlencode "subject_token_type=urn:ietf:params:oauth:token-type:id_token" \ + --data-urlencode "options=${TAR_JSON}" \ + --data-urlencode "seal=true")" +SEALED_BISCUIT="$(printf '%s' "${SEALED_RESP}" | jq -r '.access_token')" +test -n "${SEALED_BISCUIT}" && [ "${SEALED_BISCUIT}" != "null" ] + +STANDING_RESP="$(curl -sf -X POST "${PEP_URL}/oauth/token" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \ + --data-urlencode "subject_token=${ID_TOKEN}" \ + --data-urlencode "subject_token_type=urn:ietf:params:oauth:token-type:id_token")" +STANDING_BISCUIT="$(printf '%s' "${STANDING_RESP}" | jq -r '.access_token')" + +TMP_WORK="$(mktemp -d)" +trap 'rm -rf "${TMP_WORK}"' EXIT + +PASS=0 +FAIL=0 +check() { + local label="$1" ok="$2" detail="$3" + if [ "${ok}" = "1" ]; then + printf ' PASS %-48s %s\n' "${label}" "${detail}" + PASS=$((PASS + 1)) + else + printf ' FAIL %-48s %s\n' "${label}" "${detail}" + FAIL=$((FAIL + 1)) + fi +} + +echo "" +echo "==> Running live probes through real Google Cloud ALB (${ALB_IP}) + EXT_PROC_GRPC" + +# 1. Real git clone of github.com/google/agentmesh.git (ALLOW) +if GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_TERMINAL_PROMPT=0 \ + git -c "http.extraHeader=X-Mesh-Biscuit: ${SEALED_BISCUIT}" \ + -c "http.extraHeader=X-Mesh-Target-Service: egress://github.com" \ + clone --depth=1 "http://${ALB_IP}/google/agentmesh.git" "${TMP_WORK}/agentmesh" >/dev/null 2>&1 \ + && [ -f "${TMP_WORK}/agentmesh/go.mod" ]; then + HEAD_SHA="$(GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null git -C "${TMP_WORK}/agentmesh" log -1 --oneline)" + check "1. Real git clone google/agentmesh.git" 1 "cloned (${HEAD_SHA})" +else + check "1. Real git clone google/agentmesh.git" 0 "clone failed" +fi + +# 2. Real git push attempt (POST /git-receive-pack -> DENY 403 by ext_proc) +PUSH_STATUS="$(curl -s -o /dev/null -w '%{http_code}' -X POST \ + "http://${ALB_IP}/google/agentmesh.git/git-receive-pack" \ + -H "X-Mesh-Biscuit: ${SEALED_BISCUIT}" \ + -H "X-Mesh-Target-Service: egress://github.com" \ + -d '0000')" +check "2. git push (POST /git-receive-pack) denied" "$([ "${PUSH_STATUS}" = "403" ] && echo 1 || echo 0)" "HTTP ${PUSH_STATUS}" + +# 3. Real clone of unapproved repository (DENY 403 by ext_proc) +OTHER_STATUS="$(curl -s -o /dev/null -w '%{http_code}' \ + "http://${ALB_IP}/kubernetes/kubernetes.git/info/refs?service=git-upload-pack" \ + -H "X-Mesh-Biscuit: ${SEALED_BISCUIT}" \ + -H "X-Mesh-Target-Service: egress://github.com")" +check "3. Unapproved repo (kubernetes/kubernetes.git)" "$([ "${OTHER_STATUS}" = "403" ] && echo 1 || echo 0)" "HTTP ${OTHER_STATUS}" + +# 4. Real MCP list_issues (NO X-Mesh-Target-Service header; host-resolved mcp://github + spoofed header stripping!) +LIST_BODY="${TMP_WORK}/list.json" +LIST_STATUS="$(curl -s -o "${LIST_BODY}" -w '%{http_code}' -X POST "http://${ALB_IP}/mcp" \ + -H "Content-Type: application/json" \ + -H "X-Mesh-Biscuit: ${SEALED_BISCUIT}" \ + -H "X-Mesh-Claims: forged=true" \ + -H "X-Peer-Id: 12D3KooWSpoofed" \ + -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_issues","arguments":{"owner":"google","repo":"agentmesh"}}}')" +LIST_OK=0 +if [ "${LIST_STATUS}" = "200" ] \ + && jq -e '.result.live_github_data | length > 0' "${LIST_BODY}" >/dev/null 2>&1 \ + && jq -e '.result.backend_verified_headers["X-Mesh-Task-Id"] == "tasks/gcp-agw-github-readonly"' "${LIST_BODY}" >/dev/null 2>&1 \ + && ! grep -q "forged=true" "${LIST_BODY}"; then + LIST_OK=1 +fi +check "4. MCP list_issues (real GitHub + spoof strip)" "${LIST_OK}" "HTTP ${LIST_STATUS} principal=$(jq -r '.result.backend_verified_headers["X-Mesh-Principal"] // "none"' "${LIST_BODY}" 2>/dev/null || echo err)" + +# 5. Real MCP issue_read #953 (ALLOW) +READ_BODY="${TMP_WORK}/read.json" +READ_STATUS="$(curl -s -o "${READ_BODY}" -w '%{http_code}' -X POST "http://${ALB_IP}/mcp" \ + -H "Content-Type: application/json" \ + -H "X-Mesh-Biscuit: ${SEALED_BISCUIT}" \ + -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"issue_read","arguments":{"owner":"google","repo":"agentmesh","issue_number":953}}}')" +READ_OK=0 +if [ "${READ_STATUS}" = "200" ] && jq -e '.result.live_github_data.number == 953' "${READ_BODY}" >/dev/null 2>&1; then + READ_OK=1 +fi +check "5. MCP issue_read #953 (live GitHub API)" "${READ_OK}" "HTTP ${READ_STATUS}" + +# 6. All 4 mutating GitHub MCP tools (DENY 403 by ext_proc before backend) +MUT_OK=1 +MUT_SUMMARY="" +for tool in issue_write create_pull_request push_files delete_repository; do + ST="$(curl -s -o /dev/null -w '%{http_code}' -X POST "http://${ALB_IP}/mcp" \ + -H "Content-Type: application/json" \ + -H "X-Mesh-Biscuit: ${SEALED_BISCUIT}" \ + -d "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"${tool}\",\"arguments\":{\"owner\":\"google\",\"repo\":\"agentmesh\"}}}")" + MUT_SUMMARY="${MUT_SUMMARY}${tool}=${ST} " + if [ "${ST}" != "403" ]; then + MUT_OK=0 + fi +done +check "6. Mutating MCP tools (4/4 denied by ext_proc)" "${MUT_OK}" "${MUT_SUMMARY}" + +# 7. Standing unattenuated Biscuit denied (require_task_scope: true) +STAND_STATUS="$(curl -s -o /dev/null -w '%{http_code}' -X POST "http://${ALB_IP}/mcp" \ + -H "Content-Type: application/json" \ + -H "X-Mesh-Biscuit: ${STANDING_BISCUIT}" \ + -d '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"list_issues","arguments":{"owner":"google","repo":"agentmesh"}}}')" +check "7. Standing Biscuit (no TAR) denied" "$([ "${STAND_STATUS}" = "403" ] && echo 1 || echo 0)" "HTTP ${STAND_STATUS}" + +echo "" +echo "Summary: ${PASS} passed, ${FAIL} failed" +[ "${FAIL}" -eq 0 ] diff --git a/internal/envoy/envoy_test.go b/internal/envoy/envoy_test.go index 6b8fa32a9..a90bc3f02 100644 --- a/internal/envoy/envoy_test.go +++ b/internal/envoy/envoy_test.go @@ -267,7 +267,7 @@ func TestGatewayServer_TrustedTransport(t *testing.T) { } seenIn := func(headers []*corev3.HeaderValueOption) string { for _, h := range headers { - if h.GetHeader().GetKey() == seenHeader { + if h.GetHeader().GetKey() == strings.ToLower(seenHeader) { return h.GetHeader().GetValue() + string(h.GetHeader().GetRawValue()) } } @@ -483,6 +483,12 @@ func TestGatewayServer_ExtProcProcess(t *testing.T) { if r2.GetImmediateResponse() != nil { t.Fatalf("unexpected ImmediateResponse: %+v", r2.GetImmediateResponse()) } + for _, h := range r2.GetRequestBody().GetResponse().GetHeaderMutation().GetSetHeaders() { + k := h.GetHeader().GetKey() + if k != strings.ToLower(k) { + t.Errorf("ext_proc SetHeaders emitted non-lowercase HTTP/2 header key %q", k) + } + } extProcRemoved := r2.GetRequestBody().GetResponse().GetHeaderMutation().GetRemoveHeaders() for _, wantRemoved := range []string{"x-mesh-labels", "x-peer-id"} { found := false @@ -689,6 +695,715 @@ func TestGatewayServer_ExtAuthzWithoutBody(t *testing.T) { } } +func TestGatewayServer_ExtProcNeedsRequestBodyAndStreamingPost(t *testing.T) { + gw := NewGatewayServer(func(_ context.Context, in CheckInput) CheckResult { + if in.Host == "github-mcp.internal" { + if in.HeadersOnly && in.MCPTool == "" { + return CheckResult{ + Allowed: true, + HTTPStatus: http.StatusOK, + NeedsRequestBody: true, + } + } + if in.MCPTool != "list_issues" { + return CheckResult{ + Allowed: false, + HTTPStatus: http.StatusForbidden, + Message: "tool denied", + } + } + return CheckResult{ + Allowed: true, + HTTPStatus: http.StatusOK, + ResponseHeaders: map[string]string{ + api.HeaderMeshPrincipal: "capsule@example.com", + "Authorization": "Bearer mcp-secret", + }, + } + } + if in.Host == "github.com" && in.Path == "/google/agentmesh.git/git-upload-pack" { + return CheckResult{ + Allowed: true, + HTTPStatus: http.StatusOK, + ResponseHeaders: map[string]string{ + api.HeaderMeshPrincipal: "capsule@example.com", + }, + } + } + return CheckResult{ + Allowed: false, + HTTPStatus: http.StatusForbidden, + Message: "path denied", + } + }) + addr := startH2CGatewayTestServer(t, gw) + + conn, err := grpc.NewClient("passthrough:///"+addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc.NewClient: %v", err) + } + defer func() { _ = conn.Close() }() + procClient := extprocv3.NewExternalProcessorClient(conn) + + // 1. Host-resolved MCP mounted at "/" (no /mcp path, no X-Mesh-Target-Service) buffers via NeedsRequestBody. + stream, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process mcp allow: %v", err) + } + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/"}, + {Key: ":authority", Value: "github-mcp.internal"}, + }, + }, + }, + }, + }); err != nil { + t.Fatalf("Send RequestHeaders: %v", err) + } + r1, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestHeaders: %v", err) + } + if r1.GetModeOverride().GetRequestBodyMode() != extprocv3http.ProcessingMode_BUFFERED { + t.Fatalf("expected ModeOverride BUFFERED via NeedsRequestBody, got %+v", r1) + } + if r1.GetRequestHeaders().GetResponse().GetHeaderMutation() != nil { + t.Fatalf("Phase 1 pre-check must not mutate/inject credentials before body evaluation: %+v", r1) + } + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{ + Body: []byte(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_issues"}}`), + EndOfStream: true, + }, + }, + }); err != nil { + t.Fatalf("Send RequestBody: %v", err) + } + r2, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestBody: %v", err) + } + if r2.GetImmediateResponse() != nil { + t.Fatalf("expected CONTINUE for allowed tool, got %+v", r2) + } + _ = stream.CloseSend() + + // 2. Non-MCP POST (Git Smart HTTP git-upload-pack) decides on headers without buffering RequestBody. + streamGit, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process git POST: %v", err) + } + if err := streamGit.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/google/agentmesh.git/git-upload-pack"}, + {Key: ":authority", Value: "github.com"}, + }, + }, + }, + }, + }); err != nil { + t.Fatalf("Send git RequestHeaders: %v", err) + } + rGit, err := streamGit.Recv() + if err != nil { + t.Fatalf("Recv git RequestHeaders: %v", err) + } + if rGit.GetModeOverride() != nil { + t.Fatalf("non-MCP POST must not request body buffering, got ModeOverride=%+v", rGit.GetModeOverride()) + } + if rGit.GetRequestHeaders().GetResponse().GetHeaderMutation() == nil { + t.Fatalf("expected Phase 1 HeaderMutation for non-MCP POST, got %+v", rGit) + } + _ = streamGit.CloseSend() +} + +func TestGatewayServer_ExtProcPartialStreamedRejectedAndLimits(t *testing.T) { + gw := NewGatewayServer(func(_ context.Context, in CheckInput) CheckResult { + if in.HeadersOnly && in.MCPTool == "" { + return CheckResult{Allowed: true, HTTPStatus: http.StatusOK, NeedsRequestBody: true} + } + if in.MCPTool != "list_issues" { + return CheckResult{Allowed: false, HTTPStatus: http.StatusForbidden, Message: "tool denied"} + } + return CheckResult{ + Allowed: true, + HTTPStatus: http.StatusOK, + ResponseHeaders: map[string]string{ + api.HeaderMeshPrincipal: "capsule@example.com", + }, + } + }) + addr := startH2CGatewayTestServer(t, gw) + + conn, err := grpc.NewClient("passthrough:///"+addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc.NewClient: %v", err) + } + defer func() { _ = conn.Close() }() + procClient := extprocv3.NewExternalProcessorClient(conn) + + sendMCPHeaders := func(t *testing.T, stream extprocv3.ExternalProcessor_ProcessClient, fullDuplex bool) { + t.Helper() + req := &extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/mcp"}, + {Key: ":authority", Value: "github-mcp.internal"}, + }, + }, + }, + }, + } + if fullDuplex { + req.ProtocolConfig = &extprocv3.ProtocolConfiguration{ + RequestBodyMode: extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED, + ResponseBodyMode: extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED, + } + } + if err := stream.Send(req); err != nil { + t.Fatalf("Send RequestHeaders: %v", err) + } + r, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestHeaders: %v", err) + } + if r.GetImmediateResponse() != nil { + t.Fatalf("unexpected Phase 1 ImmediateResponse: %+v", r) + } + } + + // 1. Half-duplex STREAMED partial chunks (EndOfStream=false without + // FULL_DUPLEX_STREAMED) must fail closed on chunk 1 with 403 ImmediateResponse + // so zero bytes leave Envoy before the full body is authorized. + for _, tc := range []struct { + name string + firstChunk string + }{ + { + name: "excluded_tool_in_first_chunk", + firstChunk: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_repository"}}`, + }, + { + name: "allowed_tool_in_first_chunk_smuggling_guard", + firstChunk: `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"list_issues"}}`, + }, + { + name: "partial_json_fragment_in_first_chunk", + firstChunk: `{"jsonrpc":"2.0","id":3,"method":"tools/`, + }, + } { + t.Run("half_duplex_streamed_rejects_"+tc.name, func(t *testing.T) { + stream, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + sendMCPHeaders(t, stream, false) + + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: []byte(tc.firstChunk), EndOfStream: false}, + }, + }); err != nil { + t.Fatalf("Send chunk 1: %v", err) + } + r, err := stream.Recv() + if err != nil { + t.Fatalf("Recv chunk 1: %v", err) + } + if r.GetImmediateResponse().GetStatus().GetCode() != typev3.StatusCode_Forbidden { + t.Fatalf("expected 403 ImmediateResponse on first partial STREAMED chunk, got %+v", r) + } + }) + } + + // 2. Oversized BUFFERED body (> MaxHTTPBodyBytes) fails closed with 413 Payload Too Large. + t.Run("buffered_body_overflow_413", func(t *testing.T) { + stream, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + sendMCPHeaders(t, stream, false) + + oversized := bytes.Repeat([]byte("a"), MaxHTTPBodyBytes+1) + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: oversized, EndOfStream: true}, + }, + }); err != nil { + t.Fatalf("Send oversized body: %v", err) + } + r, err := stream.Recv() + if err != nil { + t.Fatalf("Recv oversized body: %v", err) + } + if r.GetImmediateResponse().GetStatus().GetCode() != typev3.StatusCode_PayloadTooLarge { + t.Fatalf("expected 413 PayloadTooLarge ImmediateResponse, got %+v", r) + } + }) + + // 3. FULL_DUPLEX_STREAMED safely buffers multi-chunk and trailers-terminated + // bodies silently (zero responses until EndOfStream / RequestTrailers), + // preventing any forbidden chunk from leaving Envoy. + for _, tc := range []struct { + name string + chunks []string + wantAllow bool + }{ + { + name: "full_duplex_chunks_allow", + chunks: []string{`{"jsonrpc":"2.0","id":1,"method":"tools/`, `call","params":{"name":"list_`, `issues"}}`}, + wantAllow: true, + }, + { + name: "full_duplex_excluded_tool_in_first_chunk_newline_in_second", + chunks: []string{`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"delete_repository"}}`, "\n"}, + wantAllow: false, + }, + } { + t.Run(tc.name, func(t *testing.T) { + stream, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + sendMCPHeaders(t, stream, true) + + for i, ch := range tc.chunks { + isLast := i == len(tc.chunks)-1 + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: []byte(ch), EndOfStream: isLast}, + }, + }); err != nil { + t.Fatalf("Send chunk %d: %v", i, err) + } + } + r, err := stream.Recv() + if err != nil { + t.Fatalf("Recv final decision: %v", err) + } + if tc.wantAllow { + sr := r.GetRequestBody().GetResponse().GetBodyMutation().GetStreamedResponse() + wantBody := strings.Join(tc.chunks, "") + if sr == nil || string(sr.GetBody()) != wantBody || !sr.GetEndOfStream() { + t.Fatalf("expected StreamedBodyResponse %q (eos=true), got %+v", wantBody, r) + } + } else if r.GetImmediateResponse().GetStatus().GetCode() != typev3.StatusCode_Forbidden { + t.Fatalf("expected 403 ImmediateResponse without echoing body, got %+v", r) + } + }) + } + + // 4. Trailers-terminated FULL_DUPLEX_STREAMED body (last body chunk has + // EndOfStream=false, followed by RequestTrailers). + for _, tc := range []struct { + name string + body string + wantAllow bool + }{ + {name: "full_duplex_trailers_allow", body: `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_issues"}}`, wantAllow: true}, + {name: "full_duplex_trailers_deny", body: `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"issue_write"}}`, wantAllow: false}, + } { + t.Run(tc.name, func(t *testing.T) { + stream, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + sendMCPHeaders(t, stream, true) + + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: []byte(tc.body), EndOfStream: false}, + }, + }); err != nil { + t.Fatalf("Send body: %v", err) + } + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestTrailers{ + RequestTrailers: &extprocv3.HttpTrailers{}, + }, + }); err != nil { + t.Fatalf("Send RequestTrailers: %v", err) + } + r1, err := stream.Recv() + if err != nil { + t.Fatalf("Recv after RequestTrailers: %v", err) + } + if !tc.wantAllow { + if r1.GetImmediateResponse().GetStatus().GetCode() != typev3.StatusCode_Forbidden { + t.Fatalf("expected 403 ImmediateResponse at trailers, got %+v", r1) + } + return + } + sr := r1.GetRequestBody().GetResponse().GetBodyMutation().GetStreamedResponse() + if sr == nil || string(sr.GetBody()) != tc.body || sr.GetEndOfStream() { + t.Fatalf("expected StreamedBodyResponse %q (eos=false), got %+v", tc.body, r1) + } + rTr, err := stream.Recv() + if err != nil { + t.Fatalf("Recv TrailersResponse: %v", err) + } + if rTr.GetRequestTrailers() == nil { + t.Fatalf("expected RequestTrailers response, got %+v", rTr) + } + }) + } + + // 5. Oversized multi-chunk FULL_DUPLEX_STREAMED body (> MaxHTTPBodyBytes) fails closed with 413. + t.Run("full_duplex_body_overflow_413", func(t *testing.T) { + stream, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + sendMCPHeaders(t, stream, true) + + half := bytes.Repeat([]byte("a"), (MaxHTTPBodyBytes/2)+1) + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: half, EndOfStream: false}, + }, + }); err != nil { + t.Fatalf("Send chunk 1: %v", err) + } + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: half, EndOfStream: false}, + }, + }); err != nil { + t.Fatalf("Send chunk 2: %v", err) + } + r, err := stream.Recv() + if err != nil { + t.Fatalf("Recv overflow response: %v", err) + } + if r.GetImmediateResponse().GetStatus().GetCode() != typev3.StatusCode_PayloadTooLarge { + t.Fatalf("expected 413 PayloadTooLarge ImmediateResponse, got %+v", r) + } + }) +} + +func TestGatewayServer_ExtProcFullDuplexStreamed(t *testing.T) { + gw := NewGatewayServer(func(_ context.Context, in CheckInput) CheckResult { + if in.Host == "mcp.example.com" { + if in.HeadersOnly && in.MCPTool == "" { + return CheckResult{ + Allowed: true, + HTTPStatus: http.StatusOK, + NeedsRequestBody: true, + ResponseHeaders: map[string]string{ + api.HeaderMeshPrincipal: "spiffe://agent", + api.HeaderMeshTaskID: "tasks/ro", + }, + } + } + if in.MCPTool != "list_issues" { + return CheckResult{Allowed: false, HTTPStatus: http.StatusForbidden, Message: "tool denied"} + } + return CheckResult{ + Allowed: true, + HTTPStatus: http.StatusOK, + ResponseHeaders: map[string]string{ + api.HeaderMeshPrincipal: "spiffe://agent", + api.HeaderMeshTaskID: "tasks/ro", + "Authorization": "Bearer mcp-secret", + }, + } + } + if in.Host == "github.com" && in.Path == "/google/agentmesh.git/git-upload-pack" { + return CheckResult{ + Allowed: true, + HTTPStatus: http.StatusOK, + ResponseHeaders: map[string]string{ + api.HeaderMeshPrincipal: "spiffe://agent", + }, + } + } + return CheckResult{Allowed: false, HTTPStatus: http.StatusForbidden, Message: "denied"} + }) + addr := startH2CGatewayTestServer(t, gw) + + conn, err := grpc.NewClient("passthrough:///"+addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc.NewClient: %v", err) + } + defer func() { _ = conn.Close() }() + procClient := extprocv3.NewExternalProcessorClient(conn) + + // 1. FULL_DUPLEX_STREAMED (SendBodyWithoutWaitingForHeaderResponse=false): + // matches Google Cloud Agent Gateway CONTENT_AUTHZ. + // Allowed MCP call stamps provenance headers on RequestHeaders (no secret), + // echoes full request body via StreamedResponse on RequestBody, and echoes + // ResponseBody chunks via StreamedResponse. + t.Run("full_duplex_mcp_allow_and_echo_req_resp_bodies", func(t *testing.T) { + stream, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + + if err := stream.Send(&extprocv3.ProcessingRequest{ + ProtocolConfig: &extprocv3.ProtocolConfiguration{ + RequestBodyMode: extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED, + ResponseBodyMode: extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED, + SendBodyWithoutWaitingForHeaderResponse: false, + }, + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/mcp"}, + {Key: ":authority", Value: "mcp.example.com"}, + {Key: "x-mesh-claims", Value: "forged=true"}, + {Key: "x-peer-id", Value: "spoofed"}, + }, + }, + }, + }, + }); err != nil { + t.Fatalf("Send RequestHeaders: %v", err) + } + rHdr, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestHeaders: %v", err) + } + if rHdr.GetModeOverride() != nil { + t.Fatalf("FULL_DUPLEX_STREAMED must not emit conflicting ModeOverride: %+v", rHdr.GetModeOverride()) + } + mut := rHdr.GetRequestHeaders().GetResponse().GetHeaderMutation() + if mut == nil { + t.Fatalf("expected HeaderMutation on FULL_DUPLEX_STREAMED RequestHeaders, got nil") + } + sawTaskID := false + for _, h := range mut.GetSetHeaders() { + k := h.GetHeader().GetKey() + if k != strings.ToLower(k) { + t.Errorf("non-lowercase header key %q", k) + } + if k == "authorization" { + t.Errorf("Phase 1 FULL_DUPLEX_STREAMED must not inject backend Authorization secret") + } + if k == "x-mesh-task-id" && string(h.GetHeader().GetRawValue()) == "tasks/ro" { + sawTaskID = true + } + } + if !sawTaskID { + t.Errorf("missing x-mesh-task-id provenance header in %+v", mut.GetSetHeaders()) + } + + // Send body split across 2 chunks; server must buffer silently until EndOfStream=true. + chunk1 := `{"jsonrpc":"2.0","id":1,"method":"tools/call",` + chunk2 := `"params":{"name":"list_issues"}}` + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: []byte(chunk1), EndOfStream: false}, + }, + }); err != nil { + t.Fatalf("Send chunk1: %v", err) + } + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: []byte(chunk2), EndOfStream: true}, + }, + }); err != nil { + t.Fatalf("Send chunk2: %v", err) + } + rBody, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestBody: %v", err) + } + sr := rBody.GetRequestBody().GetResponse().GetBodyMutation().GetStreamedResponse() + if sr == nil || string(sr.GetBody()) != chunk1+chunk2 || !sr.GetEndOfStream() { + t.Fatalf("expected StreamedResponse echoing full body with EndOfStream=true, got %+v", rBody) + } + + // Upstream ResponseBody must also echo via StreamedResponse in FULL_DUPLEX_STREAMED mode. + respPayload := `{"jsonrpc":"2.0","id":1,"result":{"ok":true}}` + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_ResponseBody{ + ResponseBody: &extprocv3.HttpBody{Body: []byte(respPayload), EndOfStream: true}, + }, + }); err != nil { + t.Fatalf("Send ResponseBody: %v", err) + } + rRespBody, err := stream.Recv() + if err != nil { + t.Fatalf("Recv ResponseBody: %v", err) + } + respSR := rRespBody.GetResponseBody().GetResponse().GetBodyMutation().GetStreamedResponse() + if respSR == nil || string(respSR.GetBody()) != respPayload || !respSR.GetEndOfStream() { + t.Fatalf("expected ResponseBody StreamedResponse echoing payload, got %+v", rRespBody) + } + }) + + // 2. FULL_DUPLEX_STREAMED MCP deny returns 403 ImmediateResponse without echoing body. + t.Run("full_duplex_mcp_deny_blocks_body", func(t *testing.T) { + stream, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + _ = stream.Send(&extprocv3.ProcessingRequest{ + ProtocolConfig: &extprocv3.ProtocolConfiguration{ + RequestBodyMode: extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED, + ResponseBodyMode: extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED, + }, + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/mcp"}, + {Key: ":authority", Value: "mcp.example.com"}, + }, + }, + }, + }, + }) + if _, err := stream.Recv(); err != nil { + t.Fatalf("Recv RequestHeaders: %v", err) + } + _ = stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{ + Body: []byte(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"delete_repository"}}`), + EndOfStream: true, + }, + }, + }) + rDeny, err := stream.Recv() + if err != nil { + t.Fatalf("Recv deny: %v", err) + } + if rDeny.GetImmediateResponse().GetStatus().GetCode() != typev3.StatusCode_Forbidden { + t.Fatalf("expected 403 ImmediateResponse, got %+v", rDeny) + } + }) + + // 3. FULL_DUPLEX_STREAMED with SendBodyWithoutWaitingForHeaderResponse=true defers + // HeadersResponse until Phase 2, then sends HeadersResponse (including Authorization) + // followed by BodyResponse StreamedResponse. + t.Run("full_duplex_send_body_nowait_defers_headers_with_secret", func(t *testing.T) { + stream, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + _ = stream.Send(&extprocv3.ProcessingRequest{ + ProtocolConfig: &extprocv3.ProtocolConfiguration{ + RequestBodyMode: extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED, + ResponseBodyMode: extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED, + SendBodyWithoutWaitingForHeaderResponse: true, + }, + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/mcp"}, + {Key: ":authority", Value: "mcp.example.com"}, + }, + }, + }, + }, + }) + body := `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_issues"}}` + _ = stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: []byte(body), EndOfStream: true}, + }, + }) + rHdr, err := stream.Recv() + if err != nil { + t.Fatalf("Recv deferred RequestHeaders: %v", err) + } + sawAuth := false + for _, h := range rHdr.GetRequestHeaders().GetResponse().GetHeaderMutation().GetSetHeaders() { + if h.GetHeader().GetKey() == "authorization" && string(h.GetHeader().GetRawValue()) == "Bearer mcp-secret" { + sawAuth = true + } + } + if !sawAuth { + t.Fatalf("expected deferred HeadersResponse with injected authorization, got %+v", rHdr) + } + rBody, err := stream.Recv() + if err != nil { + t.Fatalf("Recv deferred RequestBody: %v", err) + } + sr := rBody.GetRequestBody().GetResponse().GetBodyMutation().GetStreamedResponse() + if sr == nil || string(sr.GetBody()) != body || !sr.GetEndOfStream() { + t.Fatalf("expected StreamedResponse echoing body, got %+v", rBody) + } + }) + + // 4. Non-MCP POST (Git Smart HTTP git-upload-pack) in FULL_DUPLEX_STREAMED mode + // streams body chunks straight through via StreamedResponse without buffering. + t.Run("full_duplex_non_mcp_post_streams_verbatim", func(t *testing.T) { + stream, err := procClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + _ = stream.Send(&extprocv3.ProcessingRequest{ + ProtocolConfig: &extprocv3.ProtocolConfiguration{ + RequestBodyMode: extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED, + ResponseBodyMode: extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED, + }, + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/google/agentmesh.git/git-upload-pack"}, + {Key: ":authority", Value: "github.com"}, + }, + }, + }, + }, + }) + if rHdr, err := stream.Recv(); err != nil || rHdr.GetImmediateResponse() != nil { + t.Fatalf("Recv git headers: err=%v resp=%+v", err, rHdr) + } + _ = stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: []byte("0032want abc\n0000"), EndOfStream: true}, + }, + }) + rBody, err := stream.Recv() + if err != nil { + t.Fatalf("Recv git body: %v", err) + } + sr := rBody.GetRequestBody().GetResponse().GetBodyMutation().GetStreamedResponse() + if sr == nil || string(sr.GetBody()) != "0032want abc\n0000" || !sr.GetEndOfStream() { + t.Fatalf("expected git packfile chunk echoed verbatim, got %+v", rBody) + } + }) +} + type referenceCalloutServer struct { extprocv3.UnimplementedExternalProcessorServer diff --git a/internal/envoy/server.go b/internal/envoy/server.go index 5a85bb79d..cd469d1d9 100644 --- a/internal/envoy/server.go +++ b/internal/envoy/server.go @@ -20,6 +20,7 @@ package envoy import ( "context" "errors" + "fmt" "io" "net/http" "sort" @@ -68,6 +69,12 @@ type CheckInput struct { // authenticates the caller as the gateway. The Evaluator returns an // upstream credential only when it is set. TrustedTransport bool + // HeadersOnly is true during the ext_proc RequestHeaders pre-check when + // the request has a body that has not yet been buffered. + HeadersOnly bool + // ExtProcMode records the Envoy ext_proc ProtocolConfig summary (for + // audit logging) when invoked via ExternalProcessor.Process. + ExtProcMode string } // CheckResult represents the policy decision and header mutations returned by @@ -77,6 +84,11 @@ type CheckResult struct { HTTPStatus int Message string ResponseHeaders map[string]string + // NeedsRequestBody signals to ext_proc RequestHeaders that the resolved + // target requires buffering RequestBody (for example, an MCP service + // resolved by Host/Authority rather than by a /mcp path prefix) before + // finalizing the decision and mutating upstream headers. + NeedsRequestBody bool } // Evaluator evaluates a normalized CheckInput against Agent Mesh's Datalog and TAR policy. @@ -242,12 +254,17 @@ func (s *GatewayServer) Check(ctx context.Context, req *authv3.CheckRequest) (*a TrustedTransport: trustedTransportFromContext(ctx), }) if res.Allowed { + keys := make([]string, 0, len(res.ResponseHeaders)) + for k := range res.ResponseHeaders { + keys = append(keys, k) + } + sort.Strings(keys) var hdrs []*corev3.HeaderValueOption - for k, v := range res.ResponseHeaders { + for _, k := range keys { hdrs = append(hdrs, &corev3.HeaderValueOption{ Header: &corev3.HeaderValue{ - Key: k, - Value: v, + Key: strings.ToLower(k), + Value: res.ResponseHeaders[k], }, AppendAction: corev3.HeaderValueOption_OVERWRITE_IF_EXISTS_OR_ADD, }) @@ -286,11 +303,60 @@ func (s *GatewayServer) Check(ctx context.Context, req *authv3.CheckRequest) (*a }, nil } +func isFullDuplexBodyMode(mode extprocv3http.ProcessingMode_BodySendMode) bool { + return mode == extprocv3http.ProcessingMode_FULL_DUPLEX_STREAMED +} + +func formatExtProcMode(req *extprocv3.ProcessingRequest) string { + pc := req.GetProtocolConfig() + if pc == nil && req.GetFlowControlInit() == nil { + return "" + } + if pc == nil { + return "flow_control_init=true" + } + return fmt.Sprintf("req=%s,resp=%s,send_body_nowait=%t,flow_control=%t", + pc.GetRequestBodyMode().String(), + pc.GetResponseBodyMode().String(), + pc.GetSendBodyWithoutWaitingForHeaderResponse(), + req.GetFlowControlInit() != nil, + ) +} + +func buildFullDuplexBodyResponse(isResponse bool, body []byte, endOfStream bool) *extprocv3.ProcessingResponse { + bodyResp := &extprocv3.BodyResponse{ + Response: &extprocv3.CommonResponse{ + BodyMutation: &extprocv3.BodyMutation{ + Mutation: &extprocv3.BodyMutation_StreamedResponse{ + StreamedResponse: &extprocv3.StreamedBodyResponse{ + Body: body, + EndOfStream: endOfStream, + }, + }, + }, + }, + } + if isResponse { + return &extprocv3.ProcessingResponse{ + Response: &extprocv3.ProcessingResponse_ResponseBody{ + ResponseBody: bodyResp, + }, + } + } + return &extprocv3.ProcessingResponse{ + Response: &extprocv3.ProcessingResponse_RequestBody{ + RequestBody: bodyResp, + }, + } +} + // Process implements envoy.service.ext_proc.v3.ExternalProcessorServer. func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer) error { var capturedHeaders map[string]string - var capturedMethod, capturedPath, capturedHost string - var pendingCheck bool + var capturedMethod, capturedPath, capturedHost, extProcMode string + var pendingCheck, deferHeaderResponse bool + var isFullDuplexReq, isFullDuplexResp, sendBodyNoWait bool + var bodyBuf []byte for { req, err := stream.Recv() @@ -301,9 +367,24 @@ func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer return err } - var resp *extprocv3.ProcessingResponse + if pc := req.GetProtocolConfig(); pc != nil { + isFullDuplexReq = isFullDuplexBodyMode(pc.GetRequestBodyMode()) + isFullDuplexResp = isFullDuplexBodyMode(pc.GetResponseBodyMode()) + sendBodyNoWait = pc.GetSendBodyWithoutWaitingForHeaderResponse() + } + if req.GetFlowControlInit() != nil && !isFullDuplexReq { + isFullDuplexReq = true + } + if modeStr := formatExtProcMode(req); modeStr != "" { + extProcMode = modeStr + } + + var responses []*extprocv3.ProcessingResponse switch phase := req.GetRequest().(type) { case *extprocv3.ProcessingRequest_RequestHeaders: + pendingCheck = false + deferHeaderResponse = false + bodyBuf = nil capturedHeaders = make(map[string]string) for _, hv := range phase.RequestHeaders.GetHeaders().GetHeaders() { k := strings.ToLower(hv.GetKey()) @@ -322,40 +403,131 @@ func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer // The tool of an MCP tools/call is in the body, so ext_proc asks // Envoy for the body of a POST to an MCP service and decides when - // it arrives. Every other request is decided now, with no tool and - // no handshake allowance: a task rule with allowed_tools denies it. - if !phase.RequestHeaders.GetEndOfStream() && - strings.EqualFold(capturedMethod, http.MethodPost) && - isMCPRoute(capturedPath, capturedHeaders[strings.ToLower(api.HeaderMeshTargetService)]) { - preResp := s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, "", false, true) - if preResp.GetImmediateResponse() != nil { - resp = preResp - } else { + // it arrives. A POST with a body is also pre-checked with + // HeadersOnly=true so a host-resolved MCP service (without a /mcp + // path prefix) can request body buffering via NeedsRequestBody. + mcpRoute := isMCPRoute(capturedPath, capturedHeaders[strings.ToLower(api.HeaderMeshTargetService)]) + canBufferBody := !phase.RequestHeaders.GetEndOfStream() && + strings.EqualFold(capturedMethod, http.MethodPost) + if canBufferBody { + preRes := s.eval(stream.Context(), CheckInput{ + Method: capturedMethod, + Path: capturedPath, + Host: capturedHost, + Headers: capturedHeaders, + AllowMCPStreamInit: true, + HeadersOnly: true, + TrustedTransport: trustedTransportFromContext(stream.Context()), + ExtProcMode: extProcMode, + }) + if !preRes.Allowed { + responses = append(responses, buildExtProcResponse(preRes, capturedHeaders, false)) + } else if mcpRoute || preRes.NeedsRequestBody { pendingCheck = true - resp = &extprocv3.ProcessingResponse{ - Response: &extprocv3.ProcessingResponse_RequestHeaders{ - RequestHeaders: &extprocv3.HeadersResponse{ - Response: &extprocv3.CommonResponse{ - Status: extprocv3.CommonResponse_CONTINUE, + if isFullDuplexReq { + if sendBodyNoWait { + // Envoy streams RequestBody without waiting for HeadersResponse; + // defer header mutation until Phase 2 authorizes the MCP tool. + deferHeaderResponse = true + } else { + // FULL_DUPLEX_STREAMED waits for HeadersResponse before streaming + // RequestBody and applies HeaderMutation only on HeadersResponse. + // Stamp verified provenance headers now (never backend secrets); + // Phase 2 still blocks disallowed tools with ImmediateResponse + // before any RequestBody bytes are forwarded upstream. + responses = append(responses, buildExtProcResponse(preRes, capturedHeaders, false)) + } + } else { + responses = append(responses, &extprocv3.ProcessingResponse{ + Response: &extprocv3.ProcessingResponse_RequestHeaders{ + RequestHeaders: &extprocv3.HeadersResponse{ + Response: &extprocv3.CommonResponse{ + Status: extprocv3.CommonResponse_CONTINUE, + }, }, }, - }, - ModeOverride: &extprocv3http.ProcessingMode{ - RequestBodyMode: extprocv3http.ProcessingMode_BUFFERED, - }, + ModeOverride: &extprocv3http.ProcessingMode{ + RequestBodyMode: extprocv3http.ProcessingMode_BUFFERED, + }, + }) } + } else { + responses = append(responses, buildExtProcResponse(preRes, capturedHeaders, false)) } } else { - resp = s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, "", false, false) + responses = append(responses, s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, "", false, false, extProcMode)) } case *extprocv3.ProcessingRequest_RequestBody: if pendingCheck { + chunk := phase.RequestBody.GetBody() + if len(bodyBuf)+len(chunk) > MaxHTTPBodyBytes { + pendingCheck = false + deferHeaderResponse = false + bodyBuf = nil + responses = append(responses, &extprocv3.ProcessingResponse{ + Response: &extprocv3.ProcessingResponse_ImmediateResponse{ + ImmediateResponse: &extprocv3.ImmediateResponse{ + Status: &typev3.HttpStatus{Code: typev3.StatusCode_PayloadTooLarge}, + Body: []byte("request body exceeds inspection limit"), + Details: "mesh_ext_proc_denied", + }, + }, + }) + break + } + if !phase.RequestBody.GetEndOfStream() { + if !isFullDuplexReq { + // In half-duplex STREAMED mode, answering CONTINUE on a non-final + // chunk releases those bytes upstream before the full JSON-RPC + // body is inspected (and Envoy ignores HeaderMutation on + // BodyResponse outside BUFFERED mode). Fail closed on chunk 1 so + // zero unverified body bytes leave Envoy; MCP body authorization + // requires BUFFERED (or allow_mode_override) or FULL_DUPLEX_STREAMED. + pendingCheck = false + deferHeaderResponse = false + bodyBuf = nil + responses = append(responses, &extprocv3.ProcessingResponse{ + Response: &extprocv3.ProcessingResponse_ImmediateResponse{ + ImmediateResponse: &extprocv3.ImmediateResponse{ + Status: &typev3.HttpStatus{Code: typev3.StatusCode_Forbidden}, + Body: []byte("MCP body authorization requires BUFFERED or FULL_DUPLEX_STREAMED request body mode; partial STREAMED chunk rejected"), + Details: "mesh_ext_proc_denied", + }, + }, + }) + break + } + // FULL_DUPLEX_STREAMED buffers silently until EndOfStream (or + // RequestTrailers) so zero bytes of a forbidden tool call leave Envoy. + bodyBuf = append(bodyBuf, chunk...) + break + } + bodyBuf = append(bodyBuf, chunk...) pendingCheck = false - mcpTool, allowStreamInit := InspectJSONRPCMCPBody(phase.RequestBody.GetBody()) - resp = s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, mcpTool, true, allowStreamInit) + fullBody := bodyBuf + bodyBuf = nil + if isFullDuplexReq { + res := s.evaluateExtProcBodyResult(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, fullBody, extProcMode) + if !res.Allowed { + deferHeaderResponse = false + responses = append(responses, buildExtProcResponse(res, capturedHeaders, false)) + } else { + if deferHeaderResponse { + deferHeaderResponse = false + responses = append(responses, buildExtProcResponse(res, capturedHeaders, false)) + } + responses = append(responses, buildFullDuplexBodyResponse(false, fullBody, true)) + } + } else { + responses = append(responses, s.finalizeExtProcBodyCheck(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, fullBody, true, extProcMode)) + } + } else if isFullDuplexReq { + // Echo non-inspected request body chunks verbatim in FULL_DUPLEX_STREAMED + // mode so Envoy does not strip the request body. + responses = append(responses, buildFullDuplexBodyResponse(false, phase.RequestBody.GetBody(), phase.RequestBody.GetEndOfStream())) } else { - resp = &extprocv3.ProcessingResponse{ + responses = append(responses, &extprocv3.ProcessingResponse{ Response: &extprocv3.ProcessingResponse_RequestBody{ RequestBody: &extprocv3.BodyResponse{ Response: &extprocv3.CommonResponse{ @@ -363,18 +535,21 @@ func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer }, }, }, - } + }) } case *extprocv3.ProcessingRequest_ResponseHeaders: if pendingCheck { pendingCheck = false - if denyResp := s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, "", false, false); denyResp.GetImmediateResponse() != nil { - resp = denyResp + deferHeaderResponse = false + fullBody := bodyBuf + bodyBuf = nil + if denyResp := s.finalizeExtProcBodyCheck(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, fullBody, false, extProcMode); denyResp.GetImmediateResponse() != nil { + responses = append(responses, denyResp) break } } - resp = &extprocv3.ProcessingResponse{ + responses = append(responses, &extprocv3.ProcessingResponse{ Response: &extprocv3.ProcessingResponse_ResponseHeaders{ ResponseHeaders: &extprocv3.HeadersResponse{ Response: &extprocv3.CommonResponse{ @@ -382,42 +557,63 @@ func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer }, }, }, - } + }) case *extprocv3.ProcessingRequest_ResponseBody: - resp = &extprocv3.ProcessingResponse{ - Response: &extprocv3.ProcessingResponse_ResponseBody{ - ResponseBody: &extprocv3.BodyResponse{ - Response: &extprocv3.CommonResponse{ - Status: extprocv3.CommonResponse_CONTINUE, + if isFullDuplexResp { + responses = append(responses, buildFullDuplexBodyResponse(true, phase.ResponseBody.GetBody(), phase.ResponseBody.GetEndOfStream())) + } else { + responses = append(responses, &extprocv3.ProcessingResponse{ + Response: &extprocv3.ProcessingResponse_ResponseBody{ + ResponseBody: &extprocv3.BodyResponse{ + Response: &extprocv3.CommonResponse{ + Status: extprocv3.CommonResponse_CONTINUE, + }, }, }, - }, + }) } case *extprocv3.ProcessingRequest_RequestTrailers: if pendingCheck { pendingCheck = false - if denyResp := s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, "", false, false); denyResp.GetImmediateResponse() != nil { - resp = denyResp + fullBody := bodyBuf + bodyBuf = nil + if isFullDuplexReq { + res := s.evaluateExtProcBodyResult(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, fullBody, extProcMode) + if !res.Allowed { + deferHeaderResponse = false + responses = append(responses, buildExtProcResponse(res, capturedHeaders, false)) + break + } + if deferHeaderResponse { + deferHeaderResponse = false + responses = append(responses, buildExtProcResponse(res, capturedHeaders, false)) + } + responses = append(responses, buildFullDuplexBodyResponse(false, fullBody, false)) + } else if denyResp := s.finalizeExtProcBodyCheck(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, fullBody, false, extProcMode); denyResp.GetImmediateResponse() != nil { + responses = append(responses, denyResp) break } } - resp = &extprocv3.ProcessingResponse{ + responses = append(responses, &extprocv3.ProcessingResponse{ Response: &extprocv3.ProcessingResponse_RequestTrailers{ RequestTrailers: &extprocv3.TrailersResponse{}, }, - } + }) case *extprocv3.ProcessingRequest_ResponseTrailers: - resp = &extprocv3.ProcessingResponse{ + responses = append(responses, &extprocv3.ProcessingResponse{ Response: &extprocv3.ProcessingResponse_ResponseTrailers{ ResponseTrailers: &extprocv3.TrailersResponse{}, }, - } + }) } - if resp != nil { + for _, resp := range responses { + if resp == nil { + continue + } if err := stream.Send(resp); err != nil { return err } @@ -428,7 +624,31 @@ func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer } } -func (s *GatewayServer) evaluateExtProcDecision(ctx context.Context, method, path, host string, headers map[string]string, mcpTool string, isBodyPhase, allowMCPStreamInit bool) *extprocv3.ProcessingResponse { +func (s *GatewayServer) evaluateExtProcBodyResult(ctx context.Context, method, path, host string, headers map[string]string, body []byte, extProcMode string) CheckResult { + var mcpTool string + var allowStreamInit bool + if len(body) > 0 { + mcpTool, allowStreamInit = InspectJSONRPCMCPBody(body) + } + return s.eval(ctx, CheckInput{ + Method: method, + Path: path, + Host: host, + Headers: headers, + Body: body, + MCPTool: mcpTool, + AllowMCPStreamInit: allowStreamInit, + TrustedTransport: trustedTransportFromContext(ctx), + ExtProcMode: extProcMode, + }) +} + +func (s *GatewayServer) finalizeExtProcBodyCheck(ctx context.Context, method, path, host string, headers map[string]string, body []byte, isBodyPhase bool, extProcMode string) *extprocv3.ProcessingResponse { + res := s.evaluateExtProcBodyResult(ctx, method, path, host, headers, body, extProcMode) + return buildExtProcResponse(res, headers, isBodyPhase) +} + +func (s *GatewayServer) evaluateExtProcDecision(ctx context.Context, method, path, host string, headers map[string]string, mcpTool string, isBodyPhase, allowMCPStreamInit bool, extProcMode string) *extprocv3.ProcessingResponse { res := s.eval(ctx, CheckInput{ Method: method, Path: path, @@ -437,7 +657,12 @@ func (s *GatewayServer) evaluateExtProcDecision(ctx context.Context, method, pat MCPTool: mcpTool, AllowMCPStreamInit: allowMCPStreamInit, TrustedTransport: trustedTransportFromContext(ctx), + ExtProcMode: extProcMode, }) + return buildExtProcResponse(res, headers, isBodyPhase) +} + +func buildExtProcResponse(res CheckResult, headers map[string]string, isBodyPhase bool) *extprocv3.ProcessingResponse { if !res.Allowed { status := typev3.StatusCode_Forbidden if res.HTTPStatus == http.StatusUnauthorized { @@ -454,12 +679,18 @@ func (s *GatewayServer) evaluateExtProcDecision(ctx context.Context, method, pat } } + keys := make([]string, 0, len(res.ResponseHeaders)) + for k := range res.ResponseHeaders { + keys = append(keys, k) + } + sort.Strings(keys) var setHeaders []*corev3.HeaderValueOption - for k, v := range res.ResponseHeaders { + for _, k := range keys { setHeaders = append(setHeaders, &corev3.HeaderValueOption{ Header: &corev3.HeaderValue{ - Key: k, - RawValue: []byte(v), + // Envoy HTTP/2 HeaderMutation requires lowercase header names (RFC 9113). + Key: strings.ToLower(k), + RawValue: []byte(res.ResponseHeaders[k]), }, AppendAction: corev3.HeaderValueOption_OVERWRITE_IF_EXISTS_OR_ADD, }) diff --git a/internal/node/egress_inspect_test.go b/internal/node/egress_inspect_test.go index 518b6007c..be0a8023e 100644 --- a/internal/node/egress_inspect_test.go +++ b/internal/node/egress_inspect_test.go @@ -25,6 +25,7 @@ import ( "net" "net/http" "net/http/httptest" + "os" "path/filepath" "strings" "sync" @@ -36,6 +37,7 @@ import ( extprocv3http "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ext_proc/v3" extprocv3 "github.com/envoyproxy/go-control-plane/envoy/service/ext_proc/v3" typev3 "github.com/envoyproxy/go-control-plane/envoy/type/v3" + jwt "github.com/golang-jwt/jwt/v5" "github.com/google/agentmesh/api" "github.com/google/agentmesh/internal/identity" "google.golang.org/grpc" @@ -697,6 +699,371 @@ func TestGatewayExtProcServer(t *testing.T) { } } +func TestGatewayExtProc_UnmodifiedAgentGatewayTraffic(t *testing.T) { + h := newSTSNodeHarness(t) + node := h.node + node.services = NewServiceRegistry(&fakeDHT{}, 0) + + // Register a real egress service (github.com) and two URL-backed MCP services + // (one mounted at "/", one at "/mcp" with target_auth_path) — mirroring real + // Google Cloud Agent Gateway traffic with no X-Mesh-Target-Service header. + egressSvc, err := newEgressServiceForNode(node, &api.EgressDestination{ + Name: "github.com", + TargetUrl: "https://github.com", + ServedBy: []string{api.RoleNode}, + }, t.TempDir()) + if err != nil { + t.Fatalf("newEgressServiceForNode: %v", err) + } + t.Cleanup(func() { _ = egressSvc.Teardown() }) + if err := node.services.Register(context.Background(), egressSvc); err != nil { + t.Fatalf("Register egress github.com: %v", err) + } + + secretFile := filepath.Join(t.TempDir(), "github-ro.token") + if err := os.WriteFile(secretFile, []byte("ghp_mcp_secret_from_file\n"), 0o600); err != nil { + t.Fatalf("write secret file: %v", err) + } + mcpRootURL, err := withBackendAuthFile("https://github-mcp.internal", secretFile) + if err != nil { + t.Fatalf("withBackendAuthFile: %v", err) + } + node.services.insertService(&MCPService{ + baseService: baseService{ + info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "github"}, + backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: mcpRootURL}, + }, + }) + node.services.insertService(&MCPService{ + baseService: baseService{ + info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "github-copilot"}, + backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "https://api.githubcopilot.com/mcp"}, + }, + }) + + tar := &api.TaskAuthorizationRule{ + Name: "tasks/capsule-github-readonly", + Rules: []*api.TaskRule{ + { + AllowedServices: []string{"egress://github.com"}, + Operation: &api.TaskOperation{ + AllowedMethods: []string{"GET", "POST"}, + AllowedPaths: []string{ + "/google/agentmesh.git/info/refs", + "/google/agentmesh.git/git-upload-pack", + }, + }, + }, + { + AllowedServices: []string{"mcp://github", "mcp://github-copilot"}, + Operation: &api.TaskOperation{ + AllowedTools: []string{"list_issues", "issue_read"}, + }, + }, + }, + } + agwRoles := []*api.PolicyRole{ + { + Name: "capsule-github-agent", + AllowedServices: []string{"egress://github.com", "mcp://github", "mcp://github-copilot"}, + AllowedTargets: []string{"*"}, + }, + } + baseBiscuit, _, err := identity.MintBiscuitToken( + h.cpPriv, + jwt.MapClaims{"sub": "capsule@example.com", "email": "capsule@example.com"}, + nil, + h.peerID, + time.Now().Add(time.Hour), + []string{api.RoleNode, "capsule-github-agent"}, + agwRoles, + nil, + ) + if err != nil { + t.Fatalf("MintBiscuitToken: %v", err) + } + rawBiscuit, err := identity.AttenuateBiscuit(baseBiscuit, tar) + if err != nil { + t.Fatalf("AttenuateBiscuit: %v", err) + } + b64Biscuit := base64.StdEncoding.EncodeToString(rawBiscuit) + + socketPath := filepath.Join(t.TempDir(), "node.sock") + sidecar, err := StartSidecarServer(node, "127.0.0.1:0", socketPath, "api-token", "", "", "") + if err != nil { + t.Fatalf("StartSidecarServer: %v", err) + } + t.Cleanup(func() { _ = sidecar.Close() }) + + cc, err := grpc.NewClient("unix:"+socketPath, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc.NewClient unix: %v", err) + } + defer func() { _ = cc.Close() }() + epClient := extprocv3.NewExternalProcessorClient(cc) + + tcpConn, err := grpc.NewClient(node.BoundHTTPAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc.NewClient tcp: %v", err) + } + defer func() { _ = tcpConn.Close() }() + tcpEPClient := extprocv3.NewExternalProcessorClient(tcpConn) + + findHeader := func(mut *extprocv3.HeaderMutation, key string) (string, bool) { + for _, h := range mut.GetSetHeaders() { + if strings.EqualFold(h.GetHeader().GetKey(), key) { + v := h.GetHeader().GetValue() + if v == "" { + v = string(h.GetHeader().GetRawValue()) + } + return v, true + } + } + return "", false + } + + // 1. Unmodified MCP POST "/" (no /mcp path, no X-Mesh-Target-Service) buffers body, + // allows list_issues, strips spoofed headers, and injects target_auth_path Authorization. + t.Run("unmodified_root_mcp_allow_and_inject_secret", func(t *testing.T) { + stream, err := epClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/"}, + {Key: ":authority", Value: "github-mcp.internal"}, + {Key: "x-mesh-biscuit", Value: b64Biscuit}, + {Key: "x-mesh-claims", Value: "forged=true"}, + {Key: "x-peer-id", Value: "forged-peer"}, + }, + }, + }, + }, + }); err != nil { + t.Fatalf("Send RequestHeaders: %v", err) + } + r1, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestHeaders: %v", err) + } + if r1.GetModeOverride().GetRequestBodyMode() != extprocv3http.ProcessingMode_BUFFERED { + t.Fatalf("expected BUFFERED mode for host-resolved root MCP, got %+v", r1) + } + if r1.GetRequestHeaders().GetResponse().GetHeaderMutation() != nil { + t.Fatalf("Phase 1 must not inject Authorization before tool check: %+v", r1) + } + + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{ + Body: []byte(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_issues"}}`), + EndOfStream: true, + }, + }, + }); err != nil { + t.Fatalf("Send RequestBody: %v", err) + } + r2, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestBody: %v", err) + } + if r2.GetImmediateResponse() != nil { + t.Fatalf("expected CONTINUE for list_issues, got %+v", r2.GetImmediateResponse()) + } + mut := r2.GetRequestBody().GetResponse().GetHeaderMutation() + if got, ok := findHeader(mut, "Authorization"); !ok || got != "Bearer ghp_mcp_secret_from_file" { + t.Fatalf("Authorization = (%q, %v), want Bearer ghp_mcp_secret_from_file", got, ok) + } + if got, ok := findHeader(mut, api.HeaderMeshTaskID); !ok || got != "tasks/capsule-github-readonly" { + t.Fatalf("X-Mesh-Task-Id = (%q, %v), want tasks/capsule-github-readonly", got, ok) + } + }) + + // 1b. Over plain TCP (untrusted transport), a secret-injecting MCP service must be refused (403). + t.Run("unmodified_root_mcp_plain_tcp_refuses_secret", func(t *testing.T) { + stream, err := tcpEPClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/"}, + {Key: ":authority", Value: "github-mcp.internal"}, + {Key: "x-mesh-biscuit", Value: b64Biscuit}, + }, + }, + }, + }, + }); err != nil { + t.Fatalf("Send RequestHeaders: %v", err) + } + r1, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestHeaders: %v", err) + } + if r1.GetImmediateResponse().GetStatus().GetCode() != typev3.StatusCode_Forbidden { + t.Fatalf("expected 403 ImmediateResponse for target_auth_path MCP over plain TCP, got %+v", r1) + } + }) + + // 2. Unmodified MCP POST "/" with disallowed tool returns 403 and never injects secret. + t.Run("unmodified_root_mcp_deny_write_tool", func(t *testing.T) { + stream, err := epClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + _ = stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/"}, + {Key: ":authority", Value: "github-mcp.internal"}, + {Key: "x-mesh-biscuit", Value: b64Biscuit}, + }, + }, + }, + }, + }) + if _, err := stream.Recv(); err != nil { + t.Fatalf("Recv Phase 1: %v", err) + } + _ = stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{ + Body: []byte(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"delete_repository"}}`), + EndOfStream: true, + }, + }, + }) + r2, err := stream.Recv() + if err != nil { + t.Fatalf("Recv Phase 2: %v", err) + } + if r2.GetImmediateResponse().GetStatus().GetCode() != typev3.StatusCode_Forbidden { + t.Fatalf("expected 403 ImmediateResponse for delete_repository, got %+v", r2) + } + }) + + // 3. Unmodified MCP POST "/mcp/v1" with :authority containing explicit :443 port + // (must resolve to host-matched mcp://github-copilot, NOT misparse as mcp://v1). + t.Run("unmodified_subpath_mcp_with_port", func(t *testing.T) { + stream, err := epClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + _ = stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: false, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/mcp/v1"}, + {Key: ":authority", Value: "api.githubcopilot.com:443"}, + {Key: "x-mesh-biscuit", Value: b64Biscuit}, + }, + }, + }, + }, + }) + r1, err := stream.Recv() + if err != nil { + t.Fatalf("Recv Phase 1: %v", err) + } + if r1.GetModeOverride().GetRequestBodyMode() != extprocv3http.ProcessingMode_BUFFERED { + t.Fatalf("expected BUFFERED mode, got %+v", r1) + } + _ = stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{ + Body: []byte(`{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"issue_read"}}`), + EndOfStream: true, + }, + }, + }) + r2, err := stream.Recv() + if err != nil { + t.Fatalf("Recv Phase 2: %v", err) + } + if r2.GetImmediateResponse() != nil { + t.Fatalf("expected CONTINUE for issue_read on api.githubcopilot.com:443, got %+v", r2) + } + }) + + // 4. Unmodified Git Smart HTTP clone (GET /info/refs + POST /git-upload-pack) allowed without body buffering; + // push (POST /git-receive-pack) and unapproved repo denied 403 in Phase 1. + gitCases := []struct { + name string + method string + path string + eos bool + wantAllow bool + }{ + {name: "clone_info_refs", method: "GET", path: "/google/agentmesh.git/info/refs?service=git-upload-pack", eos: true, wantAllow: true}, + {name: "clone_upload_pack", method: "POST", path: "/google/agentmesh.git/git-upload-pack", eos: false, wantAllow: true}, + {name: "push_receive_pack_denied", method: "POST", path: "/google/agentmesh.git/git-receive-pack", eos: false, wantAllow: false}, + {name: "other_repo_denied", method: "GET", path: "/internal/secret-repo.git/info/refs?service=git-upload-pack", eos: true, wantAllow: false}, + } + for _, tc := range gitCases { + t.Run(tc.name, func(t *testing.T) { + stream, err := epClient.Process(context.Background()) + if err != nil { + t.Fatalf("Process: %v", err) + } + defer func() { _ = stream.CloseSend() }() + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: tc.eos, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: tc.method}, + {Key: ":path", Value: tc.path}, + {Key: ":authority", Value: "github.com"}, + {Key: "x-mesh-biscuit", Value: b64Biscuit}, + }, + }, + }, + }, + }); err != nil { + t.Fatalf("Send RequestHeaders: %v", err) + } + r1, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestHeaders: %v", err) + } + if tc.wantAllow { + if r1.GetImmediateResponse() != nil { + t.Fatalf("expected ALLOW, got ImmediateResponse: %+v", r1.GetImmediateResponse()) + } + if r1.GetModeOverride() != nil { + t.Fatalf("Git Smart HTTP must not buffer RequestBody, got ModeOverride=%+v", r1.GetModeOverride()) + } + } else if r1.GetImmediateResponse().GetStatus().GetCode() != typev3.StatusCode_Forbidden { + t.Fatalf("expected 403 ImmediateResponse, got %+v", r1) + } + }) + } +} + func TestBoundedResponseRecorderOverflow(t *testing.T) { rec := newBoundedResponseRecorder(16) n, err := rec.Write([]byte("0123456789")) diff --git a/internal/node/ext_authz.go b/internal/node/ext_authz.go index 742883627..7f5764e64 100644 --- a/internal/node/ext_authz.go +++ b/internal/node/ext_authz.go @@ -19,11 +19,14 @@ import ( "encoding/base64" "errors" "fmt" + "net" "net/http" + "sort" "strings" "github.com/google/agentmesh/api" "github.com/google/agentmesh/internal/envoy" + "github.com/google/agentmesh/internal/identity" "github.com/libp2p/go-libp2p/core/peer" "google.golang.org/protobuf/encoding/protojson" ) @@ -74,6 +77,14 @@ func evaluateExtAuthz(ctx context.Context, node *AgentMeshNode, in extAuthzCheck rawBiscuit, status, err := extractAndVerifyExtAuthzBiscuit(ctx, node, in.Headers) if err != nil { + logger.Warnw("ExtAuthz denied", + "stage", "credential", + "method", in.Method, + "host", in.Host, + "path", in.Path, + "status", status, + "reason", err.Error(), + ) return extAuthzCheckResult{ Allowed: false, HTTPStatus: status, @@ -83,6 +94,14 @@ func evaluateExtAuthz(ctx context.Context, node *AgentMeshNode, in extAuthzCheck claims, err := node.VerifyLocalBiscuit(rawBiscuit) if err != nil { + logger.Warnw("ExtAuthz denied", + "stage", "verify_biscuit", + "method", in.Method, + "host", in.Host, + "path", in.Path, + "status", http.StatusForbidden, + "reason", err.Error(), + ) return extAuthzCheckResult{ Allowed: false, HTTPStatus: http.StatusForbidden, @@ -92,6 +111,15 @@ func evaluateExtAuthz(ctx context.Context, node *AgentMeshNode, in extAuthzCheck target, reqPath := resolveExtAuthzTarget(node, in) if target == "" { + logger.Warnw("ExtAuthz denied", + "stage", "target_resolution", + "method", in.Method, + "host", in.Host, + "path", in.Path, + "header_keys", sortedHeaderKeys(in.Headers), + "status", http.StatusForbidden, + "reason", "unable to resolve target service", + ) return extAuthzCheckResult{ Allowed: false, HTTPStatus: http.StatusForbidden, @@ -115,6 +143,15 @@ func evaluateExtAuthz(ctx context.Context, node *AgentMeshNode, in extAuthzCheck if len(claims.TaskRules) > 0 && claims.ClientPeerID != "" { pid, decErr := peer.Decode(claims.ClientPeerID) if decErr != nil { + logger.Warnw("ExtAuthz denied", + "stage", "client_peer_id", + "method", in.Method, + "host", in.Host, + "path", in.Path, + "target", target, + "status", http.StatusBadRequest, + "reason", decErr.Error(), + ) return extAuthzCheckResult{ Allowed: false, HTTPStatus: http.StatusBadRequest, @@ -159,35 +196,42 @@ func evaluateExtAuthz(ctx context.Context, node *AgentMeshNode, in extAuthzCheck } } - respHeaders := map[string]string{ - api.HeaderMeshBiscuit: base64.StdEncoding.EncodeToString(rawBiscuit), - api.HeaderMeshPrincipal: claims.Principal(), - api.HeaderMeshRoles: strings.Join(claims.Roles, ","), - api.HeaderMeshOrigin: api.MeshOriginGateway, + if in.ExtProcMode != "" { + logger.Infow("ExtProc protocol config", "target", target, "method", method, "path", reqPath, "headers_only", in.HeadersOnly, "mode", in.ExtProcMode) } - if formattedClaims := api.FormatClaims(claims.Claims); formattedClaims != "" { - respHeaders[api.HeaderMeshClaims] = formattedClaims - } - if formattedLabels := api.FormatLabels(claims.Labels); formattedLabels != "" { - respHeaders[api.HeaderMeshLabels] = formattedLabels - } - actorNode := claims.ActorNodePeerID - if actorNode == "" { - actorNode = claims.NodePeerID - } - if actorNode == "" { - actorNode = claims.ClientPeerID - } - if actorNode != "" { - respHeaders[api.HeaderMeshActorNode] = actorNode - } - if len(claims.TaskRules) > 0 { - lastRule := claims.TaskRules[len(claims.TaskRules)-1] - if taskJSON, mErr := (protojson.MarshalOptions{UseProtoNames: true}).Marshal(lastRule); mErr == nil { - respHeaders[api.HeaderMeshTask] = string(taskJSON) + + respHeaders := buildExtAuthzProvenanceHeaders(rawBiscuit, claims) + + var mcpTargetAuth string + if after, ok := strings.CutPrefix(target, api.MCPServicePrefix); ok && node.services != nil { + if svc, ok := node.services.GetTyped(api.ServiceType_SERVICE_TYPE_MCP, after); ok { + if mcpSvc, ok := svc.(*MCPService); ok { + if bt, ok := mcpSvc.targetBackend(); ok && bt.auth != "" { + if !in.TrustedTransport { + logger.Warnf("[ExtAuthz] Check for %s by %s refused: %s", target, claims.Principal(), upstreamCredentialTransportRule) + return extAuthzCheckResult{ + Allowed: false, + HTTPStatus: http.StatusForbidden, + Message: "Forbidden: " + upstreamCredentialTransportRule, + } + } + mcpTargetAuth = bt.auth + } + } } - if lastRule.GetName() != "" { - respHeaders[api.HeaderMeshTaskID] = lastRule.GetName() + } + + // During the ext_proc RequestHeaders pre-check on an MCP POST without an + // extracted tool name, return verified provenance headers (for FULL_DUPLEX_STREAMED + // gateways that only accept HeaderMutation on RequestHeaders) while deferring + // backend credential injection until RequestBody is evaluated against TAR + // allowed_tools. + if in.HeadersOnly && strings.HasPrefix(target, api.MCPServicePrefix) && strings.EqualFold(method, http.MethodPost) && reqCtx.MCPTool == "" { + return extAuthzCheckResult{ + Allowed: true, + HTTPStatus: http.StatusOK, + ResponseHeaders: respHeaders, + NeedsRequestBody: true, } } if after, ok := strings.CutPrefix(target, api.EgressServicePrefix); ok && node.services != nil { @@ -216,6 +260,8 @@ func evaluateExtAuthz(ctx context.Context, node *AgentMeshNode, in extAuthzCheck } } } + } else if mcpTargetAuth != "" { + respHeaders["Authorization"] = mcpTargetAuth } return extAuthzCheckResult{ @@ -263,6 +309,53 @@ func extractAndVerifyExtAuthzBiscuit(ctx context.Context, node *AgentMeshNode, h return nil, http.StatusForbidden, errors.New("forbidden: unrecognizable credential") } +func buildExtAuthzProvenanceHeaders(rawBiscuit []byte, claims *identity.VerifiedBiscuitClaims) map[string]string { + respHeaders := map[string]string{ + api.HeaderMeshBiscuit: base64.StdEncoding.EncodeToString(rawBiscuit), + api.HeaderMeshPrincipal: claims.Principal(), + api.HeaderMeshRoles: strings.Join(claims.Roles, ","), + api.HeaderMeshOrigin: api.MeshOriginGateway, + } + if formattedClaims := api.FormatClaims(claims.Claims); formattedClaims != "" { + respHeaders[api.HeaderMeshClaims] = formattedClaims + } + if formattedLabels := api.FormatLabels(claims.Labels); formattedLabels != "" { + respHeaders[api.HeaderMeshLabels] = formattedLabels + } + actorNode := claims.ActorNodePeerID + if actorNode == "" { + actorNode = claims.NodePeerID + } + if actorNode == "" { + actorNode = claims.ClientPeerID + } + if actorNode != "" { + respHeaders[api.HeaderMeshActorNode] = actorNode + } + if len(claims.TaskRules) > 0 { + lastRule := claims.TaskRules[len(claims.TaskRules)-1] + if taskJSON, mErr := (protojson.MarshalOptions{UseProtoNames: true}).Marshal(lastRule); mErr == nil { + respHeaders[api.HeaderMeshTask] = string(taskJSON) + } + if lastRule.GetName() != "" { + respHeaders[api.HeaderMeshTaskID] = lastRule.GetName() + } + } + return respHeaders +} + +func sortedHeaderKeys(headers map[string]string) []string { + if len(headers) == 0 { + return nil + } + keys := make([]string, 0, len(headers)) + for k := range headers { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + func isExtAuthzServiceScheme(scheme string) bool { switch scheme { case api.ServiceTypeStringMCP, api.ServiceTypeStringInference, api.ServiceTypeStringA2A, api.ServiceTypeStringEgress, "http": @@ -272,6 +365,40 @@ func isExtAuthzServiceScheme(scheme string) bool { } } +func extractHostName(authority string) string { + h := strings.TrimSpace(authority) + if h == "" { + return "" + } + if host, _, err := net.SplitHostPort(h); err == nil { + h = host + } + return api.NormalizeMeshHost(h) +} + +func parseSchemePathTarget(trimmed string) (target, reqPath string) { + parts := strings.SplitN(trimmed, "/", 3) + if len(parts) < 2 { + return "", "" + } + scheme := strings.ToLower(parts[0]) + if !isExtAuthzServiceScheme(scheme) { + return "", "" + } + name := parts[1] + if scheme == api.ServiceTypeStringEgress { + name = api.NormalizeMeshHost(name) + } + if name == "" { + return "", "" + } + rest := "/" + if len(parts) == 3 { + rest = "/" + parts[2] + } + return scheme + "://" + name, rest +} + func resolveExtAuthzTarget(node *AgentMeshNode, in extAuthzCheckInput) (target, reqPath string) { path := in.Path if idx := strings.IndexByte(path, '?'); idx >= 0 { @@ -290,41 +417,35 @@ func resolveExtAuthzTarget(node *AgentMeshNode, in extAuthzCheckInput) (target, } return "", path } - trimmed := strings.TrimPrefix(path, "/mesh/") - trimmed = strings.TrimPrefix(trimmed, "/") - parts := strings.SplitN(trimmed, "/", 3) - if len(parts) >= 2 { - scheme := strings.ToLower(parts[0]) - if isExtAuthzServiceScheme(scheme) { - name := parts[1] - if scheme == api.ServiceTypeStringEgress { - name = api.NormalizeMeshHost(name) - } - rest := "/" - if len(parts) == 3 { - rest = "/" + parts[2] - } - if name != "" { - return scheme + "://" + name, rest - } - } - } if strings.HasPrefix(path, "/mesh/") { + if t, rest := parseSchemePathTarget(strings.TrimPrefix(path, "/mesh/")); t != "" { + return t, rest + } if route, ok := parseEgressRoute(path); ok && isExtAuthzServiceScheme(route.serviceType) { up := "/" + route.upstreamPath return route.serviceType + "://" + route.serviceName, up } } - if node != nil && node.services != nil && strings.TrimSpace(in.Host) != "" { - normHost := api.NormalizeMeshHost(in.Host) - if normHost != "" { + if node != nil && node.services != nil { + if normHost := extractHostName(in.Host); normHost != "" { + if path == "" { + path = "/" + } + mcpName, ambiguous := node.services.ResolveMCPByHostPath(normHost, path) + if ambiguous { + logger.Warnf("[ExtAuthz] ambiguous MCP host/path match for host=%q path=%q; denying fail-closed", normHost, path) + return "", path + } + if mcpName != "" { + return api.MCPServicePrefix + mcpName, path + } if _, ok := node.services.GetTyped(api.ServiceType_SERVICE_TYPE_EGRESS, normHost); ok { - if path == "" { - path = "/" - } return api.EgressServicePrefix + normHost, path } } } + if t, rest := parseSchemePathTarget(strings.TrimPrefix(path, "/")); t != "" { + return t, rest + } return "", path } diff --git a/internal/node/service.go b/internal/node/service.go index 0600c02b6..d8d6a4253 100644 --- a/internal/node/service.go +++ b/internal/node/service.go @@ -86,6 +86,20 @@ func newReverseProxy(targetURL string) (*httputil.ReverseProxy, error) { func (b *baseService) Info() *api.ServiceInfo { return b.info } func (b *baseService) Handler() http.Handler { return b.handler } +// targetBackend parses the configured target_url backend without exposing +// credentials in the returned URL. Returns false for non-URL backends. +func (b *baseService) targetBackend() (backendTarget, bool) { + t, ok := b.backend.(*api.RegisterServiceRequest_TargetUrl) + if !ok || t == nil || t.TargetUrl == "" { + return backendTarget{}, false + } + bt, err := parseBackendTarget(t.TargetUrl) + if err != nil || bt.url == nil { + return backendTarget{}, false + } + return bt, true +} + // Init builds the ingress handler for the backend: URL -> reverse-proxy, // Command -> StdioBridge, one process shared by every caller, with the // bridge owning the id space and the MCP handshake. Probes and tool diff --git a/internal/node/service_registry.go b/internal/node/service_registry.go index f9815fffe..0a7740f61 100644 --- a/internal/node/service_registry.go +++ b/internal/node/service_registry.go @@ -18,6 +18,7 @@ import ( "context" "errors" "fmt" + "strings" "sync" "sync/atomic" "time" @@ -430,6 +431,58 @@ func (r *ServiceRegistry) List(typeFilter api.ServiceType) []*api.ServiceInfo { return out } +// ResolveMCPByHostPath matches an inbound Host/Authority and request path +// against registered URL-backed MCP services using longest segment-boundary +// path prefix matching. Returns ambiguous=true if two distinct MCP services +// tie for the most specific match so callers fail closed. +func (r *ServiceRegistry) ResolveMCPByHostPath(normHost, reqPath string) (name string, ambiguous bool) { + if normHost == "" { + return "", false + } + if reqPath == "" { + reqPath = "/" + } + r.mu.RLock() + defer r.mu.RUnlock() + + bestLen := -1 + for _, svc := range r.services { + info := svc.Info() + if info.GetType() != api.ServiceType_SERVICE_TYPE_MCP { + continue + } + mcpSvc, ok := svc.(*MCPService) + if !ok { + continue + } + bt, ok := mcpSvc.targetBackend() + if !ok { + continue + } + targetHost := api.NormalizeMeshHost(bt.url.Hostname()) + if targetHost == "" || targetHost != normHost { + continue + } + basePath := strings.TrimRight(bt.url.Path, "/") + if basePath != "" && reqPath != basePath && !strings.HasPrefix(reqPath, basePath+"/") { + continue + } + matchLen := len(basePath) + switch { + case matchLen > bestLen: + bestLen = matchLen + name = info.GetName() + ambiguous = false + case matchLen == bestLen && info.GetName() != name: + ambiguous = true + } + } + if ambiguous { + return "", true + } + return name, false +} + // insertService inserts a service into the registry without calling Init or // advertising on the DHT. For tests only. func (r *ServiceRegistry) insertService(svc Service) { diff --git a/internal/node/service_registry_test.go b/internal/node/service_registry_test.go index c07bb46ac..51540a812 100644 --- a/internal/node/service_registry_test.go +++ b/internal/node/service_registry_test.go @@ -192,6 +192,67 @@ func TestServiceRegistry_ListFiltersByType(t *testing.T) { } } +func TestServiceRegistry_ResolveMCPByHostPath(t *testing.T) { + r := newServiceRegistryForTest(&fakeDHT{}) + insertMCP := func(name, targetURL string) { + r.insertService(&MCPService{ + baseService: baseService{ + info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: name}, + backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: targetURL}, + }, + }) + } + insertMCP("github-copilot", "https://:secret@api.githubcopilot.com/mcp") + insertMCP("root-mcp", "https://tools.example.com") + insertMCP("sub-mcp", "https://tools.example.com/v2/mcp") + // Command-backed MCP and non-MCP services must be ignored. + r.insertService(&MCPService{ + baseService: baseService{ + info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "stdio-mcp"}, + backend: &api.RegisterServiceRequest_Command{Command: &api.CommandBackend{Command: []string{"echo"}}}, + }, + }) + r.insertService(&A2AService{ + baseService: baseService{ + info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_A2A, Name: "other-a2a"}, + backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "https://a2a.example.com/"}, + }, + }) + + cases := []struct { + name string + host string + path string + wantName string + wantAmbig bool + }{ + {name: "exact subpath", host: "api.githubcopilot.com", path: "/mcp", wantName: "github-copilot"}, + {name: "trailing slash subpath", host: "api.githubcopilot.com", path: "/mcp/", wantName: "github-copilot"}, + {name: "nested subpath", host: "api.githubcopilot.com", path: "/mcp/tools", wantName: "github-copilot"}, + {name: "segment boundary rejects sibling prefix", host: "api.githubcopilot.com", path: "/mcp-other", wantName: ""}, + {name: "root target matches any path", host: "tools.example.com", path: "/rpc", wantName: "root-mcp"}, + {name: "longest prefix wins over root", host: "tools.example.com", path: "/v2/mcp/call", wantName: "sub-mcp"}, + {name: "non-MCP service ignored", host: "a2a.example.com", path: "/", wantName: ""}, + {name: "unknown host", host: "unknown.example.com", path: "/mcp", wantName: ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, ambig := r.ResolveMCPByHostPath(tc.host, tc.path) + if got != tc.wantName || ambig != tc.wantAmbig { + t.Fatalf("ResolveMCPByHostPath(%q, %q) = (%q, %v), want (%q, %v)", tc.host, tc.path, got, ambig, tc.wantName, tc.wantAmbig) + } + }) + } + + // Two distinct MCP services matching the same host+prefix must fail closed as ambiguous. + insertMCP("dup-a", "https://dup.example.com/mcp") + insertMCP("dup-b", "https://dup.example.com/mcp/") + got, ambig := r.ResolveMCPByHostPath("dup.example.com", "/mcp/") + if got != "" || !ambig { + t.Fatalf("ambiguous match = (%q, %v), want (\"\", true)", got, ambig) + } +} + func TestServiceRegistry_TeardownAllContinuesOnError(t *testing.T) { r := newServiceRegistryForTest(&fakeDHT{}) a := newFakeSvc("a", api.ServiceType_SERVICE_TYPE_MCP) diff --git a/site/content/docs/guides/_index.md b/site/content/docs/guides/_index.md index 00c1321e2..788ed0f2f 100644 --- a/site/content/docs/guides/_index.md +++ b/site/content/docs/guides/_index.md @@ -9,8 +9,9 @@ aliases: Step-by-step pages for common tasks: publish a service, connect an agent client, enroll machines that cannot log in, use Keycloak as the identity -provider, put agentgateway in front of the mesh, enforce IdP-attested device -posture and workload isolation, put an agent in an OpenShell sandbox, a -Substrate actor, a Wasmtime sandbox, or `a2a-serve` on the mesh, and deploy a -control plane on Kubernetes, Cloud Run, SkyPilot or a GitHub codespace. Each -page assumes that you have read the [quick start](../getting-started/quickstart/). +provider, put agentgateway, kgateway, or Google Cloud Agent Gateway in front of +the mesh, enforce IdP-attested device posture and workload isolation, put an +agent in an OpenShell sandbox, a Substrate actor, a Wasmtime sandbox, or +`a2a-serve` on the mesh, and deploy a control plane on Kubernetes, Cloud Run, +SkyPilot or a GitHub codespace. Each page assumes that you have read the +[quick start](../getting-started/quickstart/). diff --git a/site/content/docs/guides/gcp-agent-gateway.md b/site/content/docs/guides/gcp-agent-gateway.md new file mode 100644 index 000000000..1207c5bd4 --- /dev/null +++ b/site/content/docs/guides/gcp-agent-gateway.md @@ -0,0 +1,291 @@ +--- +title: "Google Cloud Agent Gateway with Service Extensions (ext_proc)" +linkTitle: "Google Cloud Agent Gateway" +weight: 3 +--- + +You can keep **Google Cloud Agent Gateway** in the L7 data path for TLS +inspection, Agent Registry, Model Armor, and Cloud Logging while plugging +`agentmesh-node` into its **Service Extensions** delegation hook +(`AuthzExtension` with `wireFormat: EXT_PROC_GRPC` and `AuthzPolicy` with +`policyProfile: CONTENT_AUTHZ`, `action: CUSTOM`). + +This lets you enforce short-lived, cryptographically sealed +**Task Authorization Rules (`tar_block`)** and IdP-attested `claim(k, v)` +Biscuit facts on unmodified HTTP, Git Smart HTTP, and MCP traffic—without +building a parallel gateway or handing standing SaaS credentials to isolated +agents. + +The full runnable deployment and verification bundle lives in +[`development/examples/gcp-agent-gateway/`](https://github.com/google/agentmesh/tree/main/development/examples/gcp-agent-gateway). + +--- + +## How the pieces fit + +```mermaid +flowchart LR + Agent["Isolated Agent
(Vertex AI Agent Runtime / Sandbox)"] + AGW["Google Cloud Agent Gateway
(Managed SWP or External ALB)
TLS Inspection · Agent Registry · Model Armor"] + PEP["agentmesh-node on Cloud Run (--use-http2)
ext_proc gRPC v3 · /oauth/token"] + CP["agentmesh-control-plane
PolicyConfig · claim() · /token/exchange"] + Git["github.com
(Git Smart HTTP)"] + MCP["GitHub MCP Server
(JSON-RPC tools/call)"] + + Agent -- "1. POST /oauth/token (OIDC JWT + TAR, seal=true)" --> PEP + PEP -- "POST /token/exchange" --> CP + Agent -- "2. HTTPS + X-Mesh-Biscuit" --> AGW + AGW <-- "3. Envoy ext_proc gRPC v3
(RequestHeaders + RequestBody + RequestTrailers)" --> PEP + AGW -- "4a. GET /info/refs + POST /git-upload-pack (ALLOW)
POST /git-receive-pack (403)" --> Git + AGW -- "4b. list_issues / issue_read (ALLOW + verified X-Mesh-*)
write/delete tools (403)" --> MCP +``` + +### Separation of responsibilities + +| Layer | Owned by Google Cloud Agent Gateway | Owned by `agentmesh-node` Service Extension | +|---|---|---| +| **Network & TLS** | Terminates egress TLS, enforces Agent Registry allowlists, runs Model Armor / DLP, and writes `agentGatewayInfo` logs. | Runs as an HTTP/2 gRPC callout (`--use-http2`) behind `AuthzExtension` (or `ProducerExtension` / `ExtensionBinding`). | +| **Task scoping** | Streams request headers, JSON-RPC bodies (`BUFFERED` or `FULL_DUPLEX_STREAMED`), and response events to `ext_proc`. | Verifies Block 0 IdP `claim(k, v)` facts, Datalog RBAC, `require_task_scope: true`, `max_task_ttl: 15m`, and sealed `tar_block` intersections (`allowed_methods`, `allowed_paths`, `allowed_tools`). | +| **Provenance & credentials** | Forwards allowed traffic to upstream destinations and applies returned `HeaderMutation`s. | Strips caller-spoofed `X-Mesh-*` / `X-Peer-Id` headers, stamps verified `X-Mesh-Principal`, `X-Mesh-Claims`, `X-Mesh-Roles`, `X-Mesh-Actor-Node`, `X-Mesh-Task`, and `X-Mesh-Origin`, and injects brokered `Authorization` headers (`PolicyConfig.egress` or MCP `target_auth_path`) **only after** authorization succeeds. | + +--- + +## How `agentmesh-node` handles unmodified Agent Gateway traffic + +Real gateways forward the upstream destination's `:authority` and `:path` +without adding mesh-specific routing headers. `agentmesh-node`'s Envoy server +(`internal/envoy/server.go`, `internal/node/ext_authz.go`) handles this +directly: + +1. **Host and path resolution (no `X-Mesh-Target-Service` required):** + - Strips explicit `:port` suffixes (for example, `github.com:443` or + `api.githubcopilot.com:443`) before matching. + - Matches registered URL-backed `mcp` services by host and longest + segment-boundary path prefix (failing closed with `403` if two MCP + services tie ambiguously on the same host and prefix). + - Falls back to control-plane-assigned `egress` destinations (`PolicyConfig.egress`) + for non-MCP HTTP/Git traffic (for example, `egress://github.com`). + - Explicit `X-Mesh-Target-Service` headers and `/mesh///...` + paths continue to take precedence when present. +2. **Selective body inspection without buffering Git packfiles:** + - For `POST` requests resolved to an `mcp://` service (even when mounted at + `/` rather than `/mcp`), Phase 1 (`RequestHeaders`) validates the Biscuit, + claims, and service grant without releasing backend credentials, then + requests `RequestBodyMode: BUFFERED` to inspect JSON-RPC `tools/call` + `params.name` in Phase 2 (`RequestBody`). + - For non-MCP `POST` requests (such as Git Smart HTTP + `POST //.git/git-upload-pack`), Phase 1 decides immediately on + method and path with zero body buffering so large packfiles stream + untouched. +3. **`BUFFERED` and `FULL_DUPLEX_STREAMED` (`CONTENT_AUTHZ`) body modes (fail-closed on half-duplex `STREAMED`):** + - Supports single-frame `BUFFERED` bodies (or `allow_mode_override: true`) and + Envoy's `FULL_DUPLEX_STREAMED` mode used by Google Cloud Agent Gateway + `CONTENT_AUTHZ` (holding all MCP body chunks silently until `end_of_stream` + or `RequestTrailers` passes `allowed_tools`, then echoing allowed request + and response bodies via `StreamedBodyResponse`). + - Rejects partial half-duplex `STREAMED` MCP body chunks fail-closed with + HTTP `403` on the first chunk, because answering `CONTINUE` on an + intermediate `STREAMED` chunk would release unverified bytes upstream before + the full JSON-RPC call is inspected. + - Emits strictly lowercase HTTP/2 header names in `HeaderMutation` and caps + buffered JSON-RPC inspection at 1 MiB (`MaxHTTPBodyBytes`), failing closed + with HTTP `413 Payload Too Large` on overflow. + +--- + +## Example policy: read-only Git clone + read-only GitHub MCP issues + +Coarse domain+verb proxies cannot allow `git clone` (which requires +`POST //.git/git-upload-pack`) without also opening `git push` +(`POST //.git/git-receive-pack`) and arbitrary repositories, nor can +they distinguish read-only vs. mutating MCP tools on `POST /mcp`. + +With a single 10-minute sealed `TaskAuthorizationRule` minted via RFC 8693 +`POST /oauth/token` (`seal=true`): + +```json +{ + "name": "tasks/gcp-agw-github-readonly", + "display_name": "Clone google/agentmesh + Read GitHub Issues Only", + "expire_time": "2026-11-27T12:30:00Z", + "rules": [ + { + "description": "Allow read-only Git Smart HTTP clone of google/agentmesh.git only", + "allowed_services": ["egress://github.com"], + "operation": { + "allowed_methods": ["GET", "POST"], + "allowed_paths": [ + "/google/agentmesh.git/info/refs", + "/google/agentmesh.git/git-upload-pack" + ] + } + }, + { + "description": "Allow read-only GitHub MCP issue tools only", + "allowed_services": ["mcp://github"], + "operation": { + "allowed_tools": ["list_issues", "issue_read", "search_issues"] + } + } + ] +} +``` + +| Request through Agent Gateway | Decision | Enforced By | +|---|---|---| +| `GET github.com/google/agentmesh.git/info/refs?service=git-upload-pack` | **200 Allow** | `ext_proc` Phase 1 (`egress://github.com`) | +| `POST github.com/google/agentmesh.git/git-upload-pack` | **200 Allow** (no body buffering) | `ext_proc` Phase 1 (`egress://github.com`) | +| `POST github.com/google/agentmesh.git/git-receive-pack` (`git push`) | **403 Deny** | `ext_proc` Phase 1 (`allowed_paths`) | +| `GET github.com/kubernetes/kubernetes.git/info/refs` | **403 Deny** | `ext_proc` Phase 1 (`allowed_paths`) | +| `HTTP CONNECT` tunnel bypass | **403 Deny** | `api/tar.go` fail-closed `CONNECT` check | +| `POST /mcp` `tools/call` `list_issues`, `issue_read`, `search_issues` | **200 Allow** + spoofed headers stripped | `ext_proc` Phase 2 (`mcp://github`) | +| `POST /mcp` `tools/call` `issue_write`, `create_pull_request`, `push_files`, `delete_repository` | **403 Deny** (before backend or secret injection) | `ext_proc` Phase 2 (`allowed_tools`) | +| Unattenuated standing Biscuit (no TAR) or TTL > 15m | **403 Deny** | `require_task_scope: true`, `max_task_ttl: 15m` | + +--- + +## Google Cloud Agent Gateway configuration + +### 1. `agentmesh-node` policy & config + +Seed `PolicyConfig` with `egress` destinations assigned to the gateway PEP +(`served_by: ["role=agent-gateway-pep"]`), and configure `agentmesh-one` / +`agentmesh-control-plane` with `--workload-issuer` including your Google Cloud +**Agent Identity** Workload Identity Pool OIDC issuer so Vertex AI Agent +Runtime `AGENT_IDENTITY` JWTs verify via standard OIDC Discovery: + +- **Organization-scoped projects:** + `https://sts.googleapis.com/v1/organizations//locations/global/workloadIdentityPools/agents.global.org-.system.id.goog` +- **Standalone projects (no organization):** + `https://sts.googleapis.com/v1/projects//locations/global/workloadIdentityPools/agents.global.project-.system.id.goog` + +Configure `agentmesh-node.yaml` with `require_task_scope: true`, +`max_task_ttl: 15m`, the allowed issuer check, and the MCP target URL (plus +optional `target_auth_path` mounted from Secret Manager): + +```yaml +version: "v1alpha1" +labels: + role: agent-gateway-pep +attenuation: + checks: + - 'check if claim("iss", "https://accounts.google.com") or claim("iss", "https://sts.googleapis.com/v1/organizations//locations/global/workloadIdentityPools/agents.global.org-.system.id.goog");' + require_task_scope: true + max_task_ttl: 15m +services: + - type: mcp + name: github + description: "GitHub MCP server governed by Agent Gateway ext_proc + TAR" + target_url: "https://api.githubcopilot.com/mcp" + # Optional (requires --socket-path or mTLS --tls-ca trusted transport): + # inject a read-only token ONLY after tool authz succeeds: + # target_auth_path: "/secrets/github-ro-token" +``` + +> **Note:** Returning an upstream `Authorization` header (`PolicyConfig.egress` +> credential brokering or MCP `target_auth_path`) requires a trusted gateway +> transport (`--socket-path` or client-certificate mTLS via `--tls-ca`). On +> Cloud Run, omit `target_auth_path` (the backend holds its own upstream secret +> and trusts the gateway-stamped `X-Mesh-*` headers) or terminate mTLS at the +> PEP with `--tls-ca`. + +Deploy the PEP container to Cloud Run with `--use-http2` (HTTP/2 `h2c` is +enabled natively on `agentmesh-node`'s `--bind-addr`). + +### 2. Managed Agent Gateway (`AGENT_TO_ANYWHERE`) resources + +```yaml +# agent-gateway.yaml +name: agentmesh-egress-gw +protocols: + - MCP +googleManaged: + governedAccessPath: AGENT_TO_ANYWHERE +``` + +```yaml +# authz-extension.yaml +# Omit forwardHeaders so Google Cloud Service Extensions forwards all client +# headers (including :authority, :method, :path, Content-Type, Authorization, +# and X-Mesh-Biscuit). Specifying a partial forwardHeaders list drops +# :authority/Host and prevents host-based target resolution. +name: agentmesh-tar-ext +service: +authority: +wireFormat: EXT_PROC_GRPC +failOpen: false +timeout: "1.0s" +loadBalancingScheme: LOAD_BALANCING_SCHEME_UNSPECIFIED +``` + +```yaml +# content-authz-policy.yaml +name: agentmesh-tar-content-authz +target: + loadBalancingScheme: LOAD_BALANCING_SCHEME_UNSPECIFIED + resources: + - "projects/PROJECT_ID/locations/us-central1/agentGateways/agentmesh-egress-gw" +action: CUSTOM +policyProfile: CONTENT_AUTHZ +httpRules: + - to: + operations: + - hosts: + - exact: "github.com" + - exact: "" + paths: + - prefix: "/" +customProvider: + authzExtension: + resources: + - "projects/PROJECT_ID/locations/us-central1/authzExtensions/agentmesh-tar-ext" +``` + +Import all three declaratively with `gcloud beta`: + +```sh +gcloud beta network-services agent-gateways import agentmesh-egress-gw \ + --source=agent-gateway.yaml --location=us-central1 --project=PROJECT_ID + +gcloud beta service-extensions authz-extensions import agentmesh-tar-ext \ + --source=authz-extension.yaml --location=us-central1 --project=PROJECT_ID + +gcloud beta network-security authz-policies import agentmesh-tar-content-authz \ + --source=content-authz-policy.yaml --location=us-central1 --project=PROJECT_ID +``` + +--- + +## Two runnable topologies + +[`development/examples/gcp-agent-gateway/`](https://github.com/google/agentmesh/tree/main/development/examples/gcp-agent-gateway) +ships idempotent scripts for both: + +1. **Managed Agent Gateway + Vertex AI Agent Runtime (`deploy_managed_agw.sh` + `agent_runtime/deploy_agent.py`):** + Provisions a Google-managed `AgentGateway` (`AGENT_TO_ANYWHERE`), attaches + `agentmesh-node` on Cloud Run via `AuthzExtension` (`EXT_PROC_GRPC`) and + `AuthzPolicy` (`CONTENT_AUTHZ`), and deploys an ADK agent with + `identity_type: AGENT_IDENTITY` and `agent_gateway_config` to run the live + allow/deny matrix against `github.com` and live `api.github.com`. +2. **Edge Agent Gateway / Regional External ALB (`deploy_edge_alb.sh` + `verify_edge_alb.sh`):** + Fronts the same `agentmesh-node` Cloud Run PEP behind a Regional External + ALB (`EXTERNAL_MANAGED`) with `AuthzExtension` (`EXT_PROC_GRPC`) and + `AuthzPolicy` (`CONTENT_AUTHZ`), allowing direct real `git clone`, + `git push`, and MCP verification from any developer terminal. + +## Logs and production hardening + +- Every `ext_proc` decision emits an `Audit Traceability` log line on + `agentmesh-node` (`protocol: "ext_authz"`, `decision`, `mcp_tool`, `task`, + `principal`, `claims`), and every `/oauth/token` exchange emits a + `Border Crossing` log line on the control plane. +- Restrict `ALLOWED_AUDIENCE` strictly to your workload audience (do not keep + the developer CLI client ID in production) and narrow `PolicyBinding.members` + and `PolicyBinding.claims` to approved workload identities. +- When deploying into a private VPC, set `--ingress=internal-and-cloud-load-balancing` + on Cloud Run, front `agentmesh-node` with a Regional Internal ALB, and attach + a VPC `networkAttachment` + `dnsPeeringConfig` to the `AgentGateway` (or + publish `agentmesh-node` behind a PSC Service Attachment as a + `ProducerExtension` + `ExtensionBinding`). +- Run `PROJECT_ID= REGION=us-central1 ./cleanup.sh` to tear down all + example resources. diff --git a/tests/integration/posture_isolation_test.go b/tests/integration/posture_isolation_test.go index d95c3449b..72e7da3fa 100644 --- a/tests/integration/posture_isolation_test.go +++ b/tests/integration/posture_isolation_test.go @@ -467,19 +467,23 @@ func TestDevicePostureAndWorkloadIsolationCUJ(t *testing.T) { } stamped := make(map[string]string) for _, h := range okResp.GetOkResponse().GetHeaders() { - stamped[h.GetHeader().GetKey()] = h.GetHeader().GetValue() + k := h.GetHeader().GetKey() + if k != strings.ToLower(k) { + t.Errorf("ext_authz emitted non-lowercase HTTP/2 header key %q", k) + } + stamped[k] = h.GetHeader().GetValue() } - if stamped[api.HeaderMeshPrincipal] != "alice@corp.example" { - t.Errorf("X-Mesh-Principal = %q, want alice@corp.example", stamped[api.HeaderMeshPrincipal]) + if stamped[strings.ToLower(api.HeaderMeshPrincipal)] != "alice@corp.example" { + t.Errorf("X-Mesh-Principal = %q, want alice@corp.example", stamped[strings.ToLower(api.HeaderMeshPrincipal)]) } - if stamped[api.HeaderMeshOrigin] != api.MeshOriginGateway { - t.Errorf("X-Mesh-Origin = %q, want %q", stamped[api.HeaderMeshOrigin], api.MeshOriginGateway) + if stamped[strings.ToLower(api.HeaderMeshOrigin)] != api.MeshOriginGateway { + t.Errorf("X-Mesh-Origin = %q, want %q", stamped[strings.ToLower(api.HeaderMeshOrigin)], api.MeshOriginGateway) } - if stamped[api.HeaderMeshClaims] != wantClaims { - t.Errorf("X-Mesh-Claims = %q, want %q", stamped[api.HeaderMeshClaims], wantClaims) + if stamped[strings.ToLower(api.HeaderMeshClaims)] != wantClaims { + t.Errorf("X-Mesh-Claims = %q, want %q", stamped[strings.ToLower(api.HeaderMeshClaims)], wantClaims) } - if stamped[api.HeaderMeshTaskID] != "workstation-status-task" { - t.Errorf("X-Mesh-Task-Id = %q, want workstation-status-task", stamped[api.HeaderMeshTaskID]) + if stamped[strings.ToLower(api.HeaderMeshTaskID)] != "workstation-status-task" { + t.Errorf("X-Mesh-Task-Id = %q, want workstation-status-task", stamped[strings.ToLower(api.HeaderMeshTaskID)]) } removed := strings.Join(okResp.GetOkResponse().GetHeadersToRemove(), ",") if !strings.Contains(removed, "x-mesh-spoofed") || !strings.Contains(removed, "x-peer-id") {