Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 25 min · revision 2

Sandboxing Code Execution

Run model-written code in a throwaway Docker container with no secrets, no network, a read-only filesystem, a non-root user and memory, process and time limits; test every limit with harmless probes, and add an egress policy that checks hosts, resolved addresses and each redirect.

Contentsand lesson path

What you will learn

  • Run model-generated code and risky tools in a sandbox with no secrets, restricted network egress and resource limits.

Prerequisites: AI Security, Tool Calling

01. Goal and setup

Many agents write and run code, for example to total a spreadsheet. That code comes from the model, whose output any untrusted text in its context can shape, so treat it as if a stranger had sent it. Run it where it cannot read secrets, reach your network or exhaust the machine.

A sandbox limits what a program can see and do; here it is a Docker container. A container is a normal process that the Linux kernel isolates: it gets its own view of files, processes and network interfaces, plus limits on memory, CPU and process count. It still shares the host's kernel. That is fine for code from your own team or a single tenant, but a kernel bug can let code escape. For hostile code from many tenants on shared hosts, use a stronger boundary: gVisor, which puts a user-space kernel between the code and the host kernel, or a microVM such as Firecracker, which gives each run its own small virtual machine. The harness below does not change; with gVisor installed, you would add --runtime=runsc to the command.

Two things are not sandboxes. Python's exec() with "restricted" globals runs inside your own process, where well-known tricks reach the rest of the interpreter, and a thread in your API server shares its memory, files and environment variables.

The model's code is JavaScript run by Node.js, because the official Node image is small; the harness is Python.

You need: Docker Engine (tested with 29.8.0) on Linux or Docker Desktop, the image node:22-bookworm-slim, Python 3.10 or later (tested with 3.12.13) and pytest 9.2.0. No API key: a fake model returns fixed code.

Files in this lab
sandbox/
├── fake_model.py    step 1: stands in for the model, returns fixed code
├── sandbox.py       step 2: builds the docker command and enforces the time limit
├── run_task.py      step 3: runs the model's code on a small CSV
├── probes.py        step 4: harmless probes of each limit
├── test_sandbox.py  step 5: regression tests for the limits
├── egress.py        step 7: policy for code or tools that must fetch URLs
└── test_egress.py   step 7: tests with a fake resolver, no network
Terminal
docker pull node:22-bookworm-slim
mkdir sandbox && cd sandbox
python3 -m venv .venv && . .venv/bin/activate
pip install pytest==9.2.0
docker run --rm node:22-bookworm-slim node -e "console.log('docker ok')"
Expected output (last line; pull and pip print progress first)
docker ok

02. Step 1: The model's code

fake_model.py plays the model: asked to total sales.csv per region, it returns a short Node.js program. In a real agent this string would arrive in the input of a tool_use block, for a tool such as run_code.

Python · sandbox/fake_model.py
"""A stand-in for the model: returns fixed JavaScript for one data task.

A real agent would get this code from a `tool_use` block of a model reply
(model from ANTHROPIC_MODEL, for example claude-sonnet-5-5).
"""
TASK = "Total the amounts in sales.csv per region."

CODE = """
const fs = require('fs');
const rows = fs.readFileSync('sales.csv', 'utf8').trim().split('\\n').slice(1);
const totals = {};
for (const row of rows) {
  const [region, amount] = row.split(',');
  totals[region] = (totals[region] || 0) + Number(amount);
}
console.log(JSON.stringify(totals));
"""

03. Step 2: The sandbox command

docker_command() lists every restriction as a flag, so a reviewer can read the whole policy in one place:

  • --network none gives the container only a loopback interface: no route out and no DNS.
  • --read-only makes the root filesystem read-only. --tmpfs /tmp adds 16 MB of scratch space in memory, mounted noexec: binaries written there cannot be started, though Node can still read a script from it.
  • --memory 128m --memory-swap 128m caps memory. Setting both to the same value means no extra swap, so a process that goes over the limit is killed instead of slowing the host.
  • --pids-limit caps the number of processes and threads, which stops runaway spawning. --cpus 1 caps CPU time.
  • --user 65534:65534 runs as nobody. --cap-drop ALL removes the Linux capabilities root would have, and no-new-privileges stops a program from gaining privileges later.
  • The input files are mounted read-only at /work.

