Sub topic 7
Protecting Files and Directories
This chapter assumes you can read JSON from stdin in a Python script. It also assumes you know how a pre-action hook blocks a tool call with exit code 2 and a stderr message. Here you apply that contract to file paths.
Why path checks need normalization
A rule such as "never touch .env" is easy to state and easy to bypass. The agent may write ./config/../.env, src/../.git/config, or a symlink that points at a protected file. A plain string comparison sees none of these as .env.
Normalization turns every requested path into one canonical form before you compare it. The standard tool is os.path.realpath, which does three things:
- It joins the path to the project root when the path is relative.
- It collapses
.and..segments. - It follows symlinks to the real location.
A protected-path check
import os
PROTECTED = [".env", ".git", "infra/prod"]
def is_protected(path, project_root):
full = os.path.realpath(os.path.join(project_root, path))
root = os.path.realpath(project_root)
if os.path.commonpath([full, root]) != root:
return True
relative = os.path.relpath(full, root)
parts = relative.split(os.sep)
return any(
relative == p or relative.startswith(p + os.sep) or p in parts
for p in PROTECTED
)The function works in four steps:
- It resolves both the requested path and the project root to their real locations.
- It compares them with
os.path.commonpath. A path outside the project root counts as protected, so../../etc/passwdis blocked. - It computes the path relative to the root and splits it into parts.
- It reports a match if the path equals a protected entry, sits under one, or contains one as a directory or file name at any depth. The last case catches
packages/api/.env.
The p in parts test matches single names such as .env. A multi-segment entry such as infra/prod is matched by the equality and prefix tests, so it only protects infra/prod at the project root.
Wiring it into a hook
Write tools carry the path in their input, and the field name varies by agent. Claude Code uses file_path for its edit tools, for example. Check your agent's documentation, then scope the hook to the write tools with a matcher.
#!/usr/bin/env python3
import json
import os
import sys
try:
event = json.load(sys.stdin)
path = event["tool_input"]["file_path"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: hook could not read the target path.", file=sys.stderr)
sys.exit(2)
if is_protected(path, os.getcwd()):
print(f"Blocked: {path} is protected. Edit a file outside .env, .git and infra/prod, or ask the user to make this change.", file=sys.stderr)
sys.exit(2)
sys.exit(0)This script assumes is_protected is defined above it in the same file. It fails closed: a missing field blocks the call. The message names the path and suggests what to do next, so the agent can recover.
Common errors
- Comparing raw strings.
".env" in pathmisses./a/../.envonly if you skip normalization. Always resolve first. - Matching only the start of the path. A
startswith(".git")test also blocks.github/, and it misses.gitwhen it appears deeper in the tree. - Checking only write tools. A shell command such as
cat secrets > .envwrites a file without using a write tool. Combine path checks with the command checks from the previous chapter.
Exercise
A hook receives the path src/../.git/config with project root /work/app. Does is_protected block it, and why?
Show answer
Yes. realpath resolves the path to /work/app/.git/config. The relative path is .git/config, which starts with .git followed by a separator, so it matches the protected entry .git.