diff options
| author | eoger-ant <eoger@anthropic.com> | 2026-11-17 17:28:25 -0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-17 17:28:25 -0800 |
| commit | 668a0c6542d1da594f2d49ddab382198abbddbb2 (patch) | |
| tree | 204c27f811ef92352698fa99e3b7cad6e84488c8 /plugins | |
| parent | d761ce2e989c211d27edffa303e5c2a3aae8f976 (diff) | |
| parent | c64782a7157f8cbde0236b4f80ef4d77e619efd8 (diff) | |
Merge branch 'main' into eoger/discord-list-emojiseoger/discord-list-emojis
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 91 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 203 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 33 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 385 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/conftest.py | 9 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_chained_commit_push.py | 405 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_renamed_into_review.py | 466 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_review_result_keys.py | 132 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_reviewer_tools.py | 32 |
9 files changed, 1645 insertions, 111 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index cd3205e6..a94363f4 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -1228,6 +1228,83 @@ def _mark_inflight(repo_root, shas): pass +_holds = {} + + +def hold_until_exit(path): + """Lock the file at `path` until this process ends or calls + `release_hold`, so that others can see it `is_held`. Best-effort; never + raises.""" + import time as _time + try: + fd = _open_own_file(path, os.O_RDWR) + except (OSError, TypeError): + return + try: + for _ in range(10): # another process may be looking at this moment + if _flock_nb(fd, exclusive=True): + _holds[path] = fd # left open: the lock goes when the process does + return + _time.sleep(0.01) + except OSError: + pass + os.close(fd) + + +def release_hold(path): + """Give up the lock `hold_until_exit` took. Never raises.""" + fd = _holds.pop(path, None) + if fd is not None: + _drop_marker(path, fd, unlink=False) + + +def is_held(path): + """Whether a live process holds the file at `path`; None when that cannot + be told (no such file, or no locks here).""" + try: + fd = _open_own_file(path, os.O_RDONLY) + except (OSError, TypeError): + return None + try: + # Shared, so two processes looking at once do not look like a holder + # to each other. + return not _flock_nb(fd, exclusive=False) + except OSError: + return None + finally: + os.close(fd) + + +def becomes_held(path, max_wait_s, poll_s=0.1): + """Whether a live process holds the file at `path` or does so soon.""" + import time as _time + end = _time.monotonic() + max_wait_s + while not is_held(path): + if _time.monotonic() >= end: + return False + _time.sleep(poll_s) + return True + + +def wait_for_holder(path, max_wait_s, poll_s=0.5): + """Wait for the process holding the file at `path` to end. Returns + (ended, waited_s); `ended` is False when it still runs after `max_wait_s`, + or when that cannot be told.""" + import time as _time + start = _time.monotonic() + waited, looks_free = False, 0 + while True: + held = is_held(path) + # Free twice in a row: a holder creates the file a moment before it + # locks it. + looks_free = 0 if held else looks_free + 1 + spent = _time.monotonic() - start + if held is None or looks_free == 2 or (held and spent >= max_wait_s): + return looks_free == 2 and held is False, spent if waited else 0.0 + waited = waited or held + _time.sleep(poll_s) + + def _load_inflight_shas(repo_root, shas, _gd=None): """Which of `shas` another live review in this clone holds right now.""" out = set() @@ -1238,18 +1315,8 @@ def _load_inflight_shas(repo_root, shas, _gd=None): p = os.path.join(gd, _INFLIGHT_PREFIX + sha) if not _is_full_sha(sha) or p in _inflight_held: continue - try: - fd = _open_own_file(p, os.O_RDONLY) - except OSError: - continue - try: - # Shared, so two reviews asking at once do not look like a - # holder to each other. - if not _flock_nb(fd, exclusive=False): - out.add(sha) - except OSError: - pass - os.close(fd) + if is_held(p): + out.add(sha) return out diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 184dba6d..f78739f3 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,129 @@ 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 + + +# Text that holds secrets by its name or its folder's (`api_keys.txt`, +# `keys/prod.md`, `.ssh/notes.txt`). It stays unread when it becomes code; so +# does a document that only has such a word in its name (`hotkeys.md`). +_SECRET_TEXT_RE = re.compile( + r"(?:secrets?|credentials?|creds?|passwords?|passwd|keys?|tokens?|vault" + r"|/\.(?:ssh|aws|gnupg|kube))/" + r"|(?:secret|credential|passw|passphrase|api.?key|recovery.?code|service.?account)[^/]*$" + r"|(?:keys?|tokens?|creds?|pass|pwd|env|logins|pem|ed25519|netrc|npmrc)" + r"(?![a-z])[^/]*$") + + +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_secret_text(file_path): + """Whether a name says the file holds secrets, if it is not a code name.""" + path = "/" + file_path.replace("\\", "/").lower() + return (_is_secret_shaped(file_path) + or os.path.splitext(path)[1] not in _CODE_EXTENSIONS + and os.path.basename(path) not in SOURCE_CODE_BASENAMES + and (_is_secret_stem(path) or bool(_SECRET_TEXT_RE.search(path)))) + + +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_text(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's 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_text, 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/llm.py b/plugins/security-guidance/hooks/llm.py index 8084665e..7b5e02fd 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -1997,6 +1997,35 @@ def _agentic_commit_review_enabled() -> bool: # precedents and an adversarial refute taxonomy to drop low-signal findings. _AGENTIC_INVESTIGATE_SYSTEM = review_api.AGENTIC_INVESTIGATE_SYSTEM + +# The investigate stages return their findings through the StructuredOutput +# tool and nothing reads what they write beside it. Told so here, not in +# review_api: a caller of that module may take its answer from the text. +_REVIEWER_OUTPUT_RULE = ( + "\n\nOUTPUT: only the `findings` you return are read, not text you write. " + "Write no prose before, between or after tool calls, and no verdicts " + "for files you clear: think them through instead. Ask for the files " + "and searches you can already name in one message, within the budget " + "above. `explanation` must still name the source, the sink and the path " + "between them. When you are done, return the findings at once." +) + + +def _investigate_system() -> str: + """The investigate stages' system prompt. Text between tool calls is where + a model reasons when thinking is off or the user picked the model, so the + output rule is left out there.""" + thinking_off = (os.environ.get("MAX_THINKING_TOKENS", "").strip() == "0" + or any(os.environ.get(v, "").strip().lower() in ("1", "true", "yes", "on") + for v in ("CLAUDE_CODE_DISABLE_THINKING", + "CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING"))) + picked = any(os.environ.get(v, "").strip() + for v in ("SG_AGENTIC_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL")) + if thinking_off or picked: + return _AGENTIC_INVESTIGATE_SYSTEM + return _AGENTIC_INVESTIGATE_SYSTEM + _REVIEWER_OUTPUT_RULE + + _FINDINGS_SCHEMA = review_api.FINDINGS_SCHEMA _SURVIVED_SCHEMA = review_api.SURVIVED_SCHEMA @@ -2528,7 +2557,7 @@ def _agentic_review( t0 = _t.time() try: inv, inv_turns, inv_subtype = _run( - _AGENTIC_INVESTIGATE_SYSTEM, user_prompt, schema=_FINDINGS_SCHEMA + _investigate_system(), user_prompt, schema=_FINDINGS_SCHEMA ) if os.environ.get("SG_AGENTIC_DEBUG_DIR"): _dd = os.environ["SG_AGENTIC_DEBUG_DIR"] @@ -2594,7 +2623,7 @@ def _agentic_review( ) try: inv2, _, _ = _run( - _AGENTIC_INVESTIGATE_SYSTEM, iter2_prompt, schema=_FINDINGS_SCHEMA + _investigate_system(), iter2_prompt, schema=_FINDINGS_SCHEMA ) if inv2: seen = {(c.get("filePath"), c.get("category")) for c in candidates} diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 160a633a..0d53b871 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,10 +261,19 @@ _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 +# A review row's result, kind and time. emit_metrics puts them right after its +# own keys (pv, launcher, usage, net_err), so the key cap cuts descriptive keys +# before any of these. Keep it short: a failed row can carry 12 keys ahead of +# them, and commit_review / push_sweep tell the rows apart under the old cap +# of 10. +_LEAD_METRIC_KEYS = ("review_failed", "api_error", "vulns_found", + "commit_review", "push_sweep", "review_ms", + "files_reviewed", "agentic", "deduped", + "critical_count", "high_count") # How long a Stop row waits for its commit count. _TURN_COMMITS_WAIT_S = 2.0 # Set by the Stop hook: queues the commit count for the row being emitted. @@ -374,7 +384,8 @@ def emit_metrics( the same reason but stale: once `rate_count` was added to every commit-review emit, the with-vulns dict hit 10 keys, `pv` was skipped, and findings metrics landed without a plugin version attached, breaking - per-version breakdowns. + per-version breakdowns. `_LEAD_METRIC_KEYS` come next on a review row, + wherever the caller put them. `rewake_summary` (asyncRewake only): per-run override of the static rewakeSummary in hooks.json, shown to the user in the terminal as the @@ -431,8 +442,15 @@ def emit_metrics( net_err = _net_error_metric() if net_err: head["net_err"] = net_err - if head: - metrics = {**head, **metrics} + # Skip rows are left as they are: theirs is the skip reason. + lead = {} if metrics.get("skipped") else { + k: metrics[k] for k in _LEAD_METRIC_KEYS if k in metrics} + metrics = {**head, **lead, **metrics} + if not metrics.get("skipped"): + # Always true on a row that is not a skip, so cut before the rest. + for k in ("commit_review_on", "push_sweep_on"): + if k in metrics: + metrics[k] = metrics.pop(k) # Diagnostic keys go last, so they are the first dropped when a row is # over CC's key cap and never displace an existing key. tail = {} @@ -1224,6 +1242,35 @@ def _unmatched_bash_sampled(input_data): return int.from_bytes(digest[:4], "big") % _UNMATCHED_BASH_SAMPLE == 0 +_bash_hook_git_dir = {} + + +def _bash_hook_sentinel(input_data, route="once"): + """The file one spawn of this Bash call's hook creates to claim `route`, + or None when there is nothing to tell the spawns apart by.""" + tuid = input_data.get("tool_use_id") + cwd = input_data.get("cwd") + if not tuid or not cwd: + return None + command = (input_data.get("tool_input") or {}).get("command", "") or "" + call = (tuid, cwd, command) + if call not in _bash_hook_git_dir: + _bash_hook_git_dir[call] = _git_dir( + _git_toplevel(cwd) + or toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS | PUSH_SUBCOMMANDS) + or cwd + ) + gd = _bash_hook_git_dir[call] + if not gd: + return None + # Sanitize tuid into a filesystem-safe basename — defensive, the value is + # CC-generated (toolu_<b64ish>), but it ends up in a path. + safe = re.sub(r"[^A-Za-z0-9_-]", "_", tuid)[:80] + # A second route ("push") lets the other spawn of a commit-and-push run + # its own review, once. + return os.path.join(gd, f"sg-hook-once-{safe}" + ("" if route == "once" else f"-{route}")) + + def _claim_bash_hook_once(input_data, route="once"): """De-dupe across hooks.json `if` matchers firing for the same Bash call. @@ -1239,20 +1286,12 @@ def _claim_bash_hook_once(input_data, route="once"): Sentinel is per-clone (`.git/sg-hook-once-<tool_use_id>`), not /tmp, so concurrent CC sessions in *different* repos don't collide. Stale - sentinels (>5min) are GC'd opportunistically. + sentinels (older than a hook can run) are GC'd opportunistically. """ - tuid = input_data.get("tool_use_id") - cwd = input_data.get("cwd") - if not tuid or not cwd: - return True - command = (input_data.get("tool_input") or {}).get("command", "") or "" - gd = _git_dir( - _git_toplevel(cwd) - or toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS | PUSH_SUBCOMMANDS) - or cwd - ) - if not gd: + sentinel = _bash_hook_sentinel(input_data, route) + if not sentinel: return True + gd = os.path.dirname(sentinel) # GC: best-effort sweep of stale sentinels so they don't accumulate. import time as _time now = _time.time() @@ -1261,21 +1300,20 @@ def _claim_bash_hook_once(input_data, route="once"): if name.startswith("sg-hook-once-"): p = os.path.join(gd, name) try: - if now - os.path.getmtime(p) > 300: + if now - os.path.getmtime(p) > 900: os.unlink(p) except OSError: pass except OSError: pass - # Sanitize tuid into a filesystem-safe basename — defensive, the value is - # CC-generated (toolu_<b64ish>), but it ends up in a path. - safe = re.sub(r"[^A-Za-z0-9_-]", "_", tuid)[:80] - # A second route ("push") lets the other spawn of a commit-and-push run - # its own review, once. - sentinel = os.path.join(gd, f"sg-hook-once-{safe}" + ("" if route == "once" else f"-{route}")) try: fd = os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY) os.close(fd) + command = (input_data.get("tool_input") or {}).get("command", "") or "" + if (route == "once" and _GIT_COMMIT_RE.search(command) + and _GIT_PUSH_RE.search(command)): + # The push spawn of this command waits for this one to end. + diffstate.hold_until_exit(sentinel) return True except FileExistsError: return False @@ -1369,6 +1407,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. @@ -1491,6 +1601,9 @@ _RACE_MAX_WAIT_S = 480 # Claude Code kills the hook. The inner CLI exits with the hook. The same limit # holds for a commit or push review's single-shot review outside a race. _RACE_END_S = 570 +# Seconds after which a failed commit review stops waiting for the push review +# of its own command, which may run to the limit above on a later clock. +_HOOK_LAST_WAIT_S = 580 # api_error for a race that hit that deadline with no verdict. _RACE_TIMED_OUT = -2 @@ -1721,12 +1834,37 @@ def _left_out_files_notice(session_id, repo_root, untracked, diff_output): f"in {DEBUG_LOG_FILE}.") -def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): +def _push_review_takes_over(input_data): + """True when the push spawn of this commit-and-push call waits to review + what this commit review has no verdict on.""" + command = input_data["tool_input"]["command"] + sentinel = _bash_hook_sentinel(input_data, "push") + return bool( + PUSH_SWEEP_ENABLED and sentinel and _GIT_PUSH_RE.search(command) + # It may still be on its way to the wait when a review fails at once. + and diffstate.becomes_held(sentinel, 3)) + + +def _push_review_settled_it(input_data): + """Let the push review that waits for this commit review go on, and wait + for its end. False when it ended without a verdict and told nobody (a cap, + no network, killed): that is for the commit review to report.""" + debug_log("Commit review: got no verdict; waiting for the push review of the same command") + diffstate._release_inflight() + diffstate.release_hold(_bash_hook_sentinel(input_data)) + diffstate.wait_for_holder(_bash_hook_sentinel(input_data, "push"), + max(0.0, _HOOK_LAST_WAIT_S - _hook_spent_s())) + return os.path.exists(_bash_hook_sentinel(input_data, "settled")) + + +def _exit_review_failed(kind, session_id, metrics, status, pushed="no", told=None): """End a commit ("Commit") or push ("Push") review that got no verdict. Never reports the code as clean. Tells Claude once per session for each kind of review and failure; repeats are only logged. `pushed` ("yes", - "maybe" or "no"): whether the commit's own command also pushed it. Exits. + "maybe" or "no"): whether the commit's own command also pushed it; + "taken_over" when that command's push review dealt with it. `told` is + called when Claude is told. Exits. """ failure, reason, cause = _review_failure_reason(status) debug_log(f"{kind} review: got no verdict ({reason}); not marked reviewed") @@ -1736,7 +1874,7 @@ def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): # A commit its own command pushed gets its own notice: no later push # re-checks it. told_key = f"review_failed:{kind}:{failure}" + (":pushed" if pushed == "yes" else "") - if not atomic_check_and_mark_warning(session_id, told_key): + if pushed == "taken_over" or not atomic_check_and_mark_warning(session_id, told_key): emit_metrics(metrics) sys.exit(0) subject = "this push" if kind == "Push" else "this commit" @@ -1763,8 +1901,41 @@ def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): emit_metrics(metrics, rewake_summary=(f"{kind} security review did not complete: {reason}. " f"Log: {DEBUG_LOG_FILE}")) + if told: + told() sys.exit(2) +def _commit_in_output(bash_output): + """The commit that a successful `git commit` printed, or None.""" + # Require BOTH a line-anchored `[branch sha]` AND a git-only diffstat + # signal before treating the tool call as a successful commit. The old + # `any()` check false-positived on (a) pre-commit/husky/lint-staged hooks + # emitting labels like `[pre-commit abc1234]`, and on (b) chained + # `git commit || git log --stat` where `N files changed` appears in output + # even though the commit itself failed. + # + # Take only the LAST match: pre-commit/husky hooks can print bracketed + # labels like `[pre-commit abc1234]` that precede the real `[branch sha]` + # line; chained commands like `git commit && git commit` produce multiple + # real SHAs and we want the most recent. The real commit line is always + # last in git's own output — the earlier matches are either decoys or + # superseded commits. + all_shas = _COMMIT_SHA_RE.findall(bash_output) + if all_shas and any(p.search(bash_output) for p in _COMMIT_DIFFSTAT_PATTERNS): + return all_shas[-1] + return None + + +def _commit_review_candidates(bash_output, repo_root): + """(shas, stale): the commits the commit review of a Bash call that was + not interrupted takes, newest first, before it leaves out those already + reviewed or under review: the one its output names, else the fresh ones in + the reflog, with the count of entries too old. Both the commit review and + the push review of the same call choose by this.""" + named = _commit_in_output(bash_output) + return ([named], 0) if named else _git_reflog_recent_commits(repo_root) + + def handle_commit_review_posttooluse(input_data): """PostToolUse handler for Bash — reviews git commits for security issues. @@ -1801,19 +1972,10 @@ def handle_commit_review_posttooluse(input_data): bash_output = stdout + "\n" + stderr interrupted = bool(tool_response.get("interrupted")) - # Require BOTH a line-anchored `[branch sha]` AND a git-only diffstat - # signal before treating the tool call as a successful commit. The old - # `any()` check false-positived on (a) pre-commit/husky/lint-staged hooks - # emitting labels like `[pre-commit abc1234]`, and on (b) chained - # `git commit || git log --stat` where `N files changed` appears in output - # even though the commit itself failed. all_shas = _COMMIT_SHA_RE.findall(bash_output) diffstate.note_seen_commits(session_id, all_shas) - commit_succeeded = ( - not interrupted - and bool(all_shas) - and any(p.search(bash_output) for p in _COMMIT_DIFFSTAT_PATTERNS) - ) + named = None if interrupted else _commit_in_output(bash_output) + commit_succeeded = bool(named) # commit_review_on emitted on every path so telemetry can filter on # commit_review and group by commit_review_on. @@ -1854,7 +2016,7 @@ def handle_commit_review_posttooluse(input_data): repo_res = RES_HINT _base["repo_resolution"] = repo_res _root = repo_root - _fresh, _stale = _git_reflog_recent_commits(_root) + _fresh, _stale = _commit_review_candidates(bash_output, _root) diffstate.note_seen_commits(session_id, _fresh) if _fresh: # Commits an earlier call's review is still working on are that @@ -1912,8 +2074,8 @@ def handle_commit_review_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 25, **_base}) sys.exit(0) - if not repo_root and all_shas and not _reflog_shas: - repo_root = repo_containing_commit(all_shas[-1], scan_roots(cwd)) + if not repo_root and named: + repo_root = repo_containing_commit(named, scan_roots(cwd)) if repo_root: repo_res = RES_SHA_SCAN if not repo_root: @@ -1939,13 +2101,6 @@ def handle_commit_review_posttooluse(input_data): # fallback above is the narrow exception: it only fires when output gave # us nothing AND the cwd repo's own reflog confirms a `commit:` just # happened there, which rules out the cross-repo case. - # - # Take only the LAST match: pre-commit/husky hooks can print bracketed - # labels like `[pre-commit abc1234]` that precede the real `[branch sha]` - # line; chained commands like `git commit && git commit` produce multiple - # real SHAs and we want the most recent. The real commit line is always - # last in git's own output — the earlier matches are either decoys or - # superseded commits. if _reflog_shas: # Output-based detection already failed above; the reflog SHAs are the # authoritative ones. Don't re-parse bash_output here — any bracketed @@ -1956,7 +2111,7 @@ def handle_commit_review_posttooluse(input_data): # all are reviewed. shas = _reflog_shas else: - shas = [all_shas[-1]] if all_shas else [] + shas = [named] if named else [] if not shas: debug_log("Commit review: no SHA in commit output") emit_metrics({"skipped": True, "skip_reason": 33, **_base}) @@ -2023,6 +2178,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: @@ -2054,8 +2210,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 @@ -2075,6 +2241,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` @@ -2082,8 +2250,19 @@ def handle_commit_review_posttooluse(input_data): # skip_reason=28 correctly. if pre_amend_sha and not diff_files: debug_log("Commit review: --amend produced empty delta (message-only?), skipping") + # Same content under a new sha: as reviewed as the original is. With + # its review still running, see that end first. A push review of the + # new sha waits for this process meanwhile: wait less than it does, so + # that it can still review what has no verdict by then. + _new = _full_shas(repo_root, shas) + _mark_inflight(repo_root, _new) + reviewed, _waited = _reviewed_after_inflight( + repo_root, [pre_amend_sha], max(0.0, INFLIGHT_WAIT_S * 0.9 - _hook_spent_s())) + if pre_amend_sha in reviewed: + _append_reviewed_shas(repo_root, _new) emit_metrics({"skipped": True, "skip_reason": 35, **_base, - "files_reviewed": 0}) + "files_reviewed": 0, + **({"inflight_wait_s": max(1, int(round(_waited)))} if _waited else {})}) sys.exit(0) debug_log(f"Commit review: {resolved}/{len(shas)} sha(s) resolved, " @@ -2179,7 +2358,7 @@ def handle_commit_review_posttooluse(input_data): # severity filter; `survived_after_sev` is the count the user actually # sees. Include `survived_after_sev` ONLY when the filter actually # dropped candidates — otherwise it's redundant with `survived` and eats - # into CC's metric-key cap, pushing files_reviewed/review_ms out of the + # into CC's metric-key cap, pushing critical_count/high_count out of the # emitted metrics. # # CC accepts only booleans and finite numbers as metric values. @@ -2222,7 +2401,9 @@ def handle_commit_review_posttooluse(input_data): **_base, **_agentic_m, "files_reviewed": len(diff_files), "review_ms": review_ms, }, api_status, pushed=( - "yes" if _push_in_output(bash_output) + "taken_over" if _push_review_takes_over(input_data) + and _push_review_settled_it(input_data) + else "yes" if _push_in_output(bash_output) else "maybe" if _GIT_PUSH_RE.search(command) or _MAY_PUSH_VIA_GH_RE.search(command) else "no")) @@ -2328,12 +2509,17 @@ def _pushed_beyond_commit_review(repo_root, push_range, bash_output): """ covered = [] if COMMIT_REVIEW_ENABLED: - named = _COMMIT_SHA_RE.findall(bash_output) - covered = named[-1:] or _git_reflog_recent_commits(repo_root)[0] + covered = _commit_review_candidates(bash_output, repo_root)[0] rest = [s for s in push_range if not any(s.startswith(c) for c in covered)] + return _without_review(repo_root, rest) + + +def _without_review(repo_root, shas): + """True when one of `shas` is neither reviewed nor under review.""" + # In that order: a review that ends in between then counts as reviewed. + held = _load_inflight_shas(repo_root, shas) reviewed = _load_reviewed_shas(repo_root) - held = _load_inflight_shas(repo_root, rest) - return any(s not in reviewed and s not in held for s in rest) + return any(s not in reviewed and s not in held for s in shas) def handle_push_sweep_posttooluse(input_data): @@ -2504,7 +2690,9 @@ def handle_push_sweep_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 41, **_base}) sys.exit(0) - push_range = _git_rev_list_range(repo_root, prev_upstream, "HEAD") + # The tip that was pushed, checked above. HEAD itself may move meanwhile. + tip = head or "HEAD" + push_range = _git_rev_list_range(repo_root, prev_upstream, tip) if not push_range: emit_metrics({"skipped": True, "skip_reason": 42, **_base, "pushed": 0}) sys.exit(0) @@ -2514,24 +2702,55 @@ def handle_push_sweep_posttooluse(input_data): "pushed": len(push_range)}) sys.exit(0) + def _note_settled(): + # Tells the commit spawn of this call that it has nothing to report. + if (_GIT_COMMIT_RE.search(command) and any( + s.startswith(c) for s in push_range + for c in _commit_review_candidates(bash_output, repo_root)[0])): + _claim_bash_hook_once(input_data, "settled") + + _spawn_wait, _take_over = 0.0, False if _GIT_COMMIT_RE.search(command) and not _pushed_beyond_commit_review( repo_root, push_range, bash_output): - emit_metrics({"skipped": True, "skip_reason": 47, **_base, - "pushed": len(push_range)}) - sys.exit(0) + # All of it is the other spawn's to review. Once pushed, no later push + # covers it, so see that review end and take over what got no verdict. + # One that outlasts the wait, or cannot be watched, is left to it. + reviewed = _load_reviewed_shas(repo_root) + if any(s not in reviewed for s in push_range): + diffstate.hold_until_exit(_bash_hook_sentinel(input_data, "push")) + _ended, _spawn_wait = diffstate.wait_for_holder( + _bash_hook_sentinel(input_data), INFLIGHT_WAIT_S) + _take_over = _ended and _without_review(repo_root, push_range) + if _ended and not _take_over: + reviewed = _load_reviewed_shas(repo_root) + if all(s in reviewed for s in push_range): + _note_settled() + # A commit the hourly cap kept out stays out. + _skip = (47 if not _take_over + else 23 if atomic_check_rate_limit( + session_id, "CommitReview", 0, COMMIT_REVIEW_RATE_WINDOW_S + )[1] >= MAX_COMMIT_REVIEWS_PER_HOUR + else 24 if not ensure_anthropic_reachable() else 0) + if _skip: + emit_metrics({"skipped": True, "skip_reason": _skip, **_base, + "pushed": len(push_range), + **({"inflight_wait_s": max(1, int(round(_spawn_wait)))} + if _spawn_wait else {})}) + sys.exit(0) # A commit review that is still running on these commits records them # once it has a verdict. Wait for it instead of reviewing the same diff a # second time; if it ends without one, they are reviewed here. reviewed, _waited = _reviewed_after_inflight( - repo_root, push_range, INFLIGHT_WAIT_S) + repo_root, push_range, max(0.0, INFLIGHT_WAIT_S - _spawn_wait)) + _waited += _spawn_wait _wait_m = {} if _waited: _wait_m = {"inflight_wait_s": max(1, int(round(_waited)))} debug_log(f"Push sweep: waited {_waited:.0f}s for a running commit review") base, tail = _compute_push_sweep_base(prev_upstream, push_range, reviewed) prefix_advanced = len(push_range) - len(tail) - _parents = _git_range_parents(repo_root, prev_upstream, "HEAD") if base else {} + _parents = _git_range_parents(repo_root, prev_upstream, tip) if base else {} _settled = [] if any(len(p) > 1 for p in _parents.values()): base, _settled = _push_sweep_base_with_merges( @@ -2546,12 +2765,15 @@ def handle_push_sweep_posttooluse(input_data): prefix_advanced = 0 if base is None: debug_log("Push sweep: every pushed commit already reviewed") + _note_settled() emit_metrics({**_base, "pushed": len(push_range), "unreviewed": 0, "prefix_advanced": prefix_advanced, **_wait_m}) sys.exit(0) - if _waited and head and _git_rev_parse_head(repo_root) != head: - # Same guard as above: the diff and the reviewer's file reads are - # both taken at HEAD, and HEAD left the pushed tip during the wait. + _head_moved = bool(_waited and head and _git_rev_parse_head(repo_root) != head) + if _head_moved and not _take_over: + # Same guard as above: the agentic reviewer reads files at HEAD, and + # HEAD left the pushed tip during the wait. A take-over goes on without + # that reviewer, on the diff of the pushed tip. debug_log("Push sweep: HEAD moved while waiting, skipping") emit_metrics({"skipped": True, "skip_reason": 44, **_base, **_wait_m}) sys.exit(0) @@ -2559,7 +2781,7 @@ def handle_push_sweep_posttooluse(input_data): debug_log(f"Push sweep: range={len(push_range)} prefix_advanced=" f"{prefix_advanced} base={base[:12]} tail={len(tail)}") - diff_text = _git_diff_range(repo_root, base, "HEAD") + diff_text = _git_diff_range(repo_root, base, tip) if diff_text is None: # Diff failed (non-zero exit / 30s timeout / git missing). Do NOT # mark `tail` reviewed — we did not actually review it. Marking @@ -2575,12 +2797,22 @@ 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}) # Still mark tail reviewed — there's nothing to review. _append_reviewed_shas(repo_root, tail, vulns_found=0) + _note_settled() sys.exit(0) # Same prioritize-don't-bail logic as commit-review (see comment there). # push-sweep ranges are net diffs over many commits so they hit the cap @@ -2601,6 +2833,8 @@ def handle_push_sweep_posttooluse(input_data): if _dropped: _base = {**_base, "diff_files_dropped": _dropped} + if _take_over: + _base["commit_no_verdict"] = True _allowed, _rate_n = atomic_check_rate_limit( session_id, "PushSweep", MAX_COMMIT_REVIEWS_PER_HOUR, COMMIT_REVIEW_RATE_WINDOW_S) @@ -2611,7 +2845,7 @@ def handle_push_sweep_posttooluse(input_data): _mark_inflight(repo_root, tail) _diff_token, _seen_m = _diff_review_started( - repo_root, _cap_files_for_prompt(diff_files)) + repo_root, _cap_files_for_prompt(diff_files), tip=tip) _TAIL_METRICS.update(_seen_m) import time as _time @@ -2625,7 +2859,7 @@ def handle_push_sweep_posttooluse(input_data): review_start = _time.time() rel_touched = [fp for fp, _ in diff_files] - if _agentic_commit_review_enabled(): + if _agentic_commit_review_enabled() and not _head_moved: concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race( repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s(), ) @@ -2650,10 +2884,11 @@ def handle_push_sweep_posttooluse(input_data): _exit_review_failed("Push", session_id, { **_base, **_wait_m, "pushed": len(push_range), "unreviewed": len(tail), "files_reviewed": len(diff_files), "review_ms": review_ms, - }, api_status) + }, api_status, told=_note_settled) # The tail is now covered by this net-diff review. _append_reviewed_shas(repo_root, tail, vulns_found=len(vulns or [])) + _note_settled() _diff_review_done(_diff_token) new_vulns, n_deduped = _dedup_against_state( @@ -3217,7 +3452,7 @@ def handle_stop_hook(input_data): record_reviewed_diff(session_id, diff_hash) wake = _left_out_wake() # CC keeps the first 20 metric keys (10 in older versions), in insertion - # order, after the pv and usage keys emit_metrics puts first. The previous + # order, after the keys emit_metrics puts first. The previous # **sweep,**v2_metrics tail meant the 3 v2_metrics keys were always sliced # off this most-common path, so the diff-strategy diagnostics never reached # telemetry. Drop sweep here (it's PostToolUse-warning state, orthogonal to @@ -3367,8 +3602,8 @@ def main(): # # The push-matcher spawn then claims the "push" route and runs the push # sweep, which reviews only when the command pushed a commit that - # commit-review will not see: once behind the upstream, no later push - # would cover it. + # commit-review will not see or gave no verdict on: once behind the + # upstream, no later push would cover it. if tool_name == "Bash" and hook_event_name == "PostToolUse": cmd = (input_data.get("tool_input") or {}).get("command", "") or "" if not (_GIT_COMMIT_RE.search(cmd) or _GIT_PUSH_RE.search(cmd)): diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index b0df08de..3987e1de 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -96,7 +96,11 @@ class _Stub(http.server.BaseHTTPRequestHandler): self.server.calls.append(self.path) if self.server.delay: time.sleep(self.server.delay) - if self.server.status == 200: + status = self.server.status + reviews = [c for c in self.server.calls if c.endswith("/v1/messages")] + if self.path.endswith("/v1/messages") and len(reviews) <= getattr(self.server, "fail_first", 0): + status = 400 + if status == 200: vulns = list(self.server.vulns) body = json.dumps({ "id": "msg_stub", "type": "message", "role": "assistant", @@ -107,7 +111,7 @@ class _Stub(http.server.BaseHTTPRequestHandler): }).encode() else: body = b'{"type":"error","error":{"type":"invalid_request_error","message":"stub"}}' - self.send_response(self.server.status) + self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() @@ -126,6 +130,7 @@ def stub_api(): srv.bodies = [] srv.status = 200 srv.delay = 0 + srv.fail_first = 0 # the first N review requests are answered with 400 srv.vulns = [] t = threading.Thread(target=srv.serve_forever, daemon=True) t.start() diff --git a/plugins/security-guidance/tests/test_chained_commit_push.py b/plugins/security-guidance/tests/test_chained_commit_push.py index 8518ed5f..9b105362 100644 --- a/plugins/security-guidance/tests/test_chained_commit_push.py +++ b/plugins/security-guidance/tests/test_chained_commit_push.py @@ -4,15 +4,23 @@ The commit review sees only the commit the command made, and no later push covers what is already behind the upstream, so the second start of the hook for such a command runs the push review when something else went out. """ +import contextlib +import errno +import json import os import subprocess +import sys +import time import pytest -from conftest import GIT_ENV, bash_payload, commit_file, git, make_repo, metrics_of, run_hook +from conftest import ( + GIT_ENV, HOOK_SCRIPT, bash_payload, commit_file, git, make_repo, metrics_of, run_hook, +) +import diffstate import security_reminder_hook as hook -from diffstate import _append_reviewed_shas +from diffstate import _append_reviewed_shas, _load_reviewed_shas CMD = "git add -A && git commit -m new && git push" @@ -110,3 +118,396 @@ def test_plain_commit_second_start_is_deduped(repo, env): first, second, _ = _three_starts(repo, env, "git commit -m x", out, err) assert first.get("commit_review") is True assert second.get("bash_hook_dedup") is True + + +# The push spawn waits for the commit spawn, and takes over what it gave no +# verdict on. + +@contextlib.contextmanager +def _spawn(payload, env): + p = subprocess.Popen([sys.executable, str(HOOK_SCRIPT)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env) + try: + p.stdin.write(json.dumps(payload)) + p.stdin.close() + p.stdin = None + yield p + finally: + if p.poll() is None: + p.kill() + p.communicate() + + +def _until(cond, what, timeout=30): + end = time.time() + timeout + while not cond(): + assert time.time() < end, f"timed out waiting for {what}" + time.sleep(0.05) + + +def _both_spawns(repo, env, out, err, meanwhile=lambda commit: None, command=CMD): + """The two spawns of one call, the commit spawn first. Returns the commit + spawn's (exit code, metrics, stderr), then the push spawn's.""" + payload = bash_payload(str(repo), command, stdout=out, stderr=err, tool_use_id="t1") + with _spawn(payload, env) as commit: + _until(lambda: (repo / ".git" / "sg-hook-once-t1").exists(), "the commit spawn's claim") + with _spawn(payload, env) as push: + _until(lambda: (repo / ".git" / "sg-hook-once-t1-push").exists(), + "the push spawn's claim") + meanwhile(commit) + ends = [] + for p in (commit, push): + so, se = p.communicate(timeout=90) + ends.append((p.returncode, metrics_of(so), se)) + return ends + + +def _reviews(stub_api): + return len([c for c in stub_api.calls if c.endswith("/v1/messages")]) + + +def _head(repo): + return git(repo, "rev-parse", "HEAD").strip() + + +def test_one_review_while_the_push_spawn_waits(repo, hook_env, stub_api): + out, err = _commit_and_push(repo) + stub_api.delay = 4 + commit, push = _both_spawns(repo, hook_env, out, err) + assert commit[1]["commit_review"] is True and "skip_reason" not in commit[1] + assert push[1]["skip_reason"] == 47 and push[1]["inflight_wait_s"] >= 1 + assert "commit_no_verdict" not in push[1] + assert _reviews(stub_api) == 1 + + +def test_failed_commit_review_is_taken_over(repo, hook_env, stub_api): + out, err = _commit_and_push(repo) + stub_api.fail_first, stub_api.delay = 2, 1 # the review and its retry + commit, push = _both_spawns(repo, hook_env, out, err) + # The push review reports, so the commit review does not. + assert commit[0] == 0 and commit[1]["review_failed"] is True and not commit[2] + assert push[1]["commit_no_verdict"] is True and push[1]["unreviewed"] == 1 + assert "skip_reason" not in push[1] and _reviews(stub_api) == 3 + assert _head(repo) in _load_reviewed_shas(str(repo)) + + +def test_killed_commit_review_is_taken_over(repo, hook_env, stub_api): + out, err = _commit_and_push(repo) + stub_api.delay = 6 + + def kill(commit): + _until(lambda: _reviews(stub_api) == 1, "the commit review's request") + commit.kill() + + _, push = _both_spawns(repo, hook_env, out, err, kill) + assert push[1]["commit_no_verdict"] is True and push[1]["unreviewed"] == 1 + assert _head(repo) in _load_reviewed_shas(str(repo)) + + +def test_take_over_keeps_to_the_commit_review_cap(repo, hook_env, stub_api): + hook_env["MAX_COMMIT_REVIEWS_PER_HOUR"] = "1" + _, first = commit_file(repo, "first.py", "print('first')\n", "first") + run_hook(bash_payload(str(repo), "git commit -m first", first), hook_env) + out, err = _commit_and_push(repo) + commit, push = _both_spawns(repo, hook_env, out, err) + assert commit[1]["skip_reason"] == 23 + assert push[1]["skip_reason"] == 23 + assert _reviews(stub_api) == 1 + + +def test_commit_without_reviewable_files_sends_nothing(repo, hook_env, stub_api): + out, err = _commit_and_push(repo, "notes.png") + commit, push = _both_spawns(repo, hook_env, out, err) + assert commit[1]["skip_reason"] == 30 and push[1]["skip_reason"] == 30 + assert _reviews(stub_api) == 0 + + +def test_message_only_amend_is_not_reviewed_again(repo, hook_env, stub_api): + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + run_hook(bash_payload(str(repo), "git commit -m a", made), hook_env) + out, err = _run(repo, "commit", "--amend", "-m", "better") + pout, perr = _run(repo, "push") + commit, push = _both_spawns(repo, hook_env, out + pout, err + perr, + command="git commit --amend -m better && git push") + assert commit[1]["skip_reason"] == 35 and push[1]["skip_reason"] == 47 + assert _reviews(stub_api) == 1 + + +def test_nothing_is_held_where_files_cannot_be_locked(repo, monkeypatch): + def no_locks(fd, exclusive): + raise OSError(errno.ENOLCK, "no locks here") + + path = str(repo / ".git" / "sg-hook-once-t1") + open(path, "w").close() + monkeypatch.setattr(diffstate, "_flock_nb", no_locks) + for p in (path, path + "-missing", None): + diffstate.hold_until_exit(p) + assert diffstate.is_held(p) is None + assert diffstate.wait_for_holder(p, 5) == (False, 0.0) + assert diffstate.becomes_held(p, 0) is False + + +def test_wait_for_holder_stops_at_the_limit(tmp_path): + path = tmp_path / "held" + path.write_text("") + script = ("import sys, time\nsys.path.insert(0, sys.argv[2])\nimport diffstate\n" + "diffstate.hold_until_exit(sys.argv[1])\n" + "print('held', flush=True)\ntime.sleep(60)\n") + p = subprocess.Popen([sys.executable, "-c", script, str(path), os.path.dirname(diffstate.__file__)], + stdout=subprocess.PIPE, text=True) + try: + assert p.stdout.readline().strip() == "held" + ended, waited = diffstate.wait_for_holder(str(path), 1) + assert ended is False and waited >= 1 + assert diffstate.is_held(str(path)) is True + p.kill() + p.wait() + assert diffstate.wait_for_holder(str(path), 20) == (True, 0.0) + finally: + p.kill() + p.communicate() + + +def test_both_reviews_pick_the_same_commits(repo): + """The output names a commit but has no diffstat: both go by the reflog.""" + (repo / "quiet.py").write_text("print('quiet')\n") + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "quiet") + out, err = _run(repo, "commit", "--allow-empty", "-m", "marker") + pout, perr = _run(repo, "push") + output = out + pout + err + perr + assert hook._COMMIT_SHA_RE.findall(output) and not hook._commit_in_output(output) + both = git(repo, "rev-list", "@{u}@{1}..HEAD").split() + assert hook._commit_review_candidates(output, str(repo))[0][:2] == both + assert not _beyond(repo, output) + + +def test_quiet_commit_then_empty_commit_runs_one_review(repo, hook_env, stub_api): + (repo / "quiet.py").write_text("print('quiet')\n") + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "quiet") + out, err = _run(repo, "commit", "--allow-empty", "-m", "marker") + pout, perr = _run(repo, "push") + stub_api.delay = 2 + commit, push = _both_spawns( + repo, hook_env, out + pout, err + perr, + command="git commit -q -m quiet && git commit --allow-empty -m marker && git push") + assert commit[1]["sha_via_reflog"] is True and push[1]["skip_reason"] == 47 + assert _reviews(stub_api) == 1 + + +def test_slow_commit_review_is_left_alone(repo, hook_env, stub_api): + """It outlasts the wait: skipped as before, not reviewed twice.""" + out, err = _commit_and_push(repo) + stub_api.delay = 4 + commit, push = _both_spawns(repo, {**hook_env, "SG_INFLIGHT_WAIT_S": "1"}, out, err) + assert "skip_reason" not in commit[1] and push[1]["skip_reason"] == 47 + assert "commit_no_verdict" not in push[1] + assert _reviews(stub_api) == 1 + + +def test_take_over_after_head_moved(repo, hook_env, stub_api): + """Another commit landed meanwhile: still reviewed, as it was pushed.""" + out, err = _commit_and_push(repo) + pushed = _head(repo) + stub_api.fail_first, stub_api.delay = 2, 2 + + def move_head(commit): + _until(lambda: diffstate.is_held(str(repo / ".git" / "sg-hook-once-t1-push")), + "the push spawn's wait") + commit_file(repo, "later.py", "print('later')\n", "later") + + _, push = _both_spawns(repo, hook_env, out, err, move_head) + assert push[1]["commit_no_verdict"] is True and "skip_reason" not in push[1] + assert "new.py" in stub_api.bodies[-1] and "later.py" not in stub_api.bodies[-1] + assert _load_reviewed_shas(str(repo)) == {pushed} + + +def test_no_promise_of_a_push_review_that_ended(repo, hook_env, stub_api): + """Two branches pushed: that push review skips, and nothing takes over.""" + git(repo, "branch", "side") + git(repo, "push", "-q", "origin", "side") + git(repo, "checkout", "-q", "side") + commit_file(repo, "side.py", "print('side')\n", "side") + git(repo, "checkout", "-q", "main") + (repo / "new.py").write_text("print('new')\n") + git(repo, "add", "-A") + out, err = _run(repo, "commit", "-m", "new") + pout, perr = _run(repo, "push", "--all", "origin") + stub_api.fail_first, stub_api.delay = 2, 2 + commit, push = _both_spawns(repo, hook_env, out + pout, err + perr, + command="git commit -m new && git push --all origin") + assert push[1]["skip_reason"] == 44 and commit[1]["review_failed"] is True + assert "a later push will not re-check it" in commit[2] + + +def test_message_only_amend_while_the_original_is_under_review(repo, hook_env, stub_api): + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + stub_api.delay = 5 + with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env): + _until(lambda: _reviews(stub_api) == 1, "the original's review") + out, err = _run(repo, "commit", "--amend", "-m", "better") + pout, perr = _run(repo, "push") + commit, push = _both_spawns(repo, hook_env, out + pout, err + perr, + command="git commit --amend -m better && git push") + assert commit[1]["skip_reason"] == 35 and push[1]["skip_reason"] == 47 + assert _reviews(stub_api) == 1 + + +def test_failed_review_at_the_cap_still_reports(repo, hook_env, stub_api): + """The cap leaves the push review no turn, so the commit review reports.""" + out, err = _commit_and_push(repo) + stub_api.fail_first, stub_api.delay = 2, 1 + commit, push = _both_spawns(repo, {**hook_env, "MAX_COMMIT_REVIEWS_PER_HOUR": "1"}, out, err) + assert commit[0] == 2 and "a later push will not re-check it" in commit[2] + assert push[1]["skip_reason"] == 23 + + +def test_both_reviews_fail(repo, hook_env, stub_api): + out, err = _commit_and_push(repo) + stub_api.status = 400 + commit, push = _both_spawns(repo, hook_env, out, err) + assert commit[0] == 0 and commit[1]["review_failed"] is True + assert push[0] == 2 and "a later push will not re-check them" in push[2] + + +def test_older_commit_under_another_review_is_left_to_it(repo, hook_env, stub_api): + _, made = commit_file(repo, "older.py", "print('older')\n", "older") + stub_api.delay = 4 + with _spawn(bash_payload(str(repo), "git commit -m older", made), hook_env) as older: + _until(lambda: _reviews(stub_api) == 1, "the older commit's review") + out, err = _commit_and_push(repo) + commit, push = _both_spawns(repo, hook_env, out, err) + older.communicate(timeout=60) + assert push[1]["skip_reason"] == 47 + assert _reviews(stub_api) == 2 + + +@pytest.mark.parametrize("chained", [False, True]) +def test_message_only_amend_of_a_commit_whose_review_fails(repo, hook_env, stub_api, chained): + """The amended commit is not recorded on the word of a review that then + gives no verdict: the push review covers it.""" + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + stub_api.delay, stub_api.fail_first = 5, 2 + amend = "git commit --amend -m better" + with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env) as orig: + _until(lambda: _reviews(stub_api) == 1, "the original's review") + out, err = _run(repo, "commit", "--amend", "-m", "better") + if chained: + pout, perr = _run(repo, "push") + _, (_, push, _) = _both_spawns(repo, hook_env, out + pout, err + perr, + command=amend + " && git push") + else: + run_hook(bash_payload(str(repo), amend, out, stderr=err, tool_use_id="t2"), hook_env) + pout, perr = _run(repo, "push") + push = metrics_of(run_hook(bash_payload( + str(repo), "git push", pout, stderr=perr, tool_use_id="t3"), hook_env)[1]) + orig.communicate(timeout=60) + assert "skip_reason" not in push and push["unreviewed"] == 1 + assert _reviews(stub_api) == 3 # the review, its retry, the push review + assert _head(repo) in _load_reviewed_shas(str(repo)) + + +def _push_only(repo, env, tool_use_id, name): + commit_file(repo, name, "print('outside')\n", name) + out, err = _run(repo, "push") + return run_hook(bash_payload(str(repo), "git push", out, stderr=err, + tool_use_id=tool_use_id), env) + + +def test_failure_is_told_when_the_push_review_is_at_its_cap(repo, hook_env, stub_api): + hook_env["MAX_COMMIT_REVIEWS_PER_HOUR"] = "2" + for n in ("p1", "p2"): + assert "skip_reason" not in metrics_of(_push_only(repo, hook_env, n, n + ".py")[1]) + out, err = _commit_and_push(repo) + stub_api.status, stub_api.delay = 400, 1 + commit, push = _both_spawns(repo, hook_env, out, err) + assert push[1]["skip_reason"] == 23 and not push[2] + assert commit[0] == 2 and "a later push will not re-check it" in commit[2] + + +def test_failure_is_told_when_the_push_review_told_of_one_before(repo, hook_env, stub_api): + stub_api.status = 400 + assert "did not complete" in _push_only(repo, hook_env, "p1", "p1.py")[2] + out, err = _commit_and_push(repo) + commit, push = _both_spawns(repo, hook_env, out, err) + assert push[0] == 0 and push[1]["review_failed"] is True + assert commit[0] == 2 and "a later push will not re-check it" in commit[2] + + +def test_failure_is_told_when_the_push_review_is_killed(repo, hook_env, stub_api): + out, err = _commit_and_push(repo) + payload = bash_payload(str(repo), CMD, stdout=out, stderr=err, tool_use_id="t1") + stub_api.fail_first, stub_api.delay = 2, 4 + with _spawn(payload, hook_env) as commit: + _until(lambda: (repo / ".git" / "sg-hook-once-t1").exists(), "the commit spawn's claim") + with _spawn(payload, hook_env) as push: + _until(lambda: _reviews(stub_api) == 3, "the push review's request") + push.kill() + _, told = commit.communicate(timeout=60) + assert commit.returncode == 2 and "a later push will not re-check it" in told + + +def test_other_commits_of_the_command_do_not_bring_a_failure_notice(repo, hook_env, stub_api): + """Only what was pushed is for the push review: the commit that was then + amended is not, and the review of the rest succeeded.""" + (repo / "new.py").write_text("print('new')\n") + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "wip") + git(repo, "commit", "-q", "--amend", "-m", "done") + out, err = _run(repo, "push") + stub_api.fail_first, stub_api.delay = 2, 1 + commit, push = _both_spawns( + repo, hook_env, out, err, + command="git commit -q -m wip && git commit -q --amend -m done && git push") + assert push[1]["commit_no_verdict"] is True and "skip_reason" not in push[1] + assert commit[0] == 0 and not commit[2] + + +def test_separate_push_waits_for_a_message_only_amend(repo, hook_env, stub_api): + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + stub_api.delay = 6 + amend = "git commit --amend -m better" + with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env): + _until(lambda: _reviews(stub_api) == 1, "the original's review") + out, err = _run(repo, "commit", "--amend", "-m", "better") + with _spawn(bash_payload(str(repo), amend, out, stderr=err, tool_use_id="t2"), hook_env) as p: + marker = repo / ".git" / ("sg-inflight-" + _head(repo)) + _until(lambda: diffstate.is_held(str(marker)), "the amend's claim") + pout, perr = _run(repo, "push") + push = metrics_of(run_hook(bash_payload( + str(repo), "git push", pout, stderr=perr, tool_use_id="t3"), hook_env)[1]) + p.communicate(timeout=60) + assert push["unreviewed"] == 0 and push["inflight_wait_s"] >= 1 + assert _reviews(stub_api) == 1 + + +def test_amend_waits_less_than_its_push_review(repo, hook_env, stub_api): + """The original outlasts both waits: the push review still gets its turn.""" + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + stub_api.delay = 25 + env = {**hook_env, "SG_INFLIGHT_WAIT_S": "15"} + with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env): + _until(lambda: _reviews(stub_api) == 1, "the original's review") + out, err = _run(repo, "commit", "--amend", "-m", "better") + pout, perr = _run(repo, "push") + commit, push = _both_spawns(repo, env, out + pout, err + perr, + command="git commit --amend -m better && git push") + assert commit[1]["skip_reason"] == 35 and commit[1]["inflight_wait_s"] >= 1 + assert push[1]["commit_no_verdict"] is True and "skip_reason" not in push[1] + + +def test_failure_of_a_commit_elsewhere_is_told(repo, hook_env, stub_api, tmp_path): + """The push is of another repository, whose commits are all reviewed.""" + _, made = commit_file(repo, "a.py", "print('a')\n", "a") + run_hook(bash_payload(str(repo), "git commit -m a", made), hook_env) + lib = make_repo(tmp_path / "lib") + (lib / "x.py").write_text("print('x')\n") + git(lib, "add", "-A") + out, err = _run(lib, "commit", "-m", "x") + pout, perr = _run(repo, "push") + stub_api.status, stub_api.delay = 400, 1 + commit, _ = _both_spawns( + repo, hook_env, out + pout, err + perr, + command=f"git -C {lib} commit -m x && git push") + assert commit[0] == 2 and "did not complete" in commit[2] 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..109f5efc --- /dev/null +++ b/plugins/security-guidance/tests/test_renamed_into_review.py @@ -0,0 +1,466 @@ +"""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"), ("notes.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) == "" + + +@pytest.mark.parametrize("name", """ + api_keys.txt tokens.txt apiKeysProd.md KEYS.md AWSkeys.txt GCPkey.md DBpass.txt stripekey.txt + API_TOKEN.rst github-token-old.txt db_password.txt db_passwd.md my.creds.txt db-cred.txt + root_pwd.txt site_logins.txt prod.env.txt env.production.txt server.pem.txt id_ed25519.md + passphrase.md github-recovery-codes.txt gcp-service-account.txt service_account.md pgpass.txt + npmrc.txt netrc.txt my-secret.txt app_credential.md + secrets/prod.txt Credentials/prod.md prod-creds/a.txt api-keys/s.txt tokens/a/b.md .secrets/a.txt + vault/a.txt passwd/a.txt .ssh/prod.txt a/.aws/prod.txt a/.gnupg/n.md .kube/n.txt a/Passwords/b.txt + api_keys passwords secrets.yaml .env .env.py server.pem server.key deploy_rsa +""".split()) +def test_name_of_a_secret(name): + assert gitutil._is_secret_text(name) + + +@pytest.mark.parametrize("name", """ + notes.txt compassion.md environment.md keyboard.rst login.md tokenizer.md jwt.md author.md + aws/setup.md ssh/setup.md password-manager/notes.txt secret-service/notes.txt keyboards/a.txt + tokenizer/notes.txt +""".split()) +def test_name_of_ordinary_text(name): + assert not gitutil._is_secret_text(name) + assert gitutil._is_text_turned_code(name, "config.py") + + +@pytest.mark.parametrize("name", [ + "tokens.py", "api_keys.py", "token_store.js", "vendor/tokens.go", "secrets/load.py", + "vault/Dockerfile", "secrets/Makefile"]) +def test_code_is_not_a_list_of_secrets(name): + assert not gitutil._is_secret_text(name) + + +@pytest.mark.parametrize("old,new", [ + ("api_keys.txt", "api_keys.py"), ("tokens.txt", "config.py"), ("keys/prod.md", "config.sh")]) +def test_list_of_secrets_is_not_sent(tmp_path, hook_env, stub_api, old, new): + repo = make_repo(tmp_path / "repo", {old: SECRET, "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, m + assert _sent(stub_api) == "" + + +@pytest.mark.parametrize("old", ["api_keys.txt", "passwords", "secrets.yaml", "server.pem"]) +def test_list_of_secrets_renamed_in_two_steps_is_not_sent(tmp_path, hook_env, stub_api, old): + repo = make_repo(tmp_path / "repo", {old: SECRET}) + _move(repo, old, "settings.txt") + git(repo, "commit", "-qm", "one") + _move(repo, "settings.txt", "settings.py") + assert _commit(repo, hook_env)["skip_reason"] == 30 + assert _sent(stub_api) == "" + + +def test_other_renames_of_the_commit_are_still_read(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", { + "api_keys.txt": SECRET, "docs/hotkeys.md": "press a\n" * 9, "notes.txt": BODY}) + _move(repo, "api_keys.txt", "settings.py") + _move(repo, "docs/hotkeys.md", "hotkeys.py") + _move(repo, "notes.txt", "payload.py") + assert _commit(repo, hook_env)["renamed_in"] == 1 + assert MARK in _sent(stub_api) and "SECRET_VALUE" not in _sent(stub_api) + + +def test_list_of_secrets_is_not_listed(): + assert not gitutil._is_text_turned_code("api_keys.txt", "config.py") + + +def test_code_with_a_secret_word_in_its_name_is_not_a_secret_origin( + tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"token_store.py": BODY, "app.py": "x = 1\n"}) + _move(repo, "token_store.py", "notes.txt") + git(repo, "commit", "-qm", "one") + _move(repo, "notes.txt", "payload.py") + assert _commit(repo, hook_env)["renamed_in"] == 1 + assert MARK in _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) == [] diff --git a/plugins/security-guidance/tests/test_review_result_keys.py b/plugins/security-guidance/tests/test_review_result_keys.py new file mode 100644 index 00000000..f6711f05 --- /dev/null +++ b/plugins/security-guidance/tests/test_review_result_keys.py @@ -0,0 +1,132 @@ +"""Review rows keep their result, kind and time when they have more keys than +Claude Code keeps (the first 20).""" +import json + +import pytest + +import security_reminder_hook as hook + +_USAGE = {"tok_in": 1, "tok_out": 1, "tok_cache_r": 0, "tok_cache_w": 0, + "cost_usd": 0.1, "api_calls": 3} +_HTTP_ERR = {"http_err_last": 429, "http_err_count": 2} +# The keys the commit and push handlers pass, in their order. +_REFLOG = {"sha_via_reflog": True, "reflog_shas_n": 1} +_COMMIT_BASE = {"commit_review": True, "commit_review_on": True, "cwd_is_repo": False, + "repo_resolution": 2, **_REFLOG, "diff_files_dropped": 3, "rate_count": 1} +_PUSH_BASE = {"push_sweep": True, "push_sweep_on": True, "cwd_is_repo": False, + "repo_resolution": 2, "diff_files_dropped": 3, "rate_count": 1} +# A commit made with `git commit -q`, the common shape of a row with findings. +_QUIET_COMMIT = {"vulns_found": 1, "commit_review": True, "commit_review_on": True, + **_REFLOG, "rate_count": 1, "agentic": True, "candidates": 1, "survived": 1, + "race_winner": 1, "critical_count": 0, "high_count": 1, + "files_reviewed": 4, "review_ms": 9500} +_COMMIT_FINDINGS = {"vulns_found": 2, **_COMMIT_BASE, "agentic": True, "candidates": 3, + "survived": 3, "survived_after_sev": 2, "race_winner": 1, + "critical_count": 1, "high_count": 1, + "files_reviewed": 4, "review_ms": 9500, "deduped": 1} +_COMMIT_CLEAN = {"vulns_found": 0, **_COMMIT_BASE, "agentic": True, "candidates": 3, + "survived": 0, "race_winner": 1, "files_reviewed": 4, "review_ms": 9500} +_COMMIT_KNOWN = {"vulns_found": 0, **_COMMIT_BASE, "agentic": True, "candidates": 3, + "survived": 3, "race_winner": 1, "deduped": 3, + "files_reviewed": 4, "review_ms": 9500} +_PUSH = {**_PUSH_BASE, "pushed": 2, "unreviewed": 1, "prefix_advanced": 1, "vulns_found": 2, + "files_reviewed": 4, "review_ms": 9500, "deduped": 1, "inflight_wait_s": 4} +_COMMIT_FAILED = {**_COMMIT_BASE, "agentic": False, "agentic_fallback": 2, + "race_winner": 1, "files_reviewed": 4, "review_ms": 9500} +_PUSH_FAILED = {**_PUSH_BASE, "inflight_wait_s": 4, "pushed": 2, "unreviewed": 1, + "files_reviewed": 4, "review_ms": 9500} + + +@pytest.fixture(autouse=True) +def _clean(monkeypatch): + monkeypatch.setattr(hook, "_PV", 20000) + monkeypatch.setattr(hook, "_TAIL_METRICS", {"diff_seen": 0, "child_stderr": 2}) + monkeypatch.setattr(hook, "_REVIEWER_EFFORT_METRICS", {"rv_effort": 5}) + monkeypatch.setattr(hook, "_LAUNCHER_METRICS", {}) + monkeypatch.setattr(hook, "_LAUNCHER_DIRECT", {}) + monkeypatch.setattr(hook, "_log_usage", lambda usage: None) + monkeypatch.setattr(hook, "_usage_metrics", lambda: dict(_USAGE)) + monkeypatch.setattr(hook, "_precheck_miss", False) + monkeypatch.setattr(hook, "_net_error_metric", lambda: 0) + monkeypatch.setattr(hook.llm, "gateway_cfg", lambda: 3) + monkeypatch.delenv("SG_LAUNCHER_FALLBACK", raising=False) + + +def _row(capsys): + return json.loads(capsys.readouterr().out)["metrics"] + + +def _kept(row, cap=hook._METRIC_KEY_CAP): + """The part of a row Claude Code forwards.""" + return dict(list(row.items())[:cap]) + + +_ROWS = {"quiet-commit": _QUIET_COMMIT, "commit-findings": _COMMIT_FINDINGS, + "commit-clean": _COMMIT_CLEAN, "commit-known": _COMMIT_KNOWN, "push": _PUSH} + + +@pytest.mark.parametrize("http_err", [{}, _HTTP_ERR], ids=["", "http-errors"]) +@pytest.mark.parametrize("name", _ROWS) +def test_result_and_time_are_kept(capsys, monkeypatch, name, http_err): + metrics = _ROWS[name] + monkeypatch.setattr(hook, "_usage_metrics", lambda: {**_USAGE, **http_err}) + hook.emit_metrics(metrics) + row = _row(capsys) + assert len(row) > hook._METRIC_KEY_CAP + kept = _kept(row) + must = ("vulns_found", "review_ms", "files_reviewed", "commit_review", + "push_sweep", "agentic", "deduped", "critical_count", "high_count") + assert {k: kept.get(k) for k in must} == {k: metrics.get(k) for k in must} + assert {"pv", *_USAGE, *http_err} <= set(kept) + + +def test_quiet_commit_loses_one_descriptive_key(capsys): + hook.emit_metrics(_QUIET_COMMIT) + row = _row(capsys) + assert set(_QUIET_COMMIT) - set(_kept(row)) == {"commit_review_on"} + + +@pytest.mark.parametrize("kind, metrics, split", [ + ("Commit", _COMMIT_FAILED, "commit_review"), ("Push", _PUSH_FAILED, "push_sweep")]) +def test_failed_review_keeps_result_and_time(capsys, monkeypatch, kind, metrics, split): + """With every key that can come ahead of them.""" + monkeypatch.setattr(hook, "_usage_metrics", lambda: {**_USAGE, **_HTTP_ERR}) + monkeypatch.setattr(hook, "_net_error_metric", lambda: 2001) + monkeypatch.setattr(hook, "_precheck_miss", True) + monkeypatch.setenv("SG_LAUNCHER_FALLBACK", "1") + monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda *a: False) + with pytest.raises(SystemExit): + hook._exit_review_failed(kind, "s1", metrics, 429) + kept = _kept(_row(capsys)) + assert kept["review_failed"] is True and kept[split] is True + assert (kept["api_error"], kept["vulns_found"]) == (429, 0) + assert (kept["review_ms"], kept["files_reviewed"]) == (9500, 4) + assert kept["net_err"] == 2001 and kept.get("agentic") == metrics.get("agentic") + + +@pytest.mark.parametrize("metrics, split", [ + (_QUIET_COMMIT, "commit_review"), (_PUSH, "push_sweep")]) +def test_kind_and_time_fit_the_old_cap_of_ten(capsys, metrics, split): + hook.emit_metrics(metrics) + kept = _kept(_row(capsys), 10) + assert {"vulns_found", split, "review_ms"} <= set(kept) + + +def test_only_the_order_changes(capsys): + hook.emit_metrics(_COMMIT_FINDINGS) + row = _row(capsys) + added = {"pv", *_USAGE, "gateway_cfg", "diff_seen", "child_stderr", "rv_effort"} + assert {k: v for k, v in row.items() if k not in added} == _COMMIT_FINDINGS + rest = [k for k in _COMMIT_FINDINGS + if k not in hook._LEAD_METRIC_KEYS and k != "commit_review_on"] + assert [k for k in row if k in rest] == rest + + +@pytest.mark.parametrize("metrics", [ + {"skipped": True, "skip_reason": 21, "commit_review": True, "commit_review_on": True}, + {"skipped": True, "skip_reason": 35, "diff_strategy_v2": True, "deduped": 2, "review_ms": 900}, +]) +def test_skip_rows_are_unchanged(capsys, monkeypatch, metrics): + monkeypatch.setattr(hook, "_usage_metrics", dict) + hook.emit_metrics(metrics) + assert list(_row(capsys))[:1 + len(metrics)] == ["pv", *metrics] diff --git a/plugins/security-guidance/tests/test_reviewer_tools.py b/plugins/security-guidance/tests/test_reviewer_tools.py index 555ef0ad..f5f75cfd 100644 --- a/plugins/security-guidance/tests/test_reviewer_tools.py +++ b/plugins/security-guidance/tests/test_reviewer_tools.py @@ -90,6 +90,10 @@ def sdk(monkeypatch, tmp_path): for var in ("CONTEXT_DIR", "DEBUG_DIR", "MODEL", "ITER2", "FILTER", "NO_ADJUDICATE", "DIFF_INTERSECT", "EXCLUDE_MEDIUM", "MAX_TURNS"): monkeypatch.delenv("SG_AGENTIC_" + var, raising=False) + for var in ("MAX_THINKING_TOKENS", "CLAUDE_CODE_DISABLE_THINKING", + "CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING", "ANTHROPIC_DEFAULT_OPUS_MODEL"): + monkeypatch.delenv(var, raising=False) + monkeypatch.setattr(llm, "_listed_models", lambda: {}) return spawned @@ -104,6 +108,34 @@ def test_every_agentic_stage_gets_only_the_read_tools(sdk, tmp_path): assert "permission_mode" not in opts +def _systems(sdk, tmp_path): + llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + return [opts["system_prompt"] for opts in sdk] + + +@pytest.mark.parametrize("opus", [None, "", " "]) +def test_investigate_stages_are_told_their_text_is_not_read(sdk, tmp_path, monkeypatch, opus): + if opus is not None: + monkeypatch.setenv("ANTHROPIC_DEFAULT_OPUS_MODEL", opus) + investigate, second, refute = _systems(sdk, tmp_path) + for system in (investigate, second): + assert system == llm._AGENTIC_INVESTIGATE_SYSTEM + llm._REVIEWER_OUTPUT_RULE + assert llm._REVIEWER_OUTPUT_RULE not in refute + # review_api's prompt, which other harnesses use as it is, keeps its text. + assert "OUTPUT:" not in llm._AGENTIC_INVESTIGATE_SYSTEM + assert "Aim for at least one candidate" in llm._AGENTIC_INVESTIGATE_SYSTEM + + +@pytest.mark.parametrize("name,value", [ + ("MAX_THINKING_TOKENS", "0"), ("CLAUDE_CODE_DISABLE_THINKING", "1"), + ("CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING", "true"), ("SG_AGENTIC_MODEL", "some-model"), + ("ANTHROPIC_DEFAULT_OPUS_MODEL", "some-model")]) +def test_output_rule_is_left_out_where_text_is_the_reasoning(sdk, tmp_path, monkeypatch, name, value): + monkeypatch.setenv(name, value) + investigate, second, _ = _systems(sdk, tmp_path) + assert investigate == second == llm._AGENTIC_INVESTIGATE_SYSTEM + + def test_single_turn_sdk_review_gets_no_tools(sdk): schema = {"type": "object", "properties": {}} assert llm._call_claude_via_sdk("review this", schema) is not None |