No secrets comes from what the harness leaves out. Docker does not copy the host's environment variables into a container; they get in only through -e or --env-file, and this command uses neither. The harness also starts the Docker client with only PATH, HOME and DOCKER_HOST, so even a later -e NAME without a value would find nothing to copy.

The time limit needs care. subprocess.run(..., timeout=...) kills the Docker client when time runs out, but the container is a separate process managed by the Docker daemon, and it keeps running. That is why the except branch removes the container by name. Output for the model is cut to 4,000 characters, so a huge print cannot flood its context.

Python · sandbox/sandbox.py
"""Run model-written JavaScript in a locked-down, throwaway container."""
import os
import subprocess
import tempfile
import uuid

IMAGE = os.environ.get("SANDBOX_IMAGE", "node:22-bookworm-slim")
PREFIX = os.environ.get("SANDBOX_PREFIX", "sandbox")
MAX_OUTPUT = 4000  # characters of stdout returned to the model
# The Docker client gets only what it needs to find the daemon, nothing of the app's.
CLIENT_VARS = ("PATH", "HOME", "DOCKER_HOST")
CLIENT_ENV = {k: v for k, v in os.environ.items() if k in CLIENT_VARS}


def docker_command(name, workdir, memory="128m", pids=64):
    return [
        "docker", "run", "--rm", "--name", name,
        "--network", "none",                           # no interfaces except lo
        "--read-only",                                 # root filesystem read-only
        "--tmpfs", "/tmp:rw,noexec,nosuid,size=16m",   # small scratch space
        "--memory", memory, "--memory-swap", memory,   # no swap beyond the limit
        "--pids-limit", str(pids), "--cpus", "1",
        "--user", "65534:65534",                       # nobody, not root
        "--cap-drop", "ALL", "--security-opt", "no-new-privileges",
        "-v", f"{workdir}:/work:ro", "-w", "/work",
        IMAGE, "node", "/work/main.js",
    ]


def run_js(code, files=None, timeout_s=10, **limits):
    """Return (exit_code, stdout). Exit code 124 means the time limit was hit."""
    name = f"{PREFIX}-{uuid.uuid4().hex[:8]}"
    with tempfile.TemporaryDirectory() as workdir:
        os.chmod(workdir, 0o755)
        for filename, text in {"main.js": code, **(files or {})}.items():
            path = os.path.join(workdir, filename)
            with open(path, "w") as f:
                f.write(text)
            os.chmod(path, 0o644)
        cmd = docker_command(name, workdir, **limits)
        try:
            done = subprocess.run(cmd, capture_output=True, text=True,
                                  timeout=timeout_s, env=CLIENT_ENV)
        except subprocess.TimeoutExpired:
            # Killing the docker client does not stop the container: remove it.
            subprocess.run(["docker", "rm", "-f", name], capture_output=True)
            return 124, ""
        return done.returncode, done.stdout[:MAX_OUTPUT]

04. Step 3: Run the model's code

run_task.py puts a fake database password into its own environment, then runs the model's code with sales.csv mounted beside it.

Python · sandbox/run_task.py
import os

from fake_model import CODE, TASK
from sandbox import run_js

SALES = "region,amount\nnorth,120\nsouth,80\nnorth,30\n"
os.environ["DEMO_DB_PASSWORD"] = "not-a-real-secret"  # lives in the host process

print("task:", TASK)
code, out = run_js(CODE, files={"sales.csv": SALES})
print("exit:", code)
print("stdout:", out.strip())
Terminal
python run_task.py
Expected output
task: Total the amounts in sales.csv per region.
exit: 0
stdout: {"north":150,"south":80}

05. Step 4: Probe each limit

An untested sandbox is a guess. Each probe is a harmless one-line program that tries one thing and prints the result. The network probes are aimed at 192.0.2.10, an address reserved for documentation that is never used on the internet, so nothing leaves your machine even if you run the probe without the sandbox.

Python · sandbox/probes.py
"""Harmless probes: each checks one limit of the sandbox and prints what it saw."""
import os

from sandbox import run_js

os.environ["DEMO_DB_PASSWORD"] = "not-a-real-secret"

