An autonomous coding agent is a process that reads untrusted text, decides what to do with it, and then runs tools with your credentials. That combination is the whole risk story. The model does not need to be malicious for something to go wrong: it only needs to follow an instruction hidden in a web page, a README or a tool result, or to keep retrying a failing step long after a human would have stopped.
This explainer gives platform and security architects a working threat model for Claude Code style agents. It maps the four threats that cause most real damage (prompt injection, secret exfiltration, destructive shell mutation and runaway loops) to the controls that actually stop them, shows a PreToolUse hook configuration checked against the Claude Code hooks reference, and describes circuit breakers that end a session before cost or damage compounds. Everything here is a design recommendation unless it links to vendor documentation.
What is agentic risk, and why do prompt rules not contain it?
Agentic risk is the gap between what an agent is allowed to do and what it should do in a given moment. The OWASP GenAI Security Project names the root problem Excessive Agency in its Top 10 for LLM Applications, and its newer Top 10 for Agentic Applications, published December 9, 2025, breaks it into agent-specific failures such as goal hijack, tool misuse, identity and privilege abuse, unexpected code execution and cascading failures.
Instructions in a system prompt or CLAUDE.md do not close that gap. The Claude Code permissions documentation is explicit that permission rules are enforced by Claude Code, not by the model, and that instructions in your prompt or CLAUDE.md shape what Claude tries to do without changing those rules. Anthropic also states plainly in its research note on mitigating prompt injection in browser use that prompt injection is far from a solved problem. The design consequence is simple: treat model behavior as a probability you improve, and treat enforcement as something that has to live outside the model.
A useful mental model is four layers, the same split used in our three-lane governance analysis: behavioral instructions, local tripwires such as hooks, operating-system isolation, and server-side enforcement such as branch protection and scoped tokens. Each layer catches what the one above it misses, and none of them is sufficient on its own.
Which threats matter most, and which control stops each one?
The matrix below pairs each threat with the place it enters the system, the control that does the real work, a check that fails closed when the control is broken, and the risk that remains after all of it. Read the last column carefully: it is the part most vendor diagrams leave out.
| Threat | Where it enters | Primary control | Fail-closed check | Residual risk |
|---|---|---|---|---|
| Prompt injection (OWASP LLM01, ASI01 goal hijack) | Fetched web pages, issue text, READMEs, MCP tool results, files in an untrusted repository | Least privilege: deny rules for network and secret paths, sandbox network allowlist, no write credentials in sessions that read untrusted content | Sandbox denies egress to any host not on the allowlist, regardless of what the model was told | An injected instruction can still misuse tools the session is legitimately allowed to call |
| Secret exfiltration (OWASP LLM02) | Read access to .env, cloud credential files and environment variables, combined with any outbound channel | Read deny rules on secret paths, sandbox credential masking, short-lived scoped tokens | PreToolUse hook denies commands that touch secret paths, with onFailure set to block | Secrets already printed into the transcript or committed to the repository |
| Destructive shell mutation (ASI02 tool misuse, ASI05 unexpected code execution) | Bash tool, package scripts, git operations, infrastructure CLIs | Sandbox filesystem isolation plus server-side branch protection and deployment approvals | PreToolUse hook denies recursive deletes, force pushes and production CLI verbs; a crashing hook blocks the call | Damage inside the writable working directory; commands written in forms the hook does not recognize |
| Runaway loop and cost blowout (OWASP LLM10 unbounded consumption, ASI08 cascading failures) | Retry loops, Stop hooks that keep forcing continuation, fan-out to many subagents | Turn caps and budget caps on headless runs, per-session call counters | Breaker hook denies further tool calls once a counter trips, and the run ends | Budget caps use a client-side estimate, so spend can pass the cap before the run stops |
Two references anchor the residual column. The Claude Code security page warns that no system is completely immune to all attacks and recommends virtual machines when an agent interacts with external web services. The permissions reference adds that a Bash deny rule matches the command as written: Bash(curl *) stops curl https://example.com but not /usr/bin/curl or sh -c 'curl ...' (see what a Bash rule does not match). Text matching is a tripwire. The sandbox is the boundary.
How do PreToolUse hooks enforce policy without failing open?
A PreToolUse hook is a command, HTTP endpoint or MCP tool that Claude Code runs before a tool call executes. It receives the call as JSON on standard input, including tool_name, tool_input and session_id, and it can block the call. According to the hooks reference, exit code 0 means success and Claude Code applies any JSON the hook printed; exit code 2 is a blocking error that stops a PreToolUse call and returns the hook's standard error to Claude as the reason; any other exit code is a non-blocking error and the action goes ahead.
That last rule is the trap. By default a policy hook with a wrong path, a crash or a timeout lets everything through. The documentation says so directly under Block the action when a hook fails: set "onFailure": "block" on a command, http or mcp_tool hook (Claude Code v2.1.295 or later) and a failed or timed-out hook blocks the call instead. For a security gate, that field is not optional.
The configuration below lives in .claude/settings.json (or in managed settings for an organization). It combines deny rules with two hook groups: one inspects every Bash command, the other inspects every file edit. Both use exec form (command plus args, no shell) and both fail closed.
{
"permissions": {
"deny": [
"Read(./.env)",
"Read(./secrets/**)",
"Bash(curl *)",
"Bash(wget *)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "node",
"args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/check-command.js"],
"timeout": 10,
"onFailure": "block"
}
]
},
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "node",
"args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/check-path.js"],
"timeout": 10,
"onFailure": "block"
}
]
}
]
}
}The hook script reads the event, checks the command and, when it finds a violation, prints a decision object. The documented PreToolUse decision control uses hookSpecificOutput with permissionDecision set to allow, deny, ask or defer. A deny reason is shown to Claude, so it can choose a safer path rather than retry the same command. The sketch below is illustrative, not a complete policy.
// .claude/hooks/check-command.js (illustrative sketch, not a complete policy)
const chunks = [];
process.stdin.on('data', (c) => chunks.push(c));
process.stdin.on('end', () => {
// A parse error exits non-zero; with onFailure "block" the call is blocked.
const input = JSON.parse(Buffer.concat(chunks).toString('utf8'));
const cmd = String(input.tool_input?.command || '');
const rules = [
[/\brm\s+-\w*[rR]\w*f|\brm\s+-\w*f\w*[rR]/, 'recursive force delete'],
[/\bgit\b.*\bpush\b.*(--force|\s-f\b)/, 'force push'],
[/\.env\b|id_rsa|\.aws\/credentials/, 'secret path'],
];
const hit = rules.find(([re]) => re.test(cmd));
if (hit) {
process.stdout.write(JSON.stringify({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: 'deny',
permissionDecisionReason: 'Blocked by policy: ' + hit[1],
},
}));
}
process.exit(0);
});Three documented behaviors shape how far you can trust this pattern. First, a hook cannot loosen your rules: the permissions reference states that PreToolUse decisions do not bypass deny and ask rules, and that a hook exiting 2 blocks the call even when an allow rule would let it proceed. Second, when several hooks disagree, precedence is deny over defer over ask over allow. Third, the hooks reference warns that silence does not approve a call, and that command hooks run with your full user permissions, so the hook script itself belongs under code review like any other privileged code (see Security considerations).
One more caution applies to automation. The same security section notes that a -p or SDK session never shows the workspace trust dialog, so hooks committed in a repository's .claude/settings.json run in a folder you have never trusted. Before scripting headless runs over a third-party repository, review its .claude/ files or start with hooks disabled for that run.
Where should the sandbox boundary sit, and how big is the blast radius?
Hooks inspect intent. Sandboxing constrains effect. The Claude Code sandboxing documentation describes two independent layers for Bash and its child processes: filesystem isolation, which limits which paths a command can read and write, and network isolation, which routes connections through a local proxy that checks each host against an allowlist that starts empty. The permissions reference recommends using both permissions and sandboxing for defense in depth, because sandbox restrictions still apply even if a prompt injection bypasses Claude's decision making.
To lock these sandbox and permission keys for a whole organization through managed settings, and to run the same policy in CI review, see Claude Code Enterprise Security.
Note what the sandbox does not cover. The same page says built-in tools such as Read, Edit, WebFetch and WebSearch follow permission rules instead, so a sandbox denyRead entry does not stop the Read tool. That is why the matrix pairs Read deny rules with the sandbox rather than relying on either alone.
Blast radius is the second axis. A practical way to scope it is to tier sessions by what their credentials can reach, then match controls to the tier:
- Tier 0, read only: analysis, review and research sessions. No write tokens, sandbox network allowlist limited to documentation and package hosts. Prompt injection here can mislead a report but cannot change systems.
- Tier 1, repository write: implementation sessions in an isolated worktree or container. Write access to the working tree only, pushes go to feature branches that server-side branch protection guards.
- Tier 2, shared infrastructure: sessions that can touch CI, package registries or staging. Short-lived scoped tokens, PreToolUse hooks that force
askon infrastructure verbs, and a human approval step outside the agent. - Tier 3, production and money: deploys, data deletion, payments, outbound messages. Keep agents out of this tier by default; when they must enter it, route each action through an approval that the agent process cannot sign.
Tiering is also an identity problem. If every session on a workstation shares one credential store, every session inherits Tier 3 reach. Our multi-tenant Claude Code architecture guide covers how to separate configuration and credentials per tenant so that a compromised research session cannot borrow a deploy token.
How do circuit breakers stop runaway loops and cost blowouts?
A circuit breaker is a rule that ends a run when a measured signal crosses a limit, regardless of what the agent believes about its progress. OWASP lists the underlying failure as Unbounded Consumption. In an agent, it usually appears as a test that keeps failing, a tool that keeps returning the same error, or a stop condition that never resolves.
Claude Code ships some breakers already. The CLI reference documents --max-turns to limit agentic turns and --max-budget-usd to stop a run once estimated spend reaches a cap, both in print mode only. The budget flag counts subagent spend toward the cap, but the documentation warns that the cap is checked against a client-side estimate, that spend can pass it, and that you should leave headroom. For Stop hooks, the hooks reference describes a stop_hook_active field and a cap on consecutive continuations so that a hook which keeps forcing more work cannot loop forever; your own Stop hook should still check that field before blocking again.
Where these breakers sit inside a full autonomous loop, alongside plan mode, worktrees and headless runs, is covered in Autonomous Coding Loops at Scale.
Everything else is yours to build. The table below lists trip conditions worth wiring into a PreToolUse breaker hook that keeps a small counter file per session_id. The thresholds are placeholders to tune against your own telemetry, not recommendations from any vendor.
| Trip condition | Signal source | Breaker action | Reset |
|---|---|---|---|
| Same command fails repeatedly | Counter keyed on a hash of the command, incremented by a PostToolUseFailure hook | PreToolUse hook denies that command with a reason telling Claude to stop and report | Human review, or a new session |
| Tool calls per session exceed a ceiling | Counter of PreToolUse events per session_id | Deny all further non-read calls | New session after review of the transcript |
| Headless run reaches turn or spend limit | --max-turns and --max-budget-usd on claude -p | Claude Code ends the run | Next scheduled run |
| Writes outside the expected path set | PreToolUse hook on Edit|Write comparing file_path to an allowlist | Deny and flag the session | Owner updates the allowlist |
| Burst of denied calls | Count of deny decisions logged by the breaker itself | Switch the session to deny everything except reads | Human review; repeated denials often signal injection |
A breaker that only pauses is not a breaker. Each trip should end in a state a human must clear, and each trip should write a record that names the session, the signal and the last few tool calls. Repeated denials are worth treating as a security event, because an injected instruction that keeps probing for an allowed path looks exactly like that.
How should an engineering leader roll this out?
Start with enforcement that does not depend on the model, then add inspection, then add breakers. The order matters because each step makes the next one cheaper to reason about.
- Write deny rules for secret paths and raw network tools, and deploy them through managed settings so project settings cannot override them.
- Turn on sandbox filesystem and network isolation for Bash, with an allowlist that starts empty and grows only by review.
- Add PreToolUse hooks for Bash and for Edit and Write, each with
onFailureset toblock, and test by deleting the script to confirm the call is blocked. - Tier every agent session by credential reach and remove write tokens from sessions that read untrusted content.
- Set
--max-turnsand--max-budget-usdon every headless run, leaving headroom below the real spending limit. - Build per-session breaker counters and route every trip to a human-cleared state with a written record.
- Keep server-side branch protection and deployment approvals as the final layer, independent of any local hook.
Pipeline-side hardening is the other half of this work. For CI gates, adversarial review of agent pull requests and repository verification, see Adversarial DevOps and CI/CD Hygiene for the AI Era on our sister repository directory, which pairs with the workstation and session controls described here.
Related Adversarial DevOps and Resilience Guides
- Adversarial DevOps and CI/CD Hygiene for the AI Era on ClaudeSkillsGitHub: Repository CI/CD hardening and automated verification gates paired with this architecture framework.
- Three-Lane Agent Governance: Where Tripwires Fit Between Prompt Rules and OS Sandboxes: Where local tripwires sit between behavioral rules and operating-system isolation.
- Multi-Tenant Claude Code Architecture and Enterprise Governance: Separating identity and credentials per tenant to keep blast radius small.
Frequently Asked Questions
Does a PreToolUse hook block a tool call if the hook script crashes?
Not by default. The Claude Code hooks reference treats a crash, a missing script, invalid JSON or a timeout as a non-blocking error, so the call continues through the normal permission flow. Set "onFailure": "block" on the command, http or mcp_tool hook (Claude Code v2.1.295 or later) to make a failed or timed-out hook block the call, which is what a security gate needs.
Can a PreToolUse hook approve something that a deny rule blocks?
No. The Claude Code permissions reference states that PreToolUse hook decisions do not bypass permission rules: a matching deny rule still blocks the call and a matching ask rule still prompts, even when the hook returned allow. The reverse is not true, because a hook that exits with code 2 blocks the call even when an allow rule would otherwise let it run.
Are Bash deny rules enough to stop secret exfiltration?
No. A Bash deny rule matches the command text as written, so Bash(curl *) does not stop the same program called by its full path or inside sh -c. Pair deny rules with Read deny rules on secret files, the sandbox network allowlist for egress, and short-lived scoped credentials, so that a missed pattern still has nowhere to send data.
What is the simplest circuit breaker for a headless Claude Code run?
Use the documented print-mode flags. --max-turns limits the number of agentic turns and --max-budget-usd stops the run once estimated spend reaches the cap, including subagent spend. The budget is a client-side estimate and spend can pass it, so set the cap below your real limit and add per-session counters in a hook for loops the flags do not see.