Files
2026-11-18 09:54:39 +01:00

78 lines
4.4 KiB
Python

"""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`, do-epic's included, 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.
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
import typing
from rule_hook.rules import Breach
from rule_hook.call import Call, text
from project_config.settings import env_files
from rule_hook.folder_search import globbed, holds, ignored, searches
from command_lines.shell_command import home_word, lexed, OPERATOR, resolved
# 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]:
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)
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 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 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 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)
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]:
"""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:
word = home_word(token)
words.append(word)
yield resolved(directory, word, home)
def names(given: str, path: pathlib.Path) -> bool:
"""Whether given leads to path, through any symlink."""
try:
return os.path.realpath(given) == os.path.realpath(path)
except ValueError:
# A word holding a NUL byte names no file.
return False