PROBES = {
    "user id": "console.log(process.getuid())",
    "env names": "console.log(Object.keys(process.env).sort().join(' '))",
    "write /": """
try { require('fs').writeFileSync('/probe.txt', 'x'); console.log('written') }
catch (e) { console.log(e.code) }""",
    "write /tmp": "require('fs').writeFileSync('/tmp/p.txt', 'x'); console.log('ok')",
    "interfaces": "console.log(Object.keys(require('os').networkInterfaces()))",
    "dns lookup": "require('dns').lookup('example.com', (e) => console.log(e?.code))",
    "connect": """
require('net').connect(80, '192.0.2.10')
  .on('connect', () => console.log('connected'))
  .on('error', (e) => console.log(e.code))""",
}

for label, code in PROBES.items():
    exit_code, out = run_js(code)
    print(f"{label:<11} exit={exit_code} {out.strip()}")
Terminal
python probes.py
Expected output
user id     exit=0 65534
env names   exit=0 HOME HOSTNAME NODE_VERSION PATH PWD YARN_VERSION
write /     exit=0 EROFS
write /tmp  exit=0 ok
interfaces  exit=0 [ 'lo' ]
dns lookup  exit=0 EAI_AGAIN
connect     exit=0 ENETUNREACH

The code runs as user 65534. Its environment holds only the variables that the image sets, and no DEMO_DB_PASSWORD. Writing to / fails with EROFS (read-only file system), while /tmp works. The only network interface is lo, so the DNS lookup fails with EAI_AGAIN and the connection with ENETUNREACH: there is no route at all. Only names are printed, because the image sets the values.

06. Step 5: Regression tests for the limits

The memory test allocates 320 MB in a 128 MB container and expects exit code 137, which means the process was killed with SIGKILL, here by the kernel's out-of-memory handling. The process test starts 100 sleep processes with a limit of 32 and expects some starts to fail. The time test runs an endless loop, expects code 124 and checks that no container with the prefix is left behind. The capability test reads /proc/self/status: CapEff is what the process can use now, CapBnd the most it could ever gain. As nobody, CapEff is 0 anyway, so the test also checks CapBnd, which only --cap-drop ALL empties; NoNewPrivs: 1 comes from no-new-privileges.

Python · sandbox/test_sandbox.py
"""Regression tests for the sandbox limits. They need Docker and the image."""
import os
import shutil
import subprocess

import pytest

import sandbox
from sandbox import run_js

pytestmark = pytest.mark.skipif(shutil.which("docker") is None, reason="no docker")


def test_host_secrets_do_not_reach_the_code(monkeypatch):
    monkeypatch.setenv("DEMO_DB_PASSWORD", "not-a-real-secret")
    _, out = run_js("console.log(JSON.stringify(process.env))")
    assert "DEMO_DB_PASSWORD" not in out and "not-a-real-secret" not in out


def test_a_stray_env_flag_still_finds_no_secret(monkeypatch):
    monkeypatch.setenv("DEMO_DB_PASSWORD", "not-a-real-secret")
    build = sandbox.docker_command

    def with_env_flag(*args, **kwargs):
        cmd = build(*args, **kwargs)
        return cmd[:2] + ["-e", "DEMO_DB_PASSWORD"] + cmd[2:]  # a later edit, say

    monkeypatch.setattr(sandbox, "docker_command", with_env_flag)
    _, out = run_js("console.log(process.env.DEMO_DB_PASSWORD || 'unset')")
    assert out.strip() == "unset"


def test_runs_as_nobody_with_read_only_root():
    _, out = run_js("""
console.log(process.getuid());
try { require('fs').writeFileSync('/x', '1') } catch (e) { console.log(e.code) }""")
    assert out.split() == ["65534", "EROFS"]


def test_no_capabilities_and_no_new_privileges():
    _, out = run_js("""
const status = require('fs').readFileSync('/proc/self/status', 'utf8');
console.log(status.match(/^(CapEff|CapBnd|NoNewPrivs):.*$/gm).join(' '));""")
    assert out.split() == ["CapEff:", "0000000000000000", "CapBnd:", "0000000000000000",
                           "NoNewPrivs:", "1"]


def test_no_network_route_and_no_dns():
    _, out = run_js("""
require('dns').lookup('example.com', (e) => console.log(e ? e.code : 'resolved'));
require('net').connect(80, '192.0.2.10').on('error', (e) => console.log(e.code))
  .on('connect', () => console.log('connected'));""")
    assert sorted(out.split()) == ["EAI_AGAIN", "ENETUNREACH"]


