From 0cc242ac1b137bf2b5fe0f9c273c03e069606d55 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 13 Nov 2026 21:25:15 +0100 Subject: [PATCH] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20say=20a=20c?= =?UTF-8?q?ommand=20names=20the=20file=20rather=20than=20reads=20it,=20nam?= =?UTF-8?q?e=20the=20way=20on,=20refuse=20redirect=20targets=20and=20a=20q?= =?UTF-8?q?uoted=20$HOME,=20check=20each=20file=20once,=20and=20drop=20the?= =?UTF-8?q?=20README=20caveat=20the=20rule=20outlived?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- README.md | 2 +- bin/rule_hook/env_file.py | 80 ++++++++++++++++++++++++++------- bin/rule_hook/rules.py | 4 +- bin/rule_hook/test_rule_hook.py | 50 ++++++++++++++++++++- todo.md | 6 +-- 6 files changed, 120 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a2047d3..1368d05d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- rule-hook refuses a Read, a Grep or a Bash command that reads `~/.claude/.env` or the `env-file` of any project's config, so no credential lands in a transcript. +- 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. - 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/.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 diff --git a/README.md b/README.md index 22fd82ea..eb447c7b 100644 --- a/README.md +++ b/README.md @@ -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. A worker that opens the file itself still puts it in its transcript. 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, 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:`, 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. diff --git a/bin/rule_hook/env_file.py b/bin/rule_hook/env_file.py index 74aa3f71..996401a3 100644 --- a/bin/rule_hook/env_file.py +++ b/bin/rule_hook/env_file.py @@ -1,41 +1,85 @@ -"""Whether a Read, Grep or Bash call reads a credentials file, for the `env-file-read` rule. +"""Whether a Read or a Grep reads a credentials file, or a Bash command names 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 them needs no git call. -A Bash command reads one where its text spells the file's path, or one of its words names the file from the directory `cd` left the command in. -This guards against an agent reading the file in passing, not against one that hides the path, such as behind a glob or a variable of its own.""" +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.""" import os import pathlib import re +import typing from rule_hook.rules import Breach 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 resolved, simple_commands +from command_lines.shell_command import lexed, OPERATOR, resolved + +# What a Grep's glob holds beyond literals, `*`, `?` and `/`: forms globbed() does not translate. +UNMATCHED = re.compile(r"[{}\[\]\\,\s]|/$") def env_file_breaches(call: Call, home: str) -> list[Breach]: - guarded = [pathlib.Path(home, ".claude", ".env"), *env_files(pathlib.Path(home))] - read = [path for path in guarded if path.is_file() and reads(call, path, home)] - return [Breach("env-file-read", f"the call reads {path}, whose credentials would land in the transcript", call.cwd) for path in read] + guarded: dict[str, pathlib.Path] = {} + for path in (pathlib.Path(home, ".claude", ".env"), *env_files(pathlib.Path(home))): + if path.is_file(): + # Several configs may name one file: it is checked, and reported, once. + guarded.setdefault(os.path.realpath(path), path) + # A command may name the file without reading it, so the detail claims no read of it. + found = "the command names {}, a file of credentials that must stay out of the transcript" if call.tool == "Bash" else "the call reads {}, whose credentials would land in the transcript" + return [Breach("env-file-read", found.format(path), call.cwd) for path in guarded.values() if reached(call, path, home)] -def reads(call: Call, path: pathlib.Path, home: str) -> bool: - """Whether a Read, a Grep or else a Bash command reads path.""" +def reached(call: Call, path: pathlib.Path, home: str) -> bool: + """Whether a Read or a Grep reads path, or a Bash command names it.""" if call.tool == "Read": return names(resolved(call.cwd, text(call.given, "file_path"), home), path) if call.tool == "Grep": searched = resolved(call.cwd, text(call.given, "path") or ".", home) - # ripgrep's --glob overrides its ignore files, so an ignored file is skipped only by a Grep without one. - return names(searched, path) or holds(searched, path) and (bool(text(call.given, "glob")) or not ignored(path)) + # ripgrep's --glob overrides its ignore files, so an ignored file is skipped unless a glob matches it. + return names(searched, path) or holds(searched, path) and (globbed(text(call.given, "glob"), searched, path) or not ignored(path)) command = text(call.given, "command") relative = os.path.relpath(path, home) 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"(? typing.Iterator[str]: + """Each word of the command as a path from the directory `cd` left it in. Unlike simple_commands, it keeps a redirect's target, which a command reads as it reads an operand.""" + tokens = lexed(command) + if tokens is None: + # One unbalanced quote should not hide the other lines. + tokens = [token for line in command.splitlines() for token in (lexed(line) or []) + ["\n"]] + directory = cwd + words: list[str] = [] + for token in [*tokens, "\n"]: + if token and set(token) <= OPERATOR: + if len(words) == 2 and words[0] == "cd": + directory = resolved(directory, words[1], home) + words = [] + else: + # The lexer has joined a quoted "$HOME" to the rest of its word. + word = re.sub(r"^\$(HOME|\{HOME\})(?=/|$)", "~", token) + words.append(word) + yield resolved(directory, word, home) + + +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: + return False + if UNMATCHED.search(glob): + return True + if glob.startswith("!"): + # It only excludes files. + return False + anchored = glob.lstrip("/") if "/" in glob else f"**/{glob}" + # A `**` that is not a whole folder name matches as `*` in ripgrep; crossing folders there only refuses more. + translated = {"**/": "(?:.*/)?", "**": ".*", "*": "[^/]*", "?": "[^/]"} + pattern = "".join(translated.get(piece, re.escape(piece)) for piece in re.split(r"(\*\*/|\*\*|\*|\?)", anchored)) + return re.fullmatch(pattern, os.path.relpath(os.path.realpath(path), os.path.realpath(searched))) is not None def names(given: str, path: pathlib.Path) -> bool: @@ -48,9 +92,13 @@ def names(given: str, path: pathlib.Path) -> bool: def holds(folder: str, path: pathlib.Path) -> bool: - return pathlib.Path(os.path.realpath(path)).is_relative_to(os.path.realpath(folder)) + try: + return pathlib.Path(os.path.realpath(path)).is_relative_to(os.path.realpath(folder)) + except ValueError: + # A folder whose path holds a NUL byte holds no file. + return False def ignored(path: pathlib.Path) -> bool: - """Whether the checkout holding path ignores it: Grep runs ripgrep, which skips such a file in a folder it searches unless a glob names it.""" + """Whether the checkout holding path ignores it: Grep runs ripgrep, which skips such a file in a folder it searches unless a glob matches it.""" return not isinstance(guarded_git(str(path.parent), "check-ignore", "--quiet", path.name), Failure) diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 17eb4252..a47a72e7 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -37,8 +37,8 @@ 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 its config names, since a value it reads lands in its transcript, which loop-claude archives and the backups copy; a tool that needs a credential reads the file itself, and `project-config env-file` prints the file's path", - "a Read of the file, a Grep of the file, or of a folder that holds it where the Grep sets a glob or no checkout ignores the file, and a Bash command that spells the file's path or names it from the directory `cd` left the command in, against ~/.claude/.env and the env-file of every config under ~/.claude-projects", + "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", overridable=False, ), "ignorefile-sorted": Rule( diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 934e99a0..ec516517 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -405,7 +405,6 @@ class EnvFileRead(unittest.TestCase): subprocess.run(["git", "init", "--quiet", str(self.home / ".claude")], check=True, env=isolated_env()) (self.home / ".claude" / ".gitignore").write_text(".env\n") self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/.claude"}), []) - self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/.claude", "glob": "*"}), ["env-file-read"], "a glob overrides ripgrep's ignore files") self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/code"}), []) def test_a_command_naming_the_file_is_refused(self): @@ -417,6 +416,55 @@ class EnvFileRead(unittest.TestCase): self.assertEqual(self.breached("Bash", {"command": f"cat ~/.claude/.envrc /backup{self.home}/.claude/.env .env"}, "/r"), []) self.assertEqual(self.breached("Bash", {"command": "cat 'a\0b'"}, f"{self.home}/.claude"), []) + def test_a_command_s_refusal_says_it_names_the_file_not_that_it_reads_it(self): + found = breaches_of(Call("Bash", {"command": "ls -l ~/.claude/.env"}, "/r"), str(self.home), {}) + details = [breach.detail for breach in found[2] if breach.rule == "env-file-read"] + self.assertEqual(len(details), 1) + self.assertTrue(details[0].startswith(f"the command names {self.home}/.claude/.env"), details[0]) + self.assertNotIn("reads", details[0]) + + def test_the_rule_names_the_way_on_for_a_command_that_only_mentions_the_path(self): + holds = RULES["env-file-read"].holds + self.assertIn('"the .env in ~/.claude"', holds) + self.assertIn("`~/.claude/bin/project-config env-file`", holds) + self.assertNotIn(". ", holds, "one sentence") + + def test_a_command_redirecting_from_the_file_is_refused(self): + self.assertEqual(self.breached("Bash", {"command": "cd ~/secrets && wc < acme.env"}), ["env-file-read"]) + self.assertEqual(self.breached("Bash", {"command": "wc < acme.env"}, f"{self.home}/secrets"), ["env-file-read"]) + self.assertEqual(self.breached("Bash", {"command": "while read l; do echo $l; done < .env"}, f"{self.home}/.claude"), ["env-file-read"]) + + def test_a_command_naming_the_file_through_a_quoted_home_is_refused(self): + for command in ('cat "$HOME"/.claude/.env', 'cat "${HOME}"/.claude/.env'): + with self.subTest(command): + self.assertEqual(self.breached("Bash", {"command": command}), ["env-file-read"]) + + def test_a_grep_s_glob_is_refused_only_where_it_can_match_the_ignored_file(self): + subprocess.run(["git", "init", "--quiet", str(self.home / ".claude")], check=True, env=isolated_env()) + (self.home / ".claude" / ".gitignore").write_text(".env\n") + for glob, expected in (("**/*.md", []), ("rules/*.md", []), ("*.py", []), ("!.env", []), ("*", ["env-file-read"]), (".env*", ["env-file-read"]), ("{*.md,.env}", ["env-file-read"])): + with self.subTest(glob): + self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/.claude", "glob": glob}), expected) + + def test_a_grep_s_glob_with_a_slash_is_matched_against_the_path_from_the_searched_folder(self): + subprocess.run(["git", "init", "--quiet", str(self.home / ".claude")], check=True, env=isolated_env()) + (self.home / ".claude" / ".gitignore").write_text(".env\n") + # ~/secrets/acme.env is in no checkout, so only the ignored file's breach tells the globs apart. + for glob, refused in ((".claude/*", True), ("**/.env", True), ("/.claude/.env", True), (".claude/**", True), ("secrets/*", False), ("*/*.md", False), (".env/*", False)): + with self.subTest(glob): + 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 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" + config.write_text(config.read_text() + 'env-file = "~/secrets/../secrets/acme.env"\n') + found = breaches_of(Call("Read", {"file_path": "~/secrets/acme.env"}, "/r"), str(self.home), {}) + self.assertEqual(len([breach for breach in found[2] if breach.rule == "env-file-read"]), 1) + + def test_a_grep_of_a_path_holding_a_nul_byte_passes(self): + self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": "a\0b"}), []) + class ReviewerReport(unittest.TestCase): def breached(self, tool: str, path: str, agent: str = "prose-reviewer", cwd: str = "/r") -> list[str]: diff --git a/todo.md b/todo.md index 54566427..5bed889e 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,7 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 370 | 0.11.0 | | security | **Refuse a Bash command that searches a folder holding an env-file recursively, as `grep -r` or `rg` do, so no credential reaches a transcript.** | 2 | 2 | 4 | 6 | 2 | 4 by 3 | 4.2 | +| 370 | 0.11.0 | | security | **Refuse a Bash command that recursively searches a folder holding an env-file, as `grep -r` or `rg` do, so no credential reaches a transcript.** | 2 | 2 | 4 | 6 | 2 | 4 by 3 | 4.2 | | 354 | 0.11.0 | | | **Read and write the decisions, score anchors, comprehension history, reading cost and changelog each through the backend its project's config names, with markdown files as one backend.** | 3 | 2 | 3 | 6 | 6 | 1.6 by 4, code health by 1 | 1.2 | | 364 | 0.11.0 | 354 | | **Read a client repo's own `CLAUDE.md` and `AGENTS.md`, propose to its team each change that aligns them with this setup, and record each conflict left as a decision in the project's records.** | 2 | 2 | 2 | 4 | 2 | 1.6 by 4, 1.2 by 2 | 2.2 | | 360 | 0.11.0 | | | **Make `chunk-pr merge` wait for the human approvals a project's config requires, as part of the gate, before it merges.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 5 | 1.6 | @@ -87,9 +87,9 @@ ## Details -### 370. Refuse a Bash command that searches a folder holding an env-file recursively, as `grep -r` or `rg` do, so no credential reaches a transcript. +### 370. Refuse a Bash command that recursively searches a folder holding an env-file, as `grep -r` or `rg` do, so no credential reaches a transcript. -The env-file-read rule refuses a Grep of a folder that holds `~/.claude/.env` or a config's env-file, but a Bash command only where it spells or names the file itself. A worker that runs `grep -r TOKEN ~/.claude-projects`, or `rg --no-ignore` over `~/.claude`, still prints the credential lines into its transcript, which loop-claude archives under `~/.claude/loop-claude-transcripts` and the backups copy. README suggests keeping the env-file at `~/.claude-projects/.env`, a folder agents search often. Extend `bin/rule_hook/env_file.py` to refuse a `grep -r`/`-R`, `rg` or `ag` whose folder operand, or the directory `cd` left it in when it names none, holds a guarded file that the tool doesn't skip. A test must show the refusal for each tool. The security pass of item 369's chunk raised it. +The env-file-read rule refuses a Grep of a folder that holds `~/.claude/.env` or a config's env-file, but a Bash command only where it spells or names the file itself. A worker that runs `grep -r TOKEN ~/.claude-projects`, or `rg --no-ignore` over `~/.claude`, still prints the credential lines into its transcript, which loop-claude archives under `~/.claude/loop-claude-transcripts` and the backups copy. README suggests keeping the env-file at `~/.claude-projects/.env`, in a folder agents search often. Extend `bin/rule_hook/env_file.py` to refuse a `grep -r`/`-R`, `rg` or `ag` whose folder operand, or the directory `cd` left it in when it names none, holds a guarded file that the tool doesn't skip. A test must show the refusal for each tool. The security pass of item 369's chunk raised it. ### 354. Read and write the decisions, score anchors, comprehension history, reading cost and changelog each through the backend its project's config names, with markdown files as one backend.