Refuse a Bash command that recursively searches a folder holding an env-file

This commit is contained in:
2026-11-13 21:36:17 +01:00
parent c8eeeadd24
commit 153a85c78f
6 changed files with 168 additions and 7 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
## Unreleased
- rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through.
- rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either or searches a folder holding either with `grep -r`, `rg` or `ag`, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through.
- To keep Mattermost DMs, move the keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, and name it in the project's config as `env-file`; `mattermost-dm` and loop-claude's DMs no longer read `~/.claude/.env`, and a project with no `env-file` gets none. A failure names each missing key and holds no token.
## 0.10.0
+1 -1
View File
@@ -94,7 +94,7 @@ goals-and-audience = "checkout:README.md"
principles = "~/.claude/principles"
```
A project may also set `env-file`, the file of `KEY=value` credentials its tools read, such as `env-file = "~/.claude-projects/log.env"`. It is a path that starts with `/` or `~/`, outside the checkout and the config's folder, so that no git remote receives it. A tool that needs a key fails and names each one the file lacks. No failure message, prompt, log line or archived loop output holds a token from the file. rule-hook refuses a Read or a Grep of the file and a Bash command that names it, so a worker doesn't read it in passing; `rule-hook --help` says which calls it checks. A project without the setting has no credentials, and never reads another project's. `project-config env-file` prints the path.
A project may also set `env-file`, the file of `KEY=value` credentials its tools read, such as `env-file = "~/.claude-projects/log.env"`. It is a path that starts with `/` or `~/`, outside the checkout and the config's folder, so that no git remote receives it. A tool that needs a key fails and names each one the file lacks. No failure message, prompt, log line or archived loop output holds a token from the file. rule-hook refuses a Read or a Grep of the file and a Bash command that names it or searches a folder holding it with `grep -r`, `rg` or `ag`, so a worker doesn't read it in passing; `rule-hook --help` says which calls it checks. A project without the setting has no credentials, and never reads another project's. `project-config env-file` prints the path.
For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:<path>`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed.
+86 -4
View File
@@ -1,8 +1,9 @@
"""Whether a Read or a Grep reads a credentials file, or a Bash command names one, for the `env-file-read` rule.
"""Whether a Read or a Grep reads a credentials file, or a Bash command names or recursively searches one, for the `env-file-read` rule.
The files are `~/.claude/.env` and every config's `env-file`, not only the calling project's: a worker in one client's project must not read another client's credentials either, and listing every config's file needs no git call, as finding the calling project's would.
A Bash command names one where its text spells the file's path, or one of its words, a redirect's target included, leads to the file from the directory `cd` left the command in. Whether the command reads the file is not judged, so one that only mentions the path is refused too.
This guards against an agent reading the file in passing, not against one that hides the path, such as behind a glob, a variable of its own or a recursive search of a folder that holds it; todo.md item 370 covers the recursive Bash searches."""
A Bash command also reaches the file where it runs `grep -r`, `rg` or `ag` over a folder that holds it, or over the directory `cd` left it in when it names none, unless the tool skips the file: `rg` and `ag` skip a hidden file, one below a hidden folder, and one a checkout ignores, unless an option or an `rg` glob lifts that skip. `grep -r` skips nothing.
This guards against an agent reading the file in passing, not against one that hides the path, such as behind a glob, a variable of its own, `xargs` or `find -exec`. A search's pipe input isn't told apart from its directory, so `x | rg y` in a folder holding the file is refused too."""
import os
import pathlib
import re
@@ -13,8 +14,16 @@ from rule_hook.call import Call, text
from project_config.settings import env_files
from failure import Failure
from rule_hook.git import guarded_git
from command_lines.shell_command import lexed, OPERATOR, resolved
from command_lines.shell_command import Launch, launched, lexed, OPERATOR, resolved, Simple, simple_commands
# Tools that search a folder's files: grep only given an option that makes it recursive, rg and ag always.
GREPS = frozenset({"egrep", "fgrep", "grep"})
SEARCHERS = GREPS | {"ag", "rg"}
RECURSIVE_GREP = re.compile(r"-[A-Za-z]*[rR][A-Za-z]*|--(?:dereference-)?recursive|--directories=recurse")
# An option that gives the pattern, so the first operand is a folder: -e and -f in a cluster, and --regexp and --file.
PATTERN_OPTION = re.compile(r"-[A-Za-z]*[ef][A-Za-z]*|--(?:regexp|file)(?:=.*)?")
# rg's --glob and --iglob, and -g in a cluster: group 1 or 2 holds the glob when it is in the same word, else it is the next word.
GLOB_OPTION = re.compile(r"--i?glob(?:=(.*))?|-[A-Za-z]*?g(.*)")
# What a Grep's glob holds beyond literals, `*`, `?` and `/`: forms globbed() does not translate.
UNMATCHED = re.compile(r"[{}\[\]\\,\s]|/$")
@@ -43,7 +52,7 @@ def reached(call: Call, path: pathlib.Path, home: str) -> bool:
spellings = "|".join(re.escape(spelling) for spelling in (str(path), *(f"{prefix}/{relative}" for prefix in ("~", "$HOME", "${HOME}"))))
# Bounded on both sides, so a longer path that holds a spelling, such as ~/.claude/.envrc, is another file.
spelt = re.search(rf"(?<![\w./~-])(?:{spellings})(?![\w.-])", command)
return spelt is not None or any(names(word, path) for word in paths(command, call.cwd, home))
return spelt is not None or any(names(word, path) for word in paths(command, call.cwd, home)) or searches(command, call.cwd, home, path)
def paths(command: str, cwd: str, home: str) -> typing.Iterator[str]:
@@ -66,6 +75,79 @@ def paths(command: str, cwd: str, home: str) -> typing.Iterator[str]:
yield resolved(directory, word, home)
def home_word(token: str) -> str:
"""The word with a leading $HOME spelt as ~; the lexer has joined a quoted "$HOME" to the rest of its word."""
return re.sub(r"^\$(HOME|\{HOME\})(?=/|$)", "~", token)
def searches(command: str, cwd: str, home: str, path: pathlib.Path) -> bool:
"""Whether a simple command of the command recursively searches a folder that holds path and does not skip it."""
for simple in simple_commands(command, cwd, home):
launch = launched(simple.words, SEARCHERS)
if launch is None:
continue
options, operands = split(launch.arguments)
if launch.tool in GREPS and not any(RECURSIVE_GREP.fullmatch(option) or option.endswith("recurse") for option in [*options, *operands]):
continue
globs = globs_of(launch.arguments) if launch.tool == "rg" else []
if any(holds(folder, path) and not skips(launch.tool, options, globs, folder, path) for folder in folders(simple, launch, options, operands, home)):
return True
return False
def split(arguments: list[str]) -> tuple[list[str], list[str]]:
"""A search's arguments as its options and its operands: the words after `--` are operands."""
end = arguments.index("--") if "--" in arguments else len(arguments)
options = [word for word in arguments[:end] if word.startswith("-") and word != "-"]
return options, [word for word in arguments[:end] if word not in options] + arguments[end + 1:]
def folders(simple: Simple, launch: Launch, options: list[str], operands: list[str], home: str) -> list[str]:
"""The folders a search reads: its operands that are folders, or the directory it runs in where none names a file or a folder. An option's value is an operand here; one that names no file or folder is dropped like any word that does not."""
if not any(PATTERN_OPTION.fullmatch(option) for option in options):
# The first operand is the pattern.
operands = operands[1:]
named = [resolved(simple.directory, home_word(operand), home) for operand in operands]
existing = [word for word in named if os.path.exists(word)]
return [word for word in existing if os.path.isdir(word)] if existing else [simple.directory]
def globs_of(arguments: list[str]) -> list[str]:
found = []
for at, word in enumerate(arguments):
option = GLOB_OPTION.fullmatch(word)
if option:
given = option.group(1) or option.group(2)
glob = given if given else "".join(arguments[at + 1:at + 2])
# --iglob matches without regard to case, which globbed() does not translate; braces make it count as matching.
found.append("{" + glob + "}" if word.startswith("--iglob") else glob)
return found
def skips(tool: str, options: list[str], globs: list[str], folder: str, path: pathlib.Path) -> bool:
"""Whether the tool passes over path when it searches folder. A grep skips nothing. rg searches only the files a positive glob matches, and ag no glob; they otherwise skip a hidden file, one below a hidden folder, and one a checkout ignores, as the options allow. Doubt, such as an option's value that looks like an option, lifts a skip."""
if tool in GREPS:
return False
positive = [glob for glob in globs if not glob.startswith("!")]
if positive:
return not any(globbed(glob, folder, path) for glob in positive)
long = [option for option in options if option.startswith("--")]
short = "".join(option[1:] for option in options if not option.startswith("--"))
unrestricted = short.count("u") + long.count("--unrestricted")
if tool == "rg":
hidden_lifted = "--hidden" in long or "." in short or unrestricted >= 2
ignored_lifted = unrestricted >= 1 or any(option.startswith("--no-ignore") for option in long)
else:
hidden_lifted = "--hidden" in long or unrestricted >= 1
ignored_lifted = unrestricted >= 1 or "U" in short or "a" in short or "--skip-vcs-ignores" in long or "--all-types" in long
return (hidden_below(folder, path) and not hidden_lifted) or (ignored(path) and not ignored_lifted)
def hidden_below(folder: str, path: pathlib.Path) -> bool:
"""Whether path, or a folder on the way to it from folder, has a name that starts with a dot."""
return any(part.startswith(".") for part in os.path.relpath(os.path.realpath(path), os.path.realpath(folder)).split("/"))
def globbed(glob: str, searched: str, path: pathlib.Path) -> bool:
"""Whether a Grep's glob can match path, as ripgrep matches it: one without a `/` against the file's name, one with a `/` against the path from the searched folder. A glob holding a form this does not translate, such as `{a,b}`, counts as matching."""
if not glob:
+1 -1
View File
@@ -38,7 +38,7 @@ RULES: dict[RuleName, Rule] = {
# A marker would let the credentials into the transcript all the same, so no marker waives it.
"env-file-read": Rule(
"an agent never reads ~/.claude/.env or a project's env-file, the file of credentials the project's config names, since a value the agent reads lands in its transcript, which loop-claude archives and the backups copy; it leaves a tool that needs a credential to read the file itself, gets the file's path from `~/.claude/bin/project-config env-file`, and spells the path another way, such as \"the .env in ~/.claude\", in a command that must mention it without reading it, such as a commit's title",
"against ~/.claude/.env and the env-file of every config under ~/.claude-projects: a Read of one; a Grep of one, or of a folder holding one, unless a checkout ignores the file and the Grep's glob cannot match it; and a Bash command that spells one's path, or names it in a word or a redirect's target from the directory `cd` left the command in, whether or not the command reads it",
"against ~/.claude/.env and the env-file of every config under ~/.claude-projects: a Read of one; a Grep of one, or of a folder holding one, unless a checkout ignores the file and the Grep's glob cannot match it; and a Bash command that spells one's path, or names it in a word or a redirect's target from the directory `cd` left the command in, whether or not the command reads it; and a Bash command that runs `grep -r`, `rg` or `ag` over a folder holding one, or over the directory `cd` left it in, unless the tool skips the file as a hidden or ignored one",
overridable=False,
),
"ignorefile-sorted": Rule(
+62
View File
@@ -455,6 +455,68 @@ class EnvFileRead(unittest.TestCase):
found = breaches_of(Call("Grep", {"pattern": "TOKEN", "path": str(self.home), "glob": glob}, "/r"), str(self.home), {})
self.assertEqual(any(breach.detail.startswith(f"the call reads {self.home}/.claude/.env,") for breach in found[2]), refused)
def ignoring(self, folder: str, patterns: str) -> None:
"""Make folder a checkout whose .gitignore holds patterns."""
subprocess.run(["git", "init", "--quiet", str(self.home / folder)], check=True, env=isolated_env())
(self.home / folder / ".gitignore").write_text(patterns)
def test_a_recursive_search_of_a_folder_holding_the_file_is_refused_for_each_tool(self):
commands = (
"grep -r TOKEN ~/secrets", "grep -R TOKEN ~/secrets", "grep -rn TOKEN $HOME/secrets", "egrep -ri TOKEN ~/secrets", "fgrep --recursive TOKEN ~/secrets",
"grep -d recurse TOKEN ~/secrets", "rg TOKEN ~/secrets", "rg -n TOKEN ~/secrets", "ag TOKEN ~/secrets", "nice rg TOKEN ~/secrets",
"rg -e TOKEN ~/secrets", "rg -A 3 TOKEN ~/secrets", "cat x | rg -g '*.env' TOKEN ~/secrets",
)
for command in commands:
with self.subTest(command):
self.assertEqual(self.breached("Bash", {"command": command}), ["env-file-read"])
def test_a_recursive_search_with_no_folder_searches_the_directory_cd_left_it_in(self):
self.assertEqual(self.breached("Bash", {"command": "grep -r TOKEN"}, f"{self.home}/secrets"), ["env-file-read"])
self.assertEqual(self.breached("Bash", {"command": "cd ~/secrets && rg TOKEN"}), ["env-file-read"])
self.assertEqual(self.breached("Bash", {"command": "cd ~/secrets && grep -rn -A 3 TOKEN"}), ["env-file-read"])
self.assertEqual(self.breached("Bash", {"command": "cd ~/code && rg TOKEN ~/secrets"}), ["env-file-read"])
self.assertEqual(self.breached("Bash", {"command": "ag TOKEN"}, f"{self.home}/secrets"), ["env-file-read"])
def test_a_search_of_another_folder_or_a_grep_that_is_not_recursive_passes(self):
(self.home / "code").mkdir()
for command in ("grep -r TOKEN ~/code", "rg TOKEN ~/code", "ag TOKEN ~/code", "grep TOKEN ~/secrets", "grep -n TOKEN ~/secrets/*", "echo rg TOKEN ~/secrets", "rg --version"):
with self.subTest(command):
self.assertEqual(self.breached("Bash", {"command": command}), [])
self.assertEqual(self.breached("Bash", {"command": "rg TOKEN"}, f"{self.home}/code"), [])
def test_rg_and_ag_skip_hidden_files_but_grep_does_not(self):
for command, expected in (("rg TOKEN ~/.claude", []), ("ag TOKEN ~/.claude", []), ("grep -r TOKEN ~/.claude", ["env-file-read"]), ("rg --hidden TOKEN ~/.claude", ["env-file-read"]), ("rg -. TOKEN ~/.claude", ["env-file-read"]), ("rg -uu TOKEN ~/.claude", ["env-file-read"]), ("ag --hidden TOKEN ~/.claude", ["env-file-read"]), ("ag -u TOKEN ~/.claude", ["env-file-read"])):
with self.subTest(command):
self.assertEqual(self.breached("Bash", {"command": command}), expected)
def test_a_search_of_a_folder_holding_a_visible_file_below_a_hidden_folder_is_refused_from_the_hidden_folder_itself(self):
write_config(self.home, self.home / "code" / "other")
config = self.home / ".claude-projects" / "other" / "config.toml"
config.write_text(config.read_text() + 'env-file = "~/.claude-projects/other.env"\n')
(self.home / ".claude-projects" / "other.env").write_text("TOKEN=z\n")
for command, expected in (("rg TOKEN ~/.claude-projects", ["env-file-read"]), ("ag TOKEN ~/.claude-projects", ["env-file-read"]), ("grep -r TOKEN ~/.claude-projects", ["env-file-read"]), ("rg TOKEN ~", ["env-file-read"])):
with self.subTest(command):
self.assertEqual(self.breached("Bash", {"command": command}), expected)
(self.home / "code").mkdir()
self.assertEqual(self.breached("Bash", {"command": "rg TOKEN ~/code"}), [])
def test_rg_and_ag_skip_an_ignored_file_unless_an_option_or_a_glob_lifts_it(self):
self.ignoring("secrets", "*.env\n")
for command, expected in (
("rg TOKEN ~/secrets", []), ("ag TOKEN ~/secrets", []), ("grep -r TOKEN ~/secrets", ["env-file-read"]),
("rg --no-ignore TOKEN ~/secrets", ["env-file-read"]), ("rg -u TOKEN ~/secrets", ["env-file-read"]), ("rg --no-ignore-vcs TOKEN ~/secrets", ["env-file-read"]),
("ag -U TOKEN ~/secrets", ["env-file-read"]), ("ag --skip-vcs-ignores TOKEN ~/secrets", ["env-file-read"]), ("ag -u TOKEN ~/secrets", ["env-file-read"]),
("rg -g '*.env' TOKEN ~/secrets", ["env-file-read"]), ("rg --glob=acme.env TOKEN ~/secrets", ["env-file-read"]), ("rg --iglob '*.ENV' TOKEN ~/secrets", ["env-file-read"]),
("rg -g '*.md' TOKEN ~/secrets", []), ("rg -g '!*.env' TOKEN ~/secrets", []),
):
with self.subTest(command):
self.assertEqual(self.breached("Bash", {"command": command}), expected)
def test_rg_searches_only_the_files_a_positive_glob_matches(self):
for command, expected in (("rg -g '*.md' TOKEN ~/secrets", []), ("rg -g '*.md' -g '*.env' TOKEN ~/secrets", ["env-file-read"]), ("rg -g '!*.md' TOKEN ~/secrets", ["env-file-read"]), ("rg -ng '*.md' TOKEN ~/secrets", [])):
with self.subTest(command):
self.assertEqual(self.breached("Bash", {"command": command}), expected)
def test_a_file_several_configs_name_is_reported_once(self):
write_config(self.home, self.home / "code" / "other")
config = self.home / ".claude-projects" / "other" / "config.toml"
+17
View File
@@ -1932,3 +1932,20 @@ Read most (opens and searches):
- `bin/loop_effects/effects.py` 2
- `bin/mattermost_dm/dm.py` 2
- `bin/project_config/main.py` 2
## Reading cost, chunk e8c6bc2198e0, finished 2026-11-13T20:29:28Z
71659 new input tokens before the first commit.
Read most (opens and searches):
- `bin/rule_hook/rules.py` 6
- `README.md` 5
- `bin/rule_hook/test_rule_hook.py` 4
- `CHANGELOG.md` 2
- `bin/command_lines/shell_command.py` 2
- `bin/project_config/settings.py` 2
- `bin/project_config/test_project_config.py` 2
- `bin/rule_hook/env_file.py` 2
- `bin/rule_hook/repeat_read.py` 2
- `settings.json` 2