---
title: "How to Run AI-Generated Code Safely in an AI Agent Sandbox"
description: "Run AI-generated code safely in an AI agent sandbox. E2B gives each session its own microVM and kernel, no secrets, allowlisted egress, and a timeout."
date: 2026-11-23
author: vaish-puri
categories:
  - guides
tags:
  - python
  - js-ts
thumbnail: "./thumbnail.png"
thumbnailAlt: "E2B logo above the headline How to run AI-generated code safely, in white and orange type over a grey dithered pattern on black"
---

To run AI-generated code safely, treat it as untrusted and execute it in a disposable sandbox that:

- Has its own kernel.
- Serves a single user session.
- Holds no secrets.
- Reaches only allowlisted hosts.
- Accepts no public inbound traffic.
- Shuts down on a timeout.

<Callout href="https://console.e2b.dev/sign-up?signup_source=blog_run_ai_code_safely" label="Get started" ctaId="blog_run_ai_code_safely">Run your first sandbox in minutes.</Callout>

Say a customer gives an AI agent a CSV and asks a question. The agent writes and runs a Python script to find the answer. That script can be influenced by other content the model is reading, including support tickets or web pages your team doesn’t control. If the script runs directly on your application server, it inherits the permissions of the process running it, potentially giving it access to application data, credentials, and connected services.

With E2B, every sandbox runs its own kernel, shuts down on a timeout, and accepts no public inbound traffic. This guide explains why options like Docker are not enough to contain model-written code and how your company can safely run AI-generated code.

## Why is AI-generated code untrusted?

AI-generated code is untrusted because the model writes it from input you do not control, and often nobody reviews it before it runs. Your engineers' code goes through review and CI before it ships. An agent's code usually runs within seconds of being written, and in most products no person ever reads it.

