Architecture
Secure tool execution treats every LLM-emitted function argument and upstream tool response as completely untrusted input—enforcing canonical normalization, out-of-model runtime authorization, short-lived credential brokering, gVisor/seccomp kernel confinement, private-CIDR egress firewalls, and explicit parameter-bound approvals before external state can ever mutate.
When an AI agent retrieves public web pages, Slack messages, PDFs, or third-party GitHub issues, adversarial indirect prompt injection can coerce the language model into calling legitimate authorized tools with malicious arguments (../../etc/shadow, http://169.254.169.254/latest/meta-data/, or arbitrary rm -rf payloads). Telling the model in a system prompt "only read files inside /workspace" provides zero deterministic security guarantee; defense-in-depth requires boundary controls operating strictly outside the model context window inside canonical parsers, OS namespaces, and network gateways.
1. Seven Enforced Guardrails Around Tool Execution
- Canonical Argument Normalization & Strict Schema Reject (
No Coercion): Normalize Unicode NFC, resolve symlinks cleanly withos.path.realpathinside jail checks before rejecting path traversal, disallow unknown extra JSON keys (additionalProperties: false), and block internal RFC1918/link-local IPs after DNS resolution (blocking DNS rebinding). - Identity-Bound Runtime Authorization (
PDP/PEP): Bindactor_idandtenant_idexclusively from cryptographically verified gateway tokens—never from LLM arguments—and authorize per-call scope (read:ticketsvsrefund:billing) at execution time. - Just-in-Time Brokered Credentials: Never inject long-lived API keys or DB strings into agent prompts or container env vars; exchange workload identity right inside the host tool broker for short-lived (
60–300s) audience-scoped tokens. - Ephemeral Sandboxing (
Firecracker / gVisor / Seatbelt): Execute code tools inside disposable containers with read-only rootfs, dropped Linux capabilities (--cap-drop=ALL), seccomp-BPF syscall filters, strict cgroups (CPU,RAM,pids_max), and execution deadlines. - Default-Deny Network Egress & Size-Capped Output: Route outbound HTTP exclusively through a forward allowlist proxy blocking raw sockets and arbitrary DNS exfiltration tunnels; cap and sanitize tool response payloads before injecting back into model context.
- Digest-Bound Human Approval Tokens: For high-blast-radius mutations (
wire_transfer,delete_bucket,git_push), require human confirmation tokens bound via HMAC-SHA256 to the exact normalized parameter payload so subsequent injection cannot swap the amount or recipient mid-step.
2. Isolation Runtime & Cost-Latency Trade-Off Matrix
| Execution Sandbox | Boot Latency | Kernel Isolation Boundary | Egress Control Mechanism | Target Workload Class |
|---|---|---|---|---|
| In-Process AST / Restricted VM | < 1 ms | Shared host kernel & runtime (weak against native C/WASM escapes) | Pure in-memory stub APIs only (0 network) | Deterministic formula evaluators, JSON transforms |
Hardened Docker (seccomp + cap-drop) | 40 – 120 ms | Shared host Linux kernel (syscall filter boundary) | Dedicated Docker bridge + proxy container only | Trusted internal read-only analysis scripts |
gVisor (runsc) User-Space Kernel | 80 – 180 ms | Intercepts Linux syscalls in memory-safe Go user-space | Native gVisor netstack egress policy filter | Arbitrary untrusted user/agent Python or Node code |
| Firecracker / Cloud Hypervisor MicroVM | 110 – 250 ms | Dedicated guest Linux kernel + KVM hardware virtualization | Explicit virtual TAP firewall / metadata block | Hostile multi-tenant execution & browser automation |
3. Canonical Path Jail & Anti-SSRF Execution Guard in Python
pythonimport ipaddressimport osimport socketfrom urllib.parse import urlparseALLOWED_WORKSPACE = os.path.realpath("/srv/agent-workspace")def assert_safe_workspace_path(untrusted_path: str) -> str:"""Resolve symlinks deterministically before rejecting workspace boundary escapes."""candidate = os.path.realpath(os.path.join(ALLOWED_WORKSPACE, untrusted_path))if candidate != ALLOWED_WORKSPACE and not candidate.startswith(ALLOWED_WORKSPACE + os.sep):raise PermissionError(f"Path escape rejected after symlink resolution: {untrusted_path}")return candidatedef assert_safe_outbound_url(untrusted_url: str, allowed_hosts: set[str]) -> str:"""Verify HTTPS scheme, allowlisted domain, and resolve all IPs outside private/link-local CIDRs."""parsed = urlparse(untrusted_url)if parsed.scheme != "https" or not parsed.hostname:raise PermissionError("Only HTTPS URLs with explicit hostnames are permitted")host = parsed.hostname.lower()if host not in allowed_hosts:raise PermissionError(f"Host {host} missing from explicit egress allowlist")for family, _, _, _, sockaddr in socket.getaddrinfo(host, parsed.port or 443, type=socket.SOCK_STREAM):ip_obj = ipaddress.ip_address(sockaddr[0])if ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_link_local or ip_obj.is_multicast:raise PermissionError(f"SSRF blocked resolution to restricted address {ip_obj}")return untrusted_url
Decisions
| Decision | Required evidence | Review trigger |
|---|---|---|
Resolve paths (O_NOFOLLOW / realpath) & re-resolve DNS IPs at TCP dial time inside allowlist egress proxies. | Negative symlink-escape + DNS-rebinding SSRF tests passing | Adding new filesystem or HTTP-fetch agent tools |
Isolate untrusted code & browser runners cleanly inside --cap-drop=ALL, --network=none / forward-proxy microVMs. | Container escape & cloud metadata IMDS block audit (169.254.169.254 dropped) | Upgrading sandbox runtime or adding OS tools |
Alternatives and trade-offs
- Ephemeral MicroVMs (
Firecracker/gVisor) vs. Native Rootless Docker Containers: MicroVMs isolate kernel syscall surfaces across hostile untrusted repos at slight boot memory overhead, whereas hardened rootless containers prioritize fast warm-pool latency for trusted CI toolboxes.
Failure modes
- Schema validation mistaken for authorization: Confirming an argument is a valid integer (
user_id = 42) does not authorize readinguser_id = 42's invoice. - TOCTOU DNS rebinding or symlink switches: Validating raw string paths (
str.startswith) or checking DNS once beforecurlre-resolves opens classic time-of-check/time-of-use exploits inside tool proxies. - Containers inheriting host mounts or metadata IP access: Default EC2/GCP IMDSv1 (
169.254.169.254) lets any agent shell fetch instance IAM role credentials immediately unless egress rules explicitly drop link-local addresses. - Unquoted or unsanitized tool responses reinjecting commands: Returning raw unescaped scraped HTML directly inside
system/assistantframes hijacks subsequent tool turns.
Operational checklist
- Every path, URL, and identifier undergoes canonical normalization right at execution time.
- Policy Enforcement Points reject unknown schema keys and fail closed when tokens expire or mismatch tenant scope.
- Sandboxes execute with
--cap-drop=ALL, read-only rootfs, bounded CPU/RAM/pids, and explicit non-root UIDs. - Outbound network traffic passes through an egress proxy denying RFC1918 and cloud metadata CIDRs.
- Irreversible writes require digest-bound human approvals checked deterministically out-of-band.
Connected Practice
- Labs: /labs/prompt-injection-threat-model, /labs/agent-loop-tool-selection
- Projects: /projects/governed-agent-reliability
- System breakdowns: /systems/inside-openai-codex
Sources
- Secure tool primary references:
owasp-llm,mcp-specification,oauth-security-bcp,nist-zero-trust
Debug live agent loops & tool-call failure recovery
Inject schema mismatches, 429 rate limits, and timeout circuit breakers inside the ReAct Agent Loop Debugger — or query this knowledge inside Cursor/Claude via MCP.
Subscribe to Engineering Briefings
Join AI systems engineers receiving architecture teardowns, benchmark notes, and new simulator releases. Unsubscribe anytime.
