An AI agent sandbox is a short-lived, policy-bound execution environment for code, files, browsers and other powerful tools. It assumes the model can be mistaken, manipulated by untrusted content or induced to combine legitimate capabilities dangerously. The sandbox limits what one run can observe, change and communicate, then produces evidence for inspection and destroys the environment. Input and output guardrails remain useful, but they do not replace operating-system, identity and network containment.
Tool-using agents cross several trust boundaries at once. Generated code is untrusted. Downloaded files may be hostile. Web pages can contain instructions aimed at the model. Credentials may grant real authority. Outputs can carry active content or secrets. The OWASP agentic AI threats and mitigations resource and MITRE ATLAS provide threat-oriented references; an implementation should translate those threats into concrete process, filesystem, network, credential and artifact controls.
Threat-model the complete tool path
Map actors, assets and channels: user, model, orchestrator, tool broker, sandbox worker, browser, package registry, internal service, artifact store and reviewer. Identify secrets, source code, customer data, tokens, cookies, signing keys and internal network reachability. Consider malicious prompts, indirect instructions in documents, dependency compromise, decompression bombs, resource exhaustion, cross-run residue, browser session theft, data exfiltration through DNS or images and unsafe output opened by a person.
Define impact by workflow. A public-data analysis sandbox can tolerate different exposure from a code assistant attached to proprietary repositories. Do not use one broad 'safe sandbox' label. Specify the data classes admitted, capabilities granted, destinations allowed, artifact types exported and maximum duration. Record assumptions about host isolation and cloud metadata. Every trust assumption should map to a control or an explicit residual risk accepted by an owner.
Layer isolation instead of trusting one boundary
| Layer | Control objective | Example mechanism | Acceptance evidence |
|---|---|---|---|
| Workload | Separate runs and tenants | Dedicated microVM, VM or hardened container policy | Cross-workload access test |
| Process | Constrain syscalls, privilege and resources | Non-root user, syscall filter, cgroup and limits | Escape and exhaustion tests |
| Filesystem | Expose only required paths | Read-only base, scoped mounts and ephemeral overlay | Traversal and residue tests |
| Network | Permit declared destinations and protocols | Default-deny egress proxy and private-address block | DNS, redirect and tunnel tests |
| Identity | Grant task-specific short authority | Brokered token bound to resource and expiry | Replay and scope tests |
| Artifact | Prevent unsafe export | Type validation, malware scan and active-content policy | Known-bad and polyglot samples |
No layer proves the others. Containerization without egress policy still permits exfiltration. Network isolation without scoped credentials still exposes reachable resources. A read-only base does not stop a malicious document from being exported. Choose the workload technology from adversary model, multitenancy and consequence, then harden the host and orchestration plane. Keep sandbox management interfaces on a separate privileged path unavailable to the agent.
Grant capabilities per task and tool
Represent filesystem read, filesystem write, shell execution, browser navigation, download, upload and network access as separate capabilities. A data-cleaning task may read one input object and write one output prefix without browser access. A browser research task may reach public HTTPS sites but should not inherit internal repository credentials. Capabilities should include resource, operation, duration, volume and destination. The runtime enforces them regardless of what the model claims it needs.
The agent tool permissions guide explains bounded action authority. Apply that model inside the sandbox with a broker that validates each operation. Avoid mounting a general cloud credential or user's home directory. For high-risk capability escalation, pause and show the requested scope, reason and affected resource. Approval grants one bounded capability token, not unrestricted shell access for the rest of the conversation.
Default-deny egress and control browser identity

