Sandboxing AI Agents: Contain the Work


An AI agent that can execute code, open files, browse the web, or call tools has crossed from language generation into systems operation. The relevant question is no longer whether the model follows instructions most of the time. It is what happens when it follows hostile instructions, makes a flawed plan, receives poisoned tool output, or encounters a bug in the execution layer.
Sandboxing is the containment answer. It is not one technology or a checkbox labelled “containerized.” A useful sandbox is a set of independent limits: process identity, filesystem mounts, network egress, credentials, resources, allowed commands, data flow, and durable audit. If one layer fails, the others keep an untrusted action from becoming a host or production incident.
A Sandbox Is a Set of Boundaries
OWASP’s current agentic-AI guidance calls tool execution a high-risk action and recommends defence in depth: allowlist tool inputs, isolated execution with no host filesystem or unrestricted network, low-privilege identities without production credentials, and recorded invocations. Those controls work together because each addresses a different failure mode.
| Boundary | Question it answers | Safe default |
|---|---|---|
| Process | What code can execute as this identity? | Ephemeral, non-root runtime |
| Filesystem | Which files can it read or change? | Empty workspace plus explicit read/write mounts |
| Network | Which services can it reach? | No egress, then allowlist specific destinations |
| Credentials | What authority does it inherit? | No ambient secrets; short-lived scoped grants only |
| Resources | How much damage can a loop cause? | CPU, memory, time, disk, and process limits |
| Tool interface | What can the agent ask for? | Typed, allowlisted domain operations |
A container may help with process and filesystem isolation, but it can still mount a host directory, inherit a cloud token, reach an internal metadata endpoint, or consume the machine’s resources. Calling that configuration a sandbox creates false confidence.
Start With a Threat Model
Write down what the agent can receive and what it can affect. Untrusted input includes user prompts, pasted documents, repository files, web pages, retrieved text, tool descriptions, and responses from third-party services. Indirect prompt injection is dangerous precisely because an attacker can hide instructions in a source the agent is expected to read.
Then list consequences: data exfiltration, shell injection, credential theft, destructive writes, lateral movement, runaway spend, and supply-chain compromise. The mitigation should match the consequence. A code interpreter that only needs to transform a CSV should not be able to reach production databases. A web retrieval tool should not be able to call private network addresses merely because a model generated a URL.
A Prompt Is Not a Security Boundary
Telling an agent not to read secrets or call destructive tools can reduce ordinary mistakes, but injected or malformed content can change model behaviour. Enforce those limits below the model at the tool and runtime boundary.
Constrain Execution, Files, Network, and Secrets
Create a fresh execution environment for each risky task or tenant boundary. Run as a non-root user with a read-only base image, a temporary writable directory, no host mounts, and a process/time budget. Destroy the workspace after collecting only the declared result and audit metadata. Never mount source-control credentials, SSH keys, cloud environment variables, or a developer home directory “for convenience.”
Network access should default to none. When a task needs a service, route it through an application proxy or allowlist an exact host and protocol. Block private address ranges and cloud metadata endpoints for URL-fetching tools to reduce SSRF risk. A proxy can add request limits, safe headers, content-type checks, and an audit record without giving an interpreter arbitrary egress.
Give tools short-lived, scoped credentials only at the moment they need them. A sandbox that holds a production administrator token is not meaningfully contained. For many actions, the safer design is no credential in the sandbox at all: submit a validated domain command to a separate policy-enforcing service.
Make Tool Calls Narrow and Observable
Do not expose runShell, readAnyFile, or callAnyApi if the product need is “run this lint command against the supplied repository” or “create a draft response.” Domain tools can validate parameters, set working directories, select a fixed executable, constrain output, and reject unexpected flags before execution.
type LintRequest = { files: readonly string[] };
export async function lintWorkspace(input: LintRequest, run: AgentRun) {
const files = input.files.filter(
(file) => file.startsWith("src/") && file.endsWith(".ts")
);
if (files.length === 0 || files.length !== input.files.length)
throw new Error("Invalid file selection");
return sandbox.execute({
command: ["pnpm", "eslint", "--", ...files],
workspace: run.ephemeralWorkspace,
network: "none",
timeoutMs: 30_000,
runAs: "agent",
});
}The model chooses from a constrained capability, not arbitrary shell syntax. Log the run ID, capability, normalized inputs, sandbox policy version, duration, exit outcome, and safe result summary. Avoid retaining secrets or full untrusted content in logs; make an escape attempt visible without creating a secondary data leak.
Test Escapes and Recover Safely
Test containment as an adversary would. Try path traversal, symlinks, hidden prompt instructions, shell metacharacters, oversized archives, loops, outbound requests, cloud metadata addresses, cross-tenant workspaces, cancelled jobs, and a tool that returns malicious-looking content. Assert that the action is denied or contained and that the host, credentials, and unrelated tenant data remain untouched.
Resource limits need a recovery path. Kill and record timed-out execution, clean temporary storage, revoke a run’s grants, and surface a controlled result to the orchestrator. A timeout should not become a retry storm that creates another identical sandbox every second. Pair budgets with backoff and a human escalation path for tasks that genuinely need more capacity.
Separate the control plane from the workspace
The system that creates a sandbox, records policy, and grants a capability should not live inside the sandbox it governs. Keep orchestration, billing limits, approval state, and long-lived audit storage in a control plane with its own tightly scoped identity. The worker receives only the task inputs and short-lived rights necessary to execute its declared capability.
This separation improves incident handling. Operators can cancel a run, revoke its grant, quarantine a suspicious image, or inspect a safe event record without attaching to an untrusted process. It also makes tenant isolation concrete: every workspace, output object, and policy decision is associated with a run and tenant rather than relying on a model’s memory of which customer it is helping.
Supply chain and image discipline
Sandbox images and third-party tool servers are part of the security boundary. Pin dependencies, keep base images minimal, scan and update them deliberately, and record image or tool versions in the audit event. A sandbox with a known vulnerable runtime or an unreviewed tool extension can be isolated and still be compromised from inside.
Make outbound artifact collection explicit. If an agent creates a report, validate its format and size, store it under a tenant-scoped destination, and serve it through a separately authorized download path. Do not automatically copy every generated file, cache directory, or execution transcript back into the application’s permanent storage.
A practical rollout sequence
Start with the highest-risk execution mode, usually arbitrary code or shell access. Remove host mounts and ambient credentials, enforce a short timeout, and block all egress. Next, introduce a narrow proxy or domain tools for the few services the workflow genuinely needs. Add per-tenant workspaces and durable run/audit records. Finally, red-team the boundary with known escape and prompt-injection scenarios before expanding capabilities.
Each stage should improve containment even if the final platform design is not complete. The most valuable early move is often deleting a broad credential from an agent environment. The goal is not a claim that agents are perfectly safe; it is a system where a predictable failure stays bounded, observable, and recoverable.
Key Takeaways
- A sandbox is defence in depth across process, filesystem, network, credentials, resource budgets, and tool interfaces.
- Treat every source an agent reads as potentially hostile; prompts and policies alone do not enforce containment.
- Start with empty, ephemeral, non-root execution and no network or ambient secrets, then grant specific needs.
- Prefer narrow domain tools over arbitrary shell, filesystem, or API access.
- Test escapes, resource exhaustion, cancellation, and poisoned tool outputs as first-class production scenarios.
Next, we begin December with the TypeScript boundary beneath every production service: Node.js modules, runtime values, asynchronous I/O, configuration, and the places compile-time types end.