AI Hints
Home›Agentic AI Tutorial›Security Two
Agentic AI · Lesson 62 of 100

Sandboxing Code

Letting agents run things safely.

⏱ 2 min read▶ Video at 1:50:04🎓 Free
Watch this lesson in the Agentic AI courseWatch on YouTube ↗Full Agentic AI course

Giving an agent the ability to run code is incredibly powerful. It can analyse data, test its own work, and fix bugs. It's also like handing your computer to a stranger. So you need a sandbox. A room that the code can't get out of.

Sandboxing Code
From the video: Sandboxing Code
  • Running code is powerful
  • Like handing a stranger your computer
  • Build a room it can't leave

A basic sandbox

Here's a first step. We run the code in a separate process, in an empty temporary folder, with an empty environment, so there are no keys to steal. And we set a time limit. Three tests. A sum, an endless loop, and an attempt to read a secret. Run it. The sum works. The loop gets stopped. And the secret isn't there. This is better than nothing, but a real attacker could still reach the network and your files.

sandbox.pypython
import subprocess, sys, tempfile

def run_untrusted(code, seconds=2):
    with tempfile.TemporaryDirectory() as folder:
        try:
            r = subprocess.run([sys.executable, "-I", "-c", code], cwd=folder, env={},
                               capture_output=True, text=True, timeout=seconds)
            return r.stdout.strip() or r.stderr.strip().splitlines()[-1]
        except subprocess.TimeoutExpired:
            return "Stopped: took too long"

print(run_untrusted("print(sum(range(100)))"))
print(run_untrusted("while True: pass"))
print(run_untrusted("import os; print(os.environ.get('API_KEY', 'no key here'))"))
Output
4950
Stopped: took too long
no key here

A proper container

For real isolation, use a container. This Docker file creates a non root user. Then we run it with strong limits. No network. A read only file system. Limits on memory and CPU. And we throw the container away after each run. For hostile code, use a stronger barrier, such as a micro virtual machine, or a hosted sandbox service.

Dockerfiledockerfile
FROM python:3.13-slim
RUN useradd --create-home runner
USER runner
WORKDIR /home/runner

Running with limits

Here's the kind of command that you'd use. Each flag closes a door. No network means that data can't get out. Read only stops it changing files. And the memory limit stops it from taking down the machine.

terminal
echo 'docker run --rm --network none --read-only --memory 256m --cpus 0.5 --user runner agent-sandbox python task.py'
docker run --rm --network none --read-only --memory 256m --cpus 0.5 --user runner agent-sandbox python task.py

Levels of isolation

Choose by how much you trust the code. A separate process is enough for your own code. A container suits code written by a model. A micro virtual machine suits code from strangers. And for coding agents, a human review of each command is often added on top.

Who wrote the code?Isolation
YouSeparate process
Your model, your dataContainer, no network
Strangers or the publicMicro-VM or hosted sandbox
Risky commandHuman approval too

Summary

No network, no secrets, time limits, and throw it away afterwards. Next, the complete picture. The official list of agent risks.

Key takeaways
  • Run code away from secrets
  • Use containers for real isolation
  • Match isolation to trust
Next up: The OWASP Top Ten for Agents — the risks everyone should know