How I Secure AI Coding Agents That Run Unattended
// contents
Agents can go wild. They are very determined, obsessed with getting their task done, and they don’t give a damn about anything other than that task. It only takes one wrong decision for an agent to wipe out your server to get rid of a warning.
When you sit next to an agent and approve each command, you are the safety net. When a script runs it at 3 a.m., there is no one to click “Deny”. So whenever I run an agent from a script, I set up the environment so that the worst thing it can do is a bad pull request.
These are the rules I follow. My agent is Claude Code, so the flags and settings below are Claude Code’s, but the ideas carry over to any coding agent.
What I’m protecting against
It helps to name the failures before choosing the defences. I worry about four:
- Destruction. The agent deletes, overwrites or reconfigures something outside its task, because that looked like the shortest path to “done”.
- Leaks. The agent reads a secret and sends it somewhere, either by mistake or because text it read (an issue, a web page, a README) told it to. That second case is prompt injection, and every file and page an agent reads is a way in.
- Cheating. The agent makes the checks pass instead of making the code right: it weakens a test, edits the CI config or rewrites its own instructions.
- Planted configuration. The repository itself carries settings or hooks that run with my rights the moment an agent opens it.
Each rule below closes off one or more of these.
Before the run: decide what the agent can see
1. Load no settings from the repository
The agent runs headless, with --setting-sources "" and --strict-mcp-config. That stops Claude Code from loading user, project or local settings files, and from starting any MCP server I didn’t pass in.
This matters more than it looks. A repository can ship a .claude/settings.json with hooks, and Claude Code’s documentation is explicit that hooks and local MCP servers run outside the sandbox, with your full access. Anyone who can get a commit into a repo could then run code on the machine that hosts your agent. So I load nothing from the repo, and pass in the instructions I do want myself: the base branch’s CLAUDE.md, appended to the system prompt.
claude -p --permission-mode dontAsk --strict-mcp-config --setting-sources "" \
--append-system-prompt-file run/system.md --settings run/settings.json \
--tools Read,Edit,Write,Glob,Grep,Bash --max-budget-usd 5
2. Sandbox it, and fail closed
Claude Code’s sandbox is on, with failIfUnavailable set and allowUnsandboxedCommands turned off. On Linux the sandbox is built on bubblewrap.
The defaults are friendlier than you want in a script. By default, if the sandbox can’t start, Claude Code runs commands unsandboxed instead. And when a command fails inside the sandbox, the agent can ask to retry it outside. Both are reasonable when a person is watching. In a script, both quietly remove the protection you thought you had. With these two settings, if the sandbox can’t start, nothing runs.
3. Make secrets unreadable
The settings file denies reads of every place a credential lives: ~/.ssh, ~/.aws, ~/.config/gh, ~/.gnupg, the SOPS and age keys, ~/.netrc, ~/.npmrc, ~/.pypirc, ~/.docker, ~/.kube, the agent’s own login file, and the orchestrator’s own config.
{
"sandbox": {
"enabled": true,
"failIfUnavailable": true,
"allowUnsandboxedCommands": false,
"filesystem": {
"denyRead": ["~/.ssh", "~/.aws", "~/.config/gh", "~/.gnupg", "~/.config/sops"],
"denyWrite": ["<checkout>/.git"]
},
"network": { "allowedDomains": ["registry.npmjs.org", "pypi.org", "crates.io"] }
}
}
Two details are easy to miss. The sandbox wraps shell commands, not the agent’s own file tools, so the same paths are also denied as Read(...) rules in the permissions. And the environment is rebuilt from scratch, with only HOME, PATH and LANG, so no GITHUB_TOKEN or cloud key leaks in from the shell that started the script.
4. Allowlist the network
By default the agent reaches package registries and documentation sites, nothing else. Any other domain has to be granted for that specific task, in a plan I approve before the work starts.
A network allowlist is the main defence against leaks. An agent that has read something it shouldn’t still can’t send it anywhere you didn’t list.
During the run: decide what the agent can do
5. The agent writes code; it never ships it
At least not yet! git push, git remote, git config, gh, ssh and sudo are on the disallowed list. Even trying to push, or to read a secret, fails the run. An agent that attempts that has misread its task, or been told to by something it read, and either way I want to know.
Pushing happens outside the agent, in the script, under a GitHub App’s bot identity. Its installation tokens expire after one hour, and the agent never sees them. Every commit shows that a bot made it, not me.
6. Run its code in a second sandbox
The agent’s sandbox protects you from the agent. But the script also runs the code the agent wrote: the setup, the tests and the build. That code is just as untrusted, and a test file can do anything a program can.
So those commands run in a second bubblewrap sandbox that the script controls directly:
bwrap --unshare-net --unshare-pid --unshare-ipc --unshare-uts --new-session --die-with-parent \
--ro-bind / / --dev /dev --proc /proc --tmpfs /run --tmpfs "$HOME" --tmpfs /tmp \
--bind "$CHECKOUT" "$CHECKOUT" --ro-bind "$CHECKOUT/.git" "$CHECKOUT/.git" \
--chdir "$CHECKOUT" -- sh -c "npm test"
The system is read-only. Home, /tmp and /run are empty, which also hides the ssh-agent, gpg-agent and Docker sockets. Only the checkout is writable, and its .git stays read-only so nothing there can plant a git hook. There is no network for tests; setup gets the network so it can install dependencies. Credential files inside the toolchain folders are covered with /dev/null. And --die-with-parent means nothing the tests start outlives them.
7. Guard the files that keep it honest
A hook runs before every file write and blocks edits to the CI config, the agent’s own instructions (CLAUDE.md and similar) and any path I mark as protected, unless the approved plan allows it. Once the agent has pushed its tests, it can’t change them while it repairs the code either.
Without this, “make the tests pass” quietly becomes “weaken the tests”. The hook fails closed too: if it crashes, the write is blocked.
8. Cap every run
Each run has a budget limit (--max-budget-usd), a timeout, and only the tools its job needs. The agent that writes the spec can edit only specs/. The reviewer can read and run git diff, but not edit. An optional daily budget sits on top of all of it.
Caps don’t stop a clever attack, but they turn a runaway loop into a small bill and an alert instead of a large bill in the morning.
After the run: decide what gets in
9. Code decides what merges, not a model
Whether a change may merge is decided by code: CI must be green, a separate agent session must approve the review, and there must be a test that fails without the change and passes with it. A model can argue that its change is fine. It can’t argue with a red test.
The agent also can’t change existing tests unless the plan grants it, so the bar it has to clear is one it didn’t set.
10. Trust depends on who wrote the task
Tasks I wrote myself can run with full autonomy, including approving their own plan. Tasks that come from a GitHub issue get one level less, so I still approve the plan before any code is written. Anyone can file an issue, and an issue is text the agent will read and act on: that’s exactly the door prompt injection uses.
What this doesn’t cover
None of this is a guarantee, and some gaps are worth naming:
- Allowed domains are still exits. If
github.comis on the allowlist, an agent could in principle push data to a gist or an issue there. Keep the default list short. - Packages run code. Setup installs dependencies with the network on. A malicious package runs inside the sandbox, but it does run. Lockfiles, pinned versions and a delay before taking new releases help more than any sandbox.
- The bot’s key is long-lived. The tokens last an hour, but the GitHub App’s private key mints new ones. It lives outside the sandbox, on the agent’s deny list, and it’s the one file worth protecting most.
- Linux quirks. Ubuntu’s restrictions on unprivileged user namespaces broke parts of the sandbox for me and needed a workaround. Test that your sandbox holds by trying to break out of it; don’t just trust the config.
Least privilege, per run
These rules add a little overhead, but it’s better to be safe than sorry. The speed at which agents deliver code doesn’t mean we can forget the principles we already know. None of this is exotic: it’s least privilege, applied per run instead of per developer, and checks written in code instead of trusted to judgement.
What’s on your list?
comments
Comments are stored as GitHub Discussions, so you need a GitHub account to post.