197 lines
11 KiB
Python
197 lines
11 KiB
Python
"""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.
|
|
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
|
|
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 launched, lexed, OPERATOR, resolved, 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"-[^-]*[rR].*|--(?: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"-[^-]*[ef].*|--(?: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]|/$")
|
|
|
|
|
|
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)
|
|
# 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 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 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"(?<![\w./~-])(?:{spellings})(?![\w.-])", command)
|
|
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]:
|
|
"""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 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.directory, 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."""
|
|
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 the directory it runs in where none is. An option's value is an operand here; one that is no folder is dropped like any word that is none."""
|
|
if not any(PATTERN_OPTION.fullmatch(option) for option in options):
|
|
# The first operand is the pattern.
|
|
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]) -> list[str]:
|
|
"""The globs of rg's -g, --glob and --iglob options; --iglob's matching without regard to case is not translated."""
|
|
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:
|
|
found.append(given)
|
|
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("--")]
|
|
clusters = [option[1:] for option in options if not option.startswith("--")]
|
|
unrestricted = sum(cluster.count("u") for cluster in clusters) + long.count("--unrestricted")
|
|
if 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("U" in cluster or "a" in cluster for cluster in clusters) 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:
|
|
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:
|
|
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:
|
|
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)
|