Mental model
A JSON Schema confirms field data types rather than authorization safety or semantic truth. Secure AI tool boundaries enforce two orthogonal checks on every call: inbound validation canonicalizes inputs (resolve paths, strip SSRF hosts, reject extra keys) ahead of authorization checks cleanly, while outbound handling clamps size, verifies real content types, escapes markup, and fences tool responses strictly as untrusted external data before models see them.
Learning outcomes
- Enforce "canonicalize once, validate once, execute from canonical output" preventing Unicode homoglyph and
../path-traversal bypasses (TOCTOU). - Protect HTTP fetch/webhook tools cleanly against Server-Side Request Forgery (
SSRFtargeting private VPC/metadata IPs). - Prevent context-window flooding and indirect prompt injection on returning tool results via strict truncation and delimiter tagging.
Theory
Teams routinely trust model-supplied arguments simply because a schema library validated { "url": "string", "path": "string" }! An attacker hiding instructions inside an analyzed ticket can instruct the tool cleanly cleanly to call url = "http://169.254.169.254/latest/meta-data/" or path = "/workspace/./../../etc/passwd"—both 100% valid JSON strings that pass Pydantic/Zod defaults unless semantic domain validation enforces boundaries explicitly:
| Validation Direction | Target Defect | Mandatory Control Pattern | Anti-Pattern to Reject |
|---|---|---|---|
| Inbound Schema | Unexpected privileged fields (role: "admin", force_bypass: true) | extra="forbid" (Pydantic) / .strict() (Zod) | Permitting arbitrary unknown JSON properties by default |
| Inbound Filesystem & URL | Directory traversal (..%2F), symlink escapes, cloud IMDS SSRF | Resolve os.path.realpath() under fixed root; resolve IP & block RFC1918/link-local | Regex string checks (not "../" in path) easily bypassed via URL decode |
| Outbound Payload Size | Tool returning 12 MB log dump crashing context budget or causing OOM | Hard truncate output bytes (max_chars) + signal "truncated: true" + pagination handle | Forwarding whole un-truncated raw database or grep dumps cleanly |
| Outbound Trust Isolation | Retrieved issue prose containing "Ignore previous rules..." injection | Wrap inside <tool_result untrusted="true"> + HTML escape UI embeds + magic-byte checks | Blending tool text seamlessly alongside system prompts or trusting .pdf filename claims |
pythonimport ipaddressimport osimport socketfrom urllib.parse import urlparsedef validate_safe_file_read(root_dir: str, requested_path: str) -> str:"""Resolve symlinks and relative segments once before enforcing directory root confinement."""root_real = os.path.realpath(root_dir)candidate_real = os.path.realpath(os.path.join(root_real, requested_path))if candidate_real != root_real and not candidate_real.startswith(root_real + os.sep):raise PermissionError("Path traversal or symlink escape outside authorized root")return candidate_real # Caller MUST use returned canonical path directly!def validate_safe_external_https(raw_url: str) -> str:"""Reject non-HTTPS schemes and private/link-local SSRF targets (cloud IMDS)."""parsed = urlparse(raw_url.strip())if parsed.scheme != "https" or not parsed.hostname:raise ValueError("Only valid external https:// URLs permitted")resolved_ip = ipaddress.ip_address(socket.gethostbyname(parsed.hostname))if resolved_ip.is_private or resolved_ip.is_loopback or resolved_ip.is_link_local or resolved_ip.is_multicast:raise PermissionError(f"Blocked internal/SSRF IP target: {resolved_ip}")return raw_url.strip()
Trade-offs
Strict strictness rules (additionalProperties: false, tight numeric ranges, binary magic-byte inspection, deterministic outbound truncation) shrink the attack surface cleanly and prevent sudden context explosions across unverified third-party endpoints. Overly brittle regex allowlists occasionally reject benign future schema additions or non-ASCII customer names unless teams test strict schemas against realistic noisy inputs cleanly alongside clean structured validation hints so models self-correct harmless format slips within 1–2 turns cleanly.
Failure modes and misconceptions
- Checking Un-Normalized Input Strings Then Opening Raw Paths: Validating
raw_pathcleanly before URL-decoding or symlink traversal enables classic%2e%2e/escapes cleanly. - Trusting User-Supplied MIME Extensions: Accepting
"report.png"purely by file suffix allows HTML/SVG script payloads (<script>) cleanly if content bytes aren't inspected. - Toggling System Rules Based on Schema-Valid Tool Data: Letting retrieved support tickets containing schema-valid JSON
"instructions": "override refund cap"steer control logic cleanly without delimiter firewalls. - Silent Output Dropping Without Truncation Flags: Truncating long search logs silently at 2KB without informing the model
"Showing lines 1..80 of 4,200"causes premature false conclusions cleanly.
Decision scenario
A documentation research assistant offers tools read_workspace_file(path) and fetch_reference_url(url) running inside shared Kubernetes pods. Red-teamers just demonstrated reading /etc/shadow via symlink paths, querying internal Kubernetes metadata (169.254.169.254), and blowing context budgets via 10MB HTML responses carrying embedded prompt overrides cleanly. Design end-to-end inbound canonicalization, SSRF filtering, outbound truncation, and untrusted tagging cleanly.
Why must an agent runtime still treat a schema-valid external tool output strictly as untrusted data rather than clean context instructions?