FullStack AI Hub
Studio
Reference architecture

Secure Tool Execution

Hardened execution boundary treating model tool proposals as untrusted input via canonical validation, runtime RBAC, gVisor/seccomp sandboxing, and egress rules.

18 minVerified 2026-11-254 primary sources
Secure Tool Execution
On This Page

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.

Intent and policy
Validated request
Controlled execution
Independent verification
Telemetry and response
Conceptual teaching model synthesized from:OWASP Top 10 for LLM ApplicationsModel Context Protocol Architecture and Tools SpecificationOAuth 2.0 Security Best Current PracticeZero Trust Architecture

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

  1. Canonical Argument Normalization & Strict Schema Reject (No Coercion): Normalize Unicode NFC, resolve symlinks cleanly with os.path.realpath inside 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).
  2. Identity-Bound Runtime Authorization (PDP/PEP): Bind actor_id and tenant_id exclusively from cryptographically verified gateway tokens—never from LLM arguments—and authorize per-call scope (read:tickets vs refund:billing) at execution time.
  3. 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.
  4. 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.
  5. 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.
  6. 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 SandboxBoot LatencyKernel Isolation BoundaryEgress Control MechanismTarget Workload Class
In-Process AST / Restricted VM< 1 msShared 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 msShared host Linux kernel (syscall filter boundary)Dedicated Docker bridge + proxy container onlyTrusted internal read-only analysis scripts
gVisor (runsc) User-Space Kernel80 – 180 msIntercepts Linux syscalls in memory-safe Go user-spaceNative gVisor netstack egress policy filterArbitrary untrusted user/agent Python or Node code
Firecracker / Cloud Hypervisor MicroVM110 – 250 msDedicated guest Linux kernel + KVM hardware virtualizationExplicit virtual TAP firewall / metadata blockHostile multi-tenant execution & browser automation
Architecture claim
Representative test
Production signal
Decision gate
Review or rollback
Conceptual teaching model synthesized from:OWASP Top 10 for LLM ApplicationsModel Context Protocol Architecture and Tools SpecificationOAuth 2.0 Security Best Current PracticeZero Trust Architecture

3. Canonical Path Jail & Anti-SSRF Execution Guard in Python

python
import ipaddress
import os
import socket
from urllib.parse import urlparse
​
​
ALLOWED_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 candidate
​
​
def 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

DecisionRequired evidenceReview 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 passingAdding 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 reading user_id = 42's invoice.
  • TOCTOU DNS rebinding or symlink switches: Validating raw string paths (str.startswith) or checking DNS once before curl re-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/assistant frames 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

Sources

  • Secure tool primary references: owasp-llm, mcp-specification, oauth-security-bcp, nist-zero-trust
Agent Runtime Workbench

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.

Weekly Engineering Dispatch

Subscribe to Engineering Briefings

Join AI systems engineers receiving architecture teardowns, benchmark notes, and new simulator releases. Unsubscribe anytime.