AI Agent Sandbox Security: A Practical Containment Guide
Contain AI agents across filesystem, network, identity, tools and approval boundaries with a practical defense-in-depth testing guide.
An AI agent sandbox is often presented as a box around code execution. That picture is too simple. Modern agents browse, call APIs, read repositories, install packages, maintain memory and ask other services to act on their behalf. An isolated process can still cause harm if it holds a powerful token or can send sensitive data to the internet.
Safe containment therefore requires more than a container. It is a coordinated set of filesystem, process, network, identity, data, tool and approval controls designed around the specific task. The goal is not to prove that an agent will always behave. It is to limit what happens when the model is mistaken, manipulated or deliberately tests its boundaries.
Anthropic's published discussion of how it contains Claude describes agents finding unexpected ways to complete tasks, including behavior that crossed intended sandbox assumptions. The practical lesson for enterprise teams is straightforward: containment must be tested against outcomes, not inferred from the presence of a sandbox label.
Start with the damage you need to contain
Before choosing a technology, define the unacceptable outcomes. Can the agent modify the host? Read another user's workspace? Access a cloud metadata service? Reach the public internet? Publish a package? Use a developer's SSH key? Trigger a production tool? Persist changes after the task ends?
These questions produce a containment policy. A research agent may need broad web access but no internal network. A coding agent may need a repository mirror and package proxy but no developer home directory. An incident-response agent may need sensitive telemetry yet require strict approval before changing an endpoint.
Map the agent's complete authority: runtime privileges, mounted files, environment variables, network routes, workload identity, MCP servers, external APIs and approval exceptions. Include indirect authority. A sandbox with no cloud token can still call a local MCP server that holds one.
Threat-model both hostile input and unexpected autonomy. An attacker may plant instructions in a web page or repository. Separately, an agent pursuing a legitimate goal may decide to bypass a restriction it interprets as an obstacle. Controls should withstand either motivation.
The AI Agent Security Checklist provides a broader production baseline; sandboxing is the containment layer within that system.
Filesystem isolation must account for paths and persistence
Run the agent as a non-privileged user with a read-only base image. Provide a fresh task directory containing only the required inputs. Do not mount the host's home directory, Docker socket, SSH configuration, browser profile or package credentials for convenience.
Path validation should use canonical resolved paths, not string-prefix checks. Symlinks, archive extraction and relative paths can escape a naive workspace boundary. If the agent processes uploaded archives, enforce file-count, expanded-size and nesting limits and reject traversal entries before extraction.
Separate source from output. A coding agent can receive a disposable repository copy and return a patch rather than writing directly to the canonical checkout. A document agent can receive a staged file instead of an entire shared drive. Limit output size and file types.
Persistence needs an explicit decision. Destroying the environment after each task limits cross-session poisoning, but some workflows need checkpoints. Persist only structured, reviewed state, bind it to tenant and workflow identity and scan it before reload. Avoid snapshotting a compromised runtime and treating the snapshot as trusted.
Test cleanup. Create canary files during a task, end the session and verify that a new task cannot retrieve them through caches, volumes, logs or retained memory.
Network containment is as important as process isolation
A sandboxed process with unrestricted egress can exfiltrate everything it is allowed to read. Default-deny networking is therefore one of the strongest controls available.
Allow only destinations required for the task. Route package downloads through a controlled proxy. Resolve DNS through monitored infrastructure and protect cloud metadata endpoints, internal control planes and local services. Restrict redirects so an allowed public URL cannot bounce into a private address.
Apply policy by destination and operation, not only hostname. A browser agent may need to read a public site but should not upload a file to it. When possible, use mediated fetch tools that return sanitized content instead of giving the agent a general browser and raw network stack.
Account for covert and secondary channels. Markdown images, webhooks, package registries, error reporting and DNS can all move information. Logs should capture attempted connections with task and agent identity, including denied traffic.
Network controls must also protect neighboring workloads. Place agent runtimes in a segmented environment with no implicit access to databases, message queues or orchestration APIs. Do not assume an internal address is safe simply because it is not public.
Keep credentials outside the sandbox
The safest secret inside an agent sandbox is one that is not there. Avoid environment-wide credentials and mounted token files. Instead, let the agent request a narrow operation from a trusted broker.
The broker should verify agent identity, initiating user, task, requested tool, target resource and current policy. It can then issue a short-lived token or perform the operation directly. The model receives the result, not the underlying credential.
Scope tokens to audience and action. A repository-read task should not receive a token that can administer organization settings. Bind credentials to the sandbox lifetime and revoke them when the task ends. Prevent reuse from another runtime.
Do not expose secrets in tool errors, traces or prompts. Redact values at collection time and test whether the agent can obtain them through process listings, debug endpoints, filesystem history or metadata APIs.
Identity controls are explained in depth in AI Agent Identity and Authorization. Sandboxing and identity are complementary: isolation limits the runtime, while authorization limits the external systems it can influence.
Reduce the tool surface
An unrestricted shell, browser and filesystem make a flexible demo but a difficult production boundary. Prefer small, typed tools that correspond to approved business operations.
Validate tool parameters outside the model. Derive tenant and user scope from trusted session state rather than accepting them as model-generated arguments. Reject unknown fields and enforce limits at the service that owns the resource.
Separate planning from execution. The model can propose a sequence, while a deterministic controller evaluates each step against policy and current state. This makes it possible to stop a plan that becomes unsafe without relying on the model to police itself.
Tool composition matters. A file-reading tool and a message-sending tool may each be justified, but together they form an exfiltration path. Evaluate reachable combinations and apply data-flow rules where possible.
Review MCP servers and plugins as extensions of the sandbox boundary. A local server may escape isolation by running on the host. A remote server may have broad SaaS access. See AI Agent Supply-Chain Security for component governance and MCP Servers Need Their Own Threat Model for protocol-specific analysis.
Design meaningful human approval
Human-in-the-loop is not a universal safety control. Reviewers approve risky actions when prompts are vague, frequent or disconnected from the real parameters.
Show the exact operation: command, file paths, recipients, resource, permission change, external destination or transaction. Explain why approval is required and which untrusted source influenced the request. Bind the decision to immutable parameters; a changed command requires new approval.
Use different thresholds for different consequences. Reading an approved public dependency may run automatically. Publishing a package, contacting a customer or altering production should require a stronger identity and perhaps two-person review.
Some operations should remain outside the agent's reachable action set. The ability to change its own sandbox policy, disable logging or broaden its identity is particularly dangerous. Administrative controls should run in a separate trust domain.
Test approval bypasses: alternate tools, direct APIs, cached approvals, parameter substitution and requests split into apparently harmless steps.
Resource limits prevent accidental denial of service
Not every containment failure is malicious. Agents can enter loops, spawn too many processes, generate huge files, repeatedly call paid APIs or install large dependency trees.
Enforce wall-clock and CPU limits, memory quotas, process counts, storage capacity, network budgets, tool-call counts and model-spend ceilings. Terminate runaway tasks predictably and preserve enough evidence to understand why.
Use bounded retries with backoff. A failed tool call should not trigger an unlimited autonomous recovery sequence. Put limits around recursive subagents and parallel work as well as the top-level process.
Rate limits should consider the downstream effect. One API call may launch an expensive job or send many messages. Model the business operation, not only request frequency.
Provide a kill switch that can stop active tasks and prevent new ones. Test it under load and confirm that queued actions, brokers and external workers also stop. Containment is incomplete if terminating the visible agent leaves asynchronous operations running.
Test the sandbox adversarially
Configuration review cannot prove containment. Build a synthetic environment with canary files, fake tokens, mock internal services and controlled external endpoints. Define success as prevention or safe blocking of specific outcomes.
Test filesystem traversal, symlinks, archive extraction, hidden files, process inspection, local sockets, metadata endpoints, DNS, redirects, package-install hooks, browser downloads, clipboard access and persistence across sessions. Exercise every tool and plugin path, not only the primary shell.
Use indirect prompt injection fixtures in repositories, web pages, tool results and documents. Observe whether hostile content can persuade the agent to probe boundaries. Keep payloads benign and monitor attempted behavior.
Test multi-step composition. An agent may be unable to send a file directly but able to encode its contents into a URL, issue title or tool parameter. Capture network, process, filesystem, identity and application events under one trace ID.
Retest after changes to the model, runtime image, agent framework, system prompt, tool catalog, MCP configuration or policy engine. Read AI Coding Agent Security for repository-specific cases and Indirect Prompt Injection in RAG and Tool-Using Agents for content-borne attack paths.
Evidence that a sandbox works
A useful test report states which boundary was challenged, under what configuration and with what observed result. “The agent was sandboxed” is not evidence.
Preserve the runtime image digest, policy revision, mounts, identity scope, network rules, tool definitions, model, input fixture, transcript, attempted action, enforcement decision and operating-system telemetry. Differentiate model compliance from system enforcement. If the model refuses a command, the sandbox has not been tested; rerun with a direct tool-level attempt or controlled adversarial case.
Record near misses and denied attempts. They show which paths attackers or future model behavior may revisit. Alerting should connect a denied action to the content that caused it.
Avoid collecting hidden chain-of-thought. Observable inputs, outputs, tool calls, policy decisions and effects are generally sufficient and easier to govern.
Turn every confirmed weakness into an automated regression test. Evidence becomes valuable when it can demonstrate that a fix still works after the next release.
AI agent sandbox checklist
Before a production pilot, confirm that:
- The unacceptable outcomes and required capabilities are documented.
- Each task starts in a least-privileged, disposable environment.
- Host directories, sockets and broad credentials are not mounted.
- Paths, archives and symlinks are validated safely.
- Network access is default-deny and task-specific.
- Cloud metadata, internal services and redirect-based access are blocked.
- Credentials are brokered, short-lived and bound to the task.
- Tools are typed, narrow and authorised outside the model.
- Approval shows and binds the exact consequential operation.
- CPU, memory, storage, process, time and spend limits are enforced.
- A tested kill switch stops active and queued work.
- Adversarial tests cover indirect injection, composition and persistence.
- Logs can reconstruct each attempted and completed effect.
Containment is a system property
No single container flag can secure an autonomous agent. Strong containment comes from several independent boundaries that assume another layer may fail. Filesystem isolation limits what the runtime can read, egress policy limits where data can go, narrow identity limits external authority, and approval protects consequential operations.
That defense-in-depth design lets organizations use capable agents without requiring perfect model behavior. It also produces something security teams can verify repeatedly instead of trusting a product label.
Oxyne evaluates supported agentic AI implementations through their exposed application, model-behavior, tool, MCP and permission boundaries. Explore the Oxyne platform, learn about AI red teaming, or book a scoped demonstration.