Sub topic 15
Layering Hooks with Permissions and Sandboxes
This chapter assumes you can read a short Python script, work with JSON on stdin, and already know the hook contract from earlier chapters: the agent sends an event as JSON on stdin, and the hook answers with an exit code and a message. Exit code 2 blocks the call.
A hook is one control among several. Used alone, it fails in predictable ways. Used with permissions and a sandbox, each layer covers gaps the others leave. This chapter shows what each layer does, where each one fails, and how to combine them.
Why one layer is not enough
A pre-action hook inspects a proposed tool call as text or structured data. It has three weaknesses:
- It sees the request, not the effect. A command like
python build.pypasses a deny-pattern check, but the script could delete anything. - It is a pattern check, and patterns can be evaded.
rm -rf /can be written with variables, encoded strings, or a wrapper script. - It is code that can fail. A bug, a timeout, or a missing interpreter can disable it, depending on how the agent treats hook errors.
Defense in depth means stacking independent controls so that the failure of one does not mean the failure of all. "Independent" matters: two layers that share the same blind spot give you no extra protection.
The three layers
| Layer | What it controls | Where it runs | Typical failure |
|---|---|---|---|
| Permissions | Which tools the agent may call, and whether each call needs approval | Inside the agent | Too broad an allow list, or approvals clicked through by habit |
| Hooks | Custom checks on a specific call, using your own logic | A script launched by the agent | Pattern gaps, bugs, timeouts |
| Sandbox | What the process can reach, enforced by the operating system | Outside the agent, at the OS or container level | Misconfigured mounts, network left open |
Permissions are coarse and declarative. Hooks are fine-grained and programmable. A sandbox is enforced by the operating system or container runtime, so it holds even when the agent or a hook gets something wrong.
Layer 1: permissions
Permissions decide which tools are available at all. A reasonable starting policy:
- Allow read-only tools (reading files, searching) without prompts.
- Require approval for writes and shell commands.
- Deny tools the task never needs, such as network fetches in an offline refactoring job.
The cheapest protection is a tool the agent cannot call. If a task never needs a shell, remove the shell tool. No hook can be bypassed on a tool that does not exist for the agent.
Permission configuration is specific to each agent product. Check your agent's documentation for the setting names and whether an allow rule can override a hook (in some systems the order of evaluation matters).
Approval fatigue
Asking the user for every action trains the user to approve everything. Keep prompts for the cases that deserve a human decision. Use hooks to deny the clearly bad calls automatically, and use permissions to allow the clearly safe ones without a prompt. The prompts that remain then carry real information.
Layer 2: hooks
Hooks are where project-specific rules live: "never touch infra/prod", "no force-push", "no .env edits". Earlier chapters built these checks. Two properties are worth keeping when you combine layers.
Fail closed. If the hook cannot parse the event, block:
import json
import sys
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: hook could not read the tool call, so it was not allowed.", file=sys.stderr)
sys.exit(2)Keep rules narrow. A hook that tries to be the whole security system grows long, slow, and full of special cases. Let it handle the rules that need your own logic, and leave broad containment to the sandbox.
Known bypasses
These are the ways a hook is commonly sidestepped. Knowing them tells you what the other layers must cover.
- Indirection. The agent writes a script file, then runs it. The hook sees only
bash cleanup.sh. - Obfuscation.
r""m -rf /or a command built from variables defeats a regex. - Other tools. A hook scoped to the shell tool does not see a file-edit tool that writes to the same protected path. Cover each tool that can reach the resource.
- Hook errors that fail open. Some agents treat a crash or timeout as "allow". Test this in your agent.
- Hook tampering. If the agent can edit the hook script or its configuration, it can disable the check. Make those files read-only to the agent's process.
Layer 3: sandboxes
A sandbox limits what the process can do no matter what command it runs. Common mechanisms:
- A container with only the project directory mounted, so
rm -rf /can destroy only the container. - A non-root user with no write access outside the workspace.
- Read-only mounts for files the agent should not change, such as
.gitor production config. - Network restrictions, so the agent cannot send data out or reach internal services.
- Scoped credentials. Give the agent a token that can do only what the task needs, and keep production credentials out of its environment entirely.
The last point is easy to overlook. If production credentials are in the environment, a sandbox that blocks file writes still lets the agent call a production API.
Here is a minimal container invocation that applies several of these limits:
docker run --rm -it \
--user 1000:1000 \
--network none \
--read-only \
--tmpfs /tmp \
-v "$PWD":/workspace \
-v "$PWD/.git":/workspace/.git:ro \
-w /workspace \
python:3.12-slim bashThis container runs as an unprivileged user, has no network, has a read-only root filesystem, and can write only to /tmp and the mounted workspace. The .git directory is mounted read-only on top of the workspace, so history cannot be rewritten from inside. Adjust it to what the task needs. A job that installs packages needs network access, for example, and then you should narrow it to the hosts required.
How the layers cover each other
Take the case where the agent decides to wipe a directory using a generated script.
| Step | Permissions | Hook | Sandbox |
|---|---|---|---|
| Agent writes `clean.sh` | Write is allowed in the workspace | Path is not protected, so allowed | Write lands in the mounted workspace only |
| Agent runs `bash clean.sh` | Shell requires approval; user sees the command | Pattern check finds nothing suspicious | Script runs, but cannot touch `.git` (read-only) or anything outside the workspace |
| Script tries `rm -rf /workspace/.git` | Not checked at this point | Not checked at this point | Fails with a read-only filesystem error |
The hook missed this attack, as the bypass list predicted. The sandbox held. In the opposite case, where the agent tries to push to a remote with --force, the sandbox might allow it because the network is open, and the hook catches it. Each layer does useful work on a different class of mistake.
Audit and review
Layers produce evidence. Have the hook append each decision to a log with a timestamp, tool name, and verdict. Review blocked calls periodically. A burst of blocks for one pattern suggests the agent is repeatedly trying something your instructions should rule out, or that your rule is too aggressive and needs refinement. Log the decision and a truncated command, and keep secrets out of the log.
A practical checklist
- List the resources that cannot be recovered if lost: production data, credentials, git history, deployment configs.
- For each, decide the strongest layer that can protect it. Prefer the sandbox, then permissions, then a hook.
- Remove tools the task does not need.
- Write hooks for rules that need custom logic, and make them fail closed.
- Protect the hook files and agent configuration from modification by the agent.
- Test each layer separately, then test attacks that should pass the first layer and be caught by the second.
- Log decisions and review them.
Exercises
Exercise
A hook blocks git push --force in the shell tool. The agent instead writes a script push.sh containing git push --force and runs bash push.sh. Which layer would reliably stop this, and why does the hook not?
Show answer
The hook only sees the command string bash push.sh, which matches no deny pattern, so it allows it. A sandbox that blocks network access or removes push credentials from the environment would stop the push regardless of how the command is written. A permission rule that requires approval for shell commands would also show the user the call, but the user would see only bash push.sh unless they inspect the script.
Exercise
Your hook script crashes with an unhandled exception on malformed input. You are not sure whether your agent allows or blocks the call in that case. What two things should you do?
Show answer
First, make the hook fail closed by catching parse errors and exiting with code 2. Second, test the agent's behavior directly by deliberately breaking the hook (or feeding it bad input) and observing whether the call proceeds. Do not rely on an assumption about how the agent treats hook errors.