"""Whether a Read, Grep or Bash call reads a credentials file, 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.""" import os import pathlib import re 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 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] def reads(call: Call, path: pathlib.Path, home: str) -> bool: """Whether a Read, a Grep or else a Bash command reads path.""" 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) return names(searched, path) or holds(searched, path) and 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"(? 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 def holds(folder: str, path: pathlib.Path) -> bool: return pathlib.Path(os.path.realpath(path)).is_relative_to(os.path.realpath(folder)) 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.""" return not isinstance(guarded_git(str(path.parent), "check-ignore", "--quiet", path.name), Failure)