def test_memory_limit_kills_the_process():
    code, out = run_js("""
const keep = [];
for (let i = 0; i < 20; i++) keep.push(Buffer.alloc(16 * 1024 * 1024, 1));
console.log('allocated 320 MB');""")
    assert code == 137 and out == ""  # 137 = killed by SIGKILL (out of memory)


def test_process_limit_stops_runaway_spawning():
    _, out = run_js("""
const { spawn } = require('child_process');
let errors = 0;
const kids = [];
for (let i = 0; i < 100; i++) {
  const k = spawn('sleep', ['2']);
  k.on('error', () => { errors += 1 });
  kids.push(k);
}
setTimeout(() => { console.log(errors > 0); kids.forEach((k) => k.kill()) }, 500);""",
                    pids=32)
    assert out.strip() == "true"


def test_time_limit_kills_and_removes_the_container():
    code, _ = run_js("while (true) {}", timeout_s=2)
    assert code == 124
    left = subprocess.run(
        ["docker", "ps", "-aq", "--filter", f"name={sandbox.PREFIX}-"],
        capture_output=True, text=True).stdout
    assert left == ""


def test_output_returned_to_the_model_is_capped():
    _, out = run_js("console.log('a'.repeat(10000))")
    assert len(out) == sandbox.MAX_OUTPUT


def test_input_files_are_read_only():
    _, out = run_js("""
try { require('fs').writeFileSync('/work/main.js', '') }
catch (e) { console.log(e.code) }""")
    assert out.strip() == "EROFS"
Terminal
python -m pytest -q test_sandbox.py
Illustrative output (the counts are exact; the time differs)
..........                                                               [100%]
10 passed in 5.90s

07. Step 6: Remove one layer and watch a test fail

Make a backup of sandbox.py, delete the line "--read-only", and run the tests again.

Terminal
cp sandbox.py sandbox.py.bak
# delete the "--read-only" line in sandbox.py, then:
python -m pytest -q --tb=no test_sandbox.py
mv sandbox.py.bak sandbox.py
Illustrative output (the counts are exact; the time and line width differ)
..F.......                                                               [100%]
=========================== short test summary info ============================
FAILED test_sandbox.py::test_runs_as_nobody_with_read_only_root - AssertionEr...
1 failed, 9 passed in 5.80s

Run the tests with --tb=short before restoring the file and the message shows why: the write to / still failed, but with EACCES (permission denied) from the nobody user instead of EROFS. Two layers were protecting the root filesystem and you removed one. The test asserts the exact error, so it notices the missing layer even though the write was still blocked. That is the point of defence in depth: each layer should hold on its own, and each layer you rely on should have its own test.

08. Step 7: When the code needs the network

If a task needs internet data, do not remove --network none. Even with no secrets inside, open egress lets code send out the data it is working on, download other tools or probe your internal network. Instead, keep the sandbox closed and let one component fetch for it, a fetch tool or an egress proxy, applying a policy like check_url().

The policy guards against server-side request forgery (SSRF): tricking a server into making requests to places the attacker cannot reach directly, such as internal services or the cloud metadata endpoint at 169.254.169.254, which can hand out credentials. The checks are, in order: HTTPS only; the host must be on an allowlist; and every address the host resolves to must be public. The policy checks the resolved addresses with ipaddress instead of matching the host string, because a host string can hide an internal address in forms such as 2130706433 (127.0.0.1 written as one number, which resolvers accept) or ::ffff:10.0.0.7 (an IPv4 address inside an IPv6 one). The MCP security best practices give the same advice and suggest an egress proxy such as Smokescreen in production.

Two more traps. DNS rebinding means a name resolves to a public address when you check it and a private one when you connect, so check_url() returns the checked address and the caller must connect to that address. Redirects can point anywhere, so follow() turns off automatic redirects and checks every hop before sending it.

Python · sandbox/egress.py
"""Egress policy for a tool or sandbox that must fetch URLs.

Run this logic in the one component that makes the request (a fetch tool or an
egress proxy), and run it again for every redirect hop.
"""
import ipaddress
import socket
from urllib.parse import urlsplit

ALLOWED_HOSTS = {"api.weather.example", "files.partner.example"}


class Blocked(Exception):
    pass


