Refuse a Bash command that recursively searches a folder holding an env-file #527
+1
-1
@@ -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 `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, 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
|
||||
|
||||
@@ -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 `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, 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.
|
||||
|
||||
|
||||
@@ -95,6 +95,11 @@ def resolved(base: str, path: str, home: str) -> str:
|
||||
return posixpath.normpath(posixpath.join(base, home + path[1:] if path == "~" or path.startswith("~/") else path))
|
||||
|
||||
|
||||
def home_word(token: str) -> str:
|
||||
"""The word with a leading $HOME or ${HOME} spelt as ~; the lexer has joined a quoted "$HOME" to the rest of its word."""
|
||||
return re.sub(r"^\$(HOME|\{HOME\})(?=/|$)", "~", token)
|
||||
|
||||
|
||||
def tool_name(word: str) -> str:
|
||||
"""The tool a word names, such as mutmut for `mutmut>=3,<4` or `.venv/bin/mutmut`; empty for a word that names none, such as a file name."""
|
||||
named = re.fullmatch(r"([A-Za-z_-]+)(?:[<>=!~@].*)?", posixpath.basename(word))
|
||||
|
||||
+19
-46
@@ -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 it or searches a folder holding it, 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."""
|
||||
It searches a folder holding one where `folder_search.searches` finds that an `ag`, `grep -r` or `rg` reaches the file.
|
||||
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`."""
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
@@ -11,12 +12,13 @@ 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 lexed, OPERATOR, resolved
|
||||
from rule_hook.folder_search import globbed, holds, ignored, searches
|
||||
from command_lines.shell_command import home_word, lexed, OPERATOR, resolved
|
||||
|
||||
# What a Grep's glob holds beyond literals, `*`, `?` and `/`: forms globbed() does not translate.
|
||||
UNMATCHED = re.compile(r"[{}\[\]\\,\s]|/$")
|
||||
# The breach's detail by how the call reached the file. A command may name the file without reading it, so its detail claims no read of it.
|
||||
READS = "the call reads {}, whose credentials would land in the transcript"
|
||||
NAMES = "the command names {}, a file of credentials that must stay out of the transcript"
|
||||
SEARCHES = "the command searches a folder holding {}, a file of credentials that must stay out of the transcript; search a folder without it"
|
||||
|
||||
|
||||
def env_file_breaches(call: Call, home: str) -> list[Breach]:
|
||||
@@ -25,25 +27,26 @@ def env_file_breaches(call: Call, home: str) -> list[Breach]:
|
||||
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)]
|
||||
reached = [(path, reaching(call, path, home)) for path in guarded.values()]
|
||||
return [Breach("env-file-read", how.format(path), call.cwd) for path, how in reached if how]
|
||||
|
||||
|
||||
def reached(call: Call, path: pathlib.Path, home: str) -> bool:
|
||||
"""Whether a Read or a Grep reads path, or a Bash command names it."""
|
||||
def reaching(call: Call, path: pathlib.Path, home: str) -> str:
|
||||
"""The detail of the breach if a Read or a Grep reads path, or a Bash command names it or searches a folder holding it; empty if none does."""
|
||||
if call.tool == "Read":
|
||||
return names(resolved(call.cwd, text(call.given, "file_path"), home), path)
|
||||
return READS if names(resolved(call.cwd, text(call.given, "file_path"), home), path) else ""
|
||||
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 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))
|
||||
return READS if names(searched, path) or holds(searched, path) and (globbed(text(call.given, "glob"), searched, path) or not ignored(path)) else ""
|
||||
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"(?<![\w./~-])(?:{spellings})(?![\w.-])", command)
|
||||
return spelt is not None or any(names(word, path) for word in paths(command, call.cwd, home))
|
||||
if spelt is not None or any(names(word, path) for word in paths(command, call.cwd, home)):
|
||||
return NAMES
|
||||
return SEARCHES if searches(command, call.cwd, home, path) else ""
|
||||
|
||||
|
||||
def paths(command: str, cwd: str, home: str) -> typing.Iterator[str]:
|
||||
@@ -60,28 +63,11 @@ def paths(command: str, cwd: str, home: str) -> typing.Iterator[str]:
|
||||
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)
|
||||
word = home_word(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:
|
||||
"""Whether given leads to path, through any symlink."""
|
||||
try:
|
||||
@@ -89,16 +75,3 @@ def names(given: str, path: pathlib.Path) -> bool:
|
||||
except ValueError:
|
||||
# A word holding a NUL byte names no file.
|
||||
return False
|
||||
|
||||
|
||||
def holds(folder: str, path: pathlib.Path) -> bool:
|
||||
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 matches it."""
|
||||
return not isinstance(guarded_git(str(path.parent), "check-ignore", "--quiet", path.name), Failure)
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Whether a search of a folder reaches a file, for the `env-file-read` rule: a Grep with its glob, and a Bash `ag`, `grep -r` or `rg`.
|
||||
|
||||
A search reaches a file in a folder it searches unless the tool skips the file. ripgrep, which a Grep runs, and `ag` skip a file that the checkout holding it ignores; a Bash `rg` or `ag` also skips a hidden file and one below a hidden folder of the searched folder, which a Grep doesn't. `grep -r` doesn't skip any file. A glob changes what ripgrep skips, as `globbed` and `skips` say.
|
||||
Each judgment refuses more where it is unsure: an option it doubts lifts a skip, and a pipe's input isn't told apart from the directory, so `x | rg y` in a folder holding the file is refused too."""
|
||||
import itertools
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from failure import Failure
|
||||
from rule_hook.git import guarded_git
|
||||
from command_lines.shell_command import home_word, Launch, launched, resolved, simple_commands
|
||||
|
||||
GREPS = frozenset({"egrep", "fgrep", "grep"})
|
||||
SEARCHERS = GREPS | {"ag", "rg"}
|
||||
# grep searches folders only with an option that makes it recursive: -r and -R in a cluster, --recursive, and `-d recurse` as one word or two.
|
||||
RECURSIVE_GREP = re.compile(r"-[^-]*[rR].*|--(?:dereference-)?recursive|--directories=recurse|-[^-]*drecurse")
|
||||
# The option before a separate `recurse` word that makes grep recursive.
|
||||
DIRECTORIES_OPTION = re.compile(r"-[^-]*d|--directories")
|
||||
# An option that gives the pattern, so that no operand is the pattern: -e and -f in a cluster, and --regexp and --file.
|
||||
PATTERN_OPTION = re.compile(r"-[^-]*[ef].*|--(?:regexp|file)(?:=.*)?")
|
||||
# rg's --glob and --iglob, and -g at the start of a word: 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(?:=(.*))?|-g(.*)")
|
||||
# The options with which ag searches an ignored file, besides -u and --unrestricted.
|
||||
AG_LIFTS_IGNORED = frozenset({"--all-text", "--all-types", "--skip-vcs-ignores"})
|
||||
# What a Grep's glob holds beyond literals, `*`, `?` and `/`: forms globbed() does not translate.
|
||||
UNMATCHED = re.compile(r"[{}\[\]\\,\s]|/$")
|
||||
|
||||
|
||||
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 its tool does not skip path there."""
|
||||
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 recursive(launch.arguments, options):
|
||||
continue
|
||||
if any(holds(folder, path) and not skips(launch, options, folder, path) for folder in folders(simple.directory, options, operands, home)):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def recursive(arguments: list[str], options: list[str]) -> bool:
|
||||
"""Whether a grep's options make it search folders."""
|
||||
pairs = itertools.pairwise(arguments)
|
||||
return any(RECURSIVE_GREP.fullmatch(option) for option in options) or any(value == "recurse" and DIRECTORIES_OPTION.fullmatch(option) for option, value in pairs)
|
||||
|
||||
|
||||
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."""
|
||||
options: list[str] = []
|
||||
operands: list[str] = []
|
||||
words = iter(arguments)
|
||||
for word in words:
|
||||
if word == "--":
|
||||
# It takes the rest of the words, which ends the loop.
|
||||
operands.extend(words)
|
||||
elif word.startswith("-"):
|
||||
options.append(word)
|
||||
else:
|
||||
operands.append(word)
|
||||
return options, operands
|
||||
|
||||
|
||||
def folders(directory: str, options: list[str], operands: list[str], home: str) -> list[str]:
|
||||
"""The folders a search reads: its operands that are folders, or else the directory it runs in. Other operands are dropped: an option's value, such as 3 in `-A 3`, is one, and so is a file."""
|
||||
if not any(PATTERN_OPTION.fullmatch(option) for option in options):
|
||||
# The first operand is the pattern, or the value of an option before it.
|
||||
operands = operands[1:]
|
||||
named = [resolved(directory, home_word(operand), home) for operand in operands]
|
||||
return [word for word in named if os.path.isdir(word)] or [directory]
|
||||
|
||||
|
||||
def globs_of(arguments: list[str]) -> tuple[list[str], bool]:
|
||||
"""The globs that rg's -g, --glob and --iglob options give, without the ones that exclude files, and whether rg matches them without regard to case, which globbed() does not translate."""
|
||||
found = []
|
||||
for at, word in enumerate(arguments):
|
||||
option = GLOB_OPTION.fullmatch(word)
|
||||
if option:
|
||||
given = option.group(1) or option.group(2)
|
||||
if not given and at + 1 < len(arguments):
|
||||
given = arguments[at + 1]
|
||||
if given and not given.startswith("!"):
|
||||
found.append(given)
|
||||
return found, any(word.startswith("--iglob") or word == "--glob-case-insensitive" for word in arguments)
|
||||
|
||||
|
||||
def skips(launch: Launch, options: list[str], folder: str, path: pathlib.Path) -> bool:
|
||||
"""Whether the tool passes over path when it searches folder. A grep doesn't pass over any file. rg searches only the files that its globs match, where it has a glob that doesn't exclude files; a glob holding a `/` counts as matching, since rg anchors it at the directory it runs in, which is not told from the folder searched. Otherwise rg and ag pass over a hidden path below folder and an ignored file, unless an option lifts that."""
|
||||
if launch.tool in GREPS:
|
||||
return False
|
||||
if launch.tool == "rg":
|
||||
globs, insensitive = globs_of(launch.arguments)
|
||||
if globs:
|
||||
return not (insensitive or any("/" in glob or globbed(glob, folder, path) for glob in globs))
|
||||
long = [option for option in options if option.startswith("--")]
|
||||
clusters = [option[1:] for option in options if not option.startswith("--")]
|
||||
unrestricted = sum(cluster.count("u") for cluster in clusters) + long.count("--unrestricted")
|
||||
if launch.tool == "rg":
|
||||
hidden_lifted = "--hidden" in long or any("." in cluster for cluster in clusters) 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 any(re.search("[Uat]", cluster) for cluster in clusters) or not AG_LIFTS_IGNORED.isdisjoint(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 holds(folder: str, path: pathlib.Path) -> bool:
|
||||
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: ripgrep and ag skip such a file in a folder they search, ripgrep unless a glob matches it."""
|
||||
return not isinstance(guarded_git(str(path.parent), "check-ignore", "--quiet", path.name), Failure)
|
||||
|
||||
|
||||
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
|
||||
anchored = glob.removeprefix("/") 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
|
||||
@@ -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 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",
|
||||
"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, and searches only a folder without 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 `ag`, `grep -r` or `rg` over a folder holding one, or over the directory `cd` left the command in where it names no folder, unless the tool skips the file: `ag` and `rg` skip a hidden file, one below a hidden folder of the search and one a checkout ignores, and `rg` one that none of its globs matches",
|
||||
overridable=False,
|
||||
),
|
||||
"ignorefile-sorted": Rule(
|
||||
|
||||
@@ -416,6 +416,11 @@ 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_search_s_refusal_says_it_searches_a_folder_holding_the_file_and_what_to_do(self):
|
||||
found = breaches_of(Call("Bash", {"command": "rg TOKEN ~/secrets"}, "/r"), str(self.home), {})
|
||||
details = [breach.detail for breach in found[2] if breach.rule == "env-file-read"]
|
||||
self.assertEqual(details, [f"the command searches a folder holding {self.home}/secrets/acme.env, a file of credentials that must stay out of the transcript; search a folder without it"])
|
||||
|
||||
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"]
|
||||
@@ -442,7 +447,7 @@ class EnvFileRead(unittest.TestCase):
|
||||
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"])):
|
||||
for glob, expected in (("**/*.md", []), ("rules/*.md", []), ("*.py", []), ("!.env", []), ("*", ["env-file-read"]), (".env*", ["env-file-read"]), ("?env", ["env-file-read"]), ("?nv", []), ("{*.md,.env}", ["env-file-read"])):
|
||||
with self.subTest(glob):
|
||||
self.assertEqual(self.breached("Grep", {"pattern": "TOKEN", "path": f"{self.home}/.claude", "glob": glob}), expected)
|
||||
|
||||
@@ -450,11 +455,117 @@ 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")
|
||||
# ~/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)):
|
||||
for glob, refused in ((".claude/*", True), ("**/.env", True), ("/.claude/.env", True), (".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 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",
|
||||
"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",
|
||||
"grep -d recurse TOKEN ~/secrets", "grep -nd recurse TOKEN ~/secrets", "grep --directories recurse TOKEN ~/secrets", "grep -drecurse TOKEN ~/secrets", "rg -eTOKEN ~/secrets", "rg --regexp=TOKEN ~/secrets", "grep -rf patterns ~/secrets", "rg TOKEN -- ~/secrets", "rg -- TOKEN ~/secrets", "ag -g '*.md' TOKEN ~/secrets",
|
||||
"grep TOKEN x; rg TOKEN ~/secrets", "cd ~/code && rg TOKEN ~/secrets", "rg -Tgo TOKEN ~/secrets", "rg -rgone TOKEN ~/secrets", "grep -rm1 TOKEN ~/secrets", "grep -rC2 TOKEN ~/secrets", "rg -e1 -nA3 TOKEN ~/secrets", "echo hi && ag 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": "ag TOKEN"}, f"{self.home}/secrets"), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Bash", {"command": "grep -rnA3 TOKEN"}, f"{self.home}/secrets"), ["env-file-read"])
|
||||
# patterns is a file the cwd holds, given as the value of -f.
|
||||
(self.home / "secrets" / "patterns").write_text("TOKEN\n")
|
||||
self.assertEqual(self.breached("Bash", {"command": "rg -f patterns"}, f"{self.home}/secrets"), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Bash", {"command": "grep -rf patterns"}, 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", "grep -n recurse notes.md"):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), [])
|
||||
self.assertEqual(self.breached("Bash", {"command": "rg TOKEN"}, f"{self.home}/code"), [])
|
||||
# The word recurse is only a pattern or a file name here, and -d read is no recursion.
|
||||
for command in ("grep -n recurse notes.md", "grep -d read TOKEN ~/secrets", "grep --directories read TOKEN ~/secrets"):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}, str(self.home)), [])
|
||||
# secrets is the pattern, not the folder ~/secrets that the home directory holds.
|
||||
self.assertEqual(self.breached("Bash", {"command": "rg secrets ~/code"}, str(self.home)), [])
|
||||
|
||||
def test_a_folder_that_starts_with_a_dash_is_searched_after_double_dash(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 = "~/real/x.env"\n')
|
||||
(self.home / "real").mkdir()
|
||||
(self.home / "real" / "x.env").write_text("TOKEN=z\n")
|
||||
(self.home / "sub").mkdir()
|
||||
# The link keeps ~/sub clear of the file, so only the operand -d reaches it.
|
||||
(self.home / "sub" / "-d").symlink_to(self.home / "real")
|
||||
self.assertEqual(self.breached("Bash", {"command": "rg TOKEN -- -d"}, f"{self.home}/sub"), ["env-file-read"])
|
||||
self.assertEqual(self.breached("Bash", {"command": "rg TOKEN"}, f"{self.home}/sub"), [])
|
||||
|
||||
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"]), ("rg -u -u TOKEN ~/.claude", ["env-file-read"]), ("rg --unrestricted TOKEN ~/.claude", []), ("rg --unrestricted --unrestricted 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_that_starts_in_a_hidden_folder_reaches_a_visible_file_below_it(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"])):
|
||||
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_a_file_below_any_hidden_folder_of_the_search(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 = "~/outer/deep/.h/b.env"\n')
|
||||
(self.home / "outer" / "deep" / ".h").mkdir(parents=True)
|
||||
(self.home / "outer" / "deep" / ".h" / "b.env").write_text("TOKEN=z\n")
|
||||
for command, expected in (("rg TOKEN ~/outer", []), ("ag TOKEN ~/outer", []), ("rg --hidden TOKEN ~/outer", ["env-file-read"]), ("grep -r TOKEN ~/outer", ["env-file-read"]), ("rg TOKEN ~/outer/deep/.h", ["env-file-read"])):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), expected)
|
||||
|
||||
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"]), ("ag -a TOKEN ~/secrets", ["env-file-read"]), ("ag -t TOKEN ~/secrets", ["env-file-read"]), ("ag --all-text TOKEN ~/secrets", ["env-file-read"]), ("ag --all-types TOKEN ~/secrets", ["env-file-read"]), ("rg -uu 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 --glob '*.md' TOKEN ~/secrets", []), ("rg --iglob '*.ENV' TOKEN ~/secrets", ["env-file-read"]), ("rg --glob-case-insensitive -g '*.ENV' TOKEN ~/secrets", ["env-file-read"]), ("rg TOKEN ~/secrets -g", ["env-file-read"]), ("rg TOKEN ~/secrets -g '*.env'", ["env-file-read"]), ("rg TOKEN ~/secrets -g '*.md'", [])):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}), expected)
|
||||
|
||||
def test_a_path_glob_of_rg_lifts_the_skip_since_rg_anchors_it_at_the_directory_it_runs_in(self):
|
||||
self.ignoring("secrets", "*.env\n")
|
||||
for command in ("rg -g 'secrets/*.env' TOKEN secrets", "rg -g 'secrets/*.env' TOKEN ~/secrets", "rg -g '/secrets/*.env' TOKEN secrets"):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.breached("Bash", {"command": command}, str(self.home)), ["env-file-read"])
|
||||
|
||||
def test_a_search_s_breach_is_logged_in_the_directory_the_command_runs_in(self):
|
||||
found = breaches_of(Call("Bash", {"command": "grep -r TOKEN ~/secrets"}, "/r"), str(self.home), {})
|
||||
self.assertEqual([breach.directory for breach in found[2] if breach.rule == "env-file-read"], ["/r"])
|
||||
|
||||
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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 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 |
|
||||
| 371 | 0.11.0 | | owner | **Remove loop-inbox, so an interrupt is answered at loop-claude's terminal only.** | 3 | 2 | 3 | 6 | 5 | code health by 3 | 2.9 |
|
||||
| 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 |
|
||||
@@ -92,10 +91,6 @@
|
||||
|
||||
## Details
|
||||
|
||||
### 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/<key>.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.
|
||||
|
||||
### 371. Remove loop-inbox, so an interrupt is answered at loop-claude's terminal only.
|
||||
|
||||
lilleman's call, 2026-11-13: loop-inbox didn't work out, so it goes, and the parallel chunks in items 372 to 375 don't build on it. An interrupt is answered at loop-claude's terminal only, with `/talk` opening the worker's session there, as before todo item 243. The Mattermost DM keeps telling the human that a loop waits.
|
||||
|
||||
Reference in New Issue
Block a user