Prompt injection is the best-known way this goes wrong. An agent reading a web page, an email, a README, or an uploaded file can pick up instructions that someone planted there for it to find. When an agent has more functionality, permissions, or autonomy than its task needs, OWASP calls it [excessive agency](https://genai.owasp.org/llmrisk/llm062025-excessive-agency/), and a prompt injection, or a plain hallucination, can turn that into harm. NVIDIA’s AI Red Team [demonstrated this in PandasAI](https://developer.nvidia.com/blog/how-code-execution-drives-key-risks-in-agentic-ai-systems) (CVE-2024-12366): the library checked generated code against a filter, but injected requests produced code that reached dangerous functions through modules the filter trusted, and that code ran on the application's machine. A filter can't anticipate every path generated code can take, which is a big part of why sandboxing code after it's written tends to work better.

Models also make up package names. A [USENIX Security 2025 study](https://arxiv.org/abs/2406.10279) generated 576,000 code samples with 16 models and checked the packages in each one: on average, at least 5.2% of the packages that commercial models recommended, and 21.7% of those from open-source models, did not exist, which added up to 205,474 unique invented names. Attackers can register those names on PyPI and npm, a trick now called slopsquatting. An agent that runs `pip install` on a name it invented may be installing their code.

On a host, environment variables and potentially the whole file system are at risk. For instance, [we tried](/resources/limitations-of-running-ai-agents-locally) AutoGen on a stock analysis task and the agent saved its chart straight to the developer's disk. This was of course harmless that day, but it is a chilling reminder that this is exactly the kind of access you do not want an agent to have.

## Is Docker enough to run AI-generated code?

No. Docker containers keep processes apart with Linux namespaces and cgroups, but all the containers on a host run on the same kernel, and a bug in that kernel is a way out of every one of them. [NIST SP 800-190](https://nvlpubs.nist.gov/nistpubs/specialpublications/nist.sp.800-190.pdf) notes that container runtimes do not isolate workloads as strongly as hypervisors do.

Untrusted code tends to run behind one of these boundaries, and what separates them is how much of the host kernel the code can touch.

| Boundary | What it shares with the host | What an exploitable kernel flaw gets an attacker | Fits |
| --- | --- | --- | --- |
| Docker container | The host kernel. Namespaces change what the process sees; cgroups limit what it uses. | The host, and every other container on it | Code your team wrote and trusts |
| gVisor | Less. A user-space kernel called the Sentry implements the code's system calls itself and makes only a restricted set of its own calls to the host. | The gVisor layer first, then a host bug on top of it | Workloads that need more than a container and can accept some compatibility limits |
| Firecracker microVM | No shared kernel. Each guest runs its own kernel behind KVM hardware virtualization, and reaches the host only through KVM and Firecracker's small device model. | Its own guest kernel. Reaching the host takes a separate hypervisor escape. | Untrusted and multi-tenant code |

The case study of [Copy Fail](https://xint.io/blog/copy-fail-linux-distributions) (CVE-2026-31431) shows what sharing a kernel can cost. The flaw lets an unprivileged process inside a container change four bytes in the kernel’s shared page cache, affecting every container that reads the same file. Theori, the cybersecurity firm that disclosed the flaw, published a [Kubernetes walkthrough](https://xint.io/blog/copy-fail-pod-to-host) in which a pod overwrites the cached copy of the host's `runc` binary and gets a root shell on the node.

[E2B sandboxes weren't affected](/resources/not-affected-by-copy-fail-heres-why), for two reasons:

- Every sandbox is its own Firecracker microVM with its own kernel and page cache, so an exploit inside the sandbox stays there; reaching the host would also take a Firecracker escape.
- E2B builds minimal kernels for agent sandboxes. The vulnerable module has never been compiled into them, because agents don't need it, and fewer kernel features leave fewer places for bugs.

ClickUp applies this exact safeguard to its AI agents, ensuring that model-generated code interacting with sensitive workspace data remains strictly contained. In the video below, the team details why they run these workloads inside isolated microVMs, avoiding a shared host kernel altogether.

<Video provider="youtube" id="Q3AodHNoj3g" url="https://www.youtube.com/embed/Q3AodHNoj3g" title="Why ClickUp runs AI code in microVMs that don't share the host kernel" uploadDate="2026-11-23T06:23:16-08:00" />

Agents that need to run Docker themselves hit a second problem. Testing a customer's development environment, for example, means starting containers inside the sandbox, and in a container-based sandbox that usually requires privileged mode (which gives up most of the isolation) or isn't possible at all. [Lark](/customers/lark-case-study) runs end-to-end tests against customer apps, sometimes with real customer data in reach, and that one requirement ruled out most of the providers it looked at. Jack Brown, Lark's CEO, said the team doesn't want "an agent in one sandbox to be peeping into another sandbox."

For code a model wrote from input you do not control, developers should use a boundary that has its own kernel.

## 8 controls for running AI-generated code safely

Isolation decides what a kernel bug can reach. Everything else on this list is about what the code can reach without one, which covers your credentials, your network, other users' data, and your cloud bill.

| Control | What it stops | How E2B handles it | Default? |
| --- | --- | --- | --- |
| Own kernel per sandbox | Kernel exploits and container escapes such as Copy Fail | Every sandbox is a Firecracker microVM with its own minimal kernel and its own page cache | On by default |
| One sandbox per session, never shared | One user's code reading another user's files or state | Create a sandbox per session and keep a server-side map from user to sandbox ID | Your code |
| No secrets inside the sandbox | Code reading keys from environment variables or files | [Stored secrets](https://docs.e2b.dev/secrets) injected into outbound HTTPS by the egress proxy, or short-lived [workload identity](https://docs.e2b.dev/iam/workload-identity) tokens that a service such as AWS STS exchanges for temporary credentials | Opt-in |
| Default-deny egress with a short allowlist | Data leaving the sandbox, and second-stage downloads | `allowInternetAccess: false`, or deny all traffic and allow specific domains or IP ranges ([docs](https://docs.e2b.dev/network/internet-access)) | Opt-in; internet access is on by default |
| No route to internal networks or cloud metadata endpoints | Reaching internal services or cloud credentials | Outbound traffic to private and link-local ranges is blocked for every sandbox ([docs](https://docs.e2b.dev/network/restrict-public-access)) | On by default |
| Private ingress | Anyone reaching a server the code starts | `allowPublicTraffic: false`, after which every request to the sandbox URL needs its traffic access token | On by default for projects created after October 30, 2026 |
| Time and resource caps | Infinite loops and runaway compute cost | A sandbox timeout (5 minutes by default, then the sandbox is killed), per-run timeouts, CPU count set at creation (up to the template's maximum), and memory set in the template ([docs](https://docs.e2b.dev/faq/sandbox-lifetime)) | Timeout on by default |
| Log the run, then destroy the sandbox | No record of what ran, and state left behind for the next user | Store each run's code and output under its sandbox ID in your application, then call `kill()` in `finally`. A paused sandbox keeps its state until it is killed. | Your code |

Rogo, which builds agents for hundreds of financial firms, runs 10,000 to 15,000 concurrent sandboxes on E2B. Its agents run behind domain-based network allowlists, and its templates ship with the scripts and Python packages the agents use, so sandboxes don't install dependencies on every run. Alex Wang, from Rogo's applied AI team, describes per-session isolation as "a hard requirement" for its clients.

Read more about this in our [Rogo case study](/customers/rogo).

## How to run AI-generated code in an offline sandbox with E2B

To start, turn internet access off when you create the sandbox, give it a sandbox timeout and a per-run timeout, and kill it in a `finally` block. Most code-interpreter work doesn't need the internet at all, as an agent analyzing a spreadsheet or plotting a chart needs only the data and a few libraries.

Create the sandbox with no outbound internet, private URLs, and a 60-second lifetime. You need an E2B API key and the Code Interpreter SDK:

<CodeGroup>

```python
from e2b_code_interpreter import Sandbox

sandbox = Sandbox.create(
    allow_internet_access=False,
    network={"allow_public_traffic": False},
    timeout=60,
)
try:
    execution = sandbox.run_code(model_code, timeout=20)
    if execution.error:
        raise RuntimeError(f"{execution.error.name}: {execution.error.value}")
finally:
    sandbox.kill()
```

```javascript
import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create({
  allowInternetAccess: false,
  network: { allowPublicTraffic: false },
  timeoutMs: 60_000,
})

try {
  const execution = await sandbox.runCode(modelCode, { timeoutMs: 20_000 })
  if (execution.error) {
    throw new Error(`${execution.error.name}: ${execution.error.value}`)
  }
} finally {
  await sandbox.kill()
}
```

</CodeGroup>

<Link href="https://console.e2b.dev/sign-up?signup_source=blog_run_ai_code_safely" data-cta-id="blog_run_ai_code_safely">Get an API key</Link> to run this example.

After 60 seconds, the sandbox timeout kills the sandbox. After 20 seconds, the run timeout ends your app’s wait with a timeout error, and the code keeps running in the sandbox. Calling `kill()` in `finally` destroys the sandbox and anything still running in it, whether the run succeeds, fails, or times out.

With outbound internet access disabled, `pip` can still install local wheels, but it can’t download packages from PyPI. If your agent needs extra libraries, extend [E2B’s `code-interpreter-v1` template](https://docs.e2b.dev/code-interpreting/customize-template), install them at build time, and pass the custom template’s name to `Sandbox.create()`.

## How to run untrusted code from an AI agent with E2B

Begin by only allowing the hosts the agent needs, and keeping its credentials out of the sandbox entirely. Agents that call APIs or clone repositories need the network. So keep the list of allowed destinations short, and put no secret where the code can read it. Close inbound traffic too. In E2B, that's one option when you create the sandbox.

Say your agent calls an external API from its sandbox, such as a model provider or a search service. The quick way is to pass the API key in as an environment variable. But then any code in the sandbox can read it, including code that a prompt injection wrote. That code can send the key anywhere the network allows.

E2B can keep the key out of the sandbox. Your backend stores the secret once, and a network rule refers to it by name. When a matching HTTPS request leaves the sandbox, E2B's egress proxy adds the real value. The code inside never holds it, though the destination receives it and could send it back in a response, so inject keys only into hosts you trust. [Workload identity](https://docs.e2b.dev/iam/workload-identity) does the same for cloud access. E2B issues short-lived identity tokens, which a service like AWS STS can exchange for temporary credentials. No long-lived cloud key is ever in the sandbox. Stored secrets and workload identity are generally available on E2B Cloud. The per-host request transforms that inject them are in public beta.

### Worked example: credential injection at the sandbox boundary

This example reads a Stripe test balance. Create a restricted Stripe test key with read access to **Balance**. On your backend, set `E2B_API_KEY` and `STRIPE_RESTRICTED_TEST_KEY`, then run either setup snippet once. Use a current [E2B SDK](https://docs.e2b.dev/quickstart).

#### 1. Store the API key once

<CodeGroup>

```python
import os
from e2b import Secret

Secret.create("stripe-balance-demo", os.environ["STRIPE_RESTRICTED_TEST_KEY"])
```

```javascript
import { Secret } from 'e2b'

const key = process.env.STRIPE_RESTRICTED_TEST_KEY
if (!key) throw new Error('Set STRIPE_RESTRICTED_TEST_KEY on the backend')

await Secret.create('stripe-balance-demo', key)
```

</CodeGroup>

#### 2. Call the API from the sandbox

Allow outbound requests to `api.stripe.com` and deny other destinations. `Secret.fill()` puts a reference to the stored key in the network rule. The proxy resolves that reference when it forwards a matching HTTPS request. Set `allow_public_traffic` or `allowPublicTraffic` to `false` at creation to require a traffic access token on the sandbox’s public URLs.

When `allowOut` lists a domain, E2B also opens all traffic to `8.8.8.8`, Google’s public resolver, so names can resolve. These examples turn that off with `dns_servers=[]`, pin `api.stripe.com` in `/etc/hosts`, and empty `/etc/resolv.conf` so other lookups fail at once instead of waiting on the blocked resolver. E2B routes HTTPS by hostname, so any public IP works in the hosts entry and no DNS lookup is needed. Hostname filtering applies to HTTP on port 80 and TLS on port 443; other traffic is filtered by IP only, and on shared endpoints such as CDNs, allowing one hostname can allow others on the same endpoint.

<CodeGroup>

```python
import json
from e2b import Sandbox, Secret

sandbox = Sandbox.create(
    timeout=60,
    network={
        "allow_out": lambda ctx: list(ctx.rules.keys()),
        "deny_out": lambda ctx: [ctx.all_traffic],
        "dns_servers": [],
        "allow_public_traffic": False,
        "rules": {
            "api.stripe.com": [
                {
                    "transform": {
                        "headers": {"Authorization": f"Bearer {Secret.fill('stripe-balance-demo')}"},
                    },
                },
            ],
        },
    },
)

try:
    # Any public IP works here, E2B routes the request by name
    sandbox.commands.run(
        "echo '1.1.1.1 api.stripe.com' >> /etc/hosts && : > /etc/resolv.conf",
        user="root",
        timeout=5,
    )
    result = sandbox.commands.run(
        "curl --silent --show-error --fail-with-body --max-time 15 https://api.stripe.com/v1/balance",
        timeout=20,
    )
    # Keep only the fields you need: the response is untrusted output.
    available = [(b["amount"], b["currency"]) for b in json.loads(result.stdout)["available"]]
    print("Available balance:", available)
finally:
    sandbox.kill()
```

```javascript
import { Sandbox, Secret } from 'e2b'

const sandbox = await Sandbox.create({
  timeoutMs: 60_000,
  network: {
    allowOut: ({ rules }) => [...rules.keys()],
    denyOut: ({ allTraffic }) => [allTraffic],
    dnsServers: [],
    allowPublicTraffic: false,
    rules: {
      'api.stripe.com': [
        {
          transform: {
            headers: { Authorization: `Bearer ${Secret.fill('stripe-balance-demo')}` },
          },
        },
      ],
    },
  },
})

try {
  // Any public IP works here, E2B routes the request by name
  await sandbox.commands.run(
    "echo '1.1.1.1 api.stripe.com' >> /etc/hosts && : > /etc/resolv.conf",
    { user: 'root', timeoutMs: 5_000 }
  )
  const result = await sandbox.commands.run(
    'curl --silent --show-error --fail-with-body --max-time 15 https://api.stripe.com/v1/balance',
    { timeoutMs: 20_000 }
  )
  // Keep only the fields you need: the response is untrusted output.
  const available = JSON.parse(result.stdout).available.map(
    ({ amount, currency }) => [amount, currency]
  )
  console.log('Available balance:', available)
} finally {
  await sandbox.kill()
}
```

</CodeGroup>

In this example, the egress proxy adds the Stripe key to the curl request as it leaves the sandbox, so the code in the sandbox never holds the key. If the secret name does not resolve, the request is sent without the key, and `--fail-with-body` turns Stripe's 401 into an error from `commands.run`.

`Secret.fill()` returns a placeholder, so the sandbox's network config names the secret without ever holding its value. Public traffic can only be turned off at creation.

If the agent needs only one operation, such as reading a balance, your backend can make the API call and return just the result. For cloud access, [E2B Workload Identity](/resources/introducing-e2b-workload-identity) can provide a short-lived token that AWS STS exchanges for temporary role credentials. If your backend returns those credentials to the sandbox, its code can use them until they expire or you revoke the role's sessions, even after the sandbox shuts down if they were copied elsewhere. For the limits of this setup, consult the [internet access](https://docs.e2b.dev/network/internet-access) and [secrets](https://docs.e2b.dev/secrets/inject) documentation.

To adapt the example to other HTTP clients, see [TLS certificates](https://docs.e2b.dev/network/internet-access#tls-certificates) and the [secrets documentation](https://docs.e2b.dev/secrets/inject).

<Image src="./credential-injection.png" alt="Diagram: your backend stores the Stripe key once in E2B Secrets and creates the sandbox. The sandbox sends HTTPS with no key to the egress proxy, which resolves the secret, adds the key, and forwards the request to api.stripe.com. Requests to any other host are blocked, and inbound requests without a token get a 403." width={2000} height={1534} />

Running agents on sensitive data? [E2B Bring Your Own Cloud (Enterprise)](/enterprise) runs E2B sandboxes inside your AWS, Google Cloud, or Azure account.

## What doesn't a sandbox protect against?

A sandbox controls where code can go. Even with all eight controls in place, a few gaps remain.

- Credentials are the biggest gap. An agent holding a GitHub token with delete rights can delete a repository through the allowed API. The sandbox forwards that request like any other. It is imperative to scope every credential to the agent's current task.
- Every line of code in the sandbox can read the files you upload. Only upload what the current user may see.
- Treat output with the same suspicion as input. Code can print a secret. It can also return text that carries a new prompt injection back to the model. If you render HTML it produced, that HTML can run in your interface.
- Keep approval steps for destructive actions. The sandbox will limit the cost of a bad decision, and someone still has to catch the decision itself.
- Finally, the boundary itself is software. A microVM moves it from a shared kernel to a hypervisor with a small interface. That is a much smaller target. The other seven controls exist for the day something in that stack fails.

## FAQ

### Is Docker enough to run AI-generated code?

No. For code generated from untrusted input, use stronger isolation than a standard Docker container provides. Linux containers share a kernel. On affected kernels, Copy Fail (CVE-2026-31431) could corrupt a readable file’s cached contents and affect other containers reading that same file. A Firecracker microVM gives each sandbox its own guest kernel.

### Can I use WebAssembly or Pyodide instead of a server-side sandbox?

Yes. Pyodide runs Python in the browser and supports pure-Python wheels, compatible WebAssembly packages, a virtual filesystem, and HTTP requests subject to browser policies. Use a server-side sandbox when the code needs OS subprocesses, a Linux shell, or native libraries without a compatible WebAssembly build. For untrusted browser code, isolate Pyodide from your signed-in app’s origin because Python can access JavaScript APIs exposed to it.

### Can an E2B sandbox access the internet?

Yes. Outbound internet access is enabled by default. Disable it with `allowInternetAccess: false` in JavaScript or `allow_internet_access=False` in Python. For selective access, deny outbound traffic by default and allow the domains or IP ranges the task needs. A domain allowlist also permits all traffic to the default DNS resolver unless you configure `dnsServers` or `dns_servers`. E2B blocks outbound traffic to private and link-local address ranges on the host network. Inside the sandbox, `169.254.169.254` still answers because it serves the sandbox’s own Firecracker metadata. It exposes no cloud-provider credentials.

### How do I give a sandboxed agent an API key?

Store the key in E2B Secrets and configure the egress proxy to add it to HTTPS requests for the allowed host. Putting the key in a sandbox environment variable makes its value readable by agent code. Proxy injection keeps the value outside the sandbox, but any process in the sandbox can still make requests with the key’s permissions, and the destination receives the value. Scope the key to the operations the agent needs. For cloud access, [E2B Workload Identity](/resources/introducing-e2b-workload-identity) issues short-lived tokens that services such as AWS STS can exchange for temporary credentials. Secrets and Workload Identity are generally available on [E2B Cloud](/pricing). The per-host transforms that inject request headers are in public beta.

### Should each user get their own sandbox?

Yes. For an agent handling customer data, create a fresh sandbox per user session. Store the association between the authenticated user, session, and sandbox ID on your backend. Check ownership on every request before executing code, reading files, or resuming a sandbox. A sandbox ID identifies the resource. Your backend decides who can access it.

### How long does an E2B sandbox live?

By default, E2B kills a sandbox after five minutes. You can set the timeout at creation and reset it while the sandbox runs, or have the timeout pause the sandbox instead of killing it. The continuous runtime limit is one hour on Hobby and 24 hours on Pro. Pausing and resuming starts a new runtime window. A paused sandbox has no automatic expiration. By default, a pause saves both memory and files. A filesystem-only pause saves files and reboots the sandbox on resume. For a one-off job, call `kill()` in `finally` so the sandbox shuts down as soon as the job finishes or fails.

<Callout>Get an <Link href="https://console.e2b.dev/sign-up?signup_source=blog_run_ai_code_safely" data-cta-id="blog_run_ai_code_safely">E2B API key</Link> to run the offline example. To run sandboxes in your own cloud, <Link href="/contact" data-cta-id="blog_run_ai_code_safely_contact">talk to an E2B engineer</Link>.</Callout>
