diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-27 20:03:52 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-27 20:03:52 +0000 |
| commit | 3654d346b45836e43e013b849be19233ff0efbc3 (patch) | |
| tree | 080cdfdff1e1f3df67ca9517251bbe8052890724 /plugins/security-guidance | |
| parent | 45bb3d5c14f7c20c9bdc9a30e798cf0d77467e2e (diff) | |
| parent | f8c5e7a1dcb71b10cb74586224b5401f3de5db28 (diff) | |
Merge remote-tracking branch 'origin/main' into mhegazy/sg-secret-rename-pairingmhegazy/sg-secret-rename-pairing
# Conflicts:
# plugins/security-guidance/hooks/diffstate.py
Diffstat (limited to 'plugins/security-guidance')
| -rw-r--r-- | plugins/security-guidance/.claude-plugin/plugin.json | 2 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 28 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 296 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 77 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 136 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 113 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/conftest.py | 9 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_add_failure_metric.py | 143 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_inflight_reviews.py | 142 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_network_failure_class.py | 356 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_repeated_diff_count.py | 268 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_reviewer_context_metrics.py | 94 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_slow_prompt_metrics.py | 175 |
13 files changed, 1776 insertions, 63 deletions
diff --git a/plugins/security-guidance/.claude-plugin/plugin.json b/plugins/security-guidance/.claude-plugin/plugin.json index 74b161db..8bcd0bdb 100644 --- a/plugins/security-guidance/.claude-plugin/plugin.json +++ b/plugins/security-guidance/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "security-guidance", - "version": "2.0.16", + "version": "2.0.17", "description": "Security review for Claude-generated code. Pattern-based warnings on edits, LLM-powered diff review on Stop, and an agentic commit reviewer that catches injection, XSS, SSRF, hardcoded secrets, and 25+ other vulnerability classes.", "author": { "name": "David Dworken", diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index e5959e68..28b189a4 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -212,6 +212,7 @@ _USAGE = { # reported it manually. "http_err_last": 0, # most recent HTTP error code this invocation "http_err_count": 0, # total HTTP errors (4xx + 5xx + network) + "net_err": 0, # why the last call got no HTTP response, 0 if it got one # For the usage log line only: model ids as recorded (the requested alias # on the Agent SDK path), and whether any call had no price-table entry. "models": [], @@ -300,6 +301,33 @@ def _record_http_error(status): _USAGE["http_err_count"] += 1 +def _record_net_error(code): + """Record why an LLM API call got no HTTP response: the packed code from + llm._net_error_code. `api_error` -1 cannot tell a certificate failure + from a refused connection or a timeout, and a failure the HTTP client + raises outside its own error type (a default TLS context that cannot be + built, a connection closed before the reply) has no `api_error` at all. + Emitted as `net_err` on the row of a hook whose last call failed this + way; a later call clears it.""" + try: + c = int(code) + except (TypeError, ValueError): + return + if c > 0: + with _USAGE_LOCK: + _USAGE["net_err"] = c + + +def _clear_net_error(): + with _USAGE_LOCK: + _USAGE["net_err"] = 0 + + +def _net_error_metric(): + with _USAGE_LOCK: + return _USAGE.get("net_err", 0) + + # Set by main() and the review handlers: which review this invocation runs # and for which Claude Code session, so the usage log line can be attributed. _USAGE_CONTEXT = {"session_id": "", "review": "stop"} diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index fc42f8c1..5f65ac7f 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -6,17 +6,18 @@ there so callers keep resolving bare names through the hook module's globals — tests that ``monkeypatch.setattr(hook, "<fn>", …)`` continue to work without retargeting. """ +import hashlib import os import subprocess import sys import time -from _base import debug_log, _PV +from _base import debug_log, portable_output, _PV from gitutil import ( GIT_CMD, _git_dir, _git_toplevel, _git_status_porcelain, _git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index, - _secret_rename_origins, + _secret_rename_origins, index_entry_count, ) from session_state import with_locked_state from extensibility import _same_dir @@ -323,6 +324,8 @@ def get_baseline_file_content(session_id, file_path, cwd): # from uncommitted work that was already there. Stored with baseline_sha. # Telemetry only. last_baseline_fail = 0 +# Entries in the index the last capture copied, None if unknown. Telemetry only. +last_index_entries = None def capture_git_baseline(cwd): @@ -351,8 +354,9 @@ def capture_git_baseline(cwd): # with `Ávila_report.txt` triggers a quotePath/locale warning) would # trip the stderr reader thread on Windows cp1252. Decode both streams # leniently for symmetry with _list_untracked. See #2056. - global last_baseline_fail + global last_baseline_fail, last_index_entries last_baseline_fail = 0 + last_index_entries = None try: # Check if HEAD exists (i.e., repo has at least one commit) head_check = subprocess.run( @@ -370,6 +374,7 @@ def capture_git_baseline(cwd): # env is None when no usable index copy could be made: fall # back to HEAD. if env is not None: + last_index_entries = index_entry_count(env["GIT_INDEX_FILE"]) result = subprocess.run( [*GIT_CMD, "stash", "create"], cwd=cwd, capture_output=True, timeout=15, env=env @@ -504,6 +509,164 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0): pass +# ─── repeated-diff count ──────────────────────────────────────────────────── +# +# Count only. A change that comes back under a new commit (undo and re-commit, +# rebase before the first push) is unknown to the reviewed-shas record and is +# reviewed again. These helpers say how often that happens, by remembering a +# hash of each reviewed hunk next to the reviewed-shas file. Nothing here +# decides whether a review runs, and nothing here waits on another process +# for more than a moment. + +_SEEN_DIFFS_BASENAME = "sg-reviewed-diffs" +_SEEN_DIFFS_TTL_S = 7 * 24 * 3600 +# Past this size the record is cut back to its newest half. +_SEEN_DIFFS_TRIM_BYTES = 1024 * 1024 +_SEEN_DIFFS_MAX_KEYS = 500 +_SEEN_DIFFS_LOCK_TRIES = 10 + +# `diff_seen` values, weakest first. A review reports the weakest of its +# hunks: 3 means every hunk already had a finished review in this clone. +DIFF_SEEN_ERROR = -1 # the record could not be read or written +DIFF_SEEN_NO = 0 # some hunk was never reviewed +DIFF_SEEN_UNFINISHED = 1 # a review of it started and has no verdict (yet) +DIFF_SEEN_OTHER_TREE = 2 # finished, on different repo contents +DIFF_SEEN_SAME_TREE = 3 # finished, on the same tree + + +def _hunk_keys(diff_files): + """One hash per hunk: the path plus the hunk's lines, context included. + + The `@@` line is left out, so a hunk keeps its key when a rebase only + moves it; the same edit next to different code gets a different key. + """ + keys = {} + for path, content in diff_files: + hunks, cur = [], [] + for ln in content.split("\n"): + if ln.startswith("@@"): + hunks.append(cur) + cur = [] + else: + cur.append(ln) + hunks.append(cur) + for body in hunks: + # A file's last hunk ends with the diff's trailing blank line. + while body and not body[-1]: + body.pop() + if not body: + continue + h = hashlib.sha256(path.encode("utf-8", "replace")) + h.update(b"\0") + h.update("\n".join(body).encode("utf-8", "replace")) + keys[h.hexdigest()[:16]] = None + keys = list(keys) + if len(keys) > _SEEN_DIFFS_MAX_KEYS: + # Keep the record small: the hunks past the cap share one key, so + # they only match the same set of hunks again. + rest = hashlib.sha256(" ".join(keys[_SEEN_DIFFS_MAX_KEYS - 1:]).encode("ascii")) + keys = keys[:_SEEN_DIFFS_MAX_KEYS - 1] + [rest.hexdigest()[:16]] + return keys + + +def _seen_lock(fd): + """True: locked. False: another process kept it. None: no flock here.""" + for _ in range(_SEEN_DIFFS_LOCK_TRIES): + try: + if _flock_nb(fd, exclusive=True): + return True + except (ImportError, OSError): + return None + time.sleep(0.05) + return False + + +def _append_diff_row(f, locked, token, done): + """Append one record for the review to `f`, the record opened "a+b".""" + _, keys, tree = token + row = f"{int(time.time())}\t{tree}\t{int(done)}\t{' '.join(keys)}\n".encode("ascii") + size = f.seek(0, os.SEEK_END) + if size: + f.seek(size - 1) + if f.read(1) != b"\n": + row = b"\n" + row # a torn last record must not swallow this one + # Cutting the record back rewrites it: not while another process holds + # the lock. Without flock at all, bounded beats exact. + if locked is not False and size + len(row) > _SEEN_DIFFS_TRIM_BYTES: + f.seek(0) + keep, room = [], _SEEN_DIFFS_TRIM_BYTES // 2 + for ln in reversed(f.read().splitlines(keepends=True)): + room -= len(ln) + if room < 0: + break + keep.append(ln) + f.seek(0) + f.truncate() + row = b"".join(reversed(keep)) + row + f.write(row) + f.flush() + + +def _diff_review_started(repo_root, diff_files, tip="HEAD"): + """Note that a review of `diff_files`, a diff ending at `tip`, is starting. + + Returns (token, metrics). `metrics` is {"diff_seen": <DIFF_SEEN_* code>}: + whether this clone already reviewed every hunk of this diff. `token` goes + to `_diff_review_done` once the review has a verdict. Never raises. + """ + if portable_output() or not diff_files: + # No metrics leave the hook in portable mode, so nothing to count. + return None, {} + try: + gd = _git_dir(repo_root) + keys = _hunk_keys(diff_files) + if not gd or not keys: + raise ValueError("no git dir" if not gd else "no hunks") + token = (os.path.join(gd, _SEEN_DIFFS_BASENAME), keys, + "".join(_full_shas(repo_root, [tip + "^{tree}"])[:1])) + tree = token[2] + now = time.time() + best = dict.fromkeys(keys, DIFF_SEEN_NO) + # Read and note under one lock, so two reviews of one diff that start + # together cannot both miss each other. + with open(token[0], "a+b") as f: + locked = _seen_lock(f.fileno()) + if locked is False: + raise OSError("record is locked") + f.seek(0) + for ln in f.read().decode("ascii", "replace").splitlines(): + row = ln.split("\t") + if len(row) != 4 or not row[0].isdigit() or len(row[0]) > 12: + continue + if now - int(row[0]) > _SEEN_DIFFS_TTL_S: + continue + if row[2] != "1": + seen = DIFF_SEEN_UNFINISHED + elif tree and row[1] == tree: + seen = DIFF_SEEN_SAME_TREE + else: + seen = DIFF_SEEN_OTHER_TREE + for k in row[3].split(" "): + if best.get(k, seen) < seen: + best[k] = seen + _append_diff_row(f, locked, token, done=False) + return token, {"diff_seen": min(best.values())} + except Exception as e: + debug_log(f"Repeated-diff count: not counted ({type(e).__name__}: {e})") + return None, {"diff_seen": DIFF_SEEN_ERROR} + + +def _diff_review_done(token): + """Note that the review `token` came from got a verdict. Never raises.""" + if not token: + return + try: + with open(token[0], "a+b") as f: + _append_diff_row(f, _seen_lock(f.fileno()), token, done=True) + except Exception as e: + debug_log(f"Repeated-diff count: verdict not noted ({type(e).__name__}: {e})") + + # ─── in-flight review markers ─────────────────────────────────────────────── # # A commit or push review records its shas only once it has a verdict, which @@ -512,14 +675,19 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0): # through a second full review. So a review first takes an exclusive flock on # `sg-inflight-<sha>`, next to the reviewed-shas file, and holds it until its # process ends; other reviews leave a locked commit to it. The kernel drops -# the lock however the holder dies, so a killed review blocks nobody. Without -# flock (native Windows Python, some network filesystems) there are no +# the lock however the holder dies, so a killed review blocks nobody. Native +# Windows Python has no flock; there the same lock is taken with LockFileEx. +# Where files cannot be locked (some network filesystems) there are no # markers and nothing changes. _INFLIGHT_PREFIX = "sg-inflight-" # A marker file nobody holds (a killed review's) is removed once this old. _INFLIGHT_GC_AGE_S = 3600 _inflight_held = {} +# Windows refuses to delete a file that is open, so a marker is closed first +# there. Elsewhere it is deleted while still locked, so nobody can lock a +# file that is about to go. +_UNLINK_BEFORE_CLOSE = os.name != "nt" def _full_shas(repo_root, shas): @@ -538,11 +706,60 @@ def _full_shas(repo_root, shas): return out +_win_lock_file_ex = None + + +def _win_lock_nb(fd, exclusive): + """`_flock_nb` for native Windows Python, with LockFileEx. + + Shared and exclusive as with flock, never waits, and Windows drops the + lock when the handle is closed or the holder's process ends. Windows + locks stop other processes reading the locked bytes, so the byte locked + is one far past the end of the (empty) marker: copying a repository while + a review runs still reads the marker. + """ + global _win_lock_file_ex + import errno + try: + import ctypes + import msvcrt + if _win_lock_file_ex is None: + from ctypes import wintypes + + class _Overlapped(ctypes.Structure): + _fields_ = [("Internal", ctypes.c_void_p), ("InternalHigh", ctypes.c_void_p), + ("Offset", wintypes.DWORD), ("OffsetHigh", wintypes.DWORD), + ("hEvent", wintypes.HANDLE)] + + fn = ctypes.WinDLL("kernel32", use_last_error=True).LockFileEx + fn.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, + wintypes.DWORD, ctypes.POINTER(_Overlapped)] + fn.restype = wintypes.BOOL + _win_lock_file_ex = (fn, _Overlapped) + except (ImportError, AttributeError, OSError) as e: + raise OSError(errno.ENOLCK, f"no file locking in this Python ({e})") + fn, _Overlapped = _win_lock_file_ex + fail_immediately, exclusive_lock = 0x1, 0x2 + where = _Overlapped(Offset=0, OffsetHigh=0x7FFFFFFF) + if fn(msvcrt.get_osfhandle(fd), fail_immediately | (exclusive_lock if exclusive else 0), + 0, 1, 0, ctypes.byref(where)): + return True + err = ctypes.get_last_error() + if err == 33: # ERROR_LOCK_VIOLATION: another handle holds it + return False + raise OSError(errno.ENOLCK, f"LockFileEx failed (WinError {err})") + + def _flock_nb(fd, exclusive): """True when the lock was taken, False when another process holds it. Raises OSError when the file cannot be locked at all.""" import errno - import fcntl + if os.name == "nt": + return _win_lock_nb(fd, exclusive) + try: + import fcntl + except ImportError as e: + raise OSError(errno.ENOLCK, f"no file locking in this Python ({e})") try: fcntl.flock(fd, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB) return True @@ -552,16 +769,36 @@ def _flock_nb(fd, exclusive): raise -def _release_inflight(): - for p, fd in list(_inflight_held.items()): +def _again_if_refused(op, *args): + """`op(*args)`, tried a few times where another process having the file + open for a moment refuses it (Windows). Raises the last OSError.""" + import time as _time + tries = 1 if _UNLINK_BEFORE_CLOSE else 3 + for attempt in range(tries): try: - os.unlink(p) - except OSError: - pass + return op(*args) + except PermissionError: + if attempt == tries - 1: + raise + _time.sleep(0.01) + + +def _drop_marker(p, fd, unlink=True): + """Close a marker this process has open and, with `unlink`, delete it, in + the order this platform needs. Never raises. A delete that stays refused + leaves an unlocked file, which is swept once old.""" + steps = [(_again_if_refused, os.unlink, p)] if unlink else [] + steps.insert(len(steps) if _UNLINK_BEFORE_CLOSE else 0, (os.close, fd)) + for step, *args in steps: try: - os.close(fd) + step(*args) except OSError: pass + + +def _release_inflight(): + for p, fd in list(_inflight_held.items()): + _drop_marker(p, fd) _inflight_held.clear() @@ -580,11 +817,10 @@ def _sweep_inflight(gd): except OSError: continue try: - if _flock_nb(fd, exclusive=True): - os.unlink(p) + unheld = _flock_nb(fd, exclusive=True) except OSError: - pass - os.close(fd) + unheld = False + _drop_marker(p, fd, unlink=unheld) def _mark_inflight(repo_root, shas): @@ -592,7 +828,6 @@ def _mark_inflight(repo_root, shas): run, until the process ends. Best-effort; never raises. A commit another live review holds stays with that review.""" try: - import fcntl # noqa: F401 gd = _git_dir(repo_root) if not gd: return @@ -601,17 +836,26 @@ def _mark_inflight(repo_root, shas): p = os.path.join(gd, _INFLIGHT_PREFIX + sha) if not _is_full_sha(sha) or p in _inflight_held: continue - fd = os.open(p, os.O_RDWR | os.O_CREAT, 0o600) try: - # The inode check: a holder unlinks its marker when it ends, - # and a lock on that unlinked file would claim nothing. - held = (_flock_nb(fd, exclusive=True) - and os.fstat(fd).st_ino == os.stat(p).st_ino) + fd = _again_if_refused(os.open, p, os.O_RDWR | os.O_CREAT, 0o600) + except OSError: + # One marker that cannot be opened does not cost the others + # their claim. + continue + try: + held = _flock_nb(fd, exclusive=True) except OSError: # Cannot lock here at all: leave no file that reads as held. - os.close(fd) - os.unlink(p) + _drop_marker(p, fd) return + if held and _UNLINK_BEFORE_CLOSE: + # The inode check: a holder unlinks its marker when it ends, + # and a lock on that unlinked file would claim nothing. Not + # where an open file cannot be unlinked in the first place. + try: + held = os.fstat(fd).st_ino == os.stat(p).st_ino + except OSError: + held = False if not held: os.close(fd) continue @@ -627,10 +871,6 @@ def _mark_inflight(repo_root, shas): def _load_inflight_shas(repo_root, shas, _gd=None): """Which of `shas` another live review in this clone holds right now.""" out = set() - try: - import fcntl # noqa: F401 - except ImportError: - return out gd = _gd or _git_dir(repo_root) if not gd: return out diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 67fec34d..6410c1c7 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -103,6 +103,50 @@ def apply_safe_git_env(): os.environ.update(SAFE_GIT_ENV) +def index_entry_count(path): + """The entry count in an index file's header (signature, version, count), + or None if it cannot be read. A split or sparse index holds fewer entries + than the repository has tracked files.""" + try: + with open(path, "rb") as f: + header = f.read(12) + except OSError: + return None + if header[:4] == b"DIRC" and len(header) == 12: + return int.from_bytes(header[8:12], "big") + return None + + +def windows_drive_mount(path, mountinfo): + """Whether `path` is on a Windows drive mounted into WSL, given the text + of /proc/self/mountinfo. Every file status there is a round trip to the + Windows host.""" + best, best_type = "", "" + for line in mountinfo.splitlines(): + # id parent dev root mountpoint options [tags] - fstype source options + before, _, after = line.partition(" - ") + fields, tail = before.split(), after.split() + if len(fields) < 5 or not tail: + continue + point = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), fields[4]) + inside = path == point or path.startswith(point.rstrip("/") + "/") + if inside and len(point) >= len(best): + best, best_type = point, tail[0] + return best_type in ("9p", "drvfs", "virtiofs") + + +def on_windows_drive(path): + """windows_drive_mount for this machine. False anywhere but WSL.""" + try: + with open("/proc/sys/kernel/osrelease") as f: + if "microsoft" not in f.read().lower(): + return False + with open("/proc/self/mountinfo") as f: + return windows_drive_mount(os.path.realpath(path), f.read()) + except (OSError, ValueError): + return False + + def _git_rev_parse_head(cwd): """Return the current HEAD SHA, or None if not a git repo / no commits.""" try: @@ -249,6 +293,15 @@ def _path_batches(paths, budget=None): # long once cut down) or "none_reviewable". _path_list_too_long = set() +# A failed `git add --intent-to-add` during this hook run, for the Stop hook's +# metrics: kind * 100000 + the paths the add was given. One number because a +# review row is near CC's key cap. A failed add leaves the new files out of the +# diff, so a turn that only added files looks like a turn with no changes; a +# timeout loses the whole diff. kind: 1 git could not write the empty blob to +# the object store, 2 any other git error, 3 timeout. A git that speaks another +# language counts as 2. +_add_failed = {"code": 0} + def _too_many_args(e): """The OS refused to start the command because its arguments are too @@ -542,6 +595,10 @@ def _hook_tmpdir(): return d +def _note_add_failure(kind, paths): + _add_failed["code"] = kind * 100000 + min(len(paths), 99999) + + @contextlib.contextmanager def _temp_index(cwd, untracked_paths=None): """Yield an env dict pointing GIT_INDEX_FILE at a throwaway copy of the @@ -632,12 +689,20 @@ def _copied_index(cwd, top, real_index, tmpdir, untracked_paths): # still spawns 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. - _run_git_on_review_paths( - ["add", "--intent-to-add"], add_args, timeout=10, cwd=cwd, - # The paths are file names, not patterns, for this git add - # only: an untracked file named `:(glob)**` must add only - # itself. - env={**env, "GIT_LITERAL_PATHSPECS": "1"}) + try: + results = _run_git_on_review_paths( + ["add", "--intent-to-add"], add_args, timeout=10, cwd=cwd, + # The paths are file names, not patterns, for this git add + # only: an untracked file named `:(glob)**` must add only + # itself. + env={**env, "GIT_LITERAL_PATHSPECS": "1"}) + except subprocess.TimeoutExpired: + _note_add_failure(3, add_args) + raise + failed = next((r for r in results if r.returncode != 0), None) + if failed: + _note_add_failure(1 if b"empty blob" in failed.stderr else 2, add_args) + debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}") # A whole-tree add puts a nested repository back. if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index): yield None diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index f4562bb4..468d9e6d 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -39,7 +39,7 @@ except ImportError: # a Python built without TLS import extensibility import review_api -from _base import debug_log, _record_usage, _record_http_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs # noqa: F401 +from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs # noqa: F401 from session_state import load_state, with_locked_state from gitutil import git_config_env, SAFE_GIT_CONFIG @@ -289,10 +289,120 @@ def _probe_anthropic(timeout: float = 5.0) -> bool: return True except urllib.error.HTTPError: return True # got a status code → connected - except (urllib.error.URLError, TimeoutError, OSError): + except (urllib.error.URLError, TimeoutError, OSError) as e: + _record_net_error(_net_error_code(e)) return False +# ===================================================================== +# Why a call got no HTTP response +# ===================================================================== +# Classes for the `net_err` metric. Measure only: nothing reads these to +# decide what the plugin does. +NET_ERR_CERT_VERIFY = 1 # the server certificate did not verify +NET_ERR_TLS = 2 # any other TLS failure, including a default context that cannot be built +NET_ERR_DNS = 3 # the host name did not resolve +NET_ERR_CONNECT = 4 # refused, reset, closed early or unreachable +NET_ERR_TIMEOUT = 5 +NET_ERR_PROXY = 6 # the proxy refused the tunnel +NET_ERR_OTHER = 7 # another failure from the HTTP client +NET_ERR_INNER_CLI = 9 # the review ran through a CLI, which failed +NET_ERR_INNER_CLI_TIMEOUT = 10 +NET_ERR_NO_SDK = 11 # the review needed the agent SDK, which could not be imported + +_NET_FLAG_NO_CA_ON_DISK = 1 # Python's default CA file and directory are missing or empty +_NET_FLAG_PROXY = 2 # the request would go through a proxy +_NET_FLAG_NODE_EXTRA_CA = 4 # NODE_EXTRA_CA_CERTS is set (Python does not read it) +_NET_FLAG_SSL_CERT_ENV = 8 # SSL_CERT_FILE or SSL_CERT_DIR is set + + +def _net_error_class(exc) -> Tuple[int, int]: + """(class, X.509 verify code) for an exception from an API call; class 0 + for one that is not a network failure. The verify code is OpenSSL's + (20 = issuer not found locally, 19 = self-signed certificate in the + chain, 10 = expired), 0 when the class is not NET_ERR_CERT_VERIFY.""" + import errno + import http.client + import socket + try: + import ssl + cert_error, tls_error = ssl.SSLCertVerificationError, ssl.SSLError + except ImportError: + cert_error = tls_error = () + reason = getattr(exc, "reason", None) + err = reason if isinstance(reason, BaseException) else exc + if isinstance(err, cert_error): + code = getattr(err, "verify_code", 0) + return NET_ERR_CERT_VERIFY, code if isinstance(code, int) and 0 < code < 100 else 0 + if isinstance(err, tls_error): + return NET_ERR_TLS, 0 + if isinstance(err, socket.gaierror): + return NET_ERR_DNS, 0 + if isinstance(err, OSError): + text = str(err).lower() + if "tunnel connection failed" in text: + return NET_ERR_PROXY, 0 + if isinstance(err, TimeoutError) or "timed out" in text: + return NET_ERR_TIMEOUT, 0 + if isinstance(err, ConnectionError) or err.errno in ( + errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN, + errno.EHOSTDOWN, errno.EADDRNOTAVAIL): + return NET_ERR_CONNECT, 0 + return NET_ERR_OTHER, 0 + if isinstance(err, http.client.HTTPException) or isinstance(exc, urllib.error.URLError): + return NET_ERR_OTHER, 0 + return 0, 0 + + +def _net_error_flags(tls: bool) -> int: + """What the machine's setup says about a failed call. Each check is + best effort: one that cannot be made leaves its flag off.""" + flags = 0 + if tls: + try: + import ssl + paths = ssl.get_default_verify_paths() + has_file = bool(paths.cafile) and os.path.getsize(paths.cafile) > 0 + has_dir = False + if paths.capath: + with os.scandir(paths.capath) as it: + has_dir = any(True for _ in it) + # Windows also reads the system store, which this cannot see. + if not has_file and not has_dir and sys.platform != "win32": + flags |= _NET_FLAG_NO_CA_ON_DISK + except Exception: + pass + if os.environ.get("NODE_EXTRA_CA_CERTS"): + flags |= _NET_FLAG_NODE_EXTRA_CA + if os.environ.get("SSL_CERT_FILE") or os.environ.get("SSL_CERT_DIR"): + flags |= _NET_FLAG_SSL_CERT_ENV + try: + url = urllib.parse.urlsplit(_anthropic_base_url()) + # As urllib chooses: the proxy for the URL's scheme, bypass by host:port. + if (urllib.request.getproxies().get(url.scheme) + and not urllib.request.proxy_bypass(url.netloc.rpartition("@")[2])): + flags |= _NET_FLAG_PROXY + except Exception: + pass + return flags + + +def _net_error_code(exc) -> int: + """`net_err` for an exception: class + 100 * verify code + 10000 * flags, + or 0 for an exception that is not a network failure.""" + try: + cls, verify = _net_error_class(exc) + except Exception: + return 0 + if not cls: + return 0 + try: + flags = _net_error_flags(cls in (NET_ERR_CERT_VERIFY, NET_ERR_TLS)) + except Exception: + flags = 0 + return cls + 100 * verify + 10000 * flags + + def _strip_anthropic_from_no_proxy() -> None: for var in ("NO_PROXY", "no_proxy"): val = os.environ.get(var) @@ -834,6 +944,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, """ global _last_call_claude_http_error, _gateway_review_timed_out _last_call_claude_http_error = None + _clear_net_error() route = "gateway" if cli_path else "3P" try: @@ -862,6 +973,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, debug_log(f"{route} sdk-single-turn: SDK unavailable ({e})") _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(NET_ERR_NO_SDK) return None _send_sdk_logs_to_debug_log() @@ -946,12 +1058,14 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, _gateway_review_timed_out = True _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(NET_ERR_INNER_CLI_TIMEOUT) return None except Exception as e: debug_log(f"{route} sdk-single-turn: query failed ({e})") _log_child_stderr() _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(NET_ERR_INNER_CLI) return None @@ -974,6 +1088,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, """ global _last_call_claude_http_error _last_call_claude_http_error = None + _clear_net_error() if _is_3p_provider(): # On Bedrock/Vertex/Foundry/Mantle the api.anthropic.com path below @@ -1092,6 +1207,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, debug_log(f"Request failed after retries: {e}") _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(_net_error_code(e)) return None if not response_data: @@ -1590,6 +1706,7 @@ Respond with a JSON object. If vulnerabilities are found, set hasVulnerabilities cacheable_prefix=_CODE_REVIEW_RUBRIC) except Exception as e: debug_log(f"LLM code review: call raised {type(e).__name__}: {e}") + _record_net_error(_net_error_code(e)) analysis = None # A reply without the schema's required flag is not a verdict either. if not isinstance(analysis, dict) or "hasVulnerabilities" not in analysis: @@ -1791,11 +1908,15 @@ def agentic_review( before the review, 2 = it went missing during it rv_tool_err Read/Grep/Glob calls that came back as errors rv_tool_calls Read/Grep/Glob calls made + rv_turns turns the reviewer took, as the CLI counts them + rv_api_ms time the reviewer spent waiting on the model, in ms - The counts cover all stages of the review. Keys are left out when 0.""" + The counts cover all stages of the review. Keys are left out when 0. + rv_turns and rv_api_ms come from each stage's result message, so a stage + that ends without one (the CLI exits early) adds nothing to them.""" context_dir = _agentic_context_dir(repo_dir) gone = 0 if os.path.isdir(context_dir) else 1 - ctx = {"rv_tool_err": 0, "rv_tool_calls": 0} + ctx = {"rv_tool_err": 0, "rv_tool_calls": 0, "rv_turns": 0, "rv_api_ms": 0} guidance, vulns, metrics = _agentic_review(repo_dir, diff_files, touched_paths, ctx) if not gone and not os.path.isdir(context_dir): gone = 2 @@ -2012,6 +2133,13 @@ def _agentic_review( # the price-table estimate. getattr guards older SDK builds. _record_usage(getattr(msg, "usage", None) or {}, model, cost_usd=getattr(msg, "total_cost_usd", None)) + for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")): + value = getattr(msg, attr, None) + # Counting must never fail the review: anything that + # is not a positive finite number adds nothing. + if (isinstance(value, (int, float)) and not isinstance(value, bool) + and 0 < value < float("inf")): + ctx[key] += int(value) else: # Tool results come back as user messages. content = getattr(msg, "content", None) diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 0cae917d..3efe344e 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -84,10 +84,10 @@ from _base import ( # noqa: E402,F401 DEBUG_LOG_FILE, DEBUG_LOG_MAX_BYTES, debug_log, PROVENANCE_TAG, PROVENANCE_BANNER, _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, - _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, + _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, _net_error_metric, _USAGE_CONTEXT, _log_usage, launcher_probe_metrics, state_dir as _resolve_state_dir, - write_hook_output as _write_hook_output, + write_hook_output as _write_hook_output, portable_output, llm_reviews_switched_off, agent_sdk_installed, ) import extensibility # noqa: E402 @@ -103,6 +103,7 @@ from session_state import ( # noqa: E402,F401 ) from gitutil import ( # noqa: E402,F401 GIT_CMD, apply_safe_git_env, remove_copies_on_termination, + on_windows_drive, _git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index, _git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range, _git_toplevel_and_head, _git_head_at, @@ -124,6 +125,7 @@ from diffstate import ( # noqa: E402,F401 _REVIEWED_SHAS_BASENAME, _REVIEWED_SHAS_CAP, _reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas, _full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight, + _diff_review_started, _diff_review_done, UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set, touched_scope, review_scope_code, baseline_origin, baseline_origin_metric, FOREIGN_ORIGINS, @@ -219,19 +221,39 @@ CONTINUATION_SUFFIX = ( # Extra keys emit_metrics appends to every row this invocation emits. _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",) -# The launcher's slow interpreter probes, if any. After everything else. +# The launcher's slow interpreter probes, if any. After the keys above. _LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics() # Reviewer context diagnostics from llm.agentic_review, most useful first. _REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls") +# How much work the agentic reviewer did, from llm.agentic_review: turns, and +# time waiting on the model. They tell more turns from slower turns when +# review_ms moves. +_REVIEWER_EFFORT_KEYS = ("rv_turns", "rv_api_ms") +# A clean commit review row has one free key under CC's key cap once +# rv_tool_calls is on it, so the two are sent as one number: +# rv_effort = rv_turns * _EFFORT_TURNS_UNIT + rv_api_ms (capped below the unit) +_EFFORT_TURNS_UNIT = 10_000_000 +# The packed value queued for this row. Emitted after every other key, the +# launcher's included, so it never displaces one at the cap. +_REVIEWER_EFFORT_METRICS: Dict[str, Any] = {} def _note_reviewer_context(agentic_metrics): - """Queue the agentic reviewer's context diagnostics for this row.""" + """Queue the agentic reviewer's context and effort diagnostics for this row.""" for key in _REVIEWER_CONTEXT_KEYS: if agentic_metrics.get(key): _TAIL_METRICS[key] = agentic_metrics[key] + turns = agentic_metrics.get("rv_turns") or 0 + api_ms = agentic_metrics.get("rv_api_ms") or 0 + if turns or api_ms: + _REVIEWER_EFFORT_METRICS["rv_effort"] = ( + turns * _EFFORT_TURNS_UNIT + min(api_ms, _EFFORT_TURNS_UNIT - 1)) def emit_metrics( @@ -304,6 +326,12 @@ def emit_metrics( head["launcher_fallback"] = 1 usage = _usage_metrics() head.update(usage) + # Why the last call got no HTTP response (api_error -1 says only that it + # did not). Ahead of the row's own keys: on a failed review this is the + # key that says what failed, so it is not the one to lose to the key cap. + net_err = _net_error_metric() + if net_err: + head["net_err"] = net_err if head: metrics = {**head, **metrics} # Diagnostic keys go last, so they are the first dropped when a row is @@ -324,7 +352,11 @@ def emit_metrics( # managed-mcp.json) and the review was started again without it. tail["strict_mcp_off"] = 1 tail.update(_TAIL_METRICS) + for k in _LAST_METRIC_KEYS: + if k in tail: + tail[k] = tail.pop(k) tail.update(_LAUNCHER_METRICS) + tail.update(_REVIEWER_EFFORT_METRICS) metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} out = {"metrics": metrics} if rewake_summary: @@ -680,6 +712,31 @@ def _store_baseline_fail(state, fail): state.pop("baseline_fail", None) +# A prompt waits for this hook, so one this slow is worth a metrics row. Faster +# prompts send none: the row would be one more event per prompt for every user. +SLOW_PROMPT_MS = 1000 + + +def _slow_prompt_metrics(cwd, total, baseline, untracked, captured, baseline_fail): + """The metrics row for a slow prompt. Times are seconds, spent in + handle_user_prompt_submit (the launcher reports its own). Counts and flags + only, never a path. Telemetry only.""" + metrics = { + "ups_ms": int(total * 1000), + "ups_baseline_ms": int(baseline * 1000), + "ups_untracked_ms": int(untracked * 1000), + } + if diffstate.last_index_entries is not None: + metrics["ups_index_entries"] = diffstate.last_index_entries + if on_windows_drive(cwd): + metrics["ups_wsl_drive"] = 1 + if not captured: + metrics["ups_no_baseline"] = 1 + if baseline_fail: + metrics["ups_baseline_fail"] = baseline_fail + return metrics + + def handle_user_prompt_submit(input_data): """ Handle UserPromptSubmit — capture git baseline SHA. @@ -692,6 +749,8 @@ def handle_user_prompt_submit(input_data): to be lost when the wipe landed before Stop's state read. """ + import time as _time + started = _time.monotonic() cwd = input_data.get("cwd", "") if not cwd: debug_log("UPS: no cwd, skipping baseline capture") @@ -704,17 +763,25 @@ def handle_user_prompt_submit(input_data): # nothing, so only the stash baseline (still read by the Write pattern # filter) is captured. snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW + spent = {"baseline": 0.0, "untracked": 0.0} + + def _timed(key, fn, repo_cwd): + began = _time.monotonic() + try: + return fn(repo_cwd) + finally: + spent[key] += _time.monotonic() - began def _capture(repo_cwd): if not snapshot_untracked: - return capture_git_baseline(repo_cwd), None + return _timed("baseline", capture_git_baseline, repo_cwd), None # stash-create and ls-files both walk the worktree (~2-5s each in a # very large repo). Run them concurrently so UPS latency stays # ≈ max(both). import concurrent.futures as _cf with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, repo_cwd) - _f_ut = _ex.submit(_list_untracked, repo_cwd) + _f_sha = _ex.submit(_timed, "baseline", capture_git_baseline, repo_cwd) + _f_ut = _ex.submit(_timed, "untracked", _list_untracked, repo_cwd) # Taken whether or not the stash produced a SHA. `git stash # create` returns empty when there are no TRACKED changes, but # pre-existing untracked files still need to be excluded from the @@ -723,7 +790,6 @@ def handle_user_prompt_submit(input_data): # something tracked is dirtied. return _f_sha.result(), _f_ut.result() or {} - import time as _time captured_at = _time.time() sha, untracked_now = _capture(cwd) # No repo here and none remembered: the listing above failed, it did not @@ -813,6 +879,13 @@ def handle_user_prompt_submit(input_data): debug_log(f"Failed to capture git baseline (cwd={cwd!r}) — not a git repo, " f"or git invocation failed (check log entries above)") + total = _time.monotonic() - started + debug_log(f"UPS: took {total:.2f}s (baseline {spent['baseline']:.2f}s, " + f"untracked {spent['untracked']:.2f}s)") + if (total * 1000 >= SLOW_PROMPT_MS or _LAUNCHER_METRICS) and not portable_output(): + emit_metrics(_slow_prompt_metrics( + cwd, total, spent["baseline"], spent["untracked"], bool(sha), baseline_fail)) + sys.exit(0) def _resolve_amend_pre_sha(repo_root, expected_post_sha=None): @@ -1284,10 +1357,11 @@ def _agentic_review_with_race( _th.Thread(target=_fallback, daemon=True).start() winner, (g, v, m) = q.get() - # What the agentic run saw of its directory is kept when the fallback's - # result replaces it below. + # What the agentic run saw of its directory, and how much work it did, + # is kept when the fallback's result replaces it below. reviewer_context = ( - {k: m[k] for k in _REVIEWER_CONTEXT_KEYS if k in m} if winner == "agentic" else {} + {k: m[k] for k in _REVIEWER_CONTEXT_KEYS + _REVIEWER_EFFORT_KEYS if k in m} + if winner == "agentic" else {} ) if winner == "agentic" and m.get("agentic_fallback") and fallback_started.is_set(): # The caller would rerun the single-shot review the fallback has @@ -1760,6 +1834,10 @@ def handle_commit_review_posttooluse(input_data): # Tell a push review (or the next commit's reflog scan) that these commits # are being reviewed, so it does not start a second review of them. _mark_inflight(repo_root, _full_shas(repo_root, shas)) + # Count only: keyed on what the reviewer is sent, after the byte caps. + _diff_token, _seen_m = _diff_review_started( + repo_root, _cap_files_for_prompt(diff_files), tip=shas[0]) + _TAIL_METRICS.update(_seen_m) review_start = _time.time() @@ -1863,6 +1941,7 @@ def handle_commit_review_posttooluse(input_data): _append_reviewed_shas(repo_root, full_shas, vulns_found=len(vulns or [])) except Exception: pass + _diff_review_done(_diff_token) if not concrete_guidance: debug_log("Commit review: no security issues found") @@ -2190,6 +2269,9 @@ def handle_push_sweep_posttooluse(input_data): sys.exit(0) _mark_inflight(repo_root, tail) + _diff_token, _seen_m = _diff_review_started( + repo_root, _cap_files_for_prompt(diff_files)) + _TAIL_METRICS.update(_seen_m) import time as _time now = _time.time() @@ -2235,6 +2317,7 @@ def handle_push_sweep_posttooluse(input_data): # The tail is now covered by this net-diff review. _append_reviewed_shas(repo_root, tail, vulns_found=len(vulns or [])) + _diff_review_done(_diff_token) new_vulns, n_deduped = _dedup_against_state( session_id, vulns or [], prompted=_finding_keys(previous_findings) @@ -2547,9 +2630,11 @@ def handle_stop_hook(input_data): debug_log(f"Stop hook: diff against {content_base[:12]} failed — falling back to {diff_base}") diff_output = get_git_diff(repo_root, diff_base, full_context=False, paths=review_paths, untracked_paths=untracked) - # Only when it happened: MiB of git diff output read, reviewable files - # whose diff was cut while reading it, diffs that hit the timeout. - for _k, _v in (("diff_mb", gitutil._diff_read["bytes"] >> 20), + # Only when it happened: a failed `git add -N` (first, so a row at CC's key + # cap keeps it), MiB of git diff output read, reviewable files whose diff + # was cut while reading it, diffs that hit the timeout. + for _k, _v in (("add_fail", gitutil._add_failed["code"]), + ("diff_mb", gitutil._diff_read["bytes"] >> 20), ("diff_cut_files", gitutil._diff_read["cut_files"]), ("diff_timeout", gitutil._diff_read["timeouts"])): if _v: diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index 84bf1788..b0df08de 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -68,6 +68,15 @@ VULN_PY = ( ) +@pytest.fixture(autouse=True) +def _no_net_err_from_an_earlier_test(): + """A hook is one process per event; tests that call it in-process share + the module's record of the last failed call.""" + import _base + _base._USAGE["net_err"] = 0 + yield + + @pytest.fixture def workspace(tmp_path): ws = tmp_path / "ws" diff --git a/plugins/security-guidance/tests/test_add_failure_metric.py b/plugins/security-guidance/tests/test_add_failure_metric.py new file mode 100644 index 00000000..3a86a8ac --- /dev/null +++ b/plugins/security-guidance/tests/test_add_failure_metric.py @@ -0,0 +1,143 @@ +"""A failed `git add --intent-to-add` leaves new files out of the Stop review's +diff. The review goes on as before; the Stop row says that it happened.""" +import os +import subprocess +import tempfile +from types import SimpleNamespace + +import pytest + +from conftest import ( + GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload, + ups_payload, +) + +import gitutil + + +def _cannot_write_read_only_dirs(): + with tempfile.TemporaryDirectory() as d: + os.chmod(d, 0o555) + try: + return not os.access(d, os.W_OK) + finally: + os.chmod(d, 0o755) + + +@pytest.fixture +def read_only_objects(): + made = [] + + def lock(repo): + made.append(repo / ".git" / "objects") + subprocess.run(["chmod", "-R", "a-w", str(made[-1])], check=True) + + yield lock + for objects in made: + subprocess.run(["chmod", "-R", "u+w", str(objects)], check=True) + + +@pytest.mark.skipif(os.name == "nt" or not _cannot_write_read_only_dirs(), + reason="needs a user that file permissions apply to") +class TestObjectStoreNotWritable: + def test_turn_that_only_adds_a_file(self, tmp_path, hook_env, stub_api, read_only_objects): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + read_only_objects(repo) + run_hook(ups_payload(repo), hook_env) + (repo / "handlers.py").write_text(VULN_PY) + m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) + assert m["skip_reason"] == 6, m + assert m["review_set_count"] == 1 + assert m["add_fail"] == 100001 + assert not stub_api.calls + + def test_tracked_edit_is_still_reviewed(self, tmp_path, hook_env, stub_api, read_only_objects): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + read_only_objects(repo) + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + (repo / "a.py").write_text("print('a')\n") + (repo / "b.py").write_text("print('b')\n") + m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) + assert not m.get("skipped"), m + assert m["files_reviewed"] == 1 + assert m["add_fail"] == 100002 + + +class TestStopRow: + def test_other_git_error(self, tmp_path, hook_env, stub_api): + # git refuses --literal-pathspecs together with a user's icase setting. + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + env = {**hook_env, "GIT_ICASE_PATHSPECS": "1"} + run_hook(ups_payload(repo), env) + (repo / "handlers.py").write_text(VULN_PY) + m = metrics_of(run_hook(stop_payload(repo), env)[1]) + assert m["skip_reason"] == 6, m + assert m["add_fail"] == 200001 + + def test_add_that_works_reports_nothing(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + run_hook(ups_payload(repo), hook_env) + (repo / "handlers.py").write_text(VULN_PY) + m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) + assert m["files_reviewed"] == 1 + assert "add_fail" not in m + + +class TestGetGitDiff: + @pytest.fixture(autouse=True) + def _env(self, tmp_path, monkeypatch): + d = tmp_path / "tmproot" + d.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(d)) + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + yield + gitutil._add_failed["code"] = 0 + + @pytest.fixture + def repo(self, tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + (repo / "new.py").write_text("print('new')\n") + return repo + + def _adds_fail_with(self, monkeypatch, outcome): + real = gitutil._run_git_on_review_paths + + def run(args, paths, timeout, **kwargs): + if args[0] != "add": + return real(args, paths, timeout, **kwargs) + if isinstance(outcome, Exception): + raise outcome + return outcome + + monkeypatch.setattr(gitutil, "_run_git_on_review_paths", run) + + def test_any_failed_batch_counts(self, repo, monkeypatch): + self._adds_fail_with(monkeypatch, [ + SimpleNamespace(returncode=0, stderr=b""), + SimpleNamespace(returncode=128, stderr=b"fatal: nope"), + ]) + gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + assert gitutil._add_failed["code"] == 200001 + + def test_timeout_counts_and_still_gives_no_diff(self, repo, monkeypatch): + self._adds_fail_with(monkeypatch, subprocess.TimeoutExpired("git", 10)) + assert gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) is None + assert gitutil._add_failed["code"] == 300001 + + def test_object_store_refusal(self, repo, monkeypatch): + self._adds_fail_with(monkeypatch, [SimpleNamespace( + returncode=128, + stderr=b"fatal: cannot create an empty blob in the object database")]) + gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + assert gitutil._add_failed["code"] == 100001 + + def test_a_later_add_that_works_keeps_the_failure(self, repo, monkeypatch): + gitutil._add_failed["code"] = 300001 + gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + assert gitutil._add_failed["code"] == 300001 diff --git a/plugins/security-guidance/tests/test_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py index 4e00c608..4c339a5f 100644 --- a/plugins/security-guidance/tests/test_inflight_reviews.py +++ b/plugins/security-guidance/tests/test_inflight_reviews.py @@ -14,12 +14,15 @@ from conftest import ( import diffstate -pytest.importorskip("fcntl") +_HOOKS_DIR = os.path.dirname(diffstate.__file__) +# Locks the way a review does on this platform: flock, or LockFileEx on Windows. _HOLD = ( - "import fcntl, os, sys, time\n" + "import os, sys, time\n" + "sys.path.insert(0, sys.argv[3])\n" + "import diffstate\n" "fd = os.open(sys.argv[1], os.O_RDWR | os.O_CREAT, 0o600)\n" - "fcntl.flock(fd, fcntl.LOCK_EX)\n" + "assert diffstate._flock_nb(fd, exclusive=True)\n" "print('held', flush=True)\n" "time.sleep(float(sys.argv[2]))\n" ) @@ -29,8 +32,9 @@ _HOLD = ( def _held_by_another_review(repo, sha, seconds=60): """A marker on `sha` that a live process holds, as a running review does.""" marker = repo / ".git" / f"sg-inflight-{sha}" - p = subprocess.Popen([sys.executable, "-c", _HOLD, str(marker), str(seconds)], - stdout=subprocess.PIPE, text=True) + p = subprocess.Popen( + [sys.executable, "-c", _HOLD, str(marker), str(seconds), _HOOKS_DIR], + stdout=subprocess.PIPE, text=True) try: assert p.stdout.readline().strip() == "held" yield marker @@ -238,7 +242,7 @@ def test_own_marker_is_held_until_released(tmp_path): "print(sorted(diffstate._load_inflight_shas(sys.argv[2], [sys.argv[3]])))" ) seen = subprocess.run( - [sys.executable, "-c", probe, os.path.dirname(diffstate.__file__), str(repo), sha], + [sys.executable, "-c", probe, _HOOKS_DIR, str(repo), sha], capture_output=True, text=True).stdout.strip() assert seen == str([sha]) reviewed, waited = diffstate._reviewed_after_inflight(str(repo), [sha], 5) @@ -246,3 +250,129 @@ def test_own_marker_is_held_until_released(tmp_path): finally: diffstate._release_inflight() assert not marker.exists() + + +def test_marker_is_closed_before_it_is_deleted_where_open_files_cannot_be(tmp_path, monkeypatch): + # The order used on Windows, where deleting an open file is refused. + repo = make_repo(tmp_path / "repo") + sha = git(repo, "rev-parse", "HEAD").strip() + marker = repo / ".git" / f"sg-inflight-{sha}" + monkeypatch.setattr(diffstate, "_UNLINK_BEFORE_CLOSE", False) + open_at_delete, refusals = [], [2] + + def delete_like_windows(p, fd): + try: + os.fstat(fd) + open_at_delete.append(True) + except OSError: + open_at_delete.append(False) + if refusals[0]: + # Another review asking about the marker has it open just now. + refusals[0] -= 1 + raise PermissionError(13, "The process cannot access the file") + real_unlink(p) + + real_unlink = os.unlink + try: + diffstate._mark_inflight(str(repo), [sha]) + (fd,) = diffstate._inflight_held.values() + monkeypatch.setattr(diffstate.os, "unlink", lambda p: delete_like_windows(p, fd)) + diffstate._release_inflight() + finally: + monkeypatch.setattr(diffstate.os, "unlink", real_unlink) + diffstate._release_inflight() + assert open_at_delete == [False, False, False] and not marker.exists() + + # An old leftover goes the same way. + marker.write_text("") + old = time.time() - diffstate._INFLIGHT_GC_AGE_S - 5 + os.utime(marker, (old, old)) + diffstate._mark_inflight(str(repo), []) + assert not marker.exists() + + +def test_no_markers_in_a_python_without_file_locks(tmp_path, monkeypatch): + if os.name == "nt": + pytest.skip("Windows locks with LockFileEx") + repo = make_repo(tmp_path / "repo") + sha = git(repo, "rev-parse", "HEAD").strip() + monkeypatch.setitem(sys.modules, "fcntl", None) + diffstate._mark_inflight(str(repo), [sha]) + assert _markers(repo) == [] and diffstate._inflight_held == {} + (repo / ".git" / f"sg-inflight-{sha}").write_text("") + assert diffstate._load_inflight_shas(str(repo), [sha]) == set() + + +def test_one_marker_that_cannot_be_claimed_does_not_stop_the_others(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo") + first = git(repo, "rev-parse", "HEAD").strip() + second, _ = commit_file(repo, "b.py", "b = 1\n") + third, _ = commit_file(repo, "c.py", "c = 1\n") + # Cannot be opened at all. + (repo / ".git" / f"sg-inflight-{first}").mkdir() + # Its last holder deletes it between this review's open and its lock. + real_flock_nb = diffstate._flock_nb + + def holder_ends_first(fd, exclusive): + taken = real_flock_nb(fd, exclusive) + gone = repo / ".git" / f"sg-inflight-{second}" + if gone.exists() and os.name != "nt": + gone.unlink() + return taken + monkeypatch.setattr(diffstate, "_flock_nb", holder_ends_first) + try: + diffstate._mark_inflight(str(repo), [first, second, third]) + held = [os.path.basename(p) for p in diffstate._inflight_held] + assert f"sg-inflight-{third}" in held and f"sg-inflight-{first}" not in held + if os.name != "nt": + assert held == [f"sg-inflight-{third}"] + finally: + diffstate._release_inflight() + + +class _FakeKernel32: + """LockFileEx as kernel32 has it, for the code path only Windows runs.""" + + def __init__(self): + self.calls, self.result, self.error = [], 1, 0 + + def LockFileEx(handle, flags, reserved, low, high, overlapped): + ov = overlapped._obj + self.calls.append((handle, flags, low, high, ov.Offset, ov.OffsetHigh)) + return self.result + self.LockFileEx = LockFileEx + + +@pytest.fixture +def kernel32(monkeypatch): + import ctypes + import types + fake = _FakeKernel32() + monkeypatch.setattr(ctypes, "WinDLL", lambda name, use_last_error=False: fake, raising=False) + monkeypatch.setattr(ctypes, "get_last_error", lambda: fake.error, raising=False) + monkeypatch.setitem(sys.modules, "msvcrt", + types.SimpleNamespace(get_osfhandle=lambda fd: 1000 + fd)) + monkeypatch.setattr(diffstate, "_win_lock_file_ex", None) + return fake + + +def test_windows_lock_call(kernel32): + assert diffstate._win_lock_nb(7, exclusive=True) is True + assert diffstate._win_lock_nb(7, exclusive=False) is True + # Fail-immediately, exclusive or shared, one byte far past the end of the + # file so that reading the marker is never refused. + assert kernel32.calls == [(1007, 0x3, 1, 0, 0, 0x7FFFFFFF), (1007, 0x1, 1, 0, 0, 0x7FFFFFFF)] + kernel32.result, kernel32.error = 0, 33 + assert diffstate._win_lock_nb(7, exclusive=True) is False + for other_error in (5, 6, 997): + kernel32.error = other_error + with pytest.raises(OSError): + diffstate._win_lock_nb(7, exclusive=True) + + +def test_windows_lock_is_off_where_the_call_is_missing(monkeypatch): + import ctypes + monkeypatch.delattr(ctypes, "WinDLL", raising=False) + monkeypatch.setattr(diffstate, "_win_lock_file_ex", None) + with pytest.raises(OSError): + diffstate._win_lock_nb(7, exclusive=True) diff --git a/plugins/security-guidance/tests/test_network_failure_class.py b/plugins/security-guidance/tests/test_network_failure_class.py new file mode 100644 index 00000000..896a251f --- /dev/null +++ b/plugins/security-guidance/tests/test_network_failure_class.py @@ -0,0 +1,356 @@ +"""A call that got no HTTP response reports why, as `net_err`.""" +import asyncio +import errno +import http.client +import socket +import ssl +import sys +import types +import urllib.error + +import pytest + +from conftest import VULN_PY, metrics_of, run_hook, stop_payload, ups_payload + +import _base +import llm +import security_reminder_hook as hook + + +def _cert_error(code): + e = ssl.SSLCertVerificationError(1, "certificate verify failed") + e.verify_code = code + return e + + +class TestClass: + @pytest.mark.parametrize("exc, expected", [ + (urllib.error.URLError(_cert_error(20)), (llm.NET_ERR_CERT_VERIFY, 20)), + (urllib.error.URLError(_cert_error(19)), (llm.NET_ERR_CERT_VERIFY, 19)), + (urllib.error.URLError(_cert_error(0)), (llm.NET_ERR_CERT_VERIFY, 0)), + (urllib.error.URLError(ssl.SSLError(1, "wrong version number")), (llm.NET_ERR_TLS, 0)), + # A default context that cannot be built is raised bare, before any connection. + (ssl.SSLError(1, "[ASN1] nested asn1 error"), (llm.NET_ERR_TLS, 0)), + (urllib.error.URLError(socket.gaierror(-2, "Name or service not known")), (llm.NET_ERR_DNS, 0)), + (urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")), (llm.NET_ERR_CONNECT, 0)), + (urllib.error.URLError(OSError(errno.ENETUNREACH, "unreachable")), (llm.NET_ERR_CONNECT, 0)), + (http.client.RemoteDisconnected("closed without response"), (llm.NET_ERR_CONNECT, 0)), + (TimeoutError("The read operation timed out"), (llm.NET_ERR_TIMEOUT, 0)), + (urllib.error.URLError(socket.timeout("timed out")), (llm.NET_ERR_TIMEOUT, 0)), + (urllib.error.URLError(OSError("Tunnel connection failed: 403 Forbidden")), (llm.NET_ERR_PROXY, 0)), + (urllib.error.URLError(OSError("Tunnel connection failed: 504 Gateway Timed Out")), + (llm.NET_ERR_PROXY, 0)), + (urllib.error.URLError("unknown url type"), (llm.NET_ERR_OTHER, 0)), + (http.client.IncompleteRead(b"x"), (llm.NET_ERR_OTHER, 0)), + (http.client.BadStatusLine("x"), (llm.NET_ERR_OTHER, 0)), + (ValueError("step timed out"), (0, 0)), + (UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid start byte"), (0, 0)), + ]) + def test_class_and_verify_code(self, exc, expected): + assert llm._net_error_class(exc) == expected + + def test_code_packs_class_verify_code_and_flags(self, monkeypatch): + monkeypatch.setattr(llm, "_net_error_flags", lambda tls: 5 if tls else 2) + assert llm._net_error_code(urllib.error.URLError(_cert_error(20))) == 1 + 2000 + 50000 + assert llm._net_error_code(urllib.error.URLError(socket.gaierror(-2, "x"))) == 3 + 20000 + + def test_no_code_and_no_setup_checks_for_an_exception_that_is_not_a_network_failure( + self, monkeypatch): + monkeypatch.setattr(llm, "_net_error_flags", lambda tls: pytest.fail("checked")) + assert llm._net_error_code(ValueError("x")) == 0 + + def test_a_setup_check_that_raises_keeps_the_class(self, monkeypatch): + def boom(tls): + raise RuntimeError("x") + monkeypatch.setattr(llm, "_net_error_flags", boom) + assert llm._net_error_code(urllib.error.URLError(_cert_error(20))) == 2001 + + +class TestFlags: + @pytest.fixture(autouse=True) + def _clean(self, monkeypatch, tmp_path): + for name in ("NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "SSL_CERT_DIR"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://api.example.com") + monkeypatch.setattr(llm.urllib.request, "getproxies", lambda: {}) + monkeypatch.setattr(llm.sys, "platform", "darwin") + self.cafile = tmp_path / "cert.pem" + self.cafile.write_text("-----BEGIN CERTIFICATE-----\n") + self.capath = tmp_path / "certs" + self.capath.mkdir() + + def _paths(self, monkeypatch, cafile, capath): + monkeypatch.setattr(ssl, "get_default_verify_paths", lambda: ssl.DefaultVerifyPaths( + cafile, capath, "SSL_CERT_FILE", str(self.cafile), "SSL_CERT_DIR", str(self.capath))) + + def test_no_ca_file_and_an_empty_directory(self, monkeypatch): + self._paths(monkeypatch, None, str(self.capath)) + assert llm._net_error_flags(True) == 1 + self._paths(monkeypatch, None, None) + assert llm._net_error_flags(True) == 1 + + def test_an_empty_ca_file_counts_as_none(self, monkeypatch): + self.cafile.write_text("") + self._paths(monkeypatch, str(self.cafile), None) + assert llm._net_error_flags(True) == 1 + + def test_a_ca_file_or_a_filled_directory_is_not_flagged(self, monkeypatch): + self._paths(monkeypatch, str(self.cafile), str(self.capath)) + assert llm._net_error_flags(True) == 0 + (self.capath / "0a1b2c3d.0").write_text("x") + self._paths(monkeypatch, None, str(self.capath)) + assert llm._net_error_flags(True) == 0 + + def test_windows_is_not_flagged_for_its_files(self, monkeypatch): + monkeypatch.setattr(llm.sys, "platform", "win32") + self._paths(monkeypatch, None, None) + assert llm._net_error_flags(True) == 0 + + def test_tls_variables(self, monkeypatch): + self._paths(monkeypatch, str(self.cafile), None) + monkeypatch.setenv("NODE_EXTRA_CA_CERTS", "/x/ca.pem") + assert llm._net_error_flags(True) == 4 + monkeypatch.setenv("SSL_CERT_DIR", "/x") + assert llm._net_error_flags(True) == 12 + # Not read for a failure that is not about TLS. + assert llm._net_error_flags(False) == 0 + + def test_proxy_for_the_url_scheme(self, monkeypatch): + monkeypatch.setattr(llm.urllib.request, "proxy_bypass", lambda host: False) + monkeypatch.setattr(llm.urllib.request, "getproxies", lambda: {"https": "http://proxy:8080"}) + assert llm._net_error_flags(False) == 2 + monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://gateway.internal:4000") + assert llm._net_error_flags(False) == 0 + monkeypatch.setattr(llm.urllib.request, "getproxies", lambda: {"http": "http://proxy:8080"}) + assert llm._net_error_flags(False) == 2 + + def test_proxy_bypass_is_asked_with_the_port(self, monkeypatch): + asked = [] + monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://gw.internal:8443/base") + monkeypatch.setattr(llm.urllib.request, "getproxies", lambda: {"https": "http://proxy:8080"}) + monkeypatch.setattr(llm.urllib.request, "proxy_bypass", lambda host: asked.append(host) or True) + assert llm._net_error_flags(False) == 0 + assert asked == ["gw.internal:8443"] + + +@pytest.fixture +def direct(monkeypatch, tmp_path): + """In-process calls with a credential, no real state dir, no model + lookup, no waiting between retries and a plain machine setup.""" + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + for var in llm._PROVIDER_ENV_VARS: + monkeypatch.delenv(var, raising=False) + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) + monkeypatch.setattr(llm, "ANTHROPIC_API_KEY", "k") + monkeypatch.setattr(llm, "default_review_model", lambda: "claude-opus-5-5") + monkeypatch.setattr(llm, "debug_log", lambda *a, **k: None) + monkeypatch.setattr(llm, "_net_error_flags", lambda tls: 0) + monkeypatch.setattr("time.sleep", lambda s: None) + monkeypatch.setitem(_base._USAGE, "http_err_count", 0) + monkeypatch.setitem(_base._USAGE, "http_err_last", 0) + + +class _Reply: + def __init__(self, text): + self._body = ('{"content": [{"type": "text", "text": %s}], "usage": {}}' + % __import__("json").dumps(text)).encode() + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def read(self): + return self._body + + +class TestRecorded: + def _urlopen(self, monkeypatch, *outcomes): + """Each call takes the next outcome (the last one repeats): an + exception is raised, anything else is the reply text.""" + calls = [] + + def urlopen(*a, **k): + outcome = outcomes[min(len(calls), len(outcomes) - 1)] + calls.append(outcome) + if isinstance(outcome, BaseException): + raise outcome + return _Reply(outcome) + monkeypatch.setattr(llm.urllib.request, "urlopen", urlopen) + return calls + + def test_call_that_never_connects(self, direct, monkeypatch): + self._urlopen(monkeypatch, urllib.error.URLError(_cert_error(20))) + assert llm._call_claude("p", {"type": "object"}, model="m") is None + assert llm._last_call_claude_http_error == -1 + assert _base._net_error_metric() == 2001 + + def test_http_error_records_nothing(self, direct, monkeypatch): + self._urlopen(monkeypatch, urllib.error.HTTPError("u", 400, "bad", {}, None)) + assert llm._call_claude("p", {"type": "object"}, model="m") is None + assert llm._last_call_claude_http_error == 400 + assert _base._net_error_metric() == 0 + + def test_a_later_call_that_gets_a_response_clears_it(self, direct, monkeypatch): + refused = urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) + self._urlopen(monkeypatch, refused, refused, refused, '{"ok": true}') + assert llm._call_claude("p", {"type": "object"}, model="m") is None + assert _base._net_error_metric() == llm.NET_ERR_CONNECT + assert llm._call_claude("p", {"type": "object"}, model="fallback") == {"ok": True} + assert _base._net_error_metric() == 0 + + def test_a_later_call_refused_with_a_status_clears_it(self, direct, monkeypatch): + refused = urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) + self._urlopen(monkeypatch, refused, refused, refused, + urllib.error.HTTPError("u", 400, "bad", {}, None)) + llm._call_claude("p", {"type": "object"}, model="m") + llm._call_claude("p", {"type": "object"}, model="fallback") + assert llm._last_call_claude_http_error == 400 + assert _base._net_error_metric() == 0 + + def test_tls_context_that_cannot_be_built(self, direct, monkeypatch): + """Raised bare by the HTTP client, so the review sees an exception + and no api_error.""" + self._urlopen(monkeypatch, ssl.SSLError(1, "[ASN1] nested asn1 error")) + assert llm.analyze_code_security([("a.py", "+x = 1\n")]) == (None, []) + assert llm.last_review_failed() and llm.last_review_status() is None + assert _base._net_error_metric() == llm.NET_ERR_TLS + + def test_failure_on_the_windows_store_context_is_recorded(self, direct, monkeypatch): + """The context built for a Windows store with an unreadable entry is + the one the call uses, and a failure on it is still classified.""" + context = ssl.create_default_context() + monkeypatch.setattr(llm, "_store_tls_context", context) + used = [] + + def urlopen(*a, **k): + used.append(k.get("context")) + raise urllib.error.URLError(_cert_error(20)) + monkeypatch.setattr(llm.urllib.request, "urlopen", urlopen) + assert llm._call_claude("p", {"type": "object"}, model="m") is None + assert used and all(c is context for c in used) + assert _base._net_error_metric() == 2001 + + def test_store_check_that_fails_is_recorded_as_tls(self, direct, monkeypatch): + """The store check raises and Python's own default context cannot be + built either: the call raises past the retry loop.""" + def check(): + raise ssl.SSLError(1, "[ASN1] nested asn1 error") + monkeypatch.setattr(llm, "_store_tls_context", llm._STORE_TLS_UNSET) + monkeypatch.setattr(llm, "_context_without_unreadable_store_certs", check) + self._urlopen(monkeypatch, ssl.SSLError(1, "[ASN1] nested asn1 error")) + assert llm.analyze_code_security([("a.py", "+x = 1\n")]) == (None, []) + assert llm.last_review_failed() + assert _base._net_error_metric() == llm.NET_ERR_TLS + + def test_reply_that_is_not_json_records_nothing(self, direct, monkeypatch): + self._urlopen(monkeypatch, "<html>sign in</html>") + assert llm.analyze_code_security([("a.py", "+x = 1\n")]) == (None, []) + assert llm.last_review_failed() + assert _base._net_error_metric() == 0 + + def test_only_a_positive_code_is_kept(self): + _base._record_net_error(None) + _base._record_net_error(0) + assert _base._net_error_metric() == 0 + _base._record_net_error(4) + _base._record_net_error(20003) + assert _base._net_error_metric() == 20003 + + def test_probe_that_cannot_connect(self, direct, monkeypatch): + self._urlopen(monkeypatch, urllib.error.URLError(socket.gaierror(-2, "x"))) + assert llm._probe_anthropic() is False + assert _base._net_error_metric() == llm.NET_ERR_DNS + + +class TestInnerCli: + @pytest.fixture + def sdk(self, direct, monkeypatch): + mod = types.ModuleType("claude_agent_sdk") + for name in ("AssistantMessage", "ClaudeAgentOptions", "ResultMessage"): + setattr(mod, name, type(name, (), {"__init__": lambda self, **k: None})) + mod.query = None + monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) + monkeypatch.setattr(llm, "_send_sdk_logs_to_debug_log", lambda: None) + return mod + + def _run(self, monkeypatch, exc): + def run(start, stderr_lines): + raise exc + monkeypatch.setattr(llm, "_run_inner_cli", run) + assert llm._call_claude_via_sdk("p", {"type": "object"}) is None + assert llm._last_call_claude_http_error == -1 + return _base._net_error_metric() + + def test_cli_failed(self, sdk, monkeypatch): + assert self._run(monkeypatch, RuntimeError("exit code 1")) == llm.NET_ERR_INNER_CLI + + def test_cli_timed_out(self, sdk, monkeypatch): + assert self._run(monkeypatch, asyncio.TimeoutError()) == llm.NET_ERR_INNER_CLI_TIMEOUT + + def test_no_sdk(self, direct, monkeypatch): + monkeypatch.setitem(sys.modules, "claude_agent_sdk", None) + monkeypatch.setattr(llm, "_inject_agent_sdk_venv_into_syspath", lambda d: None) + assert llm._call_claude_via_sdk("p", {"type": "object"}) is None + assert _base._net_error_metric() == llm.NET_ERR_NO_SDK + + +class TestEmittedRow: + @pytest.fixture(autouse=True) + def _clean(self, monkeypatch): + monkeypatch.setattr(hook, "_TAIL_METRICS", {}) + monkeypatch.setattr(hook, "_log_usage", lambda usage: None) + monkeypatch.setattr(hook.llm, "gateway_cfg", lambda: 0) + + def _row(self, capsys): + return __import__("json").loads(capsys.readouterr().out)["metrics"] + + def test_ahead_of_the_rows_own_keys(self, capsys, monkeypatch): + monkeypatch.setitem(_base._USAGE, "http_err_count", 2) + monkeypatch.setitem(_base._USAGE, "http_err_last", -1) + _base._record_net_error(2001) + hook.emit_metrics({"review_failed": True, "vulns_found": 0, "review_ms": 18000, + "api_error": -1}) + keys = list(self._row(capsys)) + at = keys.index("net_err") + assert keys[at - 1] == "http_err_count" and keys[at + 1] == "review_failed" + + def test_kept_on_a_row_over_the_key_cap(self, capsys): + _base._record_net_error(2001) + hook.emit_metrics({f"k{i}": i for i in range(25)}) + assert "net_err" in list(self._row(capsys))[:20] + + def test_absent_without_a_failure(self, capsys): + hook.emit_metrics({"vulns_found": 0, "review_ms": 10}) + assert "net_err" not in self._row(capsys) + + +def _free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def test_stop_review_that_cannot_connect(workspace, hook_env): + """Through the real hook: nothing listens at the endpoint.""" + _, repo = workspace + env = dict(hook_env) + env["ANTHROPIC_BASE_URL"] = f"http://127.0.0.1:{_free_port()}" + env["SECURITY_REVIEW_MODEL"] = "claude-sonnet-4-6" # one model: one round of retries + run_hook(ups_payload(repo), env) + (repo / "app.py").write_text(VULN_PY) + _, out, _ = run_hook(stop_payload(repo), env) + m = metrics_of(out) + assert m["api_error"] == -1 and m["review_failed"] is True + assert m["net_err"] % 100 == llm.NET_ERR_CONNECT + assert "net_err" in list(m)[:20] + + +def test_stop_review_that_ran_has_no_class(workspace, hook_env): + _, repo = workspace + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + _, out, _ = run_hook(stop_payload(repo), hook_env) + m = metrics_of(out) + assert "review_ms" in m and "net_err" not in m diff --git a/plugins/security-guidance/tests/test_repeated_diff_count.py b/plugins/security-guidance/tests/test_repeated_diff_count.py new file mode 100644 index 00000000..ede4fdcb --- /dev/null +++ b/plugins/security-guidance/tests/test_repeated_diff_count.py @@ -0,0 +1,268 @@ +"""Reviews report whether their diff was reviewed before; nothing is skipped.""" +from conftest import bash_payload, commit_file, git, make_repo, metrics_of, run_hook + +import diffstate + +import pytest + +DIFF = [("handlers.py", "@@ -0,0 +1,2 @@\n+def h(x):\n+ return x")] + + +@pytest.fixture(autouse=True) +def _claude_code_output(monkeypatch): + # diffstate reads the output mode from the test runner's environment. + monkeypatch.setattr(diffstate, "portable_output", lambda: False) + + +def _reviews(stub_api): + return [c for c in stub_api.calls if c.endswith("/v1/messages")] + + +def _records(repo): + p = repo / ".git" / "sg-reviewed-diffs" + return p.read_text().splitlines() if p.exists() else [] + + +def _recommit(repo, msg): + git(repo, "reset", "-q", "--soft", "HEAD~1") + out = git(repo, "commit", "-m", msg) + return git(repo, "rev-parse", "HEAD").strip(), out + + +def _seen(repo, diff=DIFF): + return diffstate._diff_review_started(str(repo), diff) + + +def _finished(repo, diff=DIFF): + token, _ = _seen(repo, diff) + diffstate._diff_review_done(token) + + +def _hunk(start, context, added): + return f"@@ -{start},2 +{start},3 @@ def f():\n {context}\n+{added}\n pass" + + +def test_first_review_of_a_diff_is_not_seen(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + token, m = _seen(repo) + assert m == {"diff_seen": diffstate.DIFF_SEEN_NO} + assert token and len(_records(repo)) == 1 + + +def test_unfinished_then_finished_on_same_then_other_tree(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + token, _ = _seen(repo) + assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_UNFINISHED} + diffstate._diff_review_done(token) + assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_SAME_TREE} + commit_file(repo, "other.py", "x = 1\n") + assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_OTHER_TREE} + + +def test_tree_is_the_reviewed_commits_not_where_head_went(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + sha, _ = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + token, _ = diffstate._diff_review_started(str(repo), DIFF, tip=sha) + diffstate._diff_review_done(token) + git(repo, "reset", "-q", "--hard", "HEAD~1") + assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_OTHER_TREE} + assert diffstate._diff_review_started(str(repo), DIFF, tip=sha)[1] == { + "diff_seen": diffstate.DIFF_SEEN_SAME_TREE} + + +def test_a_different_change_path_or_place_is_not_seen(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + one = [("auth.py", _hunk(3, "def login():", "return True"))] + _finished(repo, one) + for other in ([("auth.py", _hunk(3, "def login():", "return False"))], + [("other.py", one[0][1])], + # The same added line next to different code. + [("auth.py", _hunk(3, "def is_admin():", "return True"))], + one + [("b.py", "@@ -0,0 +1 @@\n+1")]): + assert _seen(repo, other)[1] == {"diff_seen": diffstate.DIFF_SEEN_NO} + + +def test_a_moved_hunk_keeps_its_key(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + _finished(repo, [("auth.py", _hunk(3, "def login():", "return True"))]) + moved = "@@ -40,2 +44,3 @@ class A:\n def login():\n+return True\n pass" + assert _seen(repo, [("auth.py", moved)])[1] == {"diff_seen": diffstate.DIFF_SEEN_SAME_TREE} + + +def test_real_diffs_of_two_commits_match_their_net_diff(tmp_path): + from gitutil import parse_diff_into_files + body = "".join(f"line {i}\n" for i in range(60)) + repo = make_repo(tmp_path / "repo", {"app.py": body}) + base = git(repo, "rev-parse", "HEAD").strip() + commit_file(repo, "app.py", body.replace("line 5\n", "line 5\nx = 1\n")) + _finished(repo, parse_diff_into_files(git(repo, "show", "-p", "HEAD"))) + commit_file(repo, "app.py", body.replace("line 5\n", "line 5\nx = 1\n") + .replace("line 50\n", "line 50\ny = 2\n")) + _finished(repo, parse_diff_into_files(git(repo, "show", "-p", "HEAD"))) + net = parse_diff_into_files(git(repo, "diff", base, "HEAD")) + assert len(diffstate._hunk_keys(net)) == 2 + # Both hunks had a finished review; the first one on an older tree. + assert _seen(repo, net)[1] == {"diff_seen": diffstate.DIFF_SEEN_OTHER_TREE} + + +def test_hunks_past_the_key_cap_are_not_dropped(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + monkeypatch.setattr(diffstate, "_SEEN_DIFFS_MAX_KEYS", 3) + hunks = [_hunk(10 * i, f"def f{i}():", f"x = {i}") for i in range(6)] + _finished(repo, [("app.py", "\n".join(hunks[:5]))]) + assert len(_records(repo)[0].split("\t")[3].split(" ")) == 3 + assert _seen(repo, [("app.py", "\n".join(hunks))])[1] == {"diff_seen": diffstate.DIFF_SEEN_NO} + assert _seen(repo, [("app.py", "\n".join(hunks[:5]))])[1] == { + "diff_seen": diffstate.DIFF_SEEN_SAME_TREE} + + +def test_removed_sql_comment_lines_tell_diffs_apart(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + _finished(repo, [("q.sql", "@@ -1,2 +1 @@\n--- drop table users;\n select 1;")]) + other = [("q.sql", "@@ -1,2 +1 @@\n--- drop table orders;\n select 1;")] + assert _seen(repo, other)[1] == {"diff_seen": diffstate.DIFF_SEEN_NO} + + +def test_commits_reviewed_one_by_one_then_as_one_net_diff(tmp_path): + # Two commit reviews of the same file, then a push review of their net diff. + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + h1, h2 = _hunk(3, "def a():", "x = 1"), _hunk(90, "def z():", "y = 2") + _finished(repo, [("app.py", h1)]) + net = [("app.py", h1 + "\n" + h2), ("b.py", "@@ -0,0 +1 @@\n+b = 2")] + assert _seen(repo, net)[1] == {"diff_seen": diffstate.DIFF_SEEN_NO} + _finished(repo, [("app.py", h2)]) + _finished(repo, [net[1]]) + assert _seen(repo, net)[1] == {"diff_seen": diffstate.DIFF_SEEN_SAME_TREE} + + +def test_old_records_do_not_count(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + _finished(repo) + monkeypatch.setattr(diffstate, "_SEEN_DIFFS_TTL_S", -1) + assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_NO} + + +@pytest.mark.parametrize("flock", [True, False]) +def test_record_is_cut_back_to_its_newest_rows(tmp_path, monkeypatch, flock): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + if not flock: + def no_flock(fd, exclusive): + raise ImportError("fcntl") + monkeypatch.setattr(diffstate, "_flock_nb", no_flock) + _finished(repo) + row = len(_records(repo)[0]) + 1 + monkeypatch.setattr(diffstate, "_SEEN_DIFFS_TRIM_BYTES", 6 * row) + for i in range(12): + _finished(repo, [("f.py", f"@@ -0,0 +1 @@\n+{i}")]) + rows = _records(repo) + assert 3 <= len(rows) <= 6 + assert rows[-1].split("\t")[2:] == ["1", diffstate._hunk_keys([("f.py", "@@ -0,0 +1 @@\n+11")])[0]] + assert _seen(repo, [("f.py", "@@ -0,0 +1 @@\n+11")])[1]["diff_seen"] == diffstate.DIFF_SEEN_SAME_TREE + assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_NO} + + +def test_damaged_record_is_read_around_and_shrinks(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + p = repo / ".git" / "sg-reviewed-diffs" + p.write_bytes(b"\xff\xfe garbage\nshort\tline\n" + b"9" * 5000 + b"\tt\t1\tk\n" + + b"x" * 5000) + monkeypatch.setattr(diffstate, "_SEEN_DIFFS_TRIM_BYTES", 2000) + token, m = _seen(repo) + assert m == {"diff_seen": diffstate.DIFF_SEEN_NO} + diffstate._diff_review_done(token) + assert p.stat().st_size < 2000 + assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_SAME_TREE} + + +def test_a_lock_another_process_keeps_is_not_waited_on(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + token, _ = _seen(repo) + monkeypatch.setattr(diffstate, "_flock_nb", lambda fd, exclusive: False) + monkeypatch.setattr(diffstate, "_SEEN_DIFFS_LOCK_TRIES", 2) + monkeypatch.setattr(diffstate, "_SEEN_DIFFS_TRIM_BYTES", 0) + # A start that cannot read the record under the lock does not guess. + assert _seen(repo) == (None, {"diff_seen": diffstate.DIFF_SEEN_ERROR}) + # A verdict is still noted, and the record is not cut back without the lock. + diffstate._diff_review_done(token) + assert [r.split("\t")[2] for r in _records(repo)] == ["0", "1"] + + +def test_failures_are_reported_and_never_raise(tmp_path): + assert _seen(tmp_path / "nope") == (None, {"diff_seen": diffstate.DIFF_SEEN_ERROR}) + diffstate._diff_review_done(None) + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + (repo / ".git" / "sg-reviewed-diffs").mkdir() + assert _seen(repo) == (None, {"diff_seen": diffstate.DIFF_SEEN_ERROR}) + diffstate._diff_review_done((str(repo / ".git" / "sg-reviewed-diffs"), ["k"], "t")) + + +def test_a_record_that_cannot_be_written_is_an_error_not_unseen(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + def full_disk(f, locked, token, done): + raise OSError(28, "No space left on device") + monkeypatch.setattr(diffstate, "_append_diff_row", full_disk) + assert _seen(repo) == (None, {"diff_seen": diffstate.DIFF_SEEN_ERROR}) + + +def test_nothing_is_recorded_in_portable_output_mode(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + monkeypatch.setattr(diffstate, "portable_output", lambda: True) + assert _seen(repo) == (None, {}) + assert _records(repo) == [] + + +def test_recommit_of_the_same_change_is_reviewed_again_and_counted(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + sha, out = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + rc, so, _ = run_hook(bash_payload(repo, "git commit -m change", out), hook_env) + first = metrics_of(so) + assert rc == 0 and first["diff_seen"] == diffstate.DIFF_SEEN_NO + + sha2, out2 = _recommit(repo, "same change again") + assert sha2 != sha + rc, so, _ = run_hook(bash_payload(repo, "git commit -m 'same change again'", out2), hook_env) + second = metrics_of(so) + assert rc == 0 and second["diff_seen"] == diffstate.DIFF_SEEN_SAME_TREE + # Last in the row, so a row over the key cap loses this and nothing older. + assert list(second)[-1] == "diff_seen" + # Count only: both commits were reviewed and recorded. + assert len(_reviews(stub_api)) == 2 + assert {sha, sha2} <= diffstate._load_reviewed_shas(str(repo)) + + +def test_push_of_a_rebased_reviewed_commit_is_counted(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + 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") + git(repo, "checkout", "-q", "-b", "feat") + sha, out = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + run_hook(bash_payload(repo, "git commit -m change", out), hook_env) + + git(repo, "checkout", "-q", "main") + commit_file(repo, "notes.md", "notes\n") + git(repo, "push", "-q", "origin", "main") + git(repo, "checkout", "-q", "feat") + git(repo, "rebase", "-q", "main") + git(repo, "push", "-q", "-u", "origin", "feat") + push_out = f"To {remote}\n * [new branch] feat -> feat\n" + rc, so, _ = run_hook(bash_payload(repo, "git push -u origin feat", push_out), hook_env) + m = metrics_of(so) + assert rc == 0 and m["push_sweep"] is True and m["unreviewed"] == 1 + assert m["diff_seen"] == diffstate.DIFF_SEEN_OTHER_TREE and list(m)[-1] == "diff_seen" + assert len(_reviews(stub_api)) == 2 + + +def test_failed_review_leaves_the_diff_unfinished(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + sha, out = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + stub_api.status = 500 + rc, so, _ = run_hook(bash_payload(repo, "git commit -m change", out), hook_env) + failed = metrics_of(so) + assert failed["review_failed"] is True and failed["diff_seen"] == diffstate.DIFF_SEEN_NO + + stub_api.status = 200 + sha2, out2 = _recommit(repo, "same change again") + rc, so, _ = run_hook(bash_payload(repo, "git commit -m 'same change again'", out2), hook_env) + assert metrics_of(so)["diff_seen"] == diffstate.DIFF_SEEN_UNFINISHED diff --git a/plugins/security-guidance/tests/test_reviewer_context_metrics.py b/plugins/security-guidance/tests/test_reviewer_context_metrics.py index c0dfb491..99e94dc7 100644 --- a/plugins/security-guidance/tests/test_reviewer_context_metrics.py +++ b/plugins/security-guidance/tests/test_reviewer_context_metrics.py @@ -1,5 +1,6 @@ """The agentic reviewer reports, as counts only, how its Read/Grep/Glob calls -went and whether the directory it ran in was still there.""" +went, whether the directory it ran in was still there, and how many turns and +how much model time the review took.""" import json import os import shutil @@ -27,7 +28,7 @@ def sdk(monkeypatch, tmp_path): """Stand-in for claude_agent_sdk whose reviewer replays `script.messages` and then returns no findings. Like the SDK, it cannot start in a directory that does not exist.""" - script = types.SimpleNamespace(messages=[], before_result=lambda: None) + script = types.SimpleNamespace(messages=[], before_result=lambda: None, result={}) class ClaudeAgentOptions: def __init__(self, **kwargs): @@ -51,7 +52,10 @@ def sdk(monkeypatch, tmp_path): for m in script.messages: yield m script.before_result() - yield ResultMessage() + result = ResultMessage() + for name, value in script.result.items(): + setattr(result, name, value) + yield result mod = types.ModuleType("claude_agent_sdk") mod.ClaudeAgentOptions, mod.ResultMessage, mod.query = ClaudeAgentOptions, ResultMessage, query @@ -122,12 +126,48 @@ class TestAgenticReview: m = _review(tmp_path) assert m["agentic_fallback"].startswith("investigate:") assert (m["rv_tool_calls"], m["rv_tool_err"]) == (1, 1) + assert "rv_turns" not in m and "rv_api_ms" not in m + + def test_turns_and_model_time_come_from_the_result_message(self, sdk, tmp_path): + # One assistant message per content block: three messages, two turns. + sdk.messages = [sdk.assistant(_ToolUse("t1", "Read")), sdk.assistant(_ToolUse("t2", "Grep")), + sdk.user([_ToolResult("t1"), _ToolResult("t2")]), sdk.assistant()] + sdk.result = {"num_turns": 2, "duration_api_ms": 4100, "duration_ms": 9000} + m = _review(tmp_path) + assert (m["rv_turns"], m["rv_api_ms"]) == (2, 4100) + + def test_turns_and_model_time_are_summed_over_stages(self, sdk, tmp_path, monkeypatch): + finding = {"severity": "high", "filePath": "a.py", "category": "xss", "vulnerableCode": "x = 1"} + monkeypatch.setattr(sys.modules["claude_agent_sdk"].ResultMessage, "structured_output", + {"findings": [finding], "verdicts": []}) + sdk.result = {"num_turns": 3, "duration_api_ms": 1000} + m = _review(tmp_path) + # Investigate, the second investigate pass, and refute. + assert (m["rv_turns"], m["rv_api_ms"]) == (9, 3000) + + def test_stage_that_ran_out_of_turns_is_counted(self, sdk, tmp_path): + sdk.result = {"num_turns": 18, "duration_api_ms": 60000, + "subtype": "error_max_turns", "structured_output": None} + m = _review(tmp_path) + assert m["agentic_fallback"] == "investigate:error_max_turns" + assert (m["rv_turns"], m["rv_api_ms"]) == (18, 60000) + + @pytest.mark.parametrize("result", [{}, {"num_turns": None, "duration_api_ms": None}, + {"num_turns": "3", "duration_api_ms": True}, + {"num_turns": -1, "duration_api_ms": 0}, + {"num_turns": float("nan"), "duration_api_ms": float("inf")}]) + def test_missing_or_unusable_result_fields_leave_the_keys_out(self, sdk, tmp_path, result): + sdk.result = result + m = _review(tmp_path) + assert "agentic_fallback" not in m + assert "rv_turns" not in m and "rv_api_ms" not in m class TestEmittedRow: @pytest.fixture(autouse=True) def _clean_tail(self, monkeypatch): monkeypatch.setattr(hook, "_TAIL_METRICS", {}) + monkeypatch.setattr(hook, "_REVIEWER_EFFORT_METRICS", {}) def _row(self, capsys): return json.loads(capsys.readouterr().out)["metrics"] @@ -139,6 +179,50 @@ class TestEmittedRow: keys = list(self._row(capsys)) assert keys[-5:] == ["vulns_found", "review_ms", "rv_cwd_gone", "rv_tool_err", "rv_tool_calls"] + def test_effort_is_one_key_after_every_other_key(self, capsys, monkeypatch): + monkeypatch.setattr(hook, "_LAUNCHER_METRICS", {"launcher_probe_ms": 7000}) + hook._note_reviewer_context({"rv_api_ms": 9100, "rv_turns": 5, "rv_tool_calls": 4}) + hook.emit_metrics({"vulns_found": 0, "review_ms": 9500}) + row = self._row(capsys) + assert list(row)[-3:] == ["rv_tool_calls", "launcher_probe_ms", "rv_effort"] + assert divmod(row["rv_effort"], 10_000_000) == (5, 9100) + assert "rv_turns" not in row and "rv_api_ms" not in row + + @pytest.mark.parametrize("metrics, packed", [ + ({"rv_turns": 3}, (3, 0)), + ({"rv_api_ms": 250}, (0, 250)), + ({"rv_turns": 54, "rv_api_ms": 123_456_789}, (54, 9_999_999)), + ]) + def test_effort_packing(self, capsys, metrics, packed): + hook._note_reviewer_context(metrics) + hook.emit_metrics({"vulns_found": 0}) + assert divmod(self._row(capsys)["rv_effort"], 10_000_000) == packed + + def test_no_effort_key_without_turns_or_model_time(self, capsys): + hook._note_reviewer_context({"rv_tool_calls": 2, "agentic_fallback": "import:ImportError"}) + hook.emit_metrics({"vulns_found": 0}) + assert "rv_effort" not in self._row(capsys) + + def test_effort_does_not_displace_a_key_at_the_cap(self, capsys, monkeypatch): + monkeypatch.setattr(hook, "_LAUNCHER_METRICS", {"launcher_probe_ms": 7000}) + hook._note_reviewer_context({"rv_api_ms": 9100, "rv_turns": 5}) + hook.emit_metrics({f"k{i}": i for i in range(40)}) + keys = list(self._row(capsys)) + assert keys[-2:] == ["launcher_probe_ms", "rv_effort"] + + def test_effort_fits_under_the_cap_on_a_clean_commit_review_row(self, capsys, monkeypatch): + """The keys of a clean agentic commit review row, with tool calls.""" + monkeypatch.setattr(hook, "_usage_metrics", lambda: { + "tok_in": 1, "tok_out": 1, "tok_cache_r": 0, "tok_cache_w": 0, "cost_usd": 0.1, "api_calls": 1}) + hook._note_reviewer_context({"rv_tool_calls": 2, "rv_turns": 3, "rv_api_ms": 9100}) + hook.emit_metrics({ + "vulns_found": 0, "commit_review": True, "commit_review_on": True, + "sha_via_reflog": True, "reflog_shas_n": 1, "rate_count": 1, "agentic": True, + "candidates": 0, "race_winner": 1, "files_reviewed": 1, "review_ms": 9500, + }) + keys = list(self._row(capsys)) + assert keys[-2:] == ["rv_tool_calls", "rv_effort"] and len(keys) <= 20 + def test_zero_or_absent_keys_are_left_out(self, capsys): hook._note_reviewer_context({"rv_tool_calls": 3, "rv_tool_err": 0}) hook.emit_metrics({"vulns_found": 0}) @@ -161,7 +245,8 @@ class TestRace: def agentic(*a): time.sleep(0.3) # fails after the fallback has started return None, [], {"agentic_fallback": "investigate:RuntimeError", - "rv_cwd_gone": 2, "rv_tool_err": 4, "rv_tool_calls": 5} + "rv_cwd_gone": 2, "rv_tool_err": 4, "rv_tool_calls": 5, + "rv_turns": 18, "rv_api_ms": 60000} monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0") monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False) @@ -176,3 +261,4 @@ class TestRace: _, _, m = hook._agentic_review_with_race("/nonexistent", [("a.py", "+x")], ["a.py"], []) assert m["race_winner"] == 2 and m["agentic"] is False assert (m["rv_cwd_gone"], m["rv_tool_err"], m["rv_tool_calls"]) == (2, 4, 5) + assert (m["rv_turns"], m["rv_api_ms"]) == (18, 60000) diff --git a/plugins/security-guidance/tests/test_slow_prompt_metrics.py b/plugins/security-guidance/tests/test_slow_prompt_metrics.py new file mode 100644 index 00000000..fa947507 --- /dev/null +++ b/plugins/security-guidance/tests/test_slow_prompt_metrics.py @@ -0,0 +1,175 @@ +import json +import os +import re +import shutil +import subprocess + +import pytest + +import gitutil +from conftest import git, make_repo, metrics_of, run_hook, ups_payload + +SLOW = 1.2 +STASH = '*"stash create"*' +MOUNTS = ( + "25 30 8:32 / / rw,relatime - ext4 /dev/sdc rw\n" + "60 25 0:50 / /mnt/c rw,noatime - 9p C:\\134 rw,aname=drivers\n" + "61 25 0:51 / /mnt/my\\040disk rw,noatime - 9p D:\\134 rw\n" + "62 60 8:40 / /mnt/c/data rw - ext4 /dev/sdd rw\n" + "63 25 0:52 / /mnt/a\\134b rw - drvfs E:\\134 rw\n" +) + +# The stalling git is a shell script, and on Windows a clean prompt can itself +# take a second. +pytestmark = pytest.mark.skipif(os.name == "nt", reason="needs a shell-script git") + + +@pytest.fixture +def repo(tmp_path): + return make_repo(tmp_path / "repo", {"app.py": "print('hi')\n", "lib.py": "x = 1\n"}) + + +def _slow(hook_env, tmp_path, match): + """hook_env with a `git` first on PATH that stalls on commands matching + `match` (a shell case pattern).""" + shim = tmp_path / "bin" + shim.mkdir(exist_ok=True) + (shim / "git").write_text( + f'#!/bin/sh\ncase "$*" in {match}) sleep {SLOW};; esac\n' + f'exec "{shutil.which("git")}" "$@"\n') + (shim / "git").chmod(0o755) + return {**hook_env, "PATH": f"{shim}{os.pathsep}{hook_env['PATH']}"} + + +def test_slow_capture_reports_where_the_time_went(repo, hook_env, tmp_path): + rc, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, STASH)) + m = metrics_of(out) + assert rc == 0 + assert m["ups_ms"] >= SLOW * 1000 + assert m["ups_baseline_ms"] >= SLOW * 1000 + assert m["ups_untracked_ms"] < m["ups_baseline_ms"] + assert m["ups_index_entries"] == 2 + assert not {"ups_no_baseline", "ups_wsl_drive", "ups_baseline_fail"} & set(m) + + +def test_slow_untracked_listing_is_told_apart(repo, hook_env, tmp_path): + env = _slow(hook_env, tmp_path, '*"ls-files"*"--others"*') + m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) + assert m["ups_untracked_ms"] >= SLOW * 1000 + assert m["ups_baseline_ms"] < m["ups_untracked_ms"] + + +def test_slow_prompt_with_stop_review_off_lists_nothing(repo, hook_env, tmp_path): + env = {**_slow(hook_env, tmp_path, STASH), "ENABLE_STOP_REVIEW": "0"} + m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) + assert m["ups_baseline_ms"] >= SLOW * 1000 + assert m["ups_untracked_ms"] == 0 + + +def test_slow_prompt_without_a_baseline_says_so(hook_env, tmp_path): + empty = tmp_path / "empty" + empty.mkdir() + subprocess.run(["git", "init", "-q", str(empty)], check=True) + env = _slow(hook_env, tmp_path, '*"rev-parse HEAD"*') + m = metrics_of(run_hook(ups_payload(str(empty)), env)[1]) + assert m["ups_no_baseline"] == 1 and "ups_index_entries" not in m + + +def test_git_that_stalls_past_its_timeout_still_reports(repo, hook_env, tmp_path): + """A hung git reads as "not a repository"; the row must still go out.""" + shim = tmp_path / "bin" + shim.mkdir() + (shim / "git").write_text('#!/bin/sh\nexec sleep 6\n') + (shim / "git").chmod(0o755) + env = {**hook_env, "PATH": f"{shim}{os.pathsep}{hook_env['PATH']}"} + m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) + assert m["ups_no_baseline"] == 1 and m["ups_ms"] >= 5000 + + +def test_failed_snapshot_is_flagged(repo, hook_env, tmp_path): + shim = tmp_path / "bin" + shim.mkdir() + (shim / "git").write_text( + f'#!/bin/sh\ncase "$*" in {STASH}) sleep {SLOW}; exit 1;; esac\n' + f'exec "{shutil.which("git")}" "$@"\n') + (shim / "git").chmod(0o755) + env = {**hook_env, "PATH": f"{shim}{os.pathsep}{hook_env['PATH']}"} + m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) + assert m["ups_baseline_fail"] == 1 + + +def test_fast_prompt_prints_nothing(repo, hook_env): + rc, out, _ = run_hook(ups_payload(str(repo)), hook_env) + assert rc == 0 and out.strip() == "" + + +def test_slow_launcher_is_reported_on_a_fast_prompt(repo, hook_env): + env = {**hook_env, "SG_LAUNCHER_PROBE_MS": "4350", "SG_LAUNCHER_PROBE_MAX_MS": "4000"} + m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) + assert m["launcher_probe_ms"] == 4350 and m["ups_ms"] < 1000 + + +def test_other_hosts_get_no_output(repo, hook_env, tmp_path): + env = {k: v for k, v in _slow(hook_env, tmp_path, STASH).items() + if k not in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "PLUGIN_ROOT")} + env["SECURITY_GUIDANCE_PORTABLE_OUTPUT"] = "1" + assert run_hook(ups_payload(str(repo)), env)[1].strip() == "" + + +def test_row_holds_no_path_and_valid_keys(repo, hook_env, tmp_path): + _, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, STASH)) + assert str(repo) not in out and str(tmp_path) not in out + metrics = json.loads(out)["metrics"] + assert all(re.fullmatch(r"[a-z][a-z0-9_]{0,39}", k) for k in metrics) + assert all(isinstance(v, (int, float)) for v in metrics.values()) + + +def test_slow_capture_saves_the_same_baseline(repo, hook_env, tmp_path): + (repo / "app.py").write_text("print('changed')\n") + (repo / "new.txt").write_text("untracked\n") + states = [] + for name, env in (("fast", hook_env), ("slow", _slow(hook_env, tmp_path, STASH))): + d = tmp_path / name + d.mkdir() + env = {k: v for k, v in env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"} + env["SECURITY_WARNINGS_STATE_DIR"] = str(d) + run_hook(ups_payload(str(repo)), env) + with open(d / "security_warnings_state_s1.json") as f: + states.append(json.load(f)) + fast, slow = states + assert git(repo, "rev-parse", fast["baseline_sha"] + "^{tree}") == \ + git(repo, "rev-parse", slow["baseline_sha"] + "^{tree}") + assert fast["baseline_sha"] != fast["head_at_capture"] + assert "new.txt" in fast["untracked_at_baseline"] + assert fast["untracked_at_baseline"] == slow["untracked_at_baseline"] + + +@pytest.mark.parametrize("path,expected", [ + ("/mnt/c/code/app", True), + ("/mnt/c", True), + ("/mnt/my disk/app", True), + ("/mnt/a\\b/app", True), + ("/mnt/cool/app", False), + ("/home/me/app", False), + ("/mnt/c/data/app", False), +]) +def test_windows_drive_mount(path, expected): + assert gitutil.windows_drive_mount(path, MOUNTS) is expected + + +@pytest.mark.parametrize("junk", ["junk\n", "1 2 - \n", "1 2 3 / /mnt/c rw - \n"]) +def test_windows_drive_mount_skips_malformed_lines(junk): + assert gitutil.windows_drive_mount("/mnt/c/x", junk + MOUNTS) is True + + +def test_wsl_drive_reaches_the_row(monkeypatch): + import security_reminder_hook as hook + monkeypatch.setattr(hook, "on_windows_drive", lambda cwd: True) + assert hook._slow_prompt_metrics("/x", 2.0, 1.5, 0.1, True, 0)["ups_wsl_drive"] == 1 + + +def test_index_entry_count(repo, tmp_path): + assert gitutil.index_entry_count(str(repo / ".git" / "index")) == 2 + assert gitutil.index_entry_count(str(tmp_path / "missing")) is None + (tmp_path / "bad").write_bytes(b"not an index") + assert gitutil.index_entry_count(str(tmp_path / "bad")) is None |
