Sub topic 12
Running the agent in a sandbox
This chapter assumes you know basic Docker usage, can read short Python and YAML, and have read the earlier chapters on the agent's privileges and the combination of private data, untrusted input, and an outbound channel. Here you will learn how to contain an agent so that a successful injection has limited effect.
Why a sandbox helps
A sandbox is an isolated environment that restricts what a running process can see and do. You cannot reliably stop a model from following injected text. You can limit what that text can accomplish once the model follows it.
A sandbox works on the capabilities side of the problem. It does not examine prompts. It removes things an attacker would need:
- Files outside the project, such as
~/.ssh, cloud credentials, and browser profiles. - Environment variables that hold tokens.
- Network access to arbitrary hosts.
- Permission to change the host system.
If the injection cannot find a secret or cannot send it anywhere, the attack fails even when the model is fully fooled.
What to isolate
Think of four resources the agent's commands can reach.
| Resource | Risk if exposed | Sandbox control |
|---|---|---|
| Filesystem | Reading keys, rewriting shell startup files | Mount only the project directory |
| Environment | Tokens in variables such as `GITHUB_TOKEN` | Start with an empty environment, pass only what is needed |
| Network | Sending data out, downloading payloads | Disable it or allowlist hosts |
| Kernel and privileges | Escaping the container, changing the host | Drop capabilities, run as a non-root user |
Isolation options
Different mechanisms give different strength and cost.
| Option | Isolation strength | Cost and notes |
|---|---|---|
| Restricted working directory only | Very weak | The process still sees your whole user account |
| Separate OS user | Moderate | Easy to set up, but network and shared files remain exposed |
| Container | Good for most cases | Shares the host kernel, so a kernel bug can break out |
| Virtual machine or microVM | Strong | Slower to start and heavier to manage |
| Disposable cloud runner | Strong, and also limits blast radius | Needs CI setup, and secrets must still be handled carefully |
A container is a sensible default for a local developer workflow. Move to a virtual machine when the repository is hostile by assumption, for example when you review code from unknown contributors.
A locked-down container
The following command runs a test suite in a container with no network, no extra Linux capabilities, and a read-only root filesystem.
docker run --rm \
--network none \
--cap-drop ALL \
--read-only \
--tmpfs /tmp \
-v "$PWD":/work \
-w /work \
python:3.12-slim \
python -m pytest -qEach flag has a purpose:
--network noneremoves every network interface except loopback. Injected text cannot send data to a server.--cap-drop ALLremoves Linux capabilities, the fine-grained root powers such as changing file ownership or binding low ports.--read-onlymakes the container's root filesystem unwritable, so the process cannot install tools or modify system files.--tmpfs /tmpgives a writable scratch space that lives only in memory.-v "$PWD":/workmounts the project and nothing else.
Notice what is absent. There is no -e flag, so no host environment variable enters the container. There is no mount of your home directory. The container also starts as root by default, so for stronger isolation add --user 1000:1000. Then the files the process creates in /work belong to your normal user, and a kernel or runtime bug has less to work with.
The project mount is still writable. A hostile process can alter or delete files in your working tree, so use version control and review the diff before you trust the result. If the task only reads code, mount it read-only by appending :ro to the volume option.
The flow of a sandboxed run
The agent's decision-making can stay outside the sandbox while its tool execution happens inside. That way the model's API credentials never enter the environment where untrusted code runs.
Tool output returns to the agent and becomes new context. This is another route for untrusted text, so isolation does not remove the need for the other defenses in this tutorial.
Combining the sandbox with an allowlist
A sandbox limits the environment. A command allowlist limits what the agent may request. Using both gives two independent checks. The wrapper below runs only exact argument lists and never invokes a shell, so injected text cannot append ; curl ... or add flags.
import subprocess
ALLOWED = {
('git', 'status'),
('git', 'diff'),
('pytest', '-q'),
}
def run_tool(argv):
if tuple(argv) not in ALLOWED:
raise PermissionError(f'command not allowed: {argv}')
return subprocess.run(argv, capture_output=True, text=True, timeout=60, check=False)Passing a list instead of a string, with no shell=True, means characters like ;, &&, and $(...) have no special meaning. The timeout bounds runaway processes.
Edge cases and gotchas
- Test commands run repository code.
pytestimportsconftest.pyand test files from the repository. A poisoned repository can run arbitrary code even through an allowlisted command. This is why the allowlist alone is not enough and the container still matters. - Mounted secrets defeat the sandbox. Mounting
~/.aws,~/.config/gh, or the Docker socket gives the contained process the keys it was meant to be denied. Mounting/var/run/docker.sockis effectively root on the host. - Network is often needed. Dependency installation requires downloads. Install dependencies in a separate, earlier step with network access, then run the agent's commands offline. For cases that need some access, use a host allowlist, covered in the egress chapter.
- Writable mounts persist. Anything written to the project mount survives the container. A hostile process can plant a git hook in
.git/hooks, or edit a script you will later run on the host. Review changes, and consider excluding.gitfrom the mount or using a fresh clone. - Shared kernel. Containers are not a hard boundary against a determined attacker with a kernel exploit. Use a virtual machine for high-risk work.
- Output as a channel. A sandboxed process can still print secrets into output that the agent then includes in a pull request comment. Keep secrets out of the sandbox, not merely out of the network.
- Developer convenience erodes defaults. People disable
--network nonewhen a command fails. Make the safe path the easy path with a small wrapper script or a prebuilt image.
A practical checklist
- Decide what the task needs: read-only code, write access to one directory, or network.
- Start from an empty environment and add variables one at a time.
- Mount the narrowest directory that works.
- Drop capabilities and run as a non-root user.
- Disable the network, or allowlist hosts.
- Keep model credentials outside the sandbox.
- Review the diff and the logs after the run.
Exercise
You run an agent's test command in a container with --network none, but you also pass -v ~/.aws:/root/.aws so a deployment test works. A malicious issue tells the agent to read the AWS credentials. Does --network none make this safe? Name one thing you would change.
Show answer
It is not safe. --network none stops the process from sending data directly, but the credentials are now inside the sandbox. The agent can still print them into its output, write them into a file in the mounted project, or include them in a pull request comment, and the data then leaves through those channels. Remove the credentials mount and run the deployment test outside the agent's reach, or supply short-lived, narrowly scoped credentials only to a step that does not process untrusted text.
Exercise
Why does the run_tool allowlist pass a list of arguments to subprocess.run instead of a single command string with shell=True?
Show answer
With a list and no shell, the text is passed to the program as literal arguments. Shell metacharacters such as ;, &&, |, and $(...) have no special meaning, so injected text cannot chain a second command. With shell=True, the shell would interpret those characters.