Route outbound traffic through an authenticated policy proxy. Resolve and validate destinations, block loopback, link-local, private and metadata ranges unless explicitly required, and recheck redirects. Restrict protocols, ports, request methods, upload size and response size. Domain allowlists help but are insufficient when trusted sites host user content or redirects. Inspect destination class and workflow purpose. Deny arbitrary DNS and covert channels where the threat model requires it, and rate-limit connection attempts.
Browser sessions are credentials. Create a fresh profile per run, disable password managers and extensions, isolate downloads, and destroy cookies at teardown. If authenticated browsing is necessary, broker a scoped session for a named site and action. Separate read-only browsing from form submission, file upload, purchase and message sending. Web content remains untrusted data even after TLS succeeds; the browser tool should label page text as evidence, not privileged instruction.
Constrain code, files and dependencies
| Tool | Primary risk | Minimum control | Export gate |
|---|---|---|---|
| Shell | Escape, destructive command and resource abuse | Non-root, syscall and resource limits, no host socket | Command log and output size check |
| Interpreter | Generated code imports unsafe modules | Pinned runtime and module allow policy | Result schema and file inventory |
| Package manager | Dependency compromise and lifecycle scripts | Approved registry, lockfile, no scripts by default | Dependency manifest and vulnerability policy |
| Filesystem | Traversal, secret discovery and residue | Scoped mounts and canonical path enforcement | Allowlisted output paths only |
| Archive handler | Traversal and decompression bomb | Entry, depth and expanded-size limits | Normalized file list and scan |
| Browser | Indirect instruction and session misuse | Fresh profile, destination and action controls | Active-content and disclosure review |
Use immutable, patched base images and verify their provenance. Disable package installation unless needed; when enabled, use approved registries, pinned versions, integrity verification and a cache that does not leak private packages across tenants. Block or review install scripts. Set CPU, memory, process, disk, file-count and wall-clock limits. A timed-out run should terminate child processes and network connections, not merely stop waiting at the orchestrator.
Broker ephemeral credentials outside the model
Keep long-lived secrets out of prompts, environment dumps and mounted files. The sandbox authenticates to a broker with workload identity; the broker issues a short-lived credential bound to task, resource and operation. Prefer services that accept downscoped tokens and preconditions. Do not reveal the token to generated code when a local proxy can perform the authorized operation. Revoke on cancellation, approval expiry or anomaly, and prevent reuse from another workload.
The NIST Zero Trust Architecture rejects implicit trust based on network location and focuses on resource-level authentication and authorization. Apply that principle inside the sandbox: being in an approved worker does not authorize every internal service. Validate subject, workload posture, action and resource at each brokered request. Log decisions with token identifiers and scopes, not secret values.
Treat exported artifacts as a second trust boundary
List every created and modified file before export. Validate media type from content, normalize filenames, reject traversal and device names, scan for malware and secrets, and apply active-content policy. Office documents, PDFs, HTML, notebooks and archives can contain scripts, links or embedded objects. Render previews in another isolated environment. A text response should be checked for credential patterns and data policy, while binary outputs require type-specific controls.
Store artifacts in quarantine with hash, producing run, source inputs, tool history and scan results. Promotion to a user-visible or production location should be a separate authorized action. If an artifact will enter another automated workflow, attach provenance and classification so downstream agents do not treat it as trusted merely because an internal sandbox produced it. The AI guardrails security review complements containment with input, output and workflow controls.
Observe and test the containment boundary
Record image and policy versions, capabilities, resource use, denied operations, destinations, broker decisions, file inventory, scan disposition and teardown result. Keep command and browser payload capture proportional to sensitivity. Alert on repeated denials, metadata-address access, unusual upload volume, process-limit pressure, credential replay or teardown failure. Preserve a minimal forensic package for high-risk anomalies without leaving the sandbox running indefinitely.
Test cross-run residue, mount escape, host-socket access, symlink races, archive traversal, DNS rebinding, redirect to private addresses, protocol smuggling, fork bombs, disk exhaustion, browser cookie persistence and artifact polyglots. Use the NIST SSDF AI profile to integrate these controls into secure development and release. The prompt engineering security review can supply adversarial content cases, but success means the runtime contains unsafe intent even when the model follows it.
Run periodic compromise exercises that begin with a realistic indirect instruction inside a webpage, repository or document. Observe whether the agent requests an undeclared capability, whether the broker refuses it, whether egress and artifact controls contain alternate paths, and whether operators receive enough evidence to investigate. Repeat after runtime, browser, base-image and policy changes. Containment confidence comes from the complete chain resisting the scenario, not from one isolation component passing its own unit tests.
Key takeaways
- Assume generated code, retrieved content and downloaded files are untrusted.
- Layer workload, process, filesystem, network, identity and artifact isolation.
- Grant task-specific capabilities and short-lived credentials through an external broker.
- Use default-deny egress with redirect, private-address and browser-session controls.
- Quarantine and inspect outputs before they cross into user or production environments.
- Test escapes, covert paths, resource abuse and cross-run residue as release requirements.
Frequently asked questions
Is a container enough for an AI agent sandbox? It may be one isolation layer, but the decision depends on multitenancy and threat impact. Network, identity, filesystem and artifact controls remain necessary regardless.
Can an agent have internet access safely? It can have policy-bound access to approved destinations and operations. Unrestricted egress makes containment and data-loss prevention substantially weaker.
Should the sandbox keep state between runs? Default to fresh ephemeral state. Persist only explicit artifacts or caches with provenance, tenant separation, scanning and lifecycle controls.
Conclusion
An AI agent sandbox is a runtime containment system, not a label attached to a code executor. Start from the tool path and assets, layer isolation, grant capabilities and credentials narrowly, deny undeclared egress and inspect every exported artifact. Observe policy decisions and repeatedly test the boundary under hostile content and resource pressure. That architecture lets agents use powerful tools while keeping one mistaken or manipulated run from inheriting the reach of the host, the user or the enterprise network.