def system_resolve(host):
    return [info[4][0] for info in socket.getaddrinfo(host, 443)]


def check_url(url, resolve=system_resolve):
    """Return the IP to connect to, or raise Blocked."""
    parts = urlsplit(url)
    if parts.scheme != "https":
        raise Blocked(f"scheme {parts.scheme!r} is not allowed")
    host = (parts.hostname or "").lower()
    if host not in ALLOWED_HOSTS:
        raise Blocked(f"host {host!r} is not on the allowlist")
    addresses = resolve(host)
    for raw in addresses:
        ip = ipaddress.ip_address(raw)
        ip = getattr(ip, "ipv4_mapped", None) or ip  # ::ffff:10.0.0.1 -> 10.0.0.1
        if not ip.is_global:
            raise Blocked(f"{host} resolves to non-public address {ip}")
    return addresses[0]  # connect to this IP, so a second lookup cannot change it


def follow(url, fetch_hop, resolve=system_resolve, max_hops=3):
    """Follow redirects by hand, checking every hop before any request is sent."""
    for _ in range(max_hops + 1):
        ip = check_url(url, resolve)
        status, location = fetch_hop(url, ip)
        if status not in (301, 302, 303, 307, 308):
            return url, status
        url = location
    raise Blocked("too many redirects")
Python · sandbox/test_egress.py
"""Egress tests with a fake resolver and fake HTTP hops: no packets leave the host."""
import pytest

from egress import Blocked, check_url, follow

DNS = {
    "api.weather.example": ["93.184.215.14"],
    "files.partner.example": ["::ffff:10.0.0.7"],  # e.g. after a DNS change
}


def fake_resolve(host):
    return DNS[host]


def test_allowlisted_public_host_passes():
    ip = check_url("https://api.weather.example/today", fake_resolve)
    assert ip == "93.184.215.14"


@pytest.mark.parametrize("url, reason", [
    ("http://api.weather.example/today", "scheme 'http'"),
    ("https://weather.example.net/", "not on the allowlist"),
    ("https://169.254.169.254/latest/meta-data/", "not on the allowlist"),
    ("https://2130706433/", "not on the allowlist"),  # 127.0.0.1 written as a number
    ("https://files.partner.example/report.csv", "non-public address 10.0.0.7"),
])
def test_blocked_before_any_request(url, reason):
    with pytest.raises(Blocked, match=reason):
        check_url(url, fake_resolve)


def test_redirect_to_metadata_address_is_blocked():
    sent = []

    def fake_hop(url, ip):
        sent.append(url)
        return 302, "https://169.254.169.254/latest/meta-data/"

    with pytest.raises(Blocked, match="not on the allowlist"):
        follow("https://api.weather.example/today", fake_hop, fake_resolve)
    assert sent == ["https://api.weather.example/today"]  # second hop never sent
Terminal
python -m pytest -q test_egress.py
Illustrative output (the counts are exact; the time differs)
.......                                                                  [100%]
7 passed in 0.02s

09. Troubleshooting

10. Check your understanding

Practice check · 3 questions

Sandbox limits

Answer from the code and the output in this lab.

Q1. In step 6, the probe still could not write to `/` after you removed `--read-only`. Why did a test fail anyway?
Q2. `run_js('while (true) {}', timeout_s=2)` hits the time limit. What happens if the `except` branch does not run `docker rm -f`?
Q3. With the fake DNS of `test_egress.py`, why is `https://files.partner.example/report.csv` blocked even though the host is on the allowlist?
Practice only: not graded, not saved, not evidence.

11. Apply it

For the practice project, run every code-execution tool of your agent through a harness like run_js(), with the limits written in one place. Add a regression test for each limit, and one that fails if any environment variable of your app process appears inside the sandbox. If a tool must fetch URLs, route it through an egress policy and add the fixture from the practice brief: an allowlisted URL that redirects to a private address must be refused before the second request is sent. Note which isolation you chose (container, gVisor or microVM) and why it fits who can send you code.

12. Review prompt

Without looking back: name the three properties a sandbox for model-written code needs, and the Docker flags that give each one. Explain why a timeout on the Docker client is not enough, why a container is a weaker boundary than gVisor or a microVM, and when that matters. Then list the checks an egress policy makes and say how it handles DNS rebinding and redirects.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check