Build Secure File System Tools for AI Agents: Block Path Traversal with Sandboxed Roots and Tests



Build Secure File System Tools for AI Agents: Block Path Traversal with Sandboxed Roots and Tests

Quick Answer / TL;DR Treat every agent file path as hostile input. Resolve it to a canonical path inside an allowed root, reject symlinks and absolute paths, enforce type and size limits, and deny by default. Then prove the boundary with adversarial tests and log every allow/deny decision as evidence.

If you are searching for ai agent security testing, the highest-value place to start is the file tool. It is concrete, it is called repeatedly during multi-step work, and a single ../ or symlink can turn a helpful assistant into an unintended data broker. This guide walks through the problem, maps the attack surface, shows a governed reference architecture, and gives you Python you can run today. The same pattern applies whether your agent reads local documents, calls a Model Context Protocol (MCP) server, or reaches SaaS connectors.

What You Will Learn

Contents

Why ai agent security testing Starts at the File Tool

An agent tool is not a normal function call. The model supplies arguments probabilistically, often from untrusted text it just read, and the tool executes with the authority of the runtime. A request like read ../secrets.json may look harmless in a transcript, but if your code joins it to a working directory without canonicalization, the agent has crossed a trust boundary. Real-world cases include support agents summarizing tickets that contain malicious attachment names, coding agents asked to “check the config one level up,” and retrieval pipelines that follow links into a shared drive.

The selected search intent here is practical: how do I test and build a safe file tool for an AI agent? That means moving beyond a checklist. ai agent security testing should produce executable proof: a request is allowed only when it matches policy, and every denial is explainable. Path traversal is a useful first target because it is deterministic, easy to reproduce, and a strong signal that the rest of your boundary is designed correctly.

Start with the assumption that the model is an untrusted caller. Do not rely on prompt instructions such as “never access outside /workspace.” Prompts are advice; code is enforcement. Once you accept that, the next step is to enumerate everything the agent can influence.

Map the Agent Attack Surface Before You Write Code

Before choosing controls, map what can be manipulated. This is the core of ai agent security architecture attack surface and defense: identify each surface, then attach a concrete defense. Use the table below as a review worksheet for your own system.

Surface What the agent can influence Primary risk Defense to attach
Identity Which human or service the agent acts for Confused deputy, privilege reuse Distinct agent identity bound to the requester
Prompts Instructions from users, documents, retrieved pages Prompt injection, goal hijack Treat content as data; separate system policy from content
Memory Persisted notes, summaries, vector stores Poisoned recall, stale authority Scoped memory, provenance, periodic revalidation
Tools Arguments to read, write, search, exec Traversal, command injection Canonicalization, allowlists, type and size limits
Connectors MCP servers, SaaS APIs, webhooks Excess capability, tool shadowing Expose only approved capabilities at the boundary
Credentials API keys, tokens, service accounts Secret exfiltration, long-lived access Delegated OAuth, JIT credentials outside the runtime
Data Files, records, attachments, logs Cross-tenant reads, data leakage Resource-bound grants, classification-aware policy
Multi-step execution Chained tool calls across turns Approval fatigue, cumulative drift Step-up approval, per-call policy checks, evidence trail

Notice that the file tool is only one row. Securing it well reduces blast radius, but it does not fix a long-lived key in the agent environment. That is why the next section places authorization before provider access rather than inside each tool.

Reference Architecture: Authorization Before Provider Access

The general principle is simple: the agent requests, the gateway decides, the provider executes. Credentials and broad provider scopes should never sit in the model runtime. A request travels through an identity check, a policy engine, and an approval step when needed, before a just-in-time grant reaches a connector.

Human request
  -> Agent runtime (no provider credentials)
     -> Governed gateway: identity + policy + approval
        -> Delegated, resource-bound grant (JIT)
           -> MCP / API / connector capability allowlist
              -> Sandboxed file tool (root + type + size guard)
                 -> Protected result + linked evidence trail

A policy file makes the boundary reviewable. Keep it declarative and deny by default:

agent_id: file-reader-v2
requested_by: user:shyam
tool: filesystem.read
policy:
  default: deny
  roots:
    - /srv/agent-workspace
  max_bytes: 1000000
  allowed_suffixes: [".txt", ".md", ".json"]
  require_approval_when:
    - write
    - suffix_in: [".env", ".key"]
  evidence:
    log_decision: true
    include_request_hash: true

