diff options
| author | Claude <noreply@anthropic.com> | 2026-10-26 23:13:53 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-26 23:13:53 +0000 |
| commit | a3c2f20c0f46e3b0a76ef6e69fcc13c6faca763a (patch) | |
| tree | 93561980a4f4d389aefbb0cae8b0636308c9710f /plugins | |
| parent | 51b34378d6c2efb5897120c322438e17763854fc (diff) | |
| parent | 1da406f428c285c701a1033a3aef368a9ab865dc (diff) | |
Merge remote-tracking branch 'origin/main' into HEADmhegazy/sg-inflight-windows-lock
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 28 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 168 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 77 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 121 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 85 | ||||
| -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_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_slow_prompt_metrics.py | 175 |
10 files changed, 1411 insertions, 19 deletions
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 289abc57..9ba40385 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -6,16 +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, + index_entry_count, ) from session_state import with_locked_state from extensibility import _same_dir @@ -322,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): @@ -350,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( @@ -369,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 @@ -503,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 diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 73d7c611..ec51e3c6 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..cc867700 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: diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 0cae917d..cb08d1c6 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,6 +221,10 @@ 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. _LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics() @@ -304,6 +310,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,6 +336,9 @@ 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) metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} out = {"metrics": metrics} @@ -680,6 +695,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 +732,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 +746,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 +773,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 +862,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): @@ -1760,6 +1816,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 +1923,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 +2251,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 +2299,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 +2612,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 f1addb9b..464f4695 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_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_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 |
