[Blog](https://cohesivity.ai/blog)

Reliability & production

Published Jul 27, 2026·Updated Aug 30, 2026

![](https://cohesivity.ai/authors/anshu.webp)![](https://cohesivity.ai/authors/shouryamaan.webp)[Anshu](https://www.linkedin.com/in/aanshuaggrawal120/) and [Shouryamaan](https://www.linkedin.com/in/shouryamaanjain/)

# Sandboxing AI Agents: A Practical Guide to Secure Code Execution

[Read as Markdown](https://cohesivity.ai/blog/sandboxing-ai-agents-secure-code-execution.md)

Sandbox

Sandbox

Isolated

Ephemeral

Sandboxing an AI agent means executing untrusted or model-generated code inside a bounded environment with explicit filesystem, process, network, credential, resource, lifetime, artifact, and cleanup controls. A container name alone does not prove those properties.

Start from what the code must access, then deny everything else. If a task only needs a typed API call, remove code execution rather than sandboxing it.

## Write the threat model first

Assume generated code may:

- read every mounted file and environment variable;
- scan internal and public networks;
- contact a command server or exfiltrate output;
- fork processes, fill disk, allocate memory, or print unlimited data;
- persist through modified files, packages, caches, or scheduled work;
- inspect cloud metadata or local runtime sockets;
- target another tenant’s artifacts or credentials.

Prompt instructions do not reduce this threat. The runtime must enforce the boundary even when the code intentionally tries to escape it.

## Isolate the filesystem and process tree

Create an ephemeral workspace for each execution. Mount only required inputs, preferably read-only. Do not mount the host repository, container socket, home directory, cloud configuration, SSH keys, or shared package caches.

Run as an unprivileged user, drop capabilities, restrict system calls where supported, and cap processes. Terminating a top-level command must also terminate its children. A wall-clock timeout that leaves background processes alive is incomplete cleanup.

Export approved artifacts through a narrow service. Validate paths and file types, set size limits, and copy outputs out before destroying the workspace.

## Deny network access by default

Many code tasks need no network. For those that do, route egress through an allowlist or authenticated proxy. Control DNS and IP access, including private ranges, loopback, link-local addresses, and cloud metadata endpoints.

An allowlisted domain can redirect or resolve to an unexpected address, so validate at connection time. Avoid giving generated code direct access to internal service discovery.

If web access is the task, a browser tool with policy and session isolation may be safer than unrestricted sockets. Treat downloaded files and page instructions as untrusted.

## Inject narrow, short-lived credentials

Do not inherit the application server’s environment. Issue a task-scoped credential for the exact resource and operation, then expire or revoke it after execution. Keep management, billing, and provisioning credentials outside the sandbox.

Assume any credential placed inside can be read by the code. A “hidden” environment variable is available to the process. The security question is whether that credential is acceptable to lose within its scope and lifetime.

The [agent security guide](https://cohesivity.ai/blog/ai-agent-security-identity-permissions-secrets-audit-logs) covers downstream authorization and audit requirements.

## Bound every resource and output channel

Set CPU, memory, disk, process, file, network, stdout, stderr, and wall-clock limits. Limit package installation and dependency sources. Stop or quarantine repeated policy violations.

Return structured summaries or capped logs to the model. Unlimited terminal output can consume memory, tokens, and observability storage even when the runtime itself remains isolated.

## Choose the isolation depth from the workload

Trusted application code may fit an in-process function or background worker. Code that needs package separation may fit a restricted container. Untrusted generated code needs a hardened sandbox, and workloads requiring a stronger kernel boundary or privileged system access may need a dedicated VM.

The [compute escalation ladder](https://cohesivity.ai/blog/ai-agent-compute-escalation-ladder) maps those tiers to code trust, network, lifetime, state, and latency. Cloudflare’s [Project Think](https://blog.cloudflare.com/project-think/) presents a related tiered approach; its product tiers are examples rather than universal boundaries.

## Make cleanup observable and idempotent

Record the execution ID, tenant, image or runtime version, policy, credential reference, timestamps, resource usage, artifact references, exit class, and cleanup result. Cleanup should run after success, failure, timeout, cancellation, and worker crash.

Use a reconciler to find expired environments that survived process failure. Revoking credentials and deleting the environment should be safe to repeat.

## Test the boundary without risking production

In a dedicated test environment, attempt to read disallowed mounts, list environment variables, reach private and public destinations, access metadata, spawn excess processes, fill output, survive termination, and retrieve another tenant’s artifact. Verify each attempt is denied and recorded without exposing sensitive values.

Also test the permitted path. Excessive restriction that breaks every real task encourages teams to add broad exceptions. Keep each exception specific, reviewed, and connected to the workload that needs it.

The prompt below audits the configured boundary without running attack code. It distinguishes provider promises from settings present in this repository, which is where sandbox reviews often uncover gaps.

or send it to[Claude Code](https://claude.ai/new?q=Inspect+this+repository%27s+code-execution+path+and+sandbox+configuration.+Do+not+execute+untrusted+code%2C+reveal+secrets%2C+or+edit+files.+Map+the+boundary+for+filesystem+mounts%2C+host+processes%2C+kernel%2C+network+egress%2C+metadata+services%2C+credentials%2C+CPU%2C+memory%2C+process+count%2C+output+size%2C+wall-clock+lifetime%2C+artifacts%2C+and+cleanup.+Identify+which+controls+are+provider+guarantees+and+which+are+application+configuration.+Design+safe+tests+for+disallowed+file+access%2C+network+destinations%2C+secret+discovery%2C+fork+or+output+exhaustion%2C+termination%2C+and+cross-tenant+artifacts.+Report+missing+controls+before+recommending+a+runtime. "Send to Claude")[Cursor](https://cursor.com/link/prompt?text=Inspect+this+repository%27s+code-execution+path+and+sandbox+configuration.+Do+not+execute+untrusted+code%2C+reveal+secrets%2C+or+edit+files.+Map+the+boundary+for+filesystem+mounts%2C+host+processes%2C+kernel%2C+network+egress%2C+metadata+services%2C+credentials%2C+CPU%2C+memory%2C+process+count%2C+output+size%2C+wall-clock+lifetime%2C+artifacts%2C+and+cleanup.+Identify+which+controls+are+provider+guarantees+and+which+are+application+configuration.+Design+safe+tests+for+disallowed+file+access%2C+network+destinations%2C+secret+discovery%2C+fork+or+output+exhaustion%2C+termination%2C+and+cross-tenant+artifacts.+Report+missing+controls+before+recommending+a+runtime. "Send to Cursor")[Codex](https://chatgpt.com/codex?prompt=Inspect+this+repository%27s+code-execution+path+and+sandbox+configuration.+Do+not+execute+untrusted+code%2C+reveal+secrets%2C+or+edit+files.+Map+the+boundary+for+filesystem+mounts%2C+host+processes%2C+kernel%2C+network+egress%2C+metadata+services%2C+credentials%2C+CPU%2C+memory%2C+process+count%2C+output+size%2C+wall-clock+lifetime%2C+artifacts%2C+and+cleanup.+Identify+which+controls+are+provider+guarantees+and+which+are+application+configuration.+Design+safe+tests+for+disallowed+file+access%2C+network+destinations%2C+secret+discovery%2C+fork+or+output+exhaustion%2C+termination%2C+and+cross-tenant+artifacts.+Report+missing+controls+before+recommending+a+runtime. "Send to Codex")[opencode](https://opencode.ai/?q=Inspect+this+repository%27s+code-execution+path+and+sandbox+configuration.+Do+not+execute+untrusted+code%2C+reveal+secrets%2C+or+edit+files.+Map+the+boundary+for+filesystem+mounts%2C+host+processes%2C+kernel%2C+network+egress%2C+metadata+services%2C+credentials%2C+CPU%2C+memory%2C+process+count%2C+output+size%2C+wall-clock+lifetime%2C+artifacts%2C+and+cleanup.+Identify+which+controls+are+provider+guarantees+and+which+are+application+configuration.+Design+safe+tests+for+disallowed+file+access%2C+network+destinations%2C+secret+discovery%2C+fork+or+output+exhaustion%2C+termination%2C+and+cross-tenant+artifacts.+Report+missing+controls+before+recommending+a+runtime. "Send to OpenCode")