As a documented example of this pattern, Axec is a governed gateway for AI access: it binds a distinct agent identity to the requesting human, uses delegated OAuth with exact resource-bound grants, returns allow/deny/require-approval decisions, keeps JIT credentials outside the agent runtime, exposes only approved capabilities at MCP/API/connector boundaries, protects results, and links an evidence trail to each decision. Revocation of delegated authority does not require redeploying the agent. These are product concepts from the brief, not customer results or certifications; check current primary sources before treating any vendor description as complete. The architectural lesson stands on its own—authorize first, then connect.

With the boundary located, the implementation can stay small and auditable. The next section turns the policy into code.

Implement a Sandboxed Root and Fail-Closed Path Checks

Build the tool so that every failure mode ends in denial. The order matters: normalize first, reject absolute and encoded forms, check symlink components, resolve fully, then verify containment and resource limits.

  1. Define the policy with an explicit root, allowed suffixes, and a size cap.
  2. Normalize Unicode to stop visually identical paths from slipping through.
  3. Reject dangerous forms such as absolute paths, Windows drives, UNC paths, null bytes, and percent-encoded traversal markers.
  4. Resolve and contain with Path.resolve() plus relative_to(), then apply type, write, and size rules.
from dataclasses import dataclass
from pathlib import Path
import unicodedata

class ToolDenied(Exception):
    pass

@dataclass(frozen=True)
class ToolPolicy:
    root: Path
    allow_write: bool = False
    max_bytes: int = 1_000_000
    allowed_suffixes: frozenset[str] = frozenset({".txt", ".md", ".json"})

def canonical(value: str) -> Path:
    normalized = unicodedata.normalize("NFC", value)
    lowered = normalized.lower()
    if "\x00" in normalized:
        raise ToolDenied("null byte in path")
    if any(token in lowered for token in ("%2e", "%2f", "%5c", "%00")):
        raise ToolDenied("encoded traversal markers are not accepted")
    candidate = Path(normalized)
    if candidate.is_absolute() or candidate.drive or str(candidate).startswith("\\\\"):
        raise ToolDenied("absolute, drive, or UNC paths are not accepted")
    if ".." in candidate.parts:
        raise ToolDenied("parent traversal is not accepted")
    return candidate

def guard(policy: ToolPolicy, raw: str, *, write: bool = False) -> Path:
    root = policy.root.resolve(strict=True)
    relative = canonical(raw)
    for index in range(1, len(relative.parts) + 1):
        probe = root.joinpath(*relative.parts[:index])
        if probe.is_symlink():
            raise ToolDenied("symlink components are not accepted")
    resolved = (root / relative).resolve(strict=True)
    try:
        resolved.relative_to(root)
    except ValueError as exc:
        raise ToolDenied("path escapes the sandboxed root") from exc
    if resolved.suffix.lower() not in policy.allowed_suffixes:
        raise ToolDenied("file type is not allowed")
    if write and not policy.allow_write:
        raise ToolDenied("write access is not granted")
    if resolved.is_file() and resolved.stat().st_size > policy.max_bytes:
        raise ToolDenied("file exceeds size limit")
    return resolved

def read_file(policy: ToolPolicy, raw: str) -> str:
    return guard(policy, raw).read_text(encoding="utf-8")

A few details are doing real work. resolve(strict=True) collapses .. and follows symlinks; relative_to(root) is the containment assertion that catches anything the explicit checks missed. Rejecting symlink components before resolution prevents a link inside the workspace from pointing to /etc. Fail-closed means a missing file, a parsing error, or an unknown condition raises ToolDenied rather than falling back to a broader path.

Now that the guard exists, the only trustworthy way to claim it works is to attack it.

ai agent security testing: Boundary Tests That Catch Traversal

Write tests from the attacker’s perspective, not the happy path. Include plain traversal, absolute paths, encoded variants, symlink escapes, Windows-style inputs, null bytes, and a legitimate read to prove you did not deny everything.

import pytest
from pathlib import Path

@pytest.fixture
def policy(tmp_path: Path) -> ToolPolicy:
    root = tmp_path / "workspace"
    root.mkdir()
    (root / "notes").mkdir()
    (root / "notes" / "report.md").write_text("ok", encoding="utf-8")
    (root / "link").symlink_to(tmp_path / "outside.md")
    return ToolPolicy(root=root)

