Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
docs: add multi-tier enterprise guardrails example, docs, and demo video
Antonio Ojea63da4998ca08
diff --git a/development/examples/multi-tier-guardrails/Makefile b/development/examples/multi-tier-guardrails/Makefilenew file mode 100644index 00000000..a1a8d788--- /dev/null+++ b/development/examples/multi-tier-guardrails/Makefile@@ -0,0 +1,30 @@+# Targets for the Multi-Tier Guardrails & Quality Gates example.+#+# make node-v1-staging start Alice's support node in env=staging (node-v1.yaml)+# make node-v1-prod start Alice's support node promoted to env=prod++WORK_DIR ?= /tmp/sam-record-guardrails+CP_URL ?= http://127.0.0.1:18190+REPO_BIN := $(abspath ../../../bin)+SAM_ONE ?= $(if $(wildcard $(REPO_BIN)/sam-one),$(REPO_BIN)/sam-one,sam-one)+SAM_NODE ?= $(if $(wildcard $(REPO_BIN)/sam-node),$(REPO_BIN)/sam-node,sam-node)++.PHONY: node-v1-staging node-v1-prod++node-v1-staging:+ $(SAM_NODE) run --control-plane "$(CP_URL)" --insecure-control-plane \+ --bootstrap-token-path "$(WORK_DIR)/dev-v1.token" \+ --config node-v1.yaml --secrets-dir "$(WORK_DIR)/secrets" \+ --data-dir "$(WORK_DIR)/node-v1" --bind-addr 127.0.0.1:19101 --socket-path="" \+ --listen "/ip4/127.0.0.1/udp/0/quic-v1,/ip4/127.0.0.1/tcp/0" \+ --api-token-path "$(WORK_DIR)/dev-api.token" \+ --allow-loopback --control-plane-sync-interval 5s++node-v1-prod:+ $(SAM_NODE) run --control-plane "$(CP_URL)" --insecure-control-plane \+ --bootstrap-token-path "$(WORK_DIR)/dev-v1-prod.token" \+ --config "$(WORK_DIR)/node-v1-prod.yaml" --secrets-dir "$(WORK_DIR)/secrets" \+ --data-dir "$(WORK_DIR)/node-v1" --bind-addr 127.0.0.1:19101 --socket-path="" \+ --listen "/ip4/127.0.0.1/udp/0/quic-v1,/ip4/127.0.0.1/tcp/0" \+ --api-token-path "$(WORK_DIR)/dev-api.token" \+ --allow-loopback --control-plane-sync-interval 5sdiff --git a/development/examples/multi-tier-guardrails/SCRIPT.md b/development/examples/multi-tier-guardrails/SCRIPT.mdnew file mode 100644index 00000000..abb2edea--- /dev/null+++ b/development/examples/multi-tier-guardrails/SCRIPT.md@@ -0,0 +1,95 @@+# Multi-Tier Guardrails & Quality Gates — Recording Script++A ~3.5-minute terminal recording demonstrating how SAM serves all **5 enterprise personas** across **4 acts** with real backends (`gemma3:1b` on Ollama, official `a2a-sdk`, official `mcp` SDK + SQLite, and `api.github.com`). Every config file (`node-v1.yaml`, `node-caller.yaml`, `node-v2.yaml`, `node-contractor.yaml`, `policy.json`) and every command (`sam-node join`, `make node-v1-staging`, `curl`, `python3 a2a_client.py`, `mcp-client`, `sam-one admin ban`) is shown directly on screen.++## Scenes++### Act 1: Developer Onboarding, Quarantine & Label Points 1 & 2a+*(Personas: Agent Developer Alice + Central Security / Platform)*++```bash+# node-v1+cat node-v1.yaml++# admin (Label Point 1 — Mesh Enforcement)+jq -c '.roles[0].allowed_labels' policy.json+sed 's/staging/prod/' node-v1.yaml > $WORK_DIR/node-v1-prod.yaml && \+ sam-node join $CP_URL --insecure-control-plane \+ --bootstrap-token-path $WORK_DIR/dev-spoof.token \+ --config $WORK_DIR/node-v1-prod.yaml --data-dir $WORK_DIR/spoof++# node-v1+make node-v1-staging 2>&1 | python3 audit.py++# caller (Label Point 2a — Input Node Enforcement)+cat node-caller.yaml+curl -i -s -H 'X-Sam-Authentication: Bearer caller-secret' \+ http://127.0.0.1:19102/sam/$V1_PEER/a2a/support.acme/.well-known/agent-card.json | head -n 5++# admin (Quality Gate Promotion)+jq '.roles[0].allowed_labels += ["env=prod"]' policy.json | \+ curl -s -X POST $CP_URL/policies -H "Authorization: Bearer $ADMIN_TOKEN" --data @-++# node-v1+make node-v1-prod 2>&1 | python3 audit.py++# caller+curl -s -H 'X-Sam-Authentication: Bearer caller-secret' \+ http://127.0.0.1:19102/sam/$V1_PEER/a2a/support.acme/.well-known/agent-card.json | \+ jq '{name, url: .supportedInterfaces[0].url}'+```++### Act 2: Zero-Downtime Replica Swap & Label Point 3 (End-User / Agent Intent)+*(Persona: Platform / Networking)*++```bash+# caller+python3 a2a_client.py http://127.0.0.1:19102/sam/$V1_PEER/a2a/support.acme \+ ctx-acme-1042 'Check order #1042 for [email protected]' replica=v1-laptop++cat node-v2.yaml++python3 a2a_client.py http://127.0.0.1:19102/sam/$V2_PEER/a2a/support.acme \+ ctx-acme-1042 'What item did Alice order and has it shipped?' replica=v2-cloudrun+```++### Act 3: 3-Tier Guardrails+*(Personas: Central Security, Department Lead, Individual End-User)*++```bash+# Layer 1 — Central Security (Org HTTP Policy + Secret Brokering)+jq -c '.roles[0].http[0], .egress[0]' policy.json+curl -s -H 'X-Sam-Authentication: Bearer caller-secret' \+ "http://127.0.0.1:19102/sam/$V1_PEER/egress/api.github.com/repos/google/sam/pulls?state=open&per_page=1" | \+ jq -c '.[0] | {number, title}'+curl -i -s -X POST -H 'X-Sam-Authentication: Bearer caller-secret' \+ http://127.0.0.1:19102/sam/$V1_PEER/egress/api.github.com/repos/google/sam/pulls -d '{}' | head -n 5++# Layer 2 — Department Lead (Label Point 2b — Egress Node Positive Check)+cat node-contractor.yaml+mcp-client -url http://127.0.0.1:19104/mcp -token contractor-secret -tool call_remote_tool \+ -args '{"peer_id":"'$V1_PEER'","tool_name":"mcp://orders-db/get_order_status","arguments":{"order_id":"1042"}}'++# Layer 3 — Individual End-User (RFC 8693 Task Biscuit tar_block)+TASK_BISCUIT=$(curl -s -X POST http://127.0.0.1:19102/oauth/token \+ -H 'Authorization: Bearer caller-secret' \+ -d 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange&resource=mcp://orders-db&scope=tool:get_order_status&seal=true' | jq -r .access_token)+mcp-client -url http://127.0.0.1:19102/mcp -token $TASK_BISCUIT -tool call_remote_tool \+ -args '{"peer_id":"'$V1_PEER'","tool_name":"mcp://orders-db/get_order_status","arguments":{"order_id":"1042"}}'+mcp-client -url http://127.0.0.1:19102/mcp -token $TASK_BISCUIT -tool call_remote_tool \+ -args '{"peer_id":"'$V1_PEER'","tool_name":"mcp://orders-db/issue_refund","arguments":{"order_id":"1042","amount_dollars":5000}}'+```++### Act 4: Day-2 Operations — Audit & Instant Kill-Switch+*(Persona: SRE / Operations)*++```bash+# admin+sam-one admin ban $CONTRACTOR_PEER --server $CP_URL --data-dir $WORK_DIR/one+```++## Recording++```bash+./development/examples/multi-tier-guardrails/record.sh+```diff --git a/development/examples/multi-tier-guardrails/a2a_client.py b/development/examples/multi-tier-guardrails/a2a_client.pynew file mode 100755index 00000000..8d9ac539--- /dev/null+++ b/development/examples/multi-tier-guardrails/a2a_client.py@@ -0,0 +1,57 @@+#!/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.++"""A2A client using the official a2a-sdk: resolves the agent card and sends a message."""++import asyncio+import os+import sys+import uuid++import httpx+from a2a.client import A2ACardResolver, ClientConfig, create_client+from a2a.helpers import get_message_text+from a2a.types import Message, Part, Role, SendMessageRequest+++async def send_once(url: str, prompt: str, context_id: str, required_labels: str = "") -> None:+ token = os.environ.get("SAM_API_TOKEN", "")+ headers = {"X-Sam-Authentication": f"Bearer {token}"}+ if required_labels:+ headers["X-Sam-Required-Labels"] = required_labels++ async with httpx.AsyncClient(timeout=120.0, headers=headers) as http:+ card = await A2ACardResolver(http, url).get_agent_card()+ client = await create_client(card, client_config=ClientConfig(httpx_client=http))+ message = Message(+ role=Role.ROLE_USER,+ message_id=str(uuid.uuid4()),+ parts=[Part(text=prompt)],+ context_id=context_id,+ )+ async for event in client.send_message(SendMessageRequest(message=message)):+ if event.HasField("task") and event.task.HasField("status") and event.task.status.HasField("message"):+ print(get_message_text(event.task.status.message))+ return+ if event.HasField("message"):+ print(get_message_text(event.message))+ return+++if __name__ == "__main__":+ if len(sys.argv) < 4:+ sys.exit("usage: a2a_client.py <mesh-a2a-url> <context-id> <prompt> [required-labels]")+ req_labels = sys.argv[4] if len(sys.argv) > 4 else ""+ asyncio.run(send_once(sys.argv[1], sys.argv[3], sys.argv[2], req_labels))diff --git a/development/examples/multi-tier-guardrails/audit.py b/development/examples/multi-tier-guardrails/audit.pynew file mode 100644index 00000000..548b64f5--- /dev/null+++ b/development/examples/multi-tier-guardrails/audit.py@@ -0,0 +1,46 @@+# 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.++"""Reads a sam-node log on stdin and prints one line per authorization or task decision."""++import json+import re+import sys++AUDIT = re.compile(r"Audit Traceability\s+(\{.*\})\s*$")+TAR_DENY = re.compile(r'task authorization denied tool "([^"]+)".*tar_block\[1\] \("([^"]+)"\)')+KEEP = re.compile(r"\[Egress\] (Serving|Withdrawn)|peer banned|SAM Node Online|PeerID:")++for raw_line in sys.stdin:+ line = raw_line.rstrip("\n")+ m = AUDIT.search(line)+ if m:+ try:+ d = json.loads(m.group(1))+ except json.JSONDecodeError:+ continue+ who = f"{d.get('role') or '-'} {d.get('peer_id', '')[:12]}…"+ what = " ".join(x for x in (d.get("method"), d.get("path")) if x) or d.get("protocol", "")+ print(f"{d.get('decision', '?').upper():<5} {who:<22} {what:<34} {d.get('target', '')}", flush=True)+ continue+ tm = TAR_DENY.search(line)+ if tm:+ print(f"DENY tar_block ({tm.group(2)}) tools/call {tm.group(1):<23} mcp://orders-db", flush=True)+ continue+ if "peer banned" in line:+ peer = re.search(r'"peer":\s*"([^"]+)"', line)+ print(f"BANNED {peer.group(1) if peer else ''}: control plane revoked peer", flush=True)+ continue+ if KEEP.search(line):+ print((line.split("\t")[-1] if "\t" in line else line).strip(), flush=True)diff --git a/development/examples/multi-tier-guardrails/node-caller.yaml b/development/examples/multi-tier-guardrails/node-caller.yamlnew file mode 100644index 00000000..8ba75a64--- /dev/null+++ b/development/examples/multi-tier-guardrails/node-caller.yaml@@ -0,0 +1,12 @@+# Input / Caller Node (node-caller.yaml) managed by Platform / Security Admin.+#+# egress.require_labels sets an operator-enforced floor on every outbound mesh+# request leaving this node: even if the local application sends NO+# X-Sam-Required-Labels header, this input node verifies that the remote+# provider's Control-Plane-signed Biscuit attests label("env", "prod").+version: "v1alpha1"+labels:+ team: support+egress:+ require_labels:+ env: proddiff --git a/development/examples/multi-tier-guardrails/node-contractor.yaml b/development/examples/multi-tier-guardrails/node-contractor.yamlnew file mode 100644index 00000000..2f2642b0--- /dev/null+++ b/development/examples/multi-tier-guardrails/node-contractor.yaml@@ -0,0 +1,4 @@+# Contractor node carrying label team=contractor.+version: "v1alpha1"+labels:+ team: contractordiff --git a/development/examples/multi-tier-guardrails/node-v1.yaml b/development/examples/multi-tier-guardrails/node-v1.yamlnew file mode 100644index 00000000..c462d43a--- /dev/null+++ b/development/examples/multi-tier-guardrails/node-v1.yaml@@ -0,0 +1,31 @@+# Primary support Egress / Provider Node (node-v1.yaml).+#+# 1. Starts in quarantine (env=staging). If it tries to claim env=prod before+# the Control Plane policy grants env=prod, enrollment is rejected.+# 2. Enforces a POSITIVE inbound label constraint via attenuation.checks:+# check if label("team", "support");+# Every incoming caller MUST hold a Control-Plane-signed Biscuit attesting+# label("team", "support"). Callers with team=contractor or with no labels+# at all are rejected locally by this egress node.+version: "v1alpha1"+labels:+ env: staging+ team: support+ site: office+ replica: v1-laptop+attenuation:+ checks:+ - 'check if label("team", "support");'+services:+ - type: a2a+ name: support.acme+ description: "Acme Customer Support & Refund Triage A2A Agent (gemma3:1b)"+ target_url: "http://127.0.0.1:17771"+ - type: inference+ name: office-llm+ description: "Ollama gemma3:1b on the support workstation"+ target_url: "http://127.0.0.1:11434"+ - type: mcp+ name: orders-db+ description: "Orders & Refunds SQLite MCP Server (mcp-sdk)"+ target_url: "http://127.0.0.1:18888/mcp"diff --git a/development/examples/multi-tier-guardrails/node-v2.yaml b/development/examples/multi-tier-guardrails/node-v2.yamlnew file mode 100644index 00000000..feee578c--- /dev/null+++ b/development/examples/multi-tier-guardrails/node-v2.yaml@@ -0,0 +1,14 @@+# Secondary Cloud Run replica (v2-cloudrun) for a2a://support.acme.+# Enrolled with env=prod and replica=v2-cloudrun so callers can either rely on+# the input node's env=prod floor or pass X-Sam-Required-Labels: replica=v2-cloudrun+# to target this specific replica.+version: "v1alpha1"+labels:+ env: prod+ team: support+ replica: v2-cloudrun+services:+ - type: a2a+ name: support.acme+ description: "Acme Customer Support & Refund Triage A2A Agent (v2-cloudrun)"+ target_url: "http://127.0.0.1:17772"diff --git a/development/examples/multi-tier-guardrails/orders_mcp.py b/development/examples/multi-tier-guardrails/orders_mcp.pynew file mode 100755index 00000000..cb3f507c--- /dev/null+++ b/development/examples/multi-tier-guardrails/orders_mcp.py@@ -0,0 +1,95 @@+#!/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.++"""Orders & Refunds MCP server backed by SQLite, exposed via sam-node."""++import os+import sqlite3+from mcp.server.mcpserver import MCPServer++DB_PATH = os.environ.get("ORDERS_DB_PATH", "/tmp/sam-multi-tier-orders.db")+PORT = int(os.environ.get("ORDERS_MCP_PORT", "18888"))+++def init_db() -> None:+ with sqlite3.connect(DB_PATH) as conn:+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS orders (+ order_id TEXT PRIMARY KEY,+ customer TEXT NOT NULL,+ item TEXT NOT NULL,+ amount_dollars REAL NOT NULL,+ status TEXT NOT NULL+ )+ """+ )+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS refunds (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ order_id TEXT NOT NULL,+ amount_dollars REAL NOT NULL,+ reason TEXT NOT NULL+ )+ """+ )+ conn.execute(+ """+ INSERT OR REPLACE INTO orders (order_id, customer, item, amount_dollars, status)+ VALUES+ ('1042', '[email protected]', 'Mechanical Keyboard Pro', 129.00, 'SHIPPED'),+ ('1043', '[email protected]', 'USB-C Dock', 89.00, 'DELIVERED')+ """+ )+ conn.commit()+++mcp = MCPServer("orders-db")+++def get_order_status(order_id: str) -> str:+ """Look up an order by order_id in the SQLite orders database (read-only)."""+ with sqlite3.connect(DB_PATH) as conn:+ row = conn.execute(+ "SELECT order_id, customer, item, amount_dollars, status FROM orders WHERE order_id = ?",+ (order_id,),+ ).fetchone()+ if not row:+ return f"Order #{order_id} not found"+ oid, customer, item, amount, status = row+ return f"Order #{oid}: status={status}, item='{item}', total=${amount:.2f}, customer={customer}"+++def issue_refund(order_id: str, amount_dollars: float, reason: str = "customer request") -> str:+ """Issue a refund for an order and update its status in SQLite (mutating financial operation)."""+ with sqlite3.connect(DB_PATH) as conn:+ conn.execute(+ "INSERT INTO refunds (order_id, amount_dollars, reason) VALUES (?, ?, ?)",+ (order_id, amount_dollars, reason),+ )+ conn.execute(+ "UPDATE orders SET status = 'REFUNDED' WHERE order_id = ?",+ (order_id,),+ )+ conn.commit()+ return f"REFUND_EXECUTED: order=#{order_id}, amount=${amount_dollars:.2f}, reason='{reason}'"+++if __name__ == "__main__":+ init_db()+ mcp.run(transport="streamable-http", host="127.0.0.1", port=PORT)diff --git a/development/examples/multi-tier-guardrails/policy.json b/development/examples/multi-tier-guardrails/policy.jsonnew file mode 100644index 00000000..2dbbff82--- /dev/null+++ b/development/examples/multi-tier-guardrails/policy.json@@ -0,0 +1,36 @@+{+ "roles": [+ {+ "name": "sam:role:node",+ "allowed_services": [+ "system://sam.catalog",+ "a2a://support.acme",+ "inference://office-llm",+ "mcp://orders-db",+ "egress://api.github.com"+ ],+ "allowed_targets": ["*"],+ "allowed_labels": [+ "env=staging",+ "team=support",+ "team=contractor",+ "site=office",+ "replica=*"+ ],+ "http": [+ {+ "service": "egress://api.github.com",+ "methods": ["GET"],+ "paths": ["/repos/google/sam/pulls*"]+ }+ ]+ }+ ],+ "egress": [+ {+ "name": "api.github.com",+ "credential": "github-ro",+ "served_by": ["site=office"]+ }+ ]+}diff --git a/development/examples/multi-tier-guardrails/record.sh b/development/examples/multi-tier-guardrails/record.shnew file mode 100755index 00000000..9143775d--- /dev/null+++ b/development/examples/multi-tier-guardrails/record.sh@@ -0,0 +1,457 @@+#!/bin/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.++# Records SCRIPT.md for the Multi-Tier Guardrails & Quality Gates example.+# Every config file (node-v1.yaml, node-caller.yaml, node-v2.yaml,+# node-contractor.yaml, policy.json) and every command (sam-node join,+# make node-v1-staging, curl, python3 a2a_client.py, mcp-client,+# sam-one admin ban) is typed directly in the panes — no hidden wrapper+# functions.++set -o errexit+set -o nounset+set -o pipefail++HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)+REPO_ROOT=$(cd "$HERE/../../.." && pwd)+OUT=$HERE/out+SESSION=samguardrails+COLS=${COLS:-190}+ROWS=${ROWS:-54}+SPEED=${SPEED:-1.0}+IDLE_MAX=${IDLE_MAX:-3.0}+CAPTION_CPS=${CAPTION_CPS:-22}+CAPTION_FILE=/tmp/samguardrails-caption.txt+CAPTIONS=$OUT/captions.tsv+SRT=$OUT/demo.srt+WORK_DIR=/tmp/sam-record-guardrails+VENV_DIR=${VENV_DIR:-/tmp/sam-multi-tier-venv}+PYTHON=$VENV_DIR/bin/python+export ORDERS_DB_PATH=$WORK_DIR/orders.db+export LLM_MODEL=${LLM_MODEL:-gemma3:1b}++SAM_ONE=$REPO_ROOT/bin/sam-one+SAM_NODE=$REPO_ROOT/bin/sam-node+MCP_CLIENT=$REPO_ROOT/bin/mcp-client++if [[ ! -x "$SAM_ONE" || ! -x "$SAM_NODE" || ! -x "$MCP_CLIENT" ]]; then+ make -C "$REPO_ROOT" build+fi++if [[ ! -x "$PYTHON" ]]; then+ python3 -m venv "$VENV_DIR"+fi+"$PYTHON" -c "import a2a.server, a2a.client, mcp.server.mcpserver" 2>/dev/null || \+ "$VENV_DIR/bin/pip" install -q -r "$HERE/requirements.txt"++if ! curl -sf http://127.0.0.1:11434/v1/models >/dev/null 2>&1; then+ docker start sam-demo-ollama >/dev/null 2>&1 || \+ docker run -d --name sam-demo-ollama -p 127.0.0.1:11434:11434 -v sam-demo-ollama:/root/.ollama ollama/ollama >/dev/null+ for _ in $(seq 1 30); do curl -sf http://127.0.0.1:11434/ >/dev/null && break; sleep 1; done+ docker exec sam-demo-ollama ollama pull "$LLM_MODEL" >/dev/null+fi++mkdir -p "$OUT"+rm -f "$SRT" "$CAPTIONS"+: > "$CAPTION_FILE"++type_in() {+ local pane=$1 text=$2 i c+ for ((i = 0; i < ${#text}; i++)); do+ c=${text:i:1}+ tmux send-keys -t "$pane" -l -- "$c"+ sleep "0.0$((RANDOM % 4 + 2))"+ done+ sleep 0.4+ tmux send-keys -t "$pane" Enter+ sleep 0.7+}++wait_for() {+ local pane=$1 re=$2 timeout=${3:-60} i+ for ((i = 0; i < timeout * 2; i++)); do+ if tmux capture-pane -J -p -t "$pane" -S -300 | grep -qE -- "$re"; then+ return 0+ fi+ sleep 0.5+ done+ echo "timed out waiting for /$re/ in $pane" >&2+ tmux capture-pane -J -p -t "$pane" -S -40 >&2+ return 1+}++count() {+ tmux capture-pane -J -p -t "$1" -S -300 | grep -cE -- "$2" || true+}++wait_prompt() {+ local pane=$1 timeout=${2:-30} i+ for ((i = 0; i < timeout * 4; i++)); do+ if tmux capture-pane -p -t "$pane" | sed -e :a -e '/^\s*$/{$d;N;ba' -e '}' | tail -1 | grep -qE '\$ ?$'; then+ return 0+ fi+ sleep 0.25+ done+ return 0+}++expect() {+ local pane=$1 cmd=$2 re=$3 timeout=${4:-60} before i+ before=$(count "$pane" "$re")+ type_in "$pane" "$cmd"+ for ((i = 0; i < timeout * 2; i++)); do+ if (( $(count "$pane" "$re") > before )); then+ wait_prompt "$pane"+ return 0+ fi+ sleep 0.5+ done+ echo "timed out waiting for new /$re/ in $pane after: $cmd" >&2+ tmux capture-pane -J -p -t "$pane" -S -40 >&2+ return 1+}++caption() {+ printf '%s\t%s\n' "$(date +%s.%N)" "$1" >> "$CAPTIONS"+ printf '%s\n' "$1" > "$CAPTION_FILE"+ sleep "$(python3 -c 'import sys; print(len(sys.argv[1]) / float(sys.argv[2]) + 1.5)' "$1" "$CAPTION_CPS")"+}++pause() { sleep "${1:-2.5}"; }++cleanup() {+ tmux kill-session -t "$SESSION" 2>/dev/null || true+ tmux kill-session -t "${SESSION}-rec" 2>/dev/null || true+ if [[ -d "$WORK_DIR" ]]; then+ for pidfile in "$WORK_DIR"/*.pid; do+ [[ -f "$pidfile" ]] && kill -9 "$(cat "$pidfile")" 2>/dev/null || true+ done+ rm -rf "$WORK_DIR"+ fi+}+trap cleanup EXIT++cleanup+mkdir -p "$WORK_DIR/secrets"+if [[ -n "${GITHUB_TOKEN_FILE:-}" && -s "${GITHUB_TOKEN_FILE}" ]]; then+ install -m 600 "${GITHUB_TOKEN_FILE}" "$WORK_DIR/secrets/github-ro"+elif command -v gh >/dev/null 2>&1 && gh auth token >/dev/null 2>&1; then+ gh auth token > "$WORK_DIR/secrets/github-ro"+ chmod 600 "$WORK_DIR/secrets/github-ro"+fi++echo "caller-secret" > "$WORK_DIR/caller-api.token"+echo "dev-secret" > "$WORK_DIR/dev-api.token"+echo "dev2-secret" > "$WORK_DIR/dev2-api.token"+echo "contractor-secret" > "$WORK_DIR/contractor-api.token"+chmod 600 "$WORK_DIR"/*.token+printf 'header = "X-Sam-Authentication: Bearer caller-secret"\n' > "$WORK_DIR/.curlrc"++# Start real SQLite MCP server (orders_mcp.py) and LLM-backed A2A agents (support_agent.py)+"$PYTHON" "$HERE/orders_mcp.py" > "$WORK_DIR/orders-mcp.log" 2>&1 &+echo $! > "$WORK_DIR/orders-mcp.pid"++"$PYTHON" "$HERE/support_agent.py" v1-laptop 17771 > "$WORK_DIR/a2a-v1.log" 2>&1 &+echo $! > "$WORK_DIR/a2a-v1.pid"++"$PYTHON" "$HERE/support_agent.py" v2-cloudrun 17772 > "$WORK_DIR/a2a-v2.log" 2>&1 &+echo $! > "$WORK_DIR/a2a-v2.pid"++for _ in $(seq 1 120); do+ if curl -sf http://127.0.0.1:17771/.well-known/agent-card.json >/dev/null && \+ curl -sf http://127.0.0.1:17772/.well-known/agent-card.json >/dev/null; then+ break+ fi+ sleep 0.25+done++# Start sam-one control plane + router in background+CP_URL="http://127.0.0.1:18190"+"$SAM_ONE" \+ --data-dir "$WORK_DIR/one" \+ --port 18190 \+ --policy-file "$HERE/policy.json" \+ --no-join-token \+ --enroll-qr=false \+ --log-level warn > "$WORK_DIR/sam-one.log" 2>&1 &+echo $! > "$WORK_DIR/sam-one.pid"++for _ in $(seq 1 80); do+ if [[ -s "$WORK_DIR/one/admin-token" ]] && curl -sf "$CP_URL/readyz" >/dev/null; then+ break+ fi+ sleep 0.25+done+ADMIN_TOKEN=$(cat "$WORK_DIR/one/admin-token")++mint_tok() {+ "$SAM_ONE" token create --server "$CP_URL" --data-dir "$WORK_DIR/one" \+ --max-usages 1 --description "$1" 2>/dev/null | awk '/^Token:/ {print $2}' > "$2"+ chmod 600 "$2"+}+mint_tok "caller-input-node" "$WORK_DIR/caller.token"+mint_tok "dev-spoof" "$WORK_DIR/dev-spoof.token"+mint_tok "dev-v1-staging" "$WORK_DIR/dev-v1.token"+mint_tok "dev-v1-prod" "$WORK_DIR/dev-v1-prod.token"+mint_tok "cloudrun-v2-prod" "$WORK_DIR/dev-v2.token"+mint_tok "contractor-node" "$WORK_DIR/contractor.token"++# Start Input / Caller Node with node-caller.yaml (egress.require_labels: {env: prod})+"$SAM_NODE" run \+ --control-plane "$CP_URL" --insecure-control-plane \+ --bootstrap-token-path "$WORK_DIR/caller.token" \+ --config "$HERE/node-caller.yaml" \+ --data-dir "$WORK_DIR/node-caller" \+ --bind-addr 127.0.0.1:19102 --socket-path="" \+ --listen "/ip4/127.0.0.1/udp/0/quic-v1,/ip4/127.0.0.1/tcp/0" \+ --api-token-path "$WORK_DIR/caller-api.token" \+ --allow-loopback --control-plane-sync-interval 5s > "$WORK_DIR/node-caller.log" 2>&1 &+echo $! > "$WORK_DIR/node-caller.pid"++# Start Contractor Node with node-contractor.yaml (labels: {team: contractor})+"$SAM_NODE" run \+ --control-plane "$CP_URL" --insecure-control-plane \+ --bootstrap-token-path "$WORK_DIR/contractor.token" \+ --config "$HERE/node-contractor.yaml" \+ --data-dir "$WORK_DIR/node-contractor" \+ --bind-addr 127.0.0.1:19104 --socket-path="" \+ --listen "/ip4/127.0.0.1/udp/0/quic-v1,/ip4/127.0.0.1/tcp/0" \+ --api-token-path "$WORK_DIR/contractor-api.token" \+ --allow-loopback --control-plane-sync-interval 5s > "$WORK_DIR/node-contractor.log" 2>&1 &+echo $! > "$WORK_DIR/node-contractor.pid"++for _ in $(seq 1 40); do+ if grep -q "SAM Node Online" "$WORK_DIR/node-caller.log" 2>/dev/null && \+ grep -q "SAM Node Online" "$WORK_DIR/node-contractor.log" 2>/dev/null; then+ break+ fi+ sleep 0.25+done+CONTRACTOR_PEER=$(awk '/PeerID:/ {print $2; exit}' "$WORK_DIR/node-contractor.log")++# --- tmux window ------------------------------------------------------------++tmux new-session -d -s "$SESSION" -x "$COLS" -y "$ROWS" -c "$HERE"+tmux set -t "$SESSION" -g pane-border-status top+tmux set -t "$SESSION" -g pane-border-format ' #{pane_title} '+tmux set -t "$SESSION" -g status off++NODE=$(tmux display -p -t "$SESSION:0.0" '#{pane_id}')+CAPTION=$(tmux split-window -P -F '#{pane_id}' -v -l 4 -t "$NODE" -c "$HERE")+CALLER=$(tmux split-window -P -F '#{pane_id}' -h -l 54% -t "$NODE" -c "$HERE")+ADMIN=$(tmux split-window -P -F '#{pane_id}' -v -l 18 -t "$NODE" -c "$HERE")++tmux select-pane -t "$NODE" -T 'support node (Alice · node-v1.yaml · gemma3:1b A2A + SQLite MCP + GitHub egress)'+tmux select-pane -t "$ADMIN" -T 'platform & security admin · policy.json & quality gate'+tmux select-pane -t "$CALLER" -T 'input node & caller (node-caller.yaml · curl · a2a_client.py · mcp-client)'+tmux select-pane -t "$CAPTION" -T ''++cat > /tmp/samguardrails-caption.py <<'EOF'+import sys, textwrap, time+path, cols, cps = sys.argv[1], int(sys.argv[2]), float(sys.argv[3])+last = None+while True:+ try:+ text = open(path).read().strip()+ except FileNotFoundError:+ text = ""+ if text != last:+ last = text+ sys.stdout.write("\033[2J\033[H")+ for line in textwrap.wrap(text, cols - 4)[:3]:+ sys.stdout.write(" \033[1m")+ for ch in line:+ sys.stdout.write(ch)+ sys.stdout.flush()+ time.sleep(1 / cps)+ sys.stdout.write("\033[0m\n")+ sys.stdout.flush()+ time.sleep(0.1)+EOF+tmux send-keys -t "$CAPTION" "python3 /tmp/samguardrails-caption.py $CAPTION_FILE $COLS $CAPTION_CPS" Enter++ENV_SETUP="export PATH=$REPO_ROOT/bin:$VENV_DIR/bin:\$PATH CP_URL=$CP_URL ADMIN_TOKEN=$ADMIN_TOKEN WORK_DIR=$WORK_DIR NODE=http://127.0.0.1:19102 SAM_API_TOKEN=caller-secret CONTRACTOR_PEER=$CONTRACTOR_PEER"+tmux send-keys -t "$NODE" "$ENV_SETUP; PS1='node-v1\$ '; clear" Enter+tmux send-keys -t "$ADMIN" "$ENV_SETUP; PS1='admin\$ '; clear" Enter+tmux send-keys -t "$CALLER" "$ENV_SETUP CURL_HOME=$WORK_DIR; PS1='caller\$ '; clear" Enter+wait_for "$NODE" 'node-v1\$' 10+wait_for "$ADMIN" 'admin\$' 10+wait_for "$CALLER" 'caller\$' 10++# --- record -----------------------------------------------------------------++tmux new-session -d -s "${SESSION}-rec" -x "$COLS" -y "$ROWS" \+ "asciinema rec -q --overwrite --cols $COLS --rows $ROWS -c 'tmux attach -t $SESSION' '$OUT/demo.cast'"+sleep 2++caption "Everyone is building AI agents, and every team wants guardrails at its own layer: Developer, Platform/Networking, Central Security, Department Leads, Individual End-Users, and Day-2 Ops."+pause 2.5++# --- Act 1: Developer Onboarding & Label Points 1 and 2a --------------------++caption "Act 1 (Developer Onboarding): Alice writes node-v1.yaml to share her gemma3:1b A2A agent (a2a://support.acme) and SQLite MCP server (mcp://orders-db) in staging (env=staging)."+expect "$NODE" "cat node-v1.yaml" 'attenuation:' 15+pause 2.5++caption "Why can't Alice just put 'env: prod' in node-v1.yaml? Point 1 is Mesh Enforcement (policy.json allowed_labels): the Control Plane rejects ungranted labels at enrollment."+expect "$ADMIN" "jq -c '.roles[0].allowed_labels' policy.json" 'env=staging' 15+expect "$ADMIN" "sed 's/staging/prod/' node-v1.yaml > \$WORK_DIR/node-v1-prod.yaml && sam-node join \$CP_URL --insecure-control-plane --bootstrap-token-path \$WORK_DIR/dev-spoof.token --config \$WORK_DIR/node-v1-prod.yaml --data-dir \$WORK_DIR/spoof" 'Label not permitted' 30+pause 3++caption "Alice starts her node with node-v1.yaml in env=staging. Meanwhile, on the caller side (Point 2a — Input Node Enforcement), node-caller.yaml requires egress.require_labels: env=prod."+type_in "$NODE" "make node-v1-staging 2>&1 | python3 audit.py"+wait_for "$NODE" 'SAM Node Online' 30+V1_STAGING=$(tmux capture-pane -J -p -t "$NODE" -S -50 | awk '/PeerID:/ {print $2; exit}')+tmux send-keys -t "$CALLER" "V1_PEER=$V1_STAGING; clear" Enter+wait_for "$CALLER" 'caller\$' 10+expect "$CALLER" "cat node-caller.yaml" 'env: prod' 15+expect "$CALLER" "curl -i -s \$NODE/sam/\$V1_PEER/a2a/support.acme/.well-known/agent-card.json | head -n 5" '403 Forbidden' 30+pause 3++caption "Now the Automated Quality Gate validates Alice's A2A 1.0 AgentCard and updates policy.json to allow env=prod. Alice restarts in env=prod, and the exact same call returns 200 OK."+expect "$ADMIN" "jq '.roles[0].allowed_labels += [\"env=prod\"]' policy.json | curl -s -X POST \$CP_URL/policies -H \"Authorization: Bearer \$ADMIN_TOKEN\" -H 'Content-Type: application/json' --data @-" 'success' 30+pkill -f "127.0.0.1:19101" 2>/dev/null || true+sleep 0.5+rm -rf "$WORK_DIR/node-v1"+wait_prompt "$NODE"+type_in "$NODE" "make node-v1-prod 2>&1 | python3 audit.py"+wait_for "$NODE" 'SAM Node Online' 30+V1_PROD=$(tmux capture-pane -J -p -t "$NODE" -S -30 | awk '/PeerID:/ {p=$2} END {print p}')+tmux send-keys -t "$CALLER" "V1_PEER=$V1_PROD" Enter+wait_for "$CALLER" 'caller\$' 10+for _ in $(seq 1 20); do+ curl -sf -H "X-Sam-Authentication: Bearer caller-secret" \+ "http://127.0.0.1:19102/sam/$V1_PROD/a2a/support.acme/.well-known/agent-card.json" >/dev/null 2>&1 && break+ sleep 0.5+done+expect "$CALLER" "curl -s \$NODE/sam/\$V1_PEER/a2a/support.acme/.well-known/agent-card.json | jq '{name, url: .supportedInterfaces[0].url}'" 'Acme Support' 30+pause 3++# --- Act 2: Zero-Downtime Replica Swap & Label Point 3 (Agent Intent) -------++caption "Act 2 (Platform / Networking & Point 3 — Agent Intent): Within the Input Node's env=prod floor, the caller passes X-Sam-Required-Labels: replica=v1-laptop on Turn 1."+expect "$CALLER" "python3 a2a_client.py \$NODE/sam/\$V1_PEER/a2a/support.acme ctx-acme-1042 'Check order #1042 for [email protected]' replica=v1-laptop" 'v1-laptop' 45+pause 3++caption "A Cloud Run replica (node-v2.yaml, replica=v2-cloudrun) joins the mesh. On Turn 2, the caller passes X-Sam-Required-Labels: replica=v2-cloudrun and keeps full conversation context."+expect "$CALLER" "cat node-v2.yaml" 'v2-cloudrun' 15+"$SAM_NODE" run \+ --control-plane "$CP_URL" --insecure-control-plane \+ --bootstrap-token-path "$WORK_DIR/dev-v2.token" --config "$HERE/node-v2.yaml" \+ --data-dir "$WORK_DIR/node-v2" --bind-addr 127.0.0.1:19103 --socket-path="" \+ --listen "/ip4/127.0.0.1/udp/0/quic-v1,/ip4/127.0.0.1/tcp/0" \+ --api-token-path "$WORK_DIR/dev2-api.token" --allow-loopback --control-plane-sync-interval 5s > "$WORK_DIR/node-v2.log" 2>&1 &+echo $! > "$WORK_DIR/node-v2.pid"+for _ in $(seq 1 40); do+ grep -q "SAM Node Online" "$WORK_DIR/node-v2.log" 2>/dev/null && break+ sleep 0.25+done+V2_PEER=$(awk '/PeerID:/ {print $2; exit}' "$WORK_DIR/node-v2.log")+for _ in $(seq 1 20); do+ curl -sf -H "X-Sam-Authentication: Bearer caller-secret" \+ "http://127.0.0.1:19102/sam/$V2_PEER/a2a/support.acme/.well-known/agent-card.json" >/dev/null 2>&1 && break+ sleep 0.5+done+tmux send-keys -t "$CALLER" "V2_PEER=$V2_PEER" Enter+wait_for "$CALLER" 'caller\$' 10+expect "$CALLER" "python3 a2a_client.py \$NODE/sam/\$V2_PEER/a2a/support.acme ctx-acme-1042 'What item did Alice order and has it shipped?' replica=v2-cloudrun" 'v2-cloudrun' 60+pause 3++# --- Act 3: 3-Tier Guardrails -----------------------------------------------++caption "Act 3, Layer 1 (Central Security): policy.json grants GET /repos/google/sam/pulls* on egress://api.github.com and injects secrets/github-ro. POST is blocked with 403."+expect "$ADMIN" "jq -c '.roles[0].http[0], .egress[0]' policy.json" 'github-ro' 15+expect "$CALLER" "curl -s \"\$NODE/sam/\$V1_PEER/egress/api.github.com/repos/google/sam/pulls?state=open&per_page=1\" | jq -c '.[0] | {number, title}'" 'number' 30+expect "$CALLER" "curl -i -s -X POST \$NODE/sam/\$V1_PEER/egress/api.github.com/repos/google/sam/pulls -d '{}' | head -n 5" '403 Forbidden' 30+pause 3++caption "Act 3, Layer 2 (Department Lead — Point 2b, Egress Node Label Check): node-v1.yaml requires positive 'check if label(\"team\", \"support\")', so node-contractor.yaml (team=contractor) is rejected."+expect "$ADMIN" "cat node-contractor.yaml" 'team: contractor' 15+expect "$CALLER" "mcp-client -url http://127.0.0.1:19104/mcp -token contractor-secret -tool call_remote_tool -args '{\"peer_id\":\"'\$V1_PEER'\",\"tool_name\":\"mcp://orders-db/get_order_status\",\"arguments\":{\"order_id\":\"1042\"}}'" 'check if label' 30+pause 3++caption "Act 3, Layer 3 (Individual User): RFC 8693 POST /oauth/token mints a sealed Task Biscuit scoped only to tool:get_order_status. get_order_status succeeds; a \$5,000 issue_refund is blocked."+expect "$CALLER" "TASK_BISCUIT=\$(curl -s -X POST \$NODE/oauth/token -H 'Authorization: Bearer caller-secret' -d 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange&resource=mcp://orders-db&scope=tool:get_order_status&seal=true' | jq -r .access_token) && echo \"TASK_BISCUIT=\${TASK_BISCUIT:0:36}...\"" 'TASK_BISCUIT=' 20+expect "$CALLER" "mcp-client -url \$NODE/mcp -token \$TASK_BISCUIT -tool call_remote_tool -args '{\"peer_id\":\"'\$V1_PEER'\",\"tool_name\":\"mcp://orders-db/get_order_status\",\"arguments\":{\"order_id\":\"1042\"}}'" 'Mechanical Keyboard Pro' 30+expect "$CALLER" "mcp-client -url \$NODE/mcp -token \$TASK_BISCUIT -tool call_remote_tool -args '{\"peer_id\":\"'\$V1_PEER'\",\"tool_name\":\"mcp://orders-db/issue_refund\",\"arguments\":{\"order_id\":\"1042\",\"amount_dollars\":5000}}'" 'task authorization denied' 30+pause 3.5++# --- Act 4: Day-2 Ops & Ban -------------------------------------------------++caption "Act 4 (Day-2 Operations): Every ALLOW and DENY across all three layers is logged in the left pane. Finally, the admin bans the contractor peer with sam-one admin ban."+expect "$ADMIN" "sam-one admin ban \$CONTRACTOR_PEER --server \$CP_URL --data-dir \$WORK_DIR/one" 'banned' 30+pause 3.5++caption "sam-mesh.dev"+pause 3++END=$(date +%s.%N)+tmux kill-session -t "$SESSION"+for _ in $(seq 1 30); do tmux has-session -t "${SESSION}-rec" 2>/dev/null || break; sleep 0.5; done++# --- render -----------------------------------------------------------------++python3 - "$OUT/demo.cast" "$CAPTIONS" "$SRT" "$END" "$IDLE_MAX" "$SPEED" <<'EOF'+import bisect, json, sys+cast, captions, srt, end, idle_max, speed = sys.argv[1], sys.argv[2], sys.argv[3], float(sys.argv[4]), float(sys.argv[5]), float(sys.argv[6])+lines = open(cast).read().splitlines()+header = json.loads(lines[0])+events = [json.loads(l) for l in lines[1:]]+caps = [(float(w), text) for w, text in (l.split("\t", 1) for l in open(captions).read().splitlines())]+first_typing = next((e[0] for prev, e in zip([[0.0]] + events, events) if e[0] - prev[0] > 0.8 and e[0] < 10), 1.0)+t0 = caps[0][0] - first_typing+events = [e for e in events if e[0] <= end - t0 - 0.2]++knots_old, knots_new = [], []+prev_old = prev_new = 0.0+for e in events:+ prev_new += min(e[0] - prev_old, idle_max)+ prev_old = e[0]+ knots_old.append(prev_old)+ knots_new.append(prev_new)+ e[0] = round(prev_new, 6)++def remap(t):+ i = bisect.bisect_right(knots_old, t) - 1+ if i < 0:+ return 0.0+ return knots_new[i] + min(t - knots_old[i], idle_max)++def stamp(t):+ t = max(t, 0) / speed+ h, m, s = int(t // 3600), int(t % 3600 // 60), t % 60+ return f"{h:02d}:{m:02d}:{int(s):02d},{int((s - int(s)) * 1000):03d}"++caps = [(w - t0, text) for w, text in caps]+last = (events[-1][0] if events else 0.0) + idle_max+with open(srt, "w") as out:+ for i, (t, text) in enumerate(caps):+ stop = remap(caps[i + 1][0]) if i + 1 < len(caps) else last+ out.write(f"{i + 1}\n{stamp(remap(t))} --> {stamp(stop)}\n{text}\n\n")+with open(cast, "w") as out:+ out.write(json.dumps(header) + "\n")+ for e in events:+ out.write(json.dumps(e) + "\n")+print(f"take {knots_old[-1]:.0f}s, cut to {last:.0f}s, plays in {last / speed:.0f}s")+EOF++agg --cols "$COLS" --rows "$ROWS" --font-size 16 --idle-time-limit 30 --speed "$SPEED" --last-frame-duration 3 "$OUT/demo.cast" "$OUT/demo.gif"+ffmpeg -y -loglevel error -i "$OUT/demo.gif" \+ -movflags faststart -pix_fmt yuv420p \+ -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" \+ "$OUT/demo.mp4"++cp "$OUT/demo.mp4" "$REPO_ROOT/site/static/demo-multi-tier-guardrails.mp4"+echo "recorded and published: $REPO_ROOT/site/static/demo-multi-tier-guardrails.mp4"diff --git a/development/examples/multi-tier-guardrails/requirements.txt b/development/examples/multi-tier-guardrails/requirements.txtnew file mode 100644index 00000000..873af4b9--- /dev/null+++ b/development/examples/multi-tier-guardrails/requirements.txt@@ -0,0 +1,6 @@+a2a-sdk>=1.1.5+httpx>=0.28.1+mcp>=2.1.1+sse-starlette>=3.4.5+starlette>=1.3.1+uvicorn>=0.40.0diff --git a/development/examples/multi-tier-guardrails/run.sh b/development/examples/multi-tier-guardrails/run.shnew file mode 100755index 00000000..418b28a7--- /dev/null+++ b/development/examples/multi-tier-guardrails/run.sh@@ -0,0 +1,449 @@+#!/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.++# Multi-Tier Guardrails & Quality Gates — End-to-End 5-Persona Runner+#+# Demonstrates how SAM serves all 5 enterprise personas across 4 acts with real+# backends (Ollama gemma3:1b, official a2a-sdk, official mcp SDK + SQLite, and+# https://api.github.com), while clarifying the 3 points where labels are used:+# 1. Mesh Enforcement (policy.json allowed_labels): Control Plane attests+# which labels a node is permitted to claim at enrollment.+# 2. Node Enforcement (node-caller.yaml egress.require_labels & node-v1.yaml+# attenuation.checks): Input and Egress node admins enforce mandatory+# outbound and inbound label constraints.+# 3. End-User / Agent Intent (X-Sam-Required-Labels): Calling agents/users+# express which replica or capability they want within admin constraints.++set -euo pipefail++INTERACTIVE=0+if [[ "${1:-}" == "--interactive" ]]; then+ INTERACTIVE=1+fi++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)"+SAM_ONE="${REPO_ROOT}/bin/sam-one"+SAM_NODE="${REPO_ROOT}/bin/sam-node"+MCP_CLIENT="${REPO_ROOT}/bin/mcp-client"+WORK_DIR="${WORK_DIR:-$(mktemp -d /tmp/sam-multi-tier-XXXXXX)}"+VENV_DIR="${VENV_DIR:-/tmp/sam-multi-tier-venv}"+PYTHON="${VENV_DIR}/bin/python"+export ORDERS_DB_PATH="${WORK_DIR}/orders.db"+export LLM_MODEL="${LLM_MODEL:-gemma3:1b}"++step_pause() {+ if [[ "${INTERACTIVE}" -eq 1 ]]; then+ echo ""+ read -r -p " [Press ENTER to continue to the next step...] " _+ echo ""+ fi+}++cleanup() {+ for pidfile in "${WORK_DIR}"/*.pid; do+ [[ -f "${pidfile}" ]] && kill -9 "$(cat "${pidfile}")" 2>/dev/null || true+ done+ if [[ "${KEEP_WORK_DIR:-0}" != "1" ]]; then+ rm -rf "${WORK_DIR}"+ fi+}+trap cleanup EXIT++if [[ ! -x "${SAM_ONE}" || ! -x "${SAM_NODE}" || ! -x "${MCP_CLIENT}" ]]; then+ echo "Building sam-one, sam-node, and mcp-client..."+ make -C "${REPO_ROOT}" build+fi++if [[ ! -x "${PYTHON}" ]]; then+ python3 -m venv "${VENV_DIR}"+fi+"${PYTHON}" -c "import a2a.server, a2a.client, mcp.server.mcpserver" 2>/dev/null || \+ "${VENV_DIR}/bin/pip" install -q -r "${SCRIPT_DIR}/requirements.txt"++if [[ "${LLM_BASE_URL:-http://127.0.0.1:11434/v1}" == "http://127.0.0.1:11434/v1" ]]; then+ if ! curl -sf http://127.0.0.1:11434/v1/models >/dev/null 2>&1; then+ docker start sam-demo-ollama >/dev/null 2>&1 || \+ docker run -d --name sam-demo-ollama -p 127.0.0.1:11434:11434 -v sam-demo-ollama:/root/.ollama ollama/ollama >/dev/null+ for _ in $(seq 1 30); do curl -sf http://127.0.0.1:11434/ >/dev/null && break; sleep 1; done+ docker exec sam-demo-ollama ollama pull "${LLM_MODEL}" >/dev/null+ fi+fi++mkdir -p "${WORK_DIR}/secrets"++if [[ -n "${GITHUB_TOKEN_FILE:-}" && -s "${GITHUB_TOKEN_FILE}" ]]; then+ install -m 600 "${GITHUB_TOKEN_FILE}" "${WORK_DIR}/secrets/github-ro"+elif command -v gh >/dev/null 2>&1 && gh auth token >/dev/null 2>&1; then+ gh auth token > "${WORK_DIR}/secrets/github-ro"+ chmod 600 "${WORK_DIR}/secrets/github-ro"+else+ echo "ERROR: Set GITHUB_TOKEN_FILE or authenticate 'gh auth login' for egress://api.github.com" >&2+ exit 1+fi++echo "1) Starting real SQLite MCP server (orders_mcp.py) and LLM-backed A2A replicas (support_agent.py, model=${LLM_MODEL})..."+"${PYTHON}" "${SCRIPT_DIR}/orders_mcp.py" >"${WORK_DIR}/orders-mcp.log" 2>&1 &+echo $! > "${WORK_DIR}/orders-mcp.pid"++"${PYTHON}" "${SCRIPT_DIR}/support_agent.py" v1-laptop 17771 >"${WORK_DIR}/a2a-v1.log" 2>&1 &+echo $! > "${WORK_DIR}/a2a-v1.pid"++"${PYTHON}" "${SCRIPT_DIR}/support_agent.py" v2-cloudrun 17772 >"${WORK_DIR}/a2a-v2.log" 2>&1 &+echo $! > "${WORK_DIR}/a2a-v2.pid"++for _ in $(seq 1 120); do+ if curl -sf http://127.0.0.1:17771/.well-known/agent-card.json >/dev/null && \+ curl -sf http://127.0.0.1:17772/.well-known/agent-card.json >/dev/null; then+ break+ fi+ sleep 0.25+done++CP_PORT=18090+CP_URL="http://127.0.0.1:${CP_PORT}"+"${SAM_ONE}" \+ --data-dir "${WORK_DIR}/one" \+ --port "${CP_PORT}" \+ --policy-file "${SCRIPT_DIR}/policy.json" \+ --no-join-token \+ --enroll-qr=false \+ --log-level info >"${WORK_DIR}/sam-one.log" 2>&1 &+echo $! > "${WORK_DIR}/sam-one.pid"++for _ in $(seq 1 80); do+ if [[ -s "${WORK_DIR}/one/admin-token" ]] && curl -sf "${CP_URL}/readyz" >/dev/null; then+ break+ fi+ sleep 0.25+done+ADMIN_TOKEN="$(cat "${WORK_DIR}/one/admin-token")"++echo "caller-secret" > "${WORK_DIR}/caller-api.token"+echo "dev-secret" > "${WORK_DIR}/dev-api.token"+echo "dev2-secret" > "${WORK_DIR}/dev2-api.token"+echo "contractor-secret" > "${WORK_DIR}/contractor-api.token"+chmod 600 "${WORK_DIR}"/*.token++create_bootstrap_token() {+ local desc="$1"+ local out="$2"+ "${SAM_ONE}" token create \+ --server "${CP_URL}" \+ --data-dir "${WORK_DIR}/one" \+ --max-usages 1 \+ --description "${desc}" 2>/dev/null | awk '/^Token:/ {print $2}' > "${out}"+ chmod 600 "${out}"+}++create_bootstrap_token "caller-input-node" "${WORK_DIR}/caller.token"+create_bootstrap_token "dev-laptop-v1-spoof" "${WORK_DIR}/dev-spoof.token"+create_bootstrap_token "dev-laptop-v1-staging" "${WORK_DIR}/dev-v1.token"+create_bootstrap_token "cloudrun-v2-prod" "${WORK_DIR}/dev-v2.token"+create_bootstrap_token "contractor-node" "${WORK_DIR}/contractor.token"++# Start Input / Caller Node with node-caller.yaml (egress.require_labels: {env: prod})+"${SAM_NODE}" run \+ --control-plane "${CP_URL}" \+ --insecure-control-plane \+ --bootstrap-token-path "${WORK_DIR}/caller.token" \+ --config "${SCRIPT_DIR}/node-caller.yaml" \+ --data-dir "${WORK_DIR}/node-caller" \+ --bind-addr 127.0.0.1:19002 \+ --socket-path="" \+ --listen "/ip4/127.0.0.1/udp/0/quic-v1,/ip4/127.0.0.1/tcp/0" \+ --api-token-path "${WORK_DIR}/caller-api.token" \+ --allow-loopback \+ --control-plane-sync-interval 5s >"${WORK_DIR}/node-caller.log" 2>&1 &+echo $! > "${WORK_DIR}/node-caller.pid"++echo ""+echo "================================================================================"+echo " ACT 1: Developer Onboarding into Quarantine (env=staging) + Automated Quality Gate"+echo " (Personas: Agent Developer Alice + Central Security / Platform)"+echo "================================================================================"+echo ""+echo "--> Alice (Developer) enrolls her node in staging quarantine (env=staging, team=support)..."+"${SAM_NODE}" run \+ --control-plane "${CP_URL}" \+ --insecure-control-plane \+ --bootstrap-token-path "${WORK_DIR}/dev-v1.token" \+ --config "${SCRIPT_DIR}/node-v1.yaml" \+ --secrets-dir "${WORK_DIR}/secrets" \+ --data-dir "${WORK_DIR}/node-v1" \+ --bind-addr 127.0.0.1:19001 \+ --socket-path="" \+ --listen "/ip4/127.0.0.1/udp/0/quic-v1,/ip4/127.0.0.1/tcp/0" \+ --api-token-path "${WORK_DIR}/dev-api.token" \+ --allow-loopback \+ --control-plane-sync-interval 5s >"${WORK_DIR}/node-v1.log" 2>&1 &+echo $! > "${WORK_DIR}/node-v1.pid"++V1_PEER=""+for _ in $(seq 1 40); do+ DISC="$(curl -sf -H "X-Sam-Authentication: Bearer caller-secret" \+ "http://127.0.0.1:19002/sam/service/discover?type=a2a&name=support.acme" 2>/dev/null || true)"+ V1_PEER="$(echo "${DISC}" | jq -r '.[0].peer_id // empty' 2>/dev/null || true)"+ if [[ -n "${V1_PEER}" ]]; then+ break+ fi+ sleep 0.5+done+echo " Discovered Alice's node PeerID via DHT/GossipSub: ${V1_PEER}"++echo ""+echo "--> Why can't Alice just set 'env: prod' in her node YAML, or the caller skip the check?"+echo " [Label Point 1 — Mesh Enforcement (policy.json allowed_labels)]:"+sed 's/env: staging/env: prod/' "${SCRIPT_DIR}/node-v1.yaml" > "${WORK_DIR}/node-v1-prod.yaml"+set +e+SPOOF_OUT="$("${SAM_NODE}" join "${CP_URL}" \+ --insecure-control-plane \+ --bootstrap-token-path "${WORK_DIR}/dev-spoof.token" \+ --config "${WORK_DIR}/node-v1-prod.yaml" \+ --data-dir "${WORK_DIR}/node-spoof" 2>&1)"+set -e+echo " Self-asserting env=prod before Quality Gate -> $(echo "${SPOOF_OUT}" | grep -oE 'Label not permitted.*' || echo "${SPOOF_OUT}" | tail -n 1)"++echo " [Label Point 2a — Input Node Enforcement (node-caller.yaml egress.require_labels: {env: prod})]:"+HTTP_CODE="$(curl -s -o "${WORK_DIR}/act1-prod-check.out" -w '%{http_code}' \+ -H "X-Sam-Authentication: Bearer caller-secret" \+ "http://127.0.0.1:19002/sam/${V1_PEER}/a2a/support.acme/.well-known/agent-card.json")"+echo " Plain app call (even with NO X-Sam-Required-Labels header) -> HTTP ${HTTP_CODE} — $(cat "${WORK_DIR}/act1-prod-check.out")"+step_pause++echo ""+echo "--> Running Automated Quality Gate: validating A2A 1.0 schema in staging & promoting policy to allow env=prod..."+STAGING_CARD="$(curl -sf "http://127.0.0.1:17771/.well-known/agent-card.json")"+echo " Staging A2A Card Validated: name='$(echo "${STAGING_CARD}" | jq -r '.name')', description='$(echo "${STAGING_CARD}" | jq -r '.description')'"++jq '.roles[0].allowed_labels += ["env=prod"]' "${SCRIPT_DIR}/policy.json" > "${WORK_DIR}/policy-prod.json"+curl -sf -X POST "${CP_URL}/policies" \+ -H "Authorization: Bearer ${ADMIN_TOKEN}" \+ -H "Content-Type: application/json" \+ --data @"${WORK_DIR}/policy-prod.json" >/dev/null++kill -9 "$(cat "${WORK_DIR}/node-v1.pid")" 2>/dev/null || true+rm -rf "${WORK_DIR}/node-v1"+create_bootstrap_token "dev-laptop-v1-prod" "${WORK_DIR}/dev-v1.token"++"${SAM_NODE}" run \+ --control-plane "${CP_URL}" \+ --insecure-control-plane \+ --bootstrap-token-path "${WORK_DIR}/dev-v1.token" \+ --config "${WORK_DIR}/node-v1-prod.yaml" \+ --secrets-dir "${WORK_DIR}/secrets" \+ --data-dir "${WORK_DIR}/node-v1" \+ --bind-addr 127.0.0.1:19001 \+ --socket-path="" \+ --listen "/ip4/127.0.0.1/udp/0/quic-v1,/ip4/127.0.0.1/tcp/0" \+ --api-token-path "${WORK_DIR}/dev-api.token" \+ --allow-loopback \+ --control-plane-sync-interval 5s >>"${WORK_DIR}/node-v1.log" 2>&1 &+echo $! > "${WORK_DIR}/node-v1.pid"++V1_STAGING_PEER="${V1_PEER}"+V1_PROD_PEER=""+for _ in $(seq 1 40); do+ DISC="$(curl -sf -H "X-Sam-Authentication: Bearer caller-secret" \+ "http://127.0.0.1:19002/sam/service/discover?type=a2a&name=support.acme" 2>/dev/null || true)"+ for p in $(echo "${DISC}" | jq -r '.[].peer_id // empty' 2>/dev/null || true); do+ if [[ "${p}" != "${V1_STAGING_PEER}" ]]; then+ V1_PROD_PEER="${p}"+ break 2+ fi+ done+ sleep 0.5+done+V1_PEER="${V1_PROD_PEER}"+echo " Promoted Production PeerID (attested env=prod): ${V1_PEER}"++echo ""+echo "--> Retrying the exact same production call now that Quality Gate promoted Alice's node to env=prod..."+for _ in $(seq 1 20); do+ HTTP_CODE_AFTER="$(curl -s -o "${WORK_DIR}/act1-prod-after.out" -w '%{http_code}' \+ -H "X-Sam-Authentication: Bearer caller-secret" \+ "http://127.0.0.1:19002/sam/${V1_PEER}/a2a/support.acme/.well-known/agent-card.json")"+ [[ "${HTTP_CODE_AFTER}" == "200" ]] && break+ sleep 0.5+done+echo " Result after Quality Gate: HTTP ${HTTP_CODE_AFTER} OK!"+echo " Rewritten Mesh A2A Interface URL: $(jq -r '.supportedInterfaces[0].url' "${WORK_DIR}/act1-prod-after.out")"+step_pause++echo ""+echo "================================================================================"+echo " ACT 2: Cross-Network A2A Routing & Zero-Downtime Replica Swap (Laptop v1 -> Cloud Run v2)"+echo " (Persona: Platform / Networking + Label Point 3: End-User/Agent Intent)"+echo "================================================================================"+echo ""+echo "--> [Label Point 3 — End-User/Agent Intent (X-Sam-Required-Labels)]:"+echo " Within the Input Node's mandatory env=prod floor, the calling agent passes"+echo " 'X-Sam-Required-Labels: replica=v1-laptop' on Turn 1 to express replica intent:"+TURN1_REPLY="$(SAM_API_TOKEN=caller-secret "${PYTHON}" "${SCRIPT_DIR}/a2a_client.py" \+ "http://127.0.0.1:19002/sam/${V1_PEER}/a2a/support.acme" \+ "ctx-acme-1042" \+ "Check order #1042 for [email protected] and tell me the item and status." \+ "replica=v1-laptop")"+echo " Turn 1 Reply: ${TURN1_REPLY}"++echo ""+echo "--> Starting Cloud Run v2 replica serving a2a://support.acme (env=prod, replica=v2-cloudrun)..."+"${SAM_NODE}" run \+ --control-plane "${CP_URL}" \+ --insecure-control-plane \+ --bootstrap-token-path "${WORK_DIR}/dev-v2.token" \+ --config "${SCRIPT_DIR}/node-v2.yaml" \+ --data-dir "${WORK_DIR}/node-v2" \+ --bind-addr 127.0.0.1:19003 \+ --socket-path="" \+ --listen "/ip4/127.0.0.1/udp/0/quic-v1,/ip4/127.0.0.1/tcp/0" \+ --api-token-path "${WORK_DIR}/dev2-api.token" \+ --allow-loopback \+ --control-plane-sync-interval 5s >"${WORK_DIR}/node-v2.log" 2>&1 &+echo $! > "${WORK_DIR}/node-v2.pid"++V2_PEER=""+for _ in $(seq 1 40); do+ DISC="$(curl -sf -H "X-Sam-Authentication: Bearer caller-secret" \+ "http://127.0.0.1:19002/sam/service/discover?type=a2a&name=support.acme" 2>/dev/null || true)"+ for p in $(echo "${DISC}" | jq -r '.[].peer_id // empty' 2>/dev/null || true); do+ if [[ "${p}" != "${V1_PEER}" && "${p}" != "${V1_STAGING_PEER}" ]]; then+ V2_PEER="${p}"+ break 2+ fi+ done+ sleep 0.5+done+echo " Discovered Cloud Run v2 PeerID: ${V2_PEER}"++echo ""+echo "--> Sending Turn 2 (preserving contextId=ctx-acme-1042) with 'X-Sam-Required-Labels: replica=v2-cloudrun'..."+TURN2_REPLY="$(SAM_API_TOKEN=caller-secret "${PYTHON}" "${SCRIPT_DIR}/a2a_client.py" \+ "http://127.0.0.1:19002/sam/${V2_PEER}/a2a/support.acme" \+ "ctx-acme-1042" \+ "Based on our previous turn, what item did Alice order and has it shipped?" \+ "replica=v2-cloudrun")"+echo " Turn 2 Reply: ${TURN2_REPLY}"+step_pause++echo ""+echo "================================================================================"+echo " ACT 3: 3-Tier Guardrails (Central Security + Department Local Veto + User Per-Task tar_block)"+echo " (Personas: Central Security, Department Lead, and Individual End-User)"+echo "================================================================================"+echo ""+echo "--> [Layer 1: Central Security Org Policy + Secret Broker] Calling real egress://api.github.com..."+GH_ALLOW="$(curl -sf -H "X-Sam-Authentication: Bearer caller-secret" \+ -H "Accept: application/vnd.github+json" \+ -H "User-Agent: sam-multi-tier-demo" \+ "http://127.0.0.1:19002/sam/${V1_PEER}/egress/api.github.com/repos/google/sam/pulls?state=open&per_page=1")"+PR_SUMMARY="$(echo "${GH_ALLOW}" | jq -r 'if type=="array" and length>0 then "#\(.[0].number) \(.[0].title)" else "200 OK (open PRs queried)" end')"+echo " Allowed Path (GET /repos/google/sam/pulls): HTTP 200 OK — ${PR_SUMMARY} (node injected secrets/github-ro)"++GH_DENY_CODE="$(curl -s -o "${WORK_DIR}/gh-deny.out" -w '%{http_code}' \+ -X POST \+ -H "X-Sam-Authentication: Bearer caller-secret" \+ -H "Accept: application/vnd.github+json" \+ -H "User-Agent: sam-multi-tier-demo" \+ "http://127.0.0.1:19002/sam/${V1_PEER}/egress/api.github.com/repos/google/sam/pulls" \+ -d '{}')"+echo " Forbidden Path (POST /repos/google/sam/pulls): HTTP ${GH_DENY_CODE} — blocked by Block 0 Org HTTP Policy before GitHub hears of it!"++echo ""+echo "--> [Layer 2: Department Lead Local Node Enforcement (Label Point 2b: Egress/Provider Node)]"+echo " Support Dept's node-v1.yaml requires positive 'check if label(\"team\", \"support\")'."+echo " Contractor node (attested team=contractor) attempts to call mcp://orders-db..."+"${SAM_NODE}" run \+ --control-plane "${CP_URL}" \+ --insecure-control-plane \+ --bootstrap-token-path "${WORK_DIR}/contractor.token" \+ --config "${SCRIPT_DIR}/node-contractor.yaml" \+ --data-dir "${WORK_DIR}/node-contractor" \+ --bind-addr 127.0.0.1:19004 \+ --socket-path="" \+ --listen "/ip4/127.0.0.1/udp/0/quic-v1,/ip4/127.0.0.1/tcp/0" \+ --api-token-path "${WORK_DIR}/contractor-api.token" \+ --allow-loopback \+ --control-plane-sync-interval 5s >"${WORK_DIR}/node-contractor.log" 2>&1 &+echo $! > "${WORK_DIR}/node-contractor.pid"++for _ in $(seq 1 30); do+ grep -q "SAM Node Online" "${WORK_DIR}/node-contractor.log" 2>/dev/null && break+ sleep 0.25+done+CONTRACTOR_PEER="$(awk '/PeerID:/ {print $2; exit}' "${WORK_DIR}/node-contractor.log")"++set +e+CONTRACTOR_OUT="$("${MCP_CLIENT}" \+ -url "http://127.0.0.1:19004/mcp" \+ -token "contractor-secret" \+ -tool "call_remote_tool" \+ -args "{\"peer_id\":\"${V1_PEER}\",\"tool_name\":\"mcp://orders-db/get_order_status\",\"arguments\":{\"order_id\":\"1042\"}}" 2>&1)"+set -e+echo " Contractor Call Result (Org Policy=ALLOW, Dept Egress-Node Label Check=DENY):"+echo " $(echo "${CONTRACTOR_OUT}" | tail -n 1)"++echo ""+echo "--> [Layer 3: Individual User Per-Task Biscuit Attenuation (tar_block)]"+echo " Minting a sealed Task Biscuit via RFC 8693 POST /oauth/token scoped ONLY to tool:get_order_status..."+TOKEN_RESP="$(curl -sf -X POST "http://127.0.0.1:19002/oauth/token" \+ -H "Authorization: Bearer caller-secret" \+ -H "Content-Type: application/x-www-form-urlencoded" \+ --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \+ --data-urlencode "resource=mcp://orders-db" \+ --data-urlencode "scope=tool:get_order_status" \+ --data-urlencode "seal=true")"+TASK_BISCUIT="$(echo "${TOKEN_RESP}" | jq -r '.access_token')"+echo " Issued Sealed Task Biscuit (first 36 chars): ${TASK_BISCUIT:0:36}..."++echo " 1) Legitimate SQLite MCP tool call (get_order_status) using the narrowed Task Biscuit:"+ALLOW_TOOL_OUT="$("${MCP_CLIENT}" \+ -url "http://127.0.0.1:19002/mcp" \+ -token "${TASK_BISCUIT}" \+ -tool "call_remote_tool" \+ -args "{\"peer_id\":\"${V1_PEER}\",\"tool_name\":\"mcp://orders-db/get_order_status\",\"arguments\":{\"order_id\":\"1042\"}}" 2>&1)"+echo " $(echo "${ALLOW_TOOL_OUT}" | tr '\n' ' ')"++echo " 2) Prompt-Injection Exploit attempt (calling issue_refund for \$5,000) using the SAME Task Biscuit:"+set +e+DENY_TOOL_OUT="$("${MCP_CLIENT}" \+ -url "http://127.0.0.1:19002/mcp" \+ -token "${TASK_BISCUIT}" \+ -tool "call_remote_tool" \+ -args "{\"peer_id\":\"${V1_PEER}\",\"tool_name\":\"mcp://orders-db/issue_refund\",\"arguments\":{\"order_id\":\"1042\",\"amount_dollars\":5000}}" 2>&1)"+set -e+echo " BLOCKED MID-FLIGHT: $(echo "${DENY_TOOL_OUT}" | tail -n 1)"+REFUND_COUNT="$("${PYTHON}" -c "import sqlite3; print(sqlite3.connect('${ORDERS_DB_PATH}').execute('SELECT COUNT(*) FROM refunds').fetchone()[0])")"+echo " SQLite verification: SELECT COUNT(*) FROM refunds => ${REFUND_COUNT} (database untouched!)"+step_pause++echo ""+echo "================================================================================"+echo " ACT 4: Day-2 Operations — Correlated Audit Receipts & Instant Kill-Switch"+echo " (Persona: Day-2 Operations / SRE)"+echo "================================================================================"+echo ""+echo "--> Hosting Node (node-v1) Structured Audit Trail (python3 audit.py):"+"${PYTHON}" "${SCRIPT_DIR}/audit.py" < "${WORK_DIR}/node-v1.log" | sed 's/^/ /'++echo ""+echo "--> Executing Instant Kill-Switch: banning contractor PeerID via sam-one admin ban..."+BAN_OUT="$("${SAM_ONE}" admin ban "${CONTRACTOR_PEER}" --server "${CP_URL}" --data-dir "${WORK_DIR}/one" 2>&1)"+echo " ${BAN_OUT}"++echo ""+echo "================================================================================"+echo " ALL 4 ACTS COMPLETED SUCCESSFULLY!"+echo "================================================================================"diff --git a/development/examples/multi-tier-guardrails/support_agent.py b/development/examples/multi-tier-guardrails/support_agent.pynew file mode 100755index 00000000..3be8579d--- /dev/null+++ b/development/examples/multi-tier-guardrails/support_agent.py@@ -0,0 +1,198 @@+#!/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.++"""LLM-backed A2A Support Agent using the official a2a-sdk and Ollama/OpenAI API.++Maintains conversation history per A2A contextId in SQLite so that when traffic+shifts across replicas (e.g. from laptop v1 to Cloud Run v2), the conversation+context survives seamlessly across the mesh hop.+"""++import json+import os+import sqlite3+import sys++import httpx+import uvicorn+from a2a.helpers.proto_helpers import new_task+from a2a.server.agent_execution.agent_executor import AgentExecutor+from a2a.server.agent_execution.context import RequestContext+from a2a.server.events.event_queue import EventQueue+from a2a.server.request_handlers import DefaultRequestHandler+from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes+from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore+from a2a.server.tasks.task_updater import TaskUpdater+from a2a.types import (+ AgentCapabilities,+ AgentCard,+ AgentInterface,+ AgentSkill,+ Part,+ TaskState,+)+from starlette.applications import Starlette++REPLICA_ID = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("REPLICA_ID", "v1-laptop")+PORT = int(sys.argv[2]) if len(sys.argv) > 2 else int(os.environ.get("PORT", "17771"))+DB_PATH = os.environ.get("ORDERS_DB_PATH", "/tmp/sam-multi-tier-orders.db")+LLM_BASE_URL = os.environ.get("LLM_BASE_URL", "http://127.0.0.1:11434/v1")+LLM_API_KEY = os.environ.get("LLM_API_KEY", "ollama")+LLM_MODEL = os.environ.get("LLM_MODEL", "gemma3:1b")++SYSTEM_PROMPT = (+ "You are the Acme Support & Refund Triage Agent. "+ "Answer the customer's question concisely in one or two short sentences using the "+ "Order Database Snapshot provided. Keep previous turns in mind."+)+++def init_history_db() -> None:+ with sqlite3.connect(DB_PATH) as conn:+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS chat_history (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ context_id TEXT NOT NULL,+ role TEXT NOT NULL,+ content TEXT NOT NULL+ )+ """+ )+ conn.commit()+++def load_orders_snapshot() -> str:+ if not os.path.exists(DB_PATH):+ return "Order #1042: [email protected], item='Mechanical Keyboard Pro', total=$129.00, status=SHIPPED"+ with sqlite3.connect(DB_PATH) as conn:+ rows = conn.execute(+ "SELECT order_id, customer, item, amount_dollars, status FROM orders ORDER BY order_id"+ ).fetchall()+ return "; ".join(+ f"Order #{r[0]} (customer={r[1]}, item={r[2]}, total=${r[3]:.2f}, status={r[4]})"+ for r in rows+ )+++def get_history(context_id: str) -> list[dict[str, str]]:+ with sqlite3.connect(DB_PATH) as conn:+ rows = conn.execute(+ "SELECT role, content FROM chat_history WHERE context_id = ? ORDER BY id",+ (context_id,),+ ).fetchall()+ return [{"role": r[0], "content": r[1]} for r in rows]+++def append_history(context_id: str, role: str, content: str) -> None:+ with sqlite3.connect(DB_PATH) as conn:+ conn.execute(+ "INSERT INTO chat_history (context_id, role, content) VALUES (?, ?, ?)",+ (context_id, role, content),+ )+ conn.commit()+++class SupportAgentExecutor(AgentExecutor):+ """Executes A2A tasks using a real LLM (Ollama / Gemini) and shared SQLite state."""++ async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:+ user_text = context.get_user_input()+ ctx_id = context.context_id+ history = get_history(ctx_id)+ orders_info = load_orders_snapshot()++ messages = [+ {"role": "system", "content": f"{SYSTEM_PROMPT}\nOrder Database Snapshot: {orders_info}"},+ *history,+ {"role": "user", "content": user_text},+ ]++ async with httpx.AsyncClient(timeout=60.0) as client:+ resp = await client.post(+ f"{LLM_BASE_URL}/chat/completions",+ headers={"Authorization": f"Bearer {LLM_API_KEY}"},+ json={+ "model": LLM_MODEL,+ "messages": messages,+ "temperature": 0.2,+ },+ )+ resp.raise_for_status()+ llm_reply = resp.json()["choices"][0]["message"]["content"].strip()++ append_history(ctx_id, "user", user_text)+ append_history(ctx_id, "assistant", llm_reply)++ updater = TaskUpdater(event_queue, context.task_id, ctx_id)+ if context.current_task is None:+ await event_queue.enqueue_event(+ new_task(context.task_id, ctx_id, TaskState.TASK_STATE_SUBMITTED)+ )+ formatted = f"[{REPLICA_ID} · {LLM_MODEL}] {llm_reply}"+ await updater.complete(updater.new_agent_message([Part(text=formatted)]))++ async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:+ pass+++agent_card = AgentCard(+ name="Acme Support & Refund Triage Agent",+ description=f"LLM-backed customer support agent ({REPLICA_ID}, model={LLM_MODEL})",+ version="1.0.0",+ capabilities=AgentCapabilities(streaming=False),+ default_input_modes=["text/plain"],+ default_output_modes=["text/plain"],+ skills=[+ AgentSkill(+ id="order_lookup",+ name="Order Status Lookup",+ description="Check shipping status and details of customer orders",+ tags=["orders", "support"],+ examples=["Check order #1042 for [email protected]"],+ ),+ AgentSkill(+ id="refund_triage",+ name="Refund Triage",+ description="Triage customer refund eligibility",+ tags=["refunds", "billing"],+ examples=["Is order #1042 eligible for a refund?"],+ ),+ ],+ supported_interfaces=[+ AgentInterface(+ protocol_binding="JSONRPC",+ protocol_version="1.0",+ url=f"http://127.0.0.1:{PORT}/",+ )+ ],+)++handler = DefaultRequestHandler(+ agent_executor=SupportAgentExecutor(),+ task_store=InMemoryTaskStore(),+ agent_card=agent_card,+)++app = Starlette(+ routes=[+ *create_jsonrpc_routes(request_handler=handler, rpc_url="/"),+ *create_agent_card_routes(agent_card=agent_card),+ ]+)++if __name__ == "__main__":+ init_history_db()+ uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="warning")diff --git a/site/content/docs/use-cases/multi-tier-guardrails.md b/site/content/docs/use-cases/multi-tier-guardrails.mdnew file mode 100644index 00000000..46da782d--- /dev/null+++ b/site/content/docs/use-cases/multi-tier-guardrails.md@@ -0,0 +1,171 @@+---+title: "Multi-Tier Enterprise Guardrails & Quality Gates"+weight: 25+description: "How Developer, Platform, Central Security, Department Leads, Individual End-Users, and Day-2 Ops each enforce their own layer of guardrails on the same mesh."+---++<video controls playsinline preload="metadata" poster="/demo-poster.png" style="width:100%; border-radius:8px; box-shadow:0 4px 20px rgba(0,0,0,0.4); margin-bottom: 1.5rem;">+ <source src="/demo-multi-tier-guardrails.mp4" type="video/mp4">+</video>++When every developer and team starts shipping AI agents, organizations hit a governance paradox:++1. **Agent Developers** want 1-command onboarding from a laptop or Cloud Run without waiting weeks for VPC peering, DNS records, or firewall tickets.+2. **Platform & Networking Engineers** want persistent logical service names (`a2a://support.acme`) that survive replica swaps across environments without static proxy limits.+3. **Central Security (CISO)** wants an organization-wide policy floor, automated quality gates before an agent can serve production (`env=staging` $\rightarrow$ `env=prod`), and zero raw API credentials inside agent containers.+4. **Department Leads & Individual End-Users** want to narrow what an agent can do on *their* infrastructure or on *their* behalf—even when the organization's baseline policy allows it.+5. **Day-2 Operations (SRE)** needs a correlated audit trail across every hop and a 1-command kill-switch (`sam-one admin ban`) if a peer misbehaves.++The runnable example in [`development/examples/multi-tier-guardrails/`](https://github.com/google/sam/tree/main/development/examples/multi-tier-guardrails) walks through all five personas in four acts using **real backends** and zero changes to SAM's core code:++- **Real Local LLM (`gemma3:1b` via Ollama):** Powers the Support A2A replicas (`support_agent.py`) over an OpenAI-compatible `/v1/chat/completions` endpoint.+- **Real A2A 1.0 SDK (`a2a-sdk`):** Both `support_agent.py` (server) and `a2a_client.py` (client) use the official [`a2a-sdk`](https://pypi.org/project/a2a-sdk/) with SQLite-backed conversation history keyed by `contextId`.+- **Real SQLite MCP Server (`orders_mcp.py`):** Built with the official [`mcp`](https://pypi.org/project/mcp/) Python SDK (`MCPServer`), exposing `get_order_status` (read) and `issue_refund` (write) against a SQLite `orders.db` database.+- **Real External API (`egress://api.github.com`):** Connects to `https://api.github.com` with node-side secret brokering (`secrets/github-ro`).++---++## The 5 Personas in One Mesh++| Persona | What They Control in SAM | Mechanism Used in This Example |+| :--- | :--- | :--- |+| **1. Agent Developer (Alice)** | Onboarding & iterating on `a2a://support.acme` (`support_agent.py`) | Enrolls `sam-node` in `env=staging` quarantine; zero code changes to promote to `env=prod` |+| **2. Platform / Networking** | Service discovery, outbound floor & replica lifecycle | Input-node `egress.require_labels: {env: prod}`, logical URI `a2a://support.acme`, and `contextId` continuity from Laptop (`v1`) to Cloud Run (`v2`) |+| **3. Central Security (CISO)** | Org-wide baseline RBAC, Quality Gate & Secret Brokering | Control-plane `policy.json` (`allowed_labels`, HTTP method/path rules on `egress://api.github.com`, `secret_ref: github-ro`) |+| **4. Department Lead & End-User** | Local team gate + per-task tool narrowing | Egress-node `attenuation` (`check if label("team", "support");`) + RFC 8693 `/oauth/token` minting a sealed Task Biscuit (`tar_block`) |+| **5. Day-2 Operations (SRE)** | Real-time audit correlation & incident response | Structured `ALLOW`/`DENY` audit stream (`audit.py`) + instant mesh-wide revocation (`sam-one admin ban`) |++---++## Understanding Labels in the Demo: The 3 Control Points++When watching Alice configure `labels:` in `node-v1.yaml` or a caller send `X-Sam-Required-Labels`, a natural question arises: *"Can a developer or agent just set arbitrary labels to influence security policy?"*++No. In SAM, labels operate at **three distinct points** with clear separation of authority:++1. **Mesh Enforcement (Control Plane `policy.json` $\rightarrow$ `allowed_labels`):**+ A node's YAML file (`labels:`) is only a **request** at enrollment time. The Control Plane validates every requested label against the role's `allowed_labels` in `policy.json` before cryptographically signing `label("k", "v")` facts into the node's authority Biscuit. If Alice tries to self-assert `env: prod` before passing the Quality Gate, enrollment is rejected (`Label not permitted: label "env=prod" is not permitted by this role's allowed_labels`).+2. **Node Enforcement (Input Node `egress.require_labels` & Egress Node `attenuation.checks`):**+ - **Input Node (`node-caller.yaml`):** The Platform Admin sets `egress.require_labels: { env: prod }` on the caller's node. Even if the calling application sends **no** `X-Sam-Required-Labels` header, the Input Node blocks calls to staging providers (`403 Forbidden`).+ - **Egress / Provider Node (`node-v1.yaml`):** The Support Department Lead configures a positive inbound Datalog check (`check if label("team", "support");`). Any caller whose Biscuit lacks a Control-Plane-signed `label("team", "support")` fact—whether `team=contractor` or carrying no labels at all—is rejected locally by `node-v1`.+3. **End-User / Agent Intent (`X-Sam-Required-Labels` HTTP Header):**+ Within the mandatory boundaries enforced by the Mesh and the Nodes, the calling application or agent can pass `X-Sam-Required-Labels` (for example `replica=v1-laptop` or `replica=v2-cloudrun`) to express **intent** about which specific replica or capability it wants from the mesh. The Input Node **ANDs** the caller's intent with its own `egress.require_labels` floor (`env=prod AND replica=v2-cloudrun`), so the application can narrow selection without ever weakening admin policy.++---++## Run It Yourself++```bash+make build+./development/examples/multi-tier-guardrails/run.sh+```++Pass `--interactive` to step through the four acts one `ENTER` at a time during a live presentation:++```bash+./development/examples/multi-tier-guardrails/run.sh --interactive+```++---++## What Happens in Each Act++### Act 1: Developer Onboarding into Quarantine (`env=staging`) & Quality Gate Promotion+*(Personas: Agent Developer Alice + Central Security / Platform)*++Alice starts her `sam-node` fronting `a2a://support.acme` (`support_agent.py` backed by `gemma3:1b`) and `mcp://orders-db` (`orders_mcp.py` backed by SQLite). Her node config (`node-v1.yaml`) declares `env: staging`, and the initial control-plane policy (`policy.json`) only permits `env=staging`.++Right here, the demo shows both **Mesh Enforcement** and **Input Node Enforcement**:+- If Alice tries to join with `env: prod` in her YAML before passing the Quality Gate, the Control Plane rejects enrollment:+ `Label not permitted: label "env=prod" is not permitted by this role's allowed_labels`+- While Alice's node is in `env=staging`, a plain request through the Input Node (`node-caller.yaml`, which enforces `egress.require_labels: { env: prod }`) is blocked even when the app sends no label headers:+ `HTTP 403 — Required labels not attested by provider`++Next, the automated Quality Gate fetches Alice's Agent Card in `env=staging`, verifies that it conforms to the A2A 1.0 schema and declares the expected skills (`order_lookup`, `refund_triage`), and promotes the policy and node to `env=prod`. Retrying the exact same production request now succeeds with `200 OK` and rewrites `supportedInterfaces[0].url` to point at the caller's local SAM proxy.++---++### Act 2: Persistent Logical Naming, Zero-Downtime Replica Swap & Agent Intent+*(Persona: Platform / Networking)*++Callers address the agent by its logical mesh name (`a2a://support.acme`), never by an ephemeral IP or Cloud Run URL. On top of the Input Node's mandatory `env=prod` floor, the calling application uses `X-Sam-Required-Labels` (**End-User / Agent Intent**) to select replicas:++1. **Turn 1 (`contextId=ctx-acme-1042`, `X-Sam-Required-Labels: replica=v1-laptop`):** The caller uses `a2a_client.py` (official `a2a-sdk`) to ask about Order `#1042`, and `gemma3:1b` on Alice's laptop replica (`[v1-laptop · gemma3:1b]`) replies that Alice's Mechanical Keyboard Pro (`$129.00`) has `SHIPPED`.+2. **Replica Scale-Up:** A second node (`node-v2.yaml`, representing a Cloud Run deployment) joins the mesh advertising `a2a://support.acme` with `env=prod, replica=v2-cloudrun`.+3. **Turn 2 (`contextId=ctx-acme-1042`, `X-Sam-Required-Labels: replica=v2-cloudrun`):** The caller sends the follow-up question with the same `contextId` to the Cloud Run replica (`[v2-cloudrun · gemma3:1b]`), which loads the conversation history from SQLite and answers seamlessly without dropping context.++---++### Act 3: The 3-Tier Guardrail Hierarchy+*(Personas: Central Security, Department Lead, and Individual End-User)*++SAM enforces the **strict intersection** of three independent guardrail layers:++```+Effective Permission = (Layer 1: Central Security Block 0 Policy)+ ∩ (Layer 2: Department Egress-Node Label Check)+ ∩ (Layer 3: Individual User Per-Task Biscuit tar_block)+```++#### Layer 1 — Central Security (Org Baseline & Secret Broker)+In `policy.json`, Central Security assigns `egress://api.github.com` (`https://api.github.com`) to nodes labelled `team=support` with `secret_ref: "github-ro"`, and restricts callers to `GET /repos/google/sam/pulls*`:++* `GET /repos/google/sam/pulls?state=open&per_page=1` $\rightarrow$ **`200 OK`** (the hosting node injects the read-only GitHub token from `secrets/github-ro`; the caller never holds the credential).+* `POST /repos/google/sam/pulls` $\rightarrow$ **`403 Forbidden`** (blocked by the Block 0 HTTP rule before GitHub ever receives the request).++#### Layer 2 — Department Lead (Egress-Node Positive Label Enforcement)+Central Security's org-wide policy allows `sam:role:node` to reach `mcp://orders-db`. However, the Support Department Lead adds a local positive label check in `node-v1.yaml`:++```yaml+attenuation:+ checks:+ - 'check if label("team", "support");'+```++When a contractor node enrolled with attested label `team=contractor` attempts to call `mcp://orders-db/get_order_status`, Alice's node rejects the request locally because the caller's Biscuit does not carry a Control-Plane-signed `label("team", "support")` fact:++```text+MCP tool "get_order_status" rejected: biscuit: verification failed: failed to verify check #2: check if label("team", "support")+```++#### Layer 3 — Individual End-User (Per-Task Biscuit `tar_block`)+When a customer asks the agent *"Where is my order #1042?"*, the caller mints a **sealed Task Biscuit** via `POST /oauth/token` (RFC 8693 token exchange) narrowed strictly to `resource=mcp://orders-db` and `scope=tool:get_order_status`:++```bash+curl -s -X POST http://127.0.0.1:19002/oauth/token \+ -H "Authorization: Bearer caller-secret" \+ -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \+ -d "resource=mcp://orders-db" \+ -d "scope=tool:get_order_status" \+ -d "seal=true"+```++Using that narrowed Task Biscuit:+1. Calling `get_order_status(order_id="1042")` against the SQLite MCP server succeeds:+ `Order #1042: status=SHIPPED, item='Mechanical Keyboard Pro', total=$129.00, [email protected]`+2. If a prompt injection inside the order notes tricks the agent into calling `issue_refund(order_id="1042", amount_dollars=5000)` using the **same** Task Biscuit, the node's authorizer blocks the tool call mid-flight and leaves the SQLite `refunds` table untouched (`COUNT(*) = 0`):+ ```text+ task authorization denied tool "issue_refund": tar_block[1] ("oauth-task") denied request to mcp://orders-db+ ```++---++### Act 4: Day-2 Operations — Correlated Audit & Instant Kill-Switch+*(Persona: Day-2 Operations / SRE)*++Every `ALLOW` and `DENY` across all three layers is emitted as a structured JSON log event on the hosting node (`audit.py` formats each decision into a single line showing verdict, role, caller PeerID, HTTP method/path or MCP protocol, and target service):++```text+ALLOW sam:role:node 12D3KooW… GET /.well-known/agent-card.json a2a://support.acme+ALLOW sam:role:node 12D3KooW… POST / a2a://support.acme+ALLOW sam:role:node 12D3KooW… GET /repos/google/sam/pulls egress://api.github.com+DENY - 12D3KooW… POST /repos/google/sam/pulls egress://api.github.com+DENY - 12D3KooW… /sam/mcp/1.0.0 mcp://orders-db+ALLOW sam:role:node 12D3KooW… /sam/mcp/1.0.0 mcp://orders-db+```++Finally, if Day-2 Operations detects repeated policy violations from the contractor peer, a single command revokes that peer's identity across the entire mesh:++```bash+./bin/sam-one admin ban <contractor-peer-id> --server $CP_URL --data-dir $WORK_DIR/one+```diff --git a/site/static/demo-multi-tier-guardrails.mp4 b/site/static/demo-multi-tier-guardrails.mp4new file mode 100644index 00000000..0facd509Binary files /dev/null and b/site/static/demo-multi-tier-guardrails.mp4 differ