Sub topic 7
Protecting Files and Directories
This chapter assumes you can write a short Python script, read JSON, and run commands in a shell. It also assumes you have seen 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 on stderr. Exit code 2 blocks the action.
Why paths need their own check
Deny patterns work well for shell commands, but file protection has a different shape. The agent can reach a file through many routes. It can call a file-edit tool with a path argument. It can run cat secrets >> .env in a shell. It can pass ./src/../.env or a symlink that points at .env. A check that compares raw strings sees only the text the agent typed, and not the file that text refers to.
So the central rule of this chapter is: compare real locations, not spellings. You convert the requested path to one canonical form first, then decide whether it falls inside a protected area.
What to protect
A protected-path list usually has three kinds of entries.
- Secrets:
.env, key files, credential stores. Reading these can leak data, and writing them can break deployments. - Version control internals:
.git. Edits here can rewrite history or plant hooks that run later. - Environment-specific configuration: for example
infra/prod, where a bad edit affects a live system.
Decide per entry whether you block reads, writes, or both. Writes to .git are almost never wanted. Reads of .env may also be unwanted because the agent's context can end up in logs or in model prompts.
Normalizing a path
Normalization turns many spellings of one location into one string. Three tricks defeat naive checks:
- Relative segments.
src/../.envresolves to.env. - Symlinks. A link named
notes.txtthat points to.envhas the same contents as.env. - Absolute paths.
/home/me/project/.envnames the same file as.env.
Python's os.path.realpath handles all three. It joins relative paths to a base, removes .. segments, and follows symlinks. Resolve against the project root, not the hook's own working directory, because the hook may start elsewhere.
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
)Walk through the function.
os.path.join(project_root, path)builds the full path. Ifpathis already absolute,joindiscards the root and keeps the absolute path. That is why the next check matters.realpathresolves it. Both the target and the root are resolved, so a project that itself lives behind a symlink still compares correctly.commonpathfinds the shared prefix of the two paths. If that prefix is not the root, the target is outside the project. The function returnsTrue, which treats everything outside the project as protected. This is a deliberate default: the agent has no business editing/etc/hostsor~/.ssh/configfrom a project task.- The last step compares the relative path against each protected entry. Matching is by whole path component, not substring.
Why component matching matters
A simple ".env" in path test would block docs/environment.md, because the text .env is not in environment, but would block src/.env.example and config.env.json in surprising ways. Component matching avoids both false alarms and misses. The function checks three conditions:
relative == p: the path is exactly the protected entry, such as.env.relative.startswith(p + os.sep): the path is inside a protected directory, such asinfra/prod/db.tf.p in parts: a protected name appears as any single component, such aspackages/api/.git/config. This catches nested copies of.gitor.env.
Notice that the multi-component entry infra/prod can never appear in parts, since each part is one component. It is matched only by the first two conditions, which anchor it at the project root. That is the intended behavior: infra/prod is protected at the root, while .git and .env are protected at any depth.
On Windows, paths are case-insensitive and use backslashes, so you should also apply os.path.normcase to both sides. On Linux, .ENV is a different file from .env.
Wiring it into a hook
File-edit tools put the target path in a field of tool_input. The field name depends on your agent, commonly file_path or path. Check your agent's documentation. The hook below reads either, and fails closed if neither is present.
#!/usr/bin/env python3
import json
import os
import sys
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
)
try:
event = json.load(sys.stdin)
tool_input = event["tool_input"]
path = tool_input.get("file_path") or tool_input["path"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: could not read a file path from the tool call.", file=sys.stderr)
sys.exit(2)
project_root = os.getcwd()
if is_protected(path, project_root):
print(
f"Blocked: {path} is protected (secrets, .git, or production config). "
"Edit a non-protected file, or ask the user to make this change.",
file=sys.stderr,
)
sys.exit(2)
sys.exit(0)Attach this hook to file-writing tools with a matcher, as covered earlier, so it does not run on unrelated tools such as shell calls. A shell tool has no path field, so this script would block every shell call by failing closed. Scope the matcher carefully.
Edge cases and gotchas
Paths that do not exist yet
realpath works on files that do not exist. It resolves as much as it can and appends the remainder. That is what you want for a "create file" call, since the target is new. Still, a new file inside a symlinked directory resolves through the link, so the check remains correct.
Time of check versus time of use
The hook resolves the path at one moment, and the tool writes later. If something swaps a directory for a symlink between those moments, the check was wrong. The window is small for a single agent, but it is real, and it is one reason hooks are not a security boundary. A later chapter covers this.
Shell commands touch files too
The path hook sees only what a file tool declares. The command echo x > .env goes through the shell tool, and its path is buried in a string. You have two options. First, add deny patterns for redirections to protected names in your command check. Second, accept that the shell is a wider door and enforce file protection with operating-system permissions. Use both when the files matter, for example by making .env read-only for the user running the agent.
Globs and directory operations
Tools that take globs or directories, such as a bulk search-and-replace, may name a folder and touch many files beneath it. Treat a directory that contains a protected entry as risky. A simple approach is to block when any protected path starts with the requested path, in addition to the checks above. Without this, an operation on the project root could rewrite .env while the hook sees only ..
Reads versus writes
If you only protect writes, the agent can still read .env and echo it into its output. Decide for each entry. A common split is read and write blocked for .env, write-only blocked for .git.
Giving useful feedback
The message you print on exit 2 goes back to the agent. State which path, why it is protected, and what to do instead. "Access denied" leaves the agent guessing, and it may retry with a different spelling of the same path. The message in the hook above names the path and offers two next steps.
Exercise
A hook uses ".env" in path to protect secrets. Name one way it blocks a path it should allow, and one way an attacker-style spelling still reaches the real .env file.
Show answer
It blocks harmless files such as docs/dotenv-guide.md... more precisely, any path whose text contains .env, such as src/.env.example or config.env.json (the latter contains .env). It misses src/../.env only if the check ran on a different form, but it does catch that text, so the clear miss is a symlink: notes.txt linking to .env contains no .env text, yet writing to it changes .env. Resolving with realpath and matching whole path components fixes both problems.
Exercise
Using the is_protected function with project root /work/app, what does it return for infra/prod/main.tf, for packages/api/.git/config, and for /etc/hosts? Why?
Show answer
All three return True. infra/prod/main.tf starts with infra/prod/. packages/api/.git/config has .git as one of its components. /etc/hosts resolves outside /work/app, so commonpath differs from the root and the function treats it as protected.