diff options
| author | Claude <noreply@anthropic.com> | 2026-11-13 00:22:21 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-13 00:22:21 +0000 |
| commit | cf694f613b8d4568b74ce55aa306aad7cf2327a7 (patch) | |
| tree | 93c0c7cdbc46edb58e8c87e1761c6d50a98768b0 /plugins | |
| parent | f75f5b25ae94f4332be4ff5f18435741d2589bdb (diff) | |
security-guidance: review text files renamed to code names
git shows no content for a renamed file, so a text or document file renamed
to a code name (notes.txt to payload.py) was never read by the commit and
push reviews. They now read it whole, behind the files they already review
and within a small share of the prompt. Other renames are reviewed as before.
Part of #4852
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 183 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 105 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_renamed_into_review.py | 391 |
3 files changed, 656 insertions, 23 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 184dba6d..041bf7ba 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -685,6 +685,16 @@ def _env_with_private_objects(env, cwd, objects_dir): return out +def _literal_paths_env(env): + """`env` with every path a git command is given taken as a file name, not + a pattern: a file named `:(glob)**` stands only for itself. git refuses + that together with a glob or icase setting from the user's environment.""" + env = {k: v for k, v in env.items() + if k not in ("GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS")} + env["GIT_LITERAL_PATHSPECS"] = "1" + return env + + def _add_new_files(cwd, paths, env, tmp_index): """`git add --intent-to-add` the untracked `paths` to the index copy `env` names, so the diff shows them. The add has to store the empty blob, so a @@ -697,12 +707,8 @@ def _add_new_files(cwd, paths, env, tmp_index): reader threads that decode stderr — git error messages can reference non-ASCII filenames and crash on cp1252. See #2099. Drop text=True so bytes stay raw.""" - # The paths are file names, not patterns, for this git add only: an - # untracked file named `:(glob)**` must add only itself. git refuses that - # together with a glob or icase setting from the user's environment. - env = {k: v for k, v in env.items() - if k not in ("GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS")} - env["GIT_LITERAL_PATHSPECS"] = "1" + # For this git add only. + env = _literal_paths_env(env) def add(add_env): results = _run_git_on_review_paths( @@ -1344,6 +1350,25 @@ def _note_rename(old_path, new_path): _secret_rename_origins[new_path] = old_path +def _name_status_pairs(stdout): + """(old path or None, path) for each entry of `git diff --name-status -z` + output. Fields are `status\\0path\\0`, or `R<score>\\0old\\0new\\0` for a + rename or copy, which is listed by its new name.""" + fields = (stdout or b"").decode("utf-8", errors="replace").split("\0") + i = 0 + while i + 1 < len(fields): + if not fields[i]: + # `git log` can put an empty field between two commits. + i += 1 + continue + old = None + if fields[i][:1] in ("R", "C") and i + 2 < len(fields): + old = fields[i + 1] + i += 1 + yield old, fields[i + 1] + i += 2 + + def _git_name_only(cwd, base, include_untracked=False): """Return the set of repo-root-relative paths that differ from `base`, or None if git failed (unresolvable ref, not a repo, timeout). Callers @@ -1371,18 +1396,11 @@ def _git_name_only(cwd, base, include_untracked=False): stderr_str = (result.stderr or b"").decode("utf-8", errors="replace") debug_log(f"_git_name_only({base!r}) rc={result.returncode}: {stderr_str[:200]}") return None - stdout = (result.stdout or b"").decode("utf-8", errors="replace") - # Fields are `status\0path\0`, or `R<score>\0old\0new\0` for a rename - # or copy, which is listed by its new name only. - fields = stdout.split("\0") names = set() - i = 0 - while i + 1 < len(fields): - if fields[i][:1] in ("R", "C") and i + 2 < len(fields): - _note_rename(fields[i + 1], fields[i + 2]) - i += 1 - names.add(fields[i + 1]) - i += 2 + for old, new in _name_status_pairs(result.stdout): + if old: + _note_rename(old, new) + names.add(new) return names try: @@ -2108,6 +2126,11 @@ def _parse_diff_header(header): `"a/we\\"ird.py" "b/we\\"ird.py"`. Either side can be quoted on its own. """ old = new = None + # The same name on both sides, as in every section but a rename or a copy. + # A name that contains ` b/` can only be told apart this way. + same = header[2:(len(header) - 1) // 2] + if same and header == f"a/{same} b/{same}": + return same, same if header.startswith('"'): first = _read_quoted_path(header, 0) if not first: @@ -2145,11 +2168,32 @@ def _section_is_reviewable(file_path, old_path): return _is_reviewable_source(file_path) and not _skip_secret_shaped(old_path) +def _rename_of(lines): + """(old path, new path) of a section git shows as a rename or a copy, or + None. Read from its `rename from` / `rename to` lines, where each path + stands alone; the header line is ambiguous when a name contains ` b/`.""" + old = None + for line in lines: + if line.startswith('@@'): + break + m = re.match(r'(?:rename|copy) (from|to) (.+)', line) + if not m: + continue + path = m.group(2) + if path.startswith('"'): + quoted = _read_quoted_path(path, 0) + path = quoted[0] if quoted else path + if m.group(1) == 'to': + return (old, path) if old else None + old = path + return None + + def _iter_diff_sections(diff_output): """Yield (new_path, old_path, lines after the header line) per file section.""" for section in _DIFF_SECTION_RE.split(diff_output)[1:]: lines = section.split('\n') - paths = _parse_diff_header(lines[0]) + paths = _rename_of(lines[1:]) or _parse_diff_header(lines[0]) if paths: yield paths[1] or paths[0], paths[0], lines[1:] else: @@ -2200,6 +2244,109 @@ def parse_diff_into_files(diff_output): return files +# Names whose content the commit and push reviews never read although it can +# be code: text and documents. Not every name they leave out: a key, an +# archive or a vendored file under a new name is still what it was. +_TEXT_EXTENSIONS = frozenset(('.txt', '.text', '.md', '.markdown', '.rst')) +_DATA_EXTENSIONS = frozenset(( + '.json', '.yaml', '.yml', '.toml', '.properties', '.tfvars', '.ipynb', +)) +_CODE_EXTENSIONS = SOURCE_CODE_EXTENSIONS - _DATA_EXTENSIONS + + +def _is_secret_stem(file_path): + """`credentials.txt`, `id_rsa.md`: a secret's name with an extension.""" + stem = os.path.splitext(os.path.basename(file_path))[0].lower() + return (_is_secret_shaped(stem) or stem in _SECRET_NAMED_STEMS + or stem.startswith('password')) + + +def _is_text_turned_code(old_path, new_path): + ext = os.path.splitext(new_path)[1].lower() + return (os.path.splitext(old_path)[1].lower() in _TEXT_EXTENSIONS + and not _is_secret_stem(old_path) and not _is_secret_stem(new_path) + and (ext in _CODE_EXTENSIONS + or os.path.basename(new_path).lower() in SOURCE_CODE_BASENAMES) + and _section_is_reviewable(new_path, old_path) + and not _is_reviewable_source(old_path)) + + +def renamed_into_review(diff_output): + """The new names of the files a diff renames or copies from a text name + the review leaves out (`notes.txt`) to a code name it reviews. git shows + only what changed across a rename, and nothing at all when the content did + not, so what nobody reviewed as text would never be read as code. + + Empty when the diff also removes or renames a secret-shaped file: git + picks which old name a new file came from, and between two alike it can be + the other one. + """ + if "\nrename to " not in diff_output and "\ncopy to " not in diff_output: + return [] + names = [] + for file_path, old_path, lines in _iter_diff_sections(diff_output): + renamed = _rename_of(lines) + if (renamed or lines[:1] and lines[0].startswith("deleted file mode")) \ + and _is_secret_shaped(old_path): + return [] + if renamed and _is_text_turned_code(old_path, file_path): + names.append(file_path) + return names + + +# How many commits back came_from_secret looks. +_SECRET_ORIGIN_COMMITS = 50 + + +def came_from_secret(repo_root, rev, paths, timeout): + """Those of `paths` at `rev` that one of the last commits renamed from a + secret-shaped name, whatever they were called in between. None on error.""" + try: + result = subprocess.run( + [*GIT_CMD, "-c", "log.diffMerges=separate", "log", "-m", + "-n", str(_SECRET_ORIGIN_COMMITS), "--format=", "--name-status", "-z", + "--no-ext-diff", rev, "--"], + cwd=repo_root, capture_output=True, timeout=timeout, + # A partial clone would download old files to compare them. + env={**os.environ, "GIT_NO_LAZY_FETCH": "1"}) + except (subprocess.TimeoutExpired, OSError) as e: + debug_log(f"came_from_secret: {e}") + return None + if result.returncode != 0: + return None + # Newest commit first: every name each path has had so far. + had = {path: {path} for path in paths} + for old, new in _name_status_pairs(result.stdout): + for names in had.values(): + if old and new in names: + names.add(old) + return {path for path, names in had.items() if any(map(_is_secret_shaped, names))} + + +def git_diff_unpaired(repo_root, revs, paths, timeout): + """{path: hunks} for those of `paths` the commit or range `revs` names + (`show` or `diff` arguments) changed, each shown whole instead of against + the name it was renamed from. Empty hunks for a file git shows none for (a + binary one). None on error.""" + try: + result = _run_diff_bounded( + [*GIT_CMD, revs[0], "-p", "--no-renames", "--no-color", "--no-ext-diff", + "--no-textconv", *revs[1:], "--", *paths], + timeout, cwd=repo_root, env=_literal_paths_env(os.environ)) + except (subprocess.TimeoutExpired, OSError) as e: + debug_log(f"git_diff_unpaired: {e}") + return None + if result.returncode != 0: + debug_log(f"git_diff_unpaired: rc={result.returncode}: " + f"{result.stderr[:200].decode('utf-8', errors='replace')}") + return None + text = result.stdout.decode("utf-8", errors="replace") + # A path that used to be a directory also matches the files under it. + shown = {name: "" for name, _, _ in _iter_diff_sections(text)} + shown.update(parse_diff_into_files(text)) + return {name: hunks for name, hunks in shown.items() if name in paths} + + def filter_preexisting_from_diff(diff_files, cwd, baseline_sha): """ Filter out pre-existing content from diff files. diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index fcd20a7f..0c0ebd68 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -117,7 +117,8 @@ from gitutil import ( # noqa: E402,F401 _LOW_PRIORITY_SUFFIXES, _LOW_PRIORITY_PATH_TOKENS, _prioritize_diff_files, _is_reviewable_source, extract_file_paths_from_diff, parse_diff_into_files, - filter_preexisting_from_diff, + filter_preexisting_from_diff, renamed_into_review, + came_from_secret, git_diff_unpaired, ) from diffstate import ( # noqa: E402,F401 STOP_LOOP_STATE_TTL_SEC, PREVIOUS_FINDINGS_TTL_SEC, @@ -260,7 +261,7 @@ _TAIL_METRICS: Dict[str, Any] = {} # Of those, the ones that go after the others whenever they were set: a row # over CC's key cap loses them before any older review key. Only the launcher # keys below come later; those are also on every smaller row of the session. -_LAST_METRIC_KEYS = ("diff_seen", "cr_pack") +_LAST_METRIC_KEYS = ("diff_seen", "cr_pack", "renamed_in") # CC keeps this many keys of a row. _METRIC_KEY_CAP = 20 @@ -1366,6 +1367,78 @@ def _merge_resolved_diff_files(repo_root, merges): resolved[path] = resolved[path] + "\n" + hunks if path in resolved else hunks return resolved + +# Files renamed into review that one review takes, by priority, how much of +# the prompt they get, and the time for the git calls behind it. +MAX_RENAMED_IN = 10 +RENAMED_IN_BYTES = DIFF_TOTAL_BYTES // 4 +RENAMED_IN_TIMEOUT_S = 15 + + +def _with_renamed_in(repo_root, diff_files, renamed, cap): + """`diff_files` plus, whole, files renamed into review (see + renamed_into_review). `renamed` is (name, git arguments that show it, the + commit they end at) per file. Returns (files, whether git failed to show + some of them). + + No file reviewed without them is dropped or cut because of them: a new + entry goes behind the others in a place they leave free, and a file + already there for an edit becomes the whole of it plus the lines the edit + removed. The rest is reviewed as before. + """ + origin = {} + for name, revs, rev in renamed: + origin.setdefault(name, (revs, rev)) + if not origin or len(diff_files) > cap: + return diff_files, False + there = dict(diff_files) + room = cap - len(diff_files) + by_revs = {} + for name, _ in _prioritize_diff_files([(n, "") for n in origin], MAX_RENAMED_IN)[0]: + if there.get(name, "").startswith("@@@"): + continue # a merge's own hunks, in another format + if name not in there: + if room <= 0: + continue + room -= 1 + by_revs.setdefault(origin[name], []).append(name) + + deadline = time.monotonic() + RENAMED_IN_TIMEOUT_S + + def left(): + return max(deadline - time.monotonic(), 0.1) + + whole, failed = {}, False + for (revs, rev), names in by_revs.items(): + secret = came_from_secret(repo_root, rev, names, left()) + names = [n for n in names if secret is not None and n not in secret] + shown = git_diff_unpaired(repo_root, revs, names, left()) if names else {} + failed = failed or secret is None or shown is None or len(shown) < len(names) + whole.update((name, hunks) for name, hunks in (shown or {}).items() if hunks) + + def size(hunks): + # With room for the marker a cut file ends in. + return min(len(hunks), DIFF_PER_FILE_BYTES) + 100 + + budget = min(RENAMED_IN_BYTES, + DIFF_TOTAL_BYTES - sum(size(hunks) for _, hunks in diff_files)) + taken = {} + for name, hunks in whole.items(): + if name in there: + removed = [ln for ln in there[name].split("\n") if ln.startswith(("@@", "-"))] + hunks = "\n".join([hunks, *removed]) + if len(hunks) > DIFF_PER_FILE_BYTES: + continue + if size(hunks) <= budget: + budget -= size(hunks) + taken[name] = hunks + if taken: + debug_log(f"{len(taken)} file(s) renamed from a text name") + _TAIL_METRICS["renamed_in"] = len(taken) + files = [(name, taken.pop(name, hunks)) for name, hunks in diff_files] + return files + list(taken.items()), failed + + def _push_section(bash_output): """Return the slice of `bash_output` that contains the push's range lines. @@ -2020,6 +2093,7 @@ def handle_commit_review_posttooluse(input_data): # can contain non-UTF8 source (latin-1, cp1252) and text=True would raise # UnicodeDecodeError outside the except clause. diff_files = [] + renamed = [] resolved = 0 for sha in shas: try: @@ -2051,8 +2125,18 @@ def handle_commit_review_posttooluse(input_data): debug_log(f"Commit review: {_cmd} {sha} rc={result.returncode}") continue resolved += 1 - diff_files.extend(parse_diff_into_files( - result.stdout.decode("utf-8", errors="replace"))) + diff_text = result.stdout.decode("utf-8", errors="replace") + diff_files.extend(parse_diff_into_files(diff_text)) + names = renamed_into_review(diff_text) + if names: + revs, rev = ("show", "--format=", sha), sha + if pre_amend_sha: + revs = ("diff", pre_amend_sha, sha) + elif sha != shas[0] and _is_ancestor(repo_root, sha, shas[0]): + # A later commit of the same call can have changed the file + # again: show it as the last one left it. + revs, rev = ("diff", f"{sha}^", shas[0]), shas[0] + renamed += [(name, revs, rev) for name in names] # Dedup by path. The widened reflog scan can return >1 SHA (e.g. # `git commit && git commit --amend` within 120s); a path that appears in @@ -2072,6 +2156,8 @@ def handle_commit_review_posttooluse(input_data): "shas_found": len(shas)}) sys.exit(0) + diff_files, _ = _with_renamed_in(repo_root, diff_files, renamed, MAX_DIFF_FILES) + # Empty amend delta = message-only amend (or whitespace-only that the # diff already collapses). No code to review; skip cleanly. skip_reason=35. # Gated on resolved > 0 so subprocess failures (caught with `continue` @@ -2572,7 +2658,16 @@ def handle_push_sweep_posttooluse(input_data): diff_files = parse_diff_into_files(diff_text) for _path, _hunks in diff_files: _resolved[_path] = _resolved[_path] + "\n" + _hunks if _path in _resolved else _hunks - diff_files = list(_resolved.items()) + diff_files, _unread = _with_renamed_in( + repo_root, list(_resolved.items()), + [(name, ("diff", base, head or "HEAD"), head or "HEAD") + for name in renamed_into_review(diff_text)], + MAX_PUSH_SWEEP_FILES) + if not diff_files and _unread: + # As for a failed diff above: there was something to review. + emit_metrics({**_base, "pushed": len(push_range), + "unreviewed": len(tail), "skip_reason": 45}) + sys.exit(0) if not diff_files: emit_metrics({**_base, "pushed": len(push_range), "unreviewed": len(tail), "skip_reason": 30}) diff --git a/plugins/security-guidance/tests/test_renamed_into_review.py b/plugins/security-guidance/tests/test_renamed_into_review.py new file mode 100644 index 00000000..236b5fdc --- /dev/null +++ b/plugins/security-guidance/tests/test_renamed_into_review.py @@ -0,0 +1,391 @@ +"""A file renamed from a name the commit and push reviews leave out to one +they read is reviewed whole; every other rename is reviewed as before.""" +import json +import os +import sys + +import pytest + +from conftest import ( + GIT_ENV, bash_payload, commit_file, git, make_repo, metrics_of, run_hook, +) + +import gitutil +import security_reminder_hook as hook +from diffstate import _load_reviewed_shas + +BODY = "import os\n" + "".join(f"value_{i} = {i}\n" for i in range(30)) + "os.system(input())\n" +MARK = "os.system(input())" +SECRET = "".join(f"KEY_{i}=SECRET_VALUE_{i}\n" for i in range(30)) + + +@pytest.fixture(autouse=True) +def git_env(monkeypatch): + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + + +def _sent(stub_api): + return "\n".join(json.dumps(b) for b, c in zip(stub_api.bodies, stub_api.calls) + if c.endswith("/v1/messages")) + + +def _move(repo, old, new): + (repo / new).parent.mkdir(parents=True, exist_ok=True) + git(repo, "mv", old, new) + + +def _commit(repo, env, command="git commit -m change", args=("-m", "change")): + git(repo, "add", "-A") + out = git(repo, "commit", *args) + return metrics_of(run_hook(bash_payload(repo, command, stdout=out), env)[1]) + + +def _push_repo(tmp_path, files): + repo = make_repo(tmp_path / "repo", files) + remote = tmp_path / "remote.git" + git(tmp_path, "init", "-q", "--bare", str(remote)) + git(repo, "remote", "add", "origin", str(remote)) + git(repo, "push", "-q", "-u", "origin", "main") + return repo, remote + + +def _push(repo, remote, env): + old = git(repo, "rev-parse", "--short", "@{u}").strip() + git(repo, "push", "-q") + new = git(repo, "rev-parse", "--short", "HEAD").strip() + out = f"To {remote}\n {old}..{new} main -> main\n" + return metrics_of(run_hook(bash_payload(repo, "git push", out), env)[1]) + + +@pytest.mark.parametrize("old,new", [ + ("notes.txt", "payload.py"), + ("docs/setup.md", "bin/setup.sh"), + ("docs/image.txt", "Dockerfile"), + ("notes.txt", "a b/pay load.py"), + ("notes.txt", "café.py"), +]) +def test_commit_review_reads_the_renamed_file(tmp_path, hook_env, stub_api, old, new): + repo = make_repo(tmp_path / "repo", {old: BODY, "app.py": "x = 1\n"}) + _move(repo, old, new) + m = _commit(repo, hook_env) + assert m.get("skip_reason") is None and m["files_reviewed"] == 1, m + assert m["renamed_in"] == 1 + assert MARK in _sent(stub_api) + + +def test_push_review_reads_the_renamed_file(tmp_path, hook_env, stub_api): + repo, remote = _push_repo(tmp_path, {"notes.txt": BODY}) + _move(repo, "notes.txt", "payload.py") + git(repo, "commit", "-qm", "rename") + m = _push(repo, remote, hook_env) + assert m.get("skip_reason") is None and m["files_reviewed"] == 1, m + assert MARK in _sent(stub_api) + + +def test_edit_in_the_rename_shows_the_whole_file_once(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"notes.txt": BODY}) + _move(repo, "notes.txt", "payload.py") + text = (repo / "payload.py").read_text().replace("value_29 = 29", "value_29 = EDITED") + (repo / "payload.py").write_text(text) + m = _commit(repo, hook_env) + assert m["renamed_in"] == 1 and m["files_reviewed"] == 1, m + # Added, not context: the reviewer is told to leave context lines alone. + assert "+" + MARK in _sent(stub_api) and "+value_29 = EDITED" in _sent(stub_api) + assert "\\n " + MARK not in _sent(stub_api) + # What the edit removed is still there to see. + assert "-value_29 = 29" in _sent(stub_api) + + +def test_edit_hunk_stays_where_the_whole_file_does_not_fit(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo", {"notes.txt": BODY, "app.py": "x = 1\n"}) + _move(repo, "notes.txt", "payload.py") + git(repo, "commit", "-qm", "c") + renamed = [("payload.py", ("show", "--format=", "HEAD"), "HEAD")] + edits = [("payload.py", "@@ -1 +1 @@\n-x\n+y"), ("app.py", "@@ -1 +1 @@\n-x\n+y")] + files, failed = hook._with_renamed_in(str(repo), edits, renamed, 30) + assert [n for n, _ in files] == ["payload.py", "app.py"] and not failed + assert MARK in files[0][1] and files[1] == edits[1] + for name, limit in (("DIFF_TOTAL_BYTES", 300), ("DIFF_PER_FILE_BYTES", 300)): + with monkeypatch.context() as m: + m.setattr(hook, name, limit) + assert hook._with_renamed_in(str(repo), edits, renamed, 30)[0] == edits + monkeypatch.setattr(hook, "RENAMED_IN_BYTES", 300) + for before in (edits, edits[1:]): + assert hook._with_renamed_in(str(repo), before, renamed, 30)[0] == before + + +def test_merge_hunks_are_left_alone(tmp_path): + repo = make_repo(tmp_path / "repo", {"notes.txt": BODY}) + _move(repo, "notes.txt", "payload.py") + git(repo, "commit", "-qm", "c") + files = [("payload.py", "@@@ -1,1 -1,1 +1,1 @@@\n- x\n -y\n++z")] + renamed = [("payload.py", ("show", "--format=", "HEAD"), "HEAD")] + assert hook._with_renamed_in(str(repo), files, renamed, 30) == (files, False) + + +def test_rename_added_by_an_amend(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"notes.txt": BODY, "app.py": "x = 1\n"}) + commit_file(repo, "app.py", "x = 2\n") + _move(repo, "notes.txt", "payload.py") + m = _commit(repo, hook_env, "git commit --amend --no-edit", ("--amend", "--no-edit")) + assert m.get("amend_delta_review") is True and m["files_reviewed"] == 1, m + assert MARK in _sent(stub_api) + + +@pytest.mark.parametrize("old,new", [ + ("a.py", "pkg/b.py"), ("a.py", "notes.txt"), ("notes.txt", "other.txt"), + ("a.py", "vendor/a.py"), ("vendor/a.py", "a.py"), ("server.pem", "server"), + ("prod.env", "prod.sh"), (".htpasswd", "htpasswd"), ("dump.csv", "dump.sql"), + ("credentials.txt", "credentials.sh"), ("deploy_rsa.txt", "deploy.sh"), + ("passwords.md", "list.py"), ("notes.txt", "notes"), ("data.txt", "data.json"), ("notes.txt", "vendor/a.py"), +]) +def test_other_renames_are_not_sent(tmp_path, hook_env, stub_api, old, new): + repo = make_repo(tmp_path / "repo", {old: BODY, "app.py": "x = 1\n"}) + _move(repo, old, new) + m = _commit(repo, hook_env) + assert m["skip_reason"] == 30 and "renamed_in" not in m + assert _sent(stub_api) == "" + + +def test_rename_away_from_a_secret_shaped_name_stays_out(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"deploy_rsa": SECRET}) + _move(repo, "deploy_rsa", "settings.py") + assert _commit(repo, hook_env)["skip_reason"] == 30 + assert _sent(stub_api) == "" + + +@pytest.mark.parametrize("secret_goes", ["deleted", "renamed"]) +def test_not_sent_whole_when_a_secret_shaped_file_goes_too( + tmp_path, hook_env, stub_api, secret_goes): + # Same content under both names: git may pair either with the new file. + repo = make_repo(tmp_path / "repo", { + ".env": SECRET, "notes.txt": SECRET, "app.py": "x = 1\n"}) + _move(repo, "notes.txt", "settings.py") + if secret_goes == "deleted": + git(repo, "rm", "-q", ".env") + else: + _move(repo, ".env", "old_env.txt") + (repo / "app.py").write_text("x = input()\n") + m = _commit(repo, hook_env) + assert m["files_reviewed"] == 1 and "renamed_in" not in m, m + assert "SECRET_VALUE" not in _sent(stub_api) + + +@pytest.mark.parametrize("amend", [False, True]) +def test_secret_shaped_file_renamed_in_two_steps_stays_out(tmp_path, hook_env, stub_api, amend): + repo = make_repo(tmp_path / "repo", {".env": SECRET}) + _move(repo, ".env", "settings.txt") + git(repo, "commit", "-qm", "one") + _move(repo, "settings.txt", "settings.py") + extra = ["--amend", "--no-edit"] if amend else ["-m", "two"] + m = _commit(repo, hook_env, "git commit " + " ".join(extra), extra) + assert "SECRET_VALUE" not in _sent(stub_api) and "renamed_in" not in m, m + assert m["skip_reason"] == (35 if amend and m.get("amend_delta_review") else 30), m + + +def test_secret_shaped_file_renamed_after_edits_stays_out(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"deploy_rsa": SECRET}) + _move(repo, "deploy_rsa", "a.txt") + with open(repo / "a.txt", "a") as f: + f.write("MORE=1\n") + git(repo, "commit", "-qam", "one") + commit_file(repo, "other.py", "x = 1\n") + _move(repo, "a.txt", "settings.py") + m = _commit(repo, hook_env) + assert "SECRET_VALUE" not in _sent(stub_api), m + + +@pytest.mark.parametrize("how", [ + "added lately", "in a merge", "in a merge, combined diffs", "on a side branch"]) +def test_secret_shaped_origin_is_followed(tmp_path, hook_env, stub_api, how): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + if how.endswith("combined diffs"): + git(repo, "config", "log.diffMerges", "combined") + if how == "on a side branch": + commit_file(repo, "app.py", "x = 2\n") + git(repo, "switch", "-qc", "side", "HEAD~1") + commit_file(repo, ".env", SECRET) + if how.startswith("in a merge"): + git(repo, "switch", "-qc", "side") + commit_file(repo, "side.py", "y = 1\n") + git(repo, "switch", "-q", "main") + git(repo, "merge", "-q", "--no-ff", "--no-commit", "side") + _move(repo, ".env", "settings.txt") + git(repo, "commit", "-qm", "one") + if how == "on a side branch": + git(repo, "switch", "-q", "main") + git(repo, "merge", "-q", "--no-ff", "--no-edit", "side") + for i in range(5): + commit_file(repo, f"m{i}.py", "z = 1\n") + _move(repo, "settings.txt", "settings.py") + m = _commit(repo, hook_env) + assert m["skip_reason"] == 30 and "SECRET_VALUE" not in _sent(stub_api), m + + +def test_unknown_origin_stays_out(tmp_path): + repo = make_repo(tmp_path / "repo", {"notes.txt": BODY}) + _move(repo, "notes.txt", "payload.py") + git(repo, "commit", "-qm", "c") + show = ("show", "--format=", "HEAD") + assert hook._with_renamed_in(str(repo), [], [("payload.py", show, "nope")], 30) == ([], True) + assert hook._with_renamed_in(str(repo), [], [("payload.py", show, "HEAD")], 30)[0] + assert gitutil.came_from_secret(str(repo), "HEAD", ["payload.py"], 10) == set() + assert gitutil.came_from_secret(str(repo), "nope", ["payload.py"], 10) is None + + +def _two_quiet_commits(repo, env, second): + _move(repo, "notes.txt", "payload.py") + git(repo, "commit", "-qm", "one") + second() + git(repo, "add", "-A") + git(repo, "commit", "-qm", "two") + command = "git commit -qm one && git commit -qam two" + return metrics_of(run_hook(bash_payload(repo, command), env)[1]) + + +def test_file_is_shown_as_the_last_of_the_commits_left_it(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"notes.txt": BODY}) + m = _two_quiet_commits(repo, hook_env, lambda: (repo / "payload.py").write_text( + BODY.replace(MARK, "print('fixed')"))) + assert m["reflog_shas_n"] > 1 and m["files_reviewed"] == 1 and m["renamed_in"] == 1, m + assert "+value_5 = 5" in _sent(stub_api) and "+print('fixed')" in _sent(stub_api) + assert "+" + MARK not in _sent(stub_api) + + +def _many(n): + return {f"d/m{i:03}.txt": f"import os\nvalue = {i}\nkey_{i} = 'k{i}'\nname_{i} = {i}\n" + for i in range(n)} + + +@pytest.mark.parametrize("edits,renames,renamed_in", [ + (28, 20, 2), (30, 5, None), (3, 12, hook.MAX_RENAMED_IN), (0, 40, hook.MAX_RENAMED_IN)]) +def test_renamed_files_take_only_free_places( + tmp_path, hook_env, stub_api, edits, renames, renamed_in): + edited = {f"e{i:02}.py": "x = 1\n" for i in range(edits)} + repo = make_repo(tmp_path / "repo", {**edited, **_many(renames)}) + for name in edited: + (repo / name).write_text("x = 2\n") + for name in _many(renames): + _move(repo, name, name[:-4] + ".py") + m = _commit(repo, hook_env) + assert m["files_reviewed"] == edits + (renamed_in or 0), m + assert m.get("renamed_in") == renamed_in and "diff_files_dropped" not in m + assert all(n in _sent(stub_api) for n in edited) + + +def test_renames_do_not_count_towards_the_skip_for_huge_diffs(tmp_path, monkeypatch): + many = [(f"e{i}.py", "@@ -1 +1 @@\n-x\n+y") for i in range(31)] + monkeypatch.setattr(hook, "git_diff_unpaired", None) + assert hook._with_renamed_in("/r", many, [("n.py", ("show", "x"), "x")], 30) == (many, False) + + +def test_a_directory_replaced_by_the_file_adds_one_file(tmp_path, hook_env, stub_api): + under = {f"makefile/auth_handler{i:02}.py": f"import os\nx = {i}\n" for i in range(20)} + edits = {f"e{i:02}.py": "x = 1\n" for i in range(9)} + repo = make_repo(tmp_path / "repo", {"notes.txt": BODY, **under, **edits}) + git(repo, "rm", "-rq", "makefile") + _move(repo, "notes.txt", "makefile") + for name in edits: + (repo / name).write_text("x = 2\n") + m = _commit(repo, hook_env) + assert m["renamed_in"] == 1 and m["files_reviewed"] == 30, m + assert "diff_files_dropped" not in m + + +def test_push_with_an_unreadable_file_leaves_the_commits_unrecorded(tmp_path, hook_env, stub_api): + repo, remote = _push_repo(tmp_path, {"notes.txt": BODY}) + blob = git(repo, "rev-parse", "HEAD:notes.txt").strip() + _move(repo, "notes.txt", "payload.py") + git(repo, "commit", "-qm", "rename") + git(repo, "push", "-q") + # git shows a rename of unchanged content without reading that content. + obj = repo / ".git" / "objects" / blob[:2] / blob[2:] + os.chmod(obj, 0o644) + obj.unlink() + out = f"To {remote}\n {git(repo, 'rev-parse', '--short', 'HEAD~1').strip()}.."\ + f"{git(repo, 'rev-parse', '--short', 'HEAD').strip()} main -> main\n" + m = metrics_of(run_hook(bash_payload(repo, "git push", out), hook_env)[1]) + assert m["skip_reason"] == 45, m + assert not _load_reviewed_shas(str(repo)) + assert _sent(stub_api) == "" + + +@pytest.mark.skipif(sys.platform in ("win32", "darwin"), reason="file names are Unicode there") +def test_push_of_a_name_that_is_not_utf8_is_not_recorded(tmp_path, hook_env, stub_api): + repo, remote = _push_repo(tmp_path, {"notes.txt": BODY}) + os.rename(repo / "notes.txt", os.fsencode(repo) + b"/caf\xe9.py") + git(repo, "add", "-A") + git(repo, "commit", "-qm", "rename") + assert _push(repo, remote, hook_env)["skip_reason"] == 45 + assert not _load_reviewed_shas(str(repo)) + + +@pytest.mark.parametrize("name", ["GIT_ICASE_PATHSPECS", "GIT_GLOB_PATHSPECS", + "GIT_NOGLOB_PATHSPECS", "GIT_LITERAL_PATHSPECS"]) +def test_pathspec_setting_in_the_environment(tmp_path, hook_env, stub_api, name): + repo = make_repo(tmp_path / "repo", {"notes.txt": BODY}) + _move(repo, "notes.txt", "payload.py") + m = _commit(repo, {**hook_env, name: "1"}) + assert m.get("renamed_in") == 1, m + + +def test_new_name_is_a_file_name_not_a_pattern(tmp_path): + repo = make_repo(tmp_path / "repo", {"notes.txt": BODY, "a.py": "x = 1\n"}) + _move(repo, "notes.txt", "[ab].py") + (repo / "a.py").write_text("x = 2\n") + git(repo, "add", "-A") + git(repo, "commit", "-qm", "c") + files = gitutil.git_diff_unpaired( + str(repo), ("show", "--format=", "HEAD"), ["[ab].py"], 10) + assert list(files) == ["[ab].py"] + + +def test_names_in_a_rename_with_an_edit_come_from_the_rename_lines(): + hunk = ["--- a/x", "+++ b/y", "@@ -1 +1 @@", "-a", "+b"] + text = (_section("a/cfg b/.env b/cfg b/app.py", "rename from cfg b/.env", + "rename to cfg b/app.py", *hunk) + + _section("a/a b/x.py b/a b/y.py", "rename from a b/x.py", "rename to a b/y.py", *hunk)) + assert [n for n, _ in gitutil.parse_diff_into_files(text)] == ["a b/y.py"] + assert gitutil.extract_file_paths_from_diff(text) == ["a b/y.py"] + + +def test_name_with_the_header_separator_in_it(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"notes.txt": BODY, "cfg b/app.py": "x = 1\n"}) + _move(repo, "notes.txt", "pkg b/tool.py") + (repo / "cfg b/app.py").write_text("x = input()\n") + m = _commit(repo, hook_env) + assert m["files_reviewed"] == 2 and m["renamed_in"] == 1, m + assert "pkg b/tool.py" in _sent(stub_api) and "cfg b/app.py" in _sent(stub_api) + assert "tool.py b/pkg" not in _sent(stub_api) and "app.py b/cfg" not in _sent(stub_api) + + +def _section(header, *lines): + return "\n".join([f"diff --git {header}", *lines]) + "\n" + + +@pytest.mark.parametrize("header,old,new,expect", [ + ("a/n.txt b/n.py", "n.txt", "n.py", ["n.py"]), + ('"a/we\\"ird.txt" "b/we\\"ird.py"', '"we\\"ird.txt"', '"we\\"ird.py"', ['we"ird.py']), + ("a/x b/y.txt b/x b/y.py", "x b/y.txt", "x b/y.py", ["x b/y.py"]), + ("a/x.py b/y.py b/x.py b/z.py", "x.py b/y.py", "x.py b/z.py", []), + ("a/.env b/n.py", ".env", "n.py", []), + ("a/n.txt b/deploy_rsa", "n.txt", "deploy_rsa", []), +]) +@pytest.mark.parametrize("verb", ["rename", "copy"]) +def test_names_come_from_the_rename_lines(verb, header, old, new, expect): + text = _section(header, "similarity index 100%", f"{verb} from {old}", f"{verb} to {new}") + assert gitutil.renamed_into_review(text) == expect + + +def test_lines_of_content_are_not_rename_lines(): + text = _section("a/a.py b/a.py", "--- a/a.py", "+++ b/a.py", "@@ -1 +1,3 @@", + " rename from n.txt", "rename from n.txt", "rename to n.py") + assert gitutil.renamed_into_review(text) == [] + + +@pytest.mark.parametrize("gone", [".env", "cfg b/.env", "deploy_rsa"]) +def test_nothing_is_listed_when_a_secret_shaped_file_goes_too(gone): + text = (_section(f"a/{gone} b/{gone}", "deleted file mode 100644", "@@ -1 +0,0 @@", "-x") + + _section("a/n.txt b/n.py", "similarity index 100%", "rename from n.txt", "rename to n.py")) + assert gitutil.renamed_into_review(text) == [] |
