Lesson 3 of 6 · Safety
Sandboxing
Run AI agent actions in a sandbox: containers, microVMs and WebAssembly, workspace-only files, network allowlists, resource limits and fresh environments.
- 6 min read
- Advanced
- Reviewed
- Explain what a sandbox is and when agents need one
- Compare containers, microVMs and WebAssembly as sandboxes
- Restrict file access to a workspace and block path traversal
- Limit network access with an allowlist, and resources with limits
- Keep secrets out of the sandbox and start fresh for each task
A safe room for risky work
Some agent tasks involve running code: analysing a spreadsheet with Python, building and testing software, opening files a user uploaded, browsing websites. That code could be wrong, or written by an attacker who influenced the agent. It must run somewhere it can't hurt anything important.
Sandboxes come in several strengths:
| Kind | How it isolates | Typical use |
|---|---|---|
| Container (e.g. Docker) | Separate files, processes and network, sharing the host's operating system kernel | Running tools and tests; good with extra hardening |
| MicroVM (e.g. Firecracker) or gVisor | A tiny virtual machine, or a layer that intercepts system calls, adding a stronger barrier to the host | Running untrusted code for many users |
| WebAssembly | Code runs in a sandboxed virtual machine inside a browser or runtime, with no direct access to the system | Running code in the browser |
Every Python example on this site runs in WebAssembly (Pyodide) inside your browser's sandbox: it can't read your files or reach your other tabs.
Files: the workspace only
An agent's file tool should only reach the agent's workspace. The classic attack is path traversal: asking for ../../etc/passwd to climb out of the folder. Here's a check, plus an audit of a sandbox's settings:
import posixpath
# 1) A file tool that can only touch files inside the agent's workspace folder
WORKSPACE = "/sandbox/work"
def safe_path(requested):
full = posixpath.normpath(posixpath.join(WORKSPACE, requested))
if full != WORKSPACE and not full.startswith(WORKSPACE + "/"):
raise PermissionError(f"outside the workspace: {full}")
return full
for request in ["report.csv", "data/../report.csv", "../../etc/passwd", "/etc/shadow", "/sandbox/work-old/keys.txt"]:
try:
print(f"{request:<28} -> allowed: {safe_path(request)}")
except PermissionError as e:
print(f"{request:<28} -> BLOCKED ({e})")
# 2) Audit the settings of the container that will run the agent's code
config = {
"network": "all", # "none", or a list of allowed hosts
"mounts": ["/sandbox/work", "/home/alex"],
"env": {"PYTHONPATH": "/sandbox/lib", "AWS_SECRET_ACCESS_KEY": "..."},
"timeout_seconds": None,
"memory_mb": 512,
"runs_as_root": True,
}
problems = []
if config["network"] == "all":
problems.append("network: allow no hosts, or only the hosts the task needs")
problems += [f"mount {m}: only mount the workspace" for m in config["mounts"] if m != WORKSPACE]
problems += [f"env {k}: never put secrets inside the sandbox" for k in config["env"] if "SECRET" in k or "KEY" in k]
if not config["timeout_seconds"]:
problems.append("timeout: set one, so runaway code is stopped")
if config["runs_as_root"]:
problems.append("user: run as an unprivileged user, not root")
print("\nSandbox problems:")
print("\n".join(" - " + p for p in problems))The path check normalises each request and only accepts results inside /sandbox/work. Notice /sandbox/work-old/keys.txt: a careless check, “starts with /sandbox/work”, would have let it through, so the code checks for /sandbox/work/ with the slash.
The audit found five common problems in one configuration: unrestricted network, the user's home folder mounted inside, a secret key in the environment, no timeout, and running as root.
Network, resources and secrets
Network. By default, a sandbox should have no network access. If the task needs some, allow only specific hosts, over HTTPS (the exercise below builds this check). Unrestricted network turns any compromise into data theft.
Resources. Set limits on processor time, memory, disk space and the number of processes, plus a timeout for the whole task. Code written by a model sometimes loops forever or loads a huge file by accident.
Secrets. Never put API keys, passwords or tokens inside the sandbox. If code in the sandbox needs to call an API, route the call through a tool outside the sandbox that holds the key and checks each request.
Fresh environments. Start each task in a new, clean sandbox and destroy it afterwards. Nothing from one user's task should be visible in the next.
Common mistakes
Write the network allowlist for a sandbox: code running inside may only reach approved hosts, over HTTPS.
from urllib.parse import urlparse
ALLOWED_HOSTS = {"api.weather.example", "docs.python.org"}
urls = ["https://api.weather.example/today", "http://api.weather.example/today",
"https://api.weather.example.evil.example/x", "https://evil.example/?next=docs.python.org",
"https://docs.python.org/3/"]
# Allow a URL only if its scheme is https AND its host is exactly one of ALLOWED_HOSTS.
# For each URL print "allow" or "block".
A sandbox needs to call one weather API. What is the best network setting?
Summary
- A sandbox isolates risky work: containers, microVMs or WebAssembly, depending on how untrusted the code is.
- Restrict files to the workspace and block path traversal; in-process checks are a layer, not the wall.
- Default to no network, or an HTTPS allowlist; set resource limits and a timeout.
- Keep secrets out, run as an unprivileged user, and use a fresh sandbox per task.
Next: approval gates.
Finished reading? Tick it off to track your progress.