@pytest.mark.parametrize("payload", [
    "../etc/passwd",
    "../../etc/passwd",
    "/etc/passwd",
    "notes/../../secrets.json",
    "notes/%2e%2e/passwd",
    "notes/%2E%2E%2Fpasswd",
    "link",
    "C:\\Windows\\win.ini",
    "\\\\server\\share\\secret",
    "notes/report.txt\x00.png",
])
def test_traversal_is_denied(policy, payload):
    with pytest.raises(ToolDenied):
        guard(policy, payload)

def test_allowed_read(policy):
    assert guard(policy, "notes/report.md").read_text(encoding="utf-8") == "ok"

Run it in CI on every change to the tool or policy:

python -m pytest tests/test_file_tools.py -q

Monitoring should mirror the tests. Emit a structured event for each decision with agent_id, requested_by, raw path hash, canonical path, policy version, decision, and reason. Alert on unusual denial spikes, repeated encoded payloads, or any approval request for a new suffix. Then review a sample of allowed reads against business intent; a permitted path can still be the wrong path. These tests and logs are the backbone of ai agent security testing because they convert a design claim into observable behavior.

Observability answers “what happened,” but governance answers “why was this allowed and who can prove it?” The next section covers that layer.

Govern, Audit, and Respond Without Overclaiming Compliance

Governance starts with ownership. Assign a human owner to the policy file, require review for changes to roots or suffixes, and version every policy. Use ai agent security best practices such as least privilege, delegated identity, just-in-time access, and approval checkpoints as design rules, not as marketing labels. A governed gateway is useful here because decisions and outcomes can be linked centrally; the same evidence discipline can be built with your own service if you control the boundary.

Evidence Why it matters Practical note
Identity binding Shows which human the agent acted for Store the requester ID, not just the agent ID
Policy version Explains which rules were active Hash or tag each deployed policy
Decision and reason Distinguishes deny, allow, and approval Include the matched rule
Request hash Preserves the raw argument without leaking it Hash untrusted paths before logging
Outcome Closes the loop from decision to result Log success, denial, and revocation

For incident response, rehearse three moves: revoke delegated authority, narrow the capability allowlist, and rotate any credential that may have been exposed. Because authority is delegated rather than embedded in the runtime, revocation should not require an agent redeploy—a key advantage of the gateway pattern described earlier. Preserve the evidence trail before clearing logs.

Regulated industries add data classification, residency, retention, and access-review requirements. Do not claim that a sandbox, a gateway, or a test suite creates compliance by itself. Map your controls to the obligations your organization actually has, validate them with the appropriate internal teams, and check current primary sources for any standard you cite. Good ai agent security tools support that work by making decisions inspectable; they do not replace the work.

With architecture, code, tests, and governance connected, the final step is to make the practice repeatable.

Conclusion: Make ai agent security testing Repeatable

A secure file tool is not a clever regex. It is a boundary: canonicalize the path, confine it to a sandboxed root, deny by default, and record the decision. Map the attack surface across identity, prompts, memory, tools, connectors, credentials, data, and multi-step execution. Put authorization before provider access, use delegated and JIT access, require approval where risk is high, and protect results with an evidence trail. Then encode every assumption as a test so ai agent security testing runs on every commit rather than once before launch.

If you want to compare your own design with a governed-gateway approach, I am happy to talk through the tradeoffs—no pitch deck required. You can book a 30-minute architecture discussion.

FAQ

What is ai agent security testing? It is the practice of proving an agent cannot exceed its granted authority. For file tools, that means adversarial tests for traversal, symlinks, encoded paths, and oversized reads, plus logs for every decision.

Which ai agent security best practices matter most for file access? Deny by default, least privilege, a distinct agent identity, delegated OAuth with resource-bound grants, JIT credentials outside the runtime, approval checkpoints, and fail-closed error handling.

What ai agent security tools help enforce the boundary? Policy gateways, MCP/connector allowlists, schema validators, canonicalization helpers like Python pathlib, and test runners. Use them together; no single tool covers the full attack surface.

How do I assess ai agent security architecture attack surface and defense? List every surface the agent can influence, attach one concrete control to each, then test the controls. Include identity, prompts, memory, tools, connectors, credentials, data, and multi-step execution.

Can delegated OAuth replace sandboxing? No. OAuth limits which resources are reachable; sandboxing limits what a tool will accept. Use both so a valid token cannot be tricked into reading an unintended path.

Further Reading

Start where you are

Have a workflow
worth rethinking?

Bring us the problem, not a predetermined solution. We will help you identify the opportunity, map the path to production and define what success looks like.

Start an AI discovery session AI opportunity workshop / proof of value / engineering pod / enterprise transformation