diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-22 00:12:11 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-22 00:12:11 +0000 |
| commit | de9e075c828f2c4438d26571dc6046472381a085 (patch) | |
| tree | c3183dd3a3dbd529c517c18500a0dd95c533760c /plugins/security-guidance/hooks | |
| parent | 437cb57a9d19329a8e6ef3ed79e19adb45e83d50 (diff) | |
| parent | af59ee3a1051a29dda4a2e7a2af221aa457ae08b (diff) | |
Merge branch 'main' into mhegazy/sg-diff-seen-countmhegazy/sg-diff-seen-count
Keeps both sides in emit_metrics: diff_seen stays after the other review
tail keys, and the launcher probe keys stay after everything else.
Diffstat (limited to 'plugins/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 20 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 38 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/ensure_agent_sdk.py | 6 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/extensibility.py | 61 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 352 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 94 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 72 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/sg-python.sh | 51 |
8 files changed, 625 insertions, 69 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index 59e8e569..e5959e68 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -330,6 +330,26 @@ def _log_usage(usage): ) +def launcher_probe_metrics(): + """How long sg-python.sh waited for interpreters to answer its probe. + + Only when this launch's probes took a second or more together, so ordinary + rows carry no extra keys: `launcher_probe_ms` is all of them, + `launcher_probe_max_ms` the slowest one. Both are capped at an hour (the + launcher reads the wall clock, which can jump). Read once: the variables + are removed so child processes do not report this launch as their own. + """ + try: + slowest = int(os.environ.pop("SG_LAUNCHER_PROBE_MAX_MS", "")) + total = int(os.environ.pop("SG_LAUNCHER_PROBE_MS", "")) + except ValueError: + return {} + if total < 1000 or slowest > total: + return {} + cap = 3_600_000 + return {"launcher_probe_ms": min(total, cap), "launcher_probe_max_ms": min(slowest, cap)} + + def _usage_metrics(): """Snapshot the accumulator as metric keys. Returns {} when no API calls AND no HTTP errors were made so skip-path emits don't burn key budget. diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 004fe0f7..480b8c9c 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -287,16 +287,31 @@ def get_baseline_file_content(session_id, file_path, cwd): try: abs_path = os.path.abspath(file_path) cwd_abs = os.path.abspath(cwd) if cwd else os.getcwd() - try: - rel_path = os.path.relpath(abs_path, cwd_abs) - except ValueError: - return None - result = subprocess.run( - [*GIT_CMD, "show", f"{baseline_sha}:{rel_path}"], - cwd=cwd, capture_output=True, timeout=5 - ) - if result.returncode == 0: - return (result.stdout or b"").decode("utf-8", errors="replace") + attempts = [(abs_path, cwd_abs, cwd)] + # The tool's path and the session directory can name the same place + # through different symlinks (/tmp and /var on macOS). The relative + # path between the two spellings then leaves the repo and git finds + # nothing, so the lookup is tried again with both resolved. + real_path, real_cwd = os.path.realpath(abs_path), os.path.realpath(cwd_abs) + if (real_path, real_cwd) != (abs_path, cwd_abs): + attempts.append((real_path, real_cwd, real_cwd)) + for path, start, git_cwd in attempts: + try: + rel_path = os.path.relpath(path, start) + except ValueError: + continue + # `<rev>:<path>` is read from the repo root unless the path starts + # with `./`, and takes forward slashes only. Without both, the + # lookup fails for a session started below the repo root, and on + # Windows for any file that is not directly in the session + # directory. + rel_path = rel_path.replace(os.sep, "/") + result = subprocess.run( + [*GIT_CMD, "show", f"{baseline_sha}:./{rel_path}"], + cwd=git_cwd, capture_output=True, timeout=5 + ) + if result.returncode == 0: + return (result.stdout or b"").decode("utf-8", errors="replace") return None except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError): return None @@ -352,7 +367,8 @@ def capture_git_baseline(cwd): sha = "" # untracked_paths=[]: a plain copy of the index, no `add -N` pass. with _temp_index(cwd, untracked_paths=[]) as env: - # env is None when there is no index file to copy: treat as clean. + # env is None when no usable index copy could be made: fall + # back to HEAD. if env is not None: result = subprocess.run( [*GIT_CMD, "stash", "create"], diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index fadeae00..d3aaf96b 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -27,7 +27,10 @@ from pathlib import Path # → ~/.claude/security. See _base.state_dir for resolution precedence. Re-aliased # here to match the existing local name (state_dir was already a local var in # main() and _maybe_emit_user_notice). -from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output +from _base import ( + launcher_probe_metrics, portable_output, state_dir as _resolve_state_dir, + write_hook_output, +) from _base import llm_reviews_switched_off @@ -973,6 +976,7 @@ if __name__ == "__main__": # not read the plugin files. if os.environ.get("SG_LAUNCHER_FALLBACK") == "1": metrics["launcher_fallback"] = 1 + metrics.update(launcher_probe_metrics()) response: dict[str, object] = {"metrics": metrics} # One-time user-visible notice when the agentic reviewer is dead on # arrival. Uses hookSpecificOutput.additionalContext (SessionStart's diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index cb3e0a8d..ed332c99 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -175,13 +175,16 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]: # try each supported extension. for ext in (".yaml", ".yml", ".json"): candidate = path + ext - data = _read_config(candidate) - if data is None: + # One unusable file is skipped on its own, so the rules from the + # other locations still load. + try: + found = _rules_from_file(candidate, label) + except Exception as e: + debug_log(f"extensibility: skipping {candidate}: {type(e).__name__}: {e}") continue - for entry in (data or {}).get("patterns", []): - rule = _validate_pattern(entry, source=label) - if rule: - rules.append(rule) + if found is None: + continue + rules.extend(found) break # found one extension; don't double-load .yaml AND .json if len(rules) >= PATTERN_MAX_RULES: break @@ -191,8 +194,32 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]: return rules +def _rules_from_file(path: str, label: str) -> Optional[List[Dict[str, Any]]]: + """The valid rules in one config file, or None when the file is missing + or does not hold a mapping with a ``patterns`` list.""" + data = _read_config(path) + if data is None: + return None + entries = data.get("patterns", []) + if entries is None: + entries = [] + if not isinstance(entries, list): + debug_log( + f"extensibility: skipping {path}: 'patterns' must be a list, " + f"got {type(entries).__name__}" + ) + return None + rules = [] + for entry in entries: + rule = _validate_pattern(entry, source=label) + if rule: + rules.append(rule) + return rules + + def _read_config(path: str) -> Optional[Dict[str, Any]]: - """Read a YAML or JSON config file. Returns None on missing/malformed.""" + """Read a YAML or JSON config file. Returns None on missing/malformed, + and when the file parses to something other than a mapping.""" try: with open(path, encoding="utf-8") as f: raw = f.read() @@ -202,7 +229,7 @@ def _read_config(path: str) -> Optional[Dict[str, Any]]: return None if path.endswith(".json"): try: - return json.loads(raw) + return _mapping_or_none(path, json.loads(raw)) except ValueError as e: debug_log(f"extensibility: skipping {path}: invalid JSON: {e}") return None @@ -213,12 +240,26 @@ def _read_config(path: str) -> Optional[Dict[str, Any]]: debug_log(f"extensibility: skipping {path}: PyYAML not installed (use .json)") return None try: - return yaml.safe_load(raw) + return _mapping_or_none(path, yaml.safe_load(raw)) except yaml.YAMLError as e: # type: ignore debug_log(f"extensibility: skipping {path}: invalid YAML: {e}") return None +def _mapping_or_none(path: str, data: Any) -> Optional[Dict[str, Any]]: + """A config file must hold a mapping. A scalar or a list is valid YAML or + JSON too (e.g. the pattern list written without its ``patterns:`` key); + skip that one file so the other locations still load.""" + if isinstance(data, dict): + return data + if data is not None: + debug_log( + f"extensibility: skipping {path}: expected a mapping, " + f"got {type(data).__name__}" + ) + return None + + def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]: """Validate one user pattern entry. Returns a rule dict in the same shape as the built-in SECURITY_PATTERNS, or None if invalid (logged).""" @@ -250,7 +291,7 @@ def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]: try: rule["regex"] = regex re.compile(regex) - except re.error as e: + except (re.error, OverflowError, RecursionError) as e: debug_log(f"extensibility: skipping {name}: invalid regex: {e}") return None diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 4177a573..73d7c611 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -15,9 +15,11 @@ Functions that DO compose patched leaves (``compute_v2_review_set``, ``security_reminder_hook.py`` for that reason. """ import contextlib +import errno import os import re import subprocess +import sys import tempfile import threading import time @@ -55,9 +57,9 @@ GIT_CMD = [ # vendored checkout, an unpacked archive) is another repository with its # own config. To report it as modified, or to show its changes inline # (diff.submodule=diff), git starts a second git inside it, which reads - # that config and runs the commands it names. The hook stays out of it: - # such a directory is left out of the review set, and a commit that moves - # one shows as the two commit ids. + # that config and runs the commands it names. Such a directory is left + # out of the review set, and so is a commit that moves one. See also + # _drop_gitlinks for the commands that take no such setting. "-c", "diff.ignoreSubmodules=all", "-c", "diff.submodule=short", ] @@ -148,6 +150,35 @@ def _find_git_index(cwd): return None +def _find_git_index_and_top(cwd): + """_find_git_index plus the work tree's top directory, from one git + call. (None, None) when either is missing: no index file, a bare + repository, or a `cwd` inside the git directory.""" + try: + result = subprocess.run( + [*GIT_CMD, "rev-parse", "--git-dir", "--show-toplevel"], + cwd=cwd, capture_output=True, timeout=5 + ) + if result.returncode != 0: + return None, None + # Paths as bytes from git: decode by hand (see _find_git_index). + out = result.stdout.decode("utf-8", errors="replace") + parts = out[:-1].split("\n") if out.endswith("\n") else [] + if len(parts) != 2 or not all(parts): + # A newline in one of the paths: ask for them one at a time. + index_path, top = _find_git_index(cwd), _git_toplevel(cwd) + return (index_path, top) if index_path and top else (None, None) + git_dir, top = parts + if not os.path.isabs(git_dir): + git_dir = os.path.join(cwd, git_dir) + index_path = os.path.join(git_dir, "index") + if not os.path.isfile(index_path): + return None, None + return index_path, top + except (subprocess.TimeoutExpired, FileNotFoundError, OSError): + return None, None + + def _diff_pathspec(cwd, paths): """Convert absolute touched-paths to repo-relative pathspec args for git diff. Paths outside cwd (e.g. ~/.claude/…) are dropped. Returns the @@ -169,6 +200,119 @@ def _diff_pathspec(cwd, paths): return ["--"] + rel if rel else [] +# Bytes of file paths per git call once a path list has proved too long for +# one command. Windows caps a whole command line at 32,767 characters; +# elsewhere the limit is about 1 MB (macOS) or 2 MB (Linux), environment +# included. +_MAX_PATH_ARGS_BYTES = ( + 20000 if sys.platform in ("win32", "cygwin", "msys") else 500000) +# More commands than this and the path list is not worth diffing: each one +# matches its paths against the whole index, and a set that large is thrown +# away as pathological after the diff anyway. +_MAX_PATH_BATCHES = 4 + + +def _arg_cost(path): + # The exec limit also counts a terminator and a pointer per argument. + return len(os.fsencode(path)) + 9 + + +def _path_args_budget(env=None): + """_MAX_PATH_ARGS_BYTES, or less where this system's own limit is lower + (a small stack limit, a BSD, a very large environment). Half of what the + system leaves after the environment, so the rest of the command fits.""" + try: + arg_max = os.sysconf("SC_ARG_MAX") + except (AttributeError, ValueError, OSError): + return _MAX_PATH_ARGS_BYTES + env_bytes = sum(len(k) + len(v) + 2 for k, v in (env or os.environ).items()) + return min(_MAX_PATH_ARGS_BYTES, max(4096, (arg_max - env_bytes) // 2)) + + +def _path_batches(paths, budget=None): + if budget is None: + budget = _MAX_PATH_ARGS_BYTES + batch, size = [], 0 + for p in paths: + n = _arg_cost(p) + if batch and size + n > budget: + yield batch + batch, size = [], 0 + batch.append(p) + size += n + if batch: + yield batch + + +# Why a path list too long for one command left the last get_git_diff call +# without a diff, for the Stop review's skip reason: "gave_up" (still too +# long once cut down) or "none_reviewable". +_path_list_too_long = set() + + +def _too_many_args(e): + """The OS refused to start the command because its arguments are too + long. Windows reports ERROR_FILENAME_EXCED_RANGE, which Python turns into + a FileNotFoundError.""" + return e.errno == errno.E2BIG or getattr(e, "winerror", None) == 206 + + +def _run_captured(cmd, timeout, **kwargs): + return subprocess.run(cmd, capture_output=True, timeout=timeout, **kwargs) + + +def _run_git_on_review_paths(args, paths, timeout, run=_run_captured, **kwargs): + """Run `git <args> -- <paths>` for the Stop review; return the results. + `run(cmd, timeout, **kwargs)` starts each command (_run_diff_bounded for + the diff, so its output is never held whole). + + One command with every path whenever the OS takes it. When the OS refuses + the argument list as too long, only reviewable source paths are kept (the + review drops the rest from the diff anyway) and they go out in as few + commands as they need, all within `timeout` seconds together. If even + those need more than _MAX_PATH_BATCHES commands, the refusal is raised + again. + + Secret-shaped paths that are gone from the work tree go into every one + of those commands: `git diff` must still pair a rename away from such a + name, or the secret's content would show as a new source file. A new file + that only resembles the secret may be paired with it too and left out of + the review. Any other rename is paired only when both of its paths are + reviewable source and in the same command; otherwise it shows as a delete + or an add. + """ + cmd = [*GIT_CMD, *args, "--"] + paths = list(paths) + deadline = time.monotonic() + timeout + try: + return [run(cmd + paths, timeout, **kwargs)] + except OSError as e: + if not _too_many_args(e): + raise + too_long = e + budget = _path_args_budget(kwargs.get("env")) + batches = list(_path_batches( + [p for p in paths if _is_reviewable_source(p)], budget)) + root = kwargs.get("cwd") or os.getcwd() + secret = [p for p in paths if _is_secret_shaped(p) + and not os.path.lexists(os.path.join(root, p))] + debug_log(f"git {args[0]}: {len(paths)} paths do not fit one command; " + f"{len(batches)} command(s) for the reviewable ones") + # The secret-shaped paths ride along with every batch, so they get a + # small share of a command of their own. + if (len(batches) > _MAX_PATH_BATCHES + or sum(map(_arg_cost, secret)) > budget // 4): + raise too_long + cmd += secret + results = [] + for batch in batches: + left = deadline - time.monotonic() + if left <= 0: + raise subprocess.TimeoutExpired(cmd, timeout) + results.append(run(cmd + batch, left, **kwargs)) + return results + + _TEMP_INDEX_PREFIX = "security_hook_idx_" # A copy is named <prefix>pid<hook pid>_<8 random chars>, so a later run can # tell that the hook which made it is gone. Names from earlier releases have @@ -403,9 +547,11 @@ def _temp_index(cwd, untracked_paths=None): """Yield an env dict pointing GIT_INDEX_FILE at a throwaway copy of the repo's index with `git add --intent-to-add` applied, so untracked files show up in subsequent `git diff` calls without touching the user's real - index. Yields None if no index can be found (bare repo / not a repo) or - no copy slot came free; the caller should fall back to a plain diff. - Always cleans up the temp file. + index. The copy has no gitlink entry for a nested repository (see + _drop_gitlinks). Yields None if no index can be found (bare repo / not a + repo), no copy slot came free, or those entries could not be removed. + Callers then go on without the copy: the diff reads the real index, and + the baseline falls back to HEAD. Always cleans up the temp file. Perf: when `untracked_paths` is given, only those paths are added (O(n) in untracked count). The default `add -N .` stats every file in the @@ -416,7 +562,7 @@ def _temp_index(cwd, untracked_paths=None): Cleanup removes `<tmp_index>*`, not just the copy: git writes `<index>.lock` and `<index>.stash.<pid>` next to the index it is given and cannot remove them itself when a subprocess timeout kills it.""" - real_index = _find_git_index(cwd) + real_index, top = _find_git_index_and_top(cwd) if not real_index: yield None return @@ -432,12 +578,12 @@ def _temp_index(cwd, untracked_paths=None): debug_log("no index copy slot came free; going without a copy") yield None return - with _copied_index(cwd, real_index, tmpdir, untracked_paths) as env: + with _copied_index(cwd, top, real_index, tmpdir, untracked_paths) as env: yield env @contextlib.contextmanager -def _copied_index(cwd, real_index, tmpdir, untracked_paths): +def _copied_index(cwd, top, real_index, tmpdir, untracked_paths): import shutil import tempfile @@ -459,6 +605,12 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths): except (OSError, NotImplementedError, AttributeError): shutil.copy2(real_index, tmp_index) env = {**os.environ, "GIT_INDEX_FILE": tmp_index} + # Before `git add` runs, since add reads the gitlinks its paths cover. + if not _drop_gitlinks(top, env, tmp_index): + debug_log("could not remove gitlinks from the index copy; going on " + "without the copy") + yield None + return if untracked_paths is None: add_args = ["."] elif untracked_paths: @@ -472,7 +624,7 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths): surviving = [p for p in untracked_paths if not p.endswith("/") and os.path.lexists(os.path.join(cwd, p))] - add_args = ["--"] + surviving if surviving else None + add_args = surviving or None else: add_args = None if add_args: @@ -480,17 +632,147 @@ def _copied_index(cwd, 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. - subprocess.run( - [*GIT_CMD, "add", "--intent-to-add"] + add_args, - cwd=cwd, capture_output=True, timeout=10, - env=env, - ) + _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"}) + # A whole-tree add puts a nested repository back. + if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index): + yield None + return yield env finally: _remove_copy(tmp_index) _live_copies.discard(tmp_index) +# An index entry stores its mode as four bytes; this is a gitlink's. +_GITLINK_MODE = b"\x00\x00\xe0\x00" +# Signature of the index extension that says most entries are in a second, +# shared file (core.splitIndex). +_SPLIT_INDEX_EXT = b"link" + + +def _may_have_gitlinks(index_path): + """False only when the index file at `index_path` cannot hold a gitlink + entry: neither a gitlink's mode bytes nor the split-index signature occur + anywhere in it. Either can occur by chance (in an object id, a file + size, a path), so True means "list the entries and see". Most + repositories have no gitlink, and for them this saves a git process on + every index copy.""" + keep = max(len(_GITLINK_MODE), len(_SPLIT_INDEX_EXT)) - 1 + try: + with open(index_path, "rb") as f: + tail = b"" + while True: + chunk = f.read(1 << 20) + if not chunk: + return False + data = tail + chunk + if _GITLINK_MODE in data or _SPLIT_INDEX_EXT in data: + return True + tail = data[-keep:] + except OSError: + return True + + +_GITLINK_LIST_TIMEOUT = 10 +# `git ls-files --sparse` (git 2.35) lists a sparse index as it is stored; +# without it git first expands the index to every path in the repository. +# Set to False once this git has refused the option. +_ls_files_sparse = True + + +def _gitlink_paths(top, env): + """Paths (bytes, relative to `top`) of the gitlink entries, at any depth, + in the index `env` names. None if they could not be listed. The listing + is read as it comes, so a large index costs time but not memory.""" + global _ls_files_sparse + cmd = [*GIT_CMD, "ls-files", "-s", "-z"] + (["--sparse"] if _ls_files_sparse else []) + p = subprocess.Popen(cmd, cwd=top, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, env=env) + killer = threading.Timer(_GITLINK_LIST_TIMEOUT, p.kill) + killer.daemon = True + found = set() + tail = b"" + try: + killer.start() + while True: + chunk = p.stdout.read1(65536) + if not chunk: + break + data = tail + chunk + end = data.rfind(b"\0") + 1 + # "<mode> <object> <stage>\t<path>", NUL-terminated. Most chunks + # have no gitlink and are not split up. + if b"160000 " in data: + for rec in data[:end].split(b"\0"): + if rec.startswith(b"160000 "): + found.add(rec.split(b"\t", 1)[1]) + tail = data[end:] + rc = p.wait() + finally: + killer.cancel() + if p.poll() is None: + p.kill() + p.wait() + p.stdout.close() + if rc == 129 and _ls_files_sparse: + # Usage error: a git without --sparse. + _ls_files_sparse = False + return _gitlink_paths(top, env) + if rc != 0: + debug_log(f"git ls-files on the index copy failed (rc={rc})") + return None + return found + + +def _drop_gitlinks(top, env, tmp_index): + """Remove the gitlink (mode 160000) entry of every nested repository from + the index copy that `env` names, never from the real index, before + anything else runs on the copy. A gitlink marks a directory that is, or + can be, another repository (see diff.ignoreSubmodules in GIT_CMD): + `git stash create` takes no flag like IGNORE_SUBMODULES, and `git add` + reads the gitlinks its paths cover. An entry whose directory has no + `.git` stays: git starts nothing there, and without the entry an older + `git stash create` fails on the empty directory. `top` is the work + tree's top directory. Returns True on success, False on any failure; the + copy must not be used then.""" + try: + if not _may_have_gitlinks(tmp_index): + return True + gitlinks = _gitlink_paths(top, env) + if gitlinks is None: + return False + top_b = os.fsencode(top) + nested = sorted(p for p in gitlinks + if os.path.lexists(os.path.join(top_b, p, b".git"))) + if not nested: + return True + mtime_ns = os.stat(tmp_index).st_mtime_ns + # git writes a new file and renames it over the copy, so a copy that + # is a hard link to the real index leaves the real one as it was. + rm = subprocess.run( + [*GIT_CMD, "update-index", "--force-remove", "-z", "--stdin"], + cwd=top, input=b"".join(p + b"\0" for p in nested), + capture_output=True, timeout=10, env=env) + if rm.returncode != 0: + debug_log(f"git update-index on the index copy failed (rc={rm.returncode}): " + f"{rm.stderr[:200].decode('utf-8', errors='replace')}") + return False + # Keep the mtime the copy came with; see _copied_index. + os.utime(tmp_index, ns=(mtime_ns, mtime_ns)) + debug_log(f"gitlink entries (nested repositories) removed from the " + f"index copy: {len(nested)}; their contents are not reviewed") + return True + except (subprocess.TimeoutExpired, OSError, RuntimeError, ValueError) as e: + # RuntimeError: the timer thread could not start. + debug_log(f"removing gitlinks from the index copy failed: {e}") + return False + + def _git_toplevel(cwd): """Absolute repo root for `cwd`, or None if not in a work tree.""" try: @@ -1097,12 +1379,15 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa If `paths` is given, the diff is restricted to those paths (relative to cwd; absolute paths are converted, paths outside cwd are dropped). + A path list too long for one command is cut down to reviewable source + files: see _run_git_on_review_paths. `untracked_paths` (repo-root-relative) is forwarded to _temp_index so it can add only those files instead of scanning the whole worktree. The output is read through _DiffKeeper: files the review would drop come back as their header line only, and a file's diff past MAX_FILE_DIFF_BYTES is cut down to its added lines. """ + _path_list_too_long.clear() pathspec = _diff_pathspec(cwd, paths) if paths and not pathspec: # Caller restricted to specific paths but none are inside this repo @@ -1112,25 +1397,36 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa return "" # core.quotePath=false comes from GIT_CMD globally (see definition). - cmd = [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec + args = ["diff", IGNORE_SUBMODULES, "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) _diff_read.update(bytes=0, cut_files=0, cut_bytes=0) + + def _run(env): + if pathspec: + results = _run_git_on_review_paths(args, pathspec[1:], timeout=30, run=_run_diff_bounded, cwd=cwd, env=env) + else: + results = [_run_diff_bounded([*GIT_CMD, *args], 30, cwd=cwd, env=env)] + if not results: + _path_list_too_long.add("none_reviewable") + for result in results: + if result.returncode != 0: + debug_log(f"git diff failed: {result.stderr[:200].decode('utf-8', errors='replace')}") + return None + # Decode with errors='replace' so binary diffs don't crash + return b"".join(r.stdout for r in results).decode("utf-8", errors="replace") + try: if untracked_paths is not None and not untracked_paths: # Nothing to `add -N`, and the diff only reads the index. - result = _run_diff_bounded(cmd, 30, cwd=cwd) - else: - with _temp_index(cwd, untracked_paths) as env: - # env is None when there is no index (bare repo / not a repo) - # or no copy slot — diff still runs, just without - # untracked-file support. - result = _run_diff_bounded(cmd, 30, cwd=cwd, env=env) - if result.returncode != 0: - debug_log(f"git diff failed: {result.stderr[:200].decode('utf-8', errors='replace')}") - return None - # Decode with errors='replace' so binary diffs don't crash - return result.stdout.decode("utf-8", errors="replace") + return _run(None) + with _temp_index(cwd, untracked_paths) as env: + # env is None when there is no index (bare repo / not a repo) + # or no copy slot — diff still runs, just without + # untracked-file support. + return _run(env) except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e: debug_log(f"git diff error: {e}") + if isinstance(e, OSError) and _too_many_args(e): + _path_list_too_long.add("gave_up") return None diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 76d04c54..f4562bb4 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -32,6 +32,11 @@ import urllib.parse import urllib.request from typing import Optional, Tuple, Dict, Any, List, Callable +try: + import ssl +except ImportError: # a Python built without TLS + ssl = None + 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 @@ -196,10 +201,91 @@ def _anthropic_base_url() -> str: return os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com").rstrip("/") +# ── Windows certificate store with an entry OpenSSL cannot read ────────── +# Older Python releases (3.11 and 3.12 among them) hand each Windows +# certificate store to OpenSSL in one call, so a single certificate it cannot +# parse makes ssl.create_default_context() raise, and every HTTPS call fails +# before a byte is sent. SSL_CERT_FILE does not help: the store is read +# first. Newer releases load the store one certificate at a time and skip +# the ones that fail; _urlopen does the same on the releases that do not. + +_STORE_TLS_UNSET = object() +_store_tls_context = _STORE_TLS_UNSET # None once Python's default context is known to build +_store_tls_lock = threading.Lock() +# Store entries left out of that context; emit_metrics reports it. +_store_certs_skipped = 0 + + +def _context_without_unreadable_store_certs(): + """(context, skipped): Python's default TLS context built from the + Windows store entries OpenSSL can parse, and how many it could not. + The context is None when the default one builds as it is, off Windows, + or when no entry is readable. Trust is never widened: the certificates + come from the same stores, under the same server-authentication filter, + and the chain and host name are verified as in any default context.""" + enum_certificates = getattr(ssl, "enum_certificates", None) # Windows only + if enum_certificates is None: + return None, 0 + try: + ssl.create_default_context() + return None, 0 + except ssl.SSLError: + pass + server_auth = ssl.Purpose.SERVER_AUTH.oid + context, skipped = None, 0 + for store in getattr(ssl.SSLContext, "_windows_cert_stores", ("CA", "ROOT")): + try: + for cert, encoding, trust in enum_certificates(store): + if encoding != "x509_asn" or not (trust is True or server_auth in trust): + continue + try: + if context is None: + # With cadata, create_default_context applies every + # default except reading the store itself. + context = ssl.create_default_context(cadata=cert) + else: + context.load_verify_locations(cadata=cert) + except ssl.SSLError: + skipped += 1 + except PermissionError: + pass + if context is None: + return None, skipped + context.set_default_verify_paths() + # What http.client sets on the context it would have made. + context.set_alpn_protocols(["http/1.1"]) + if context.post_handshake_auth is not None: + context.post_handshake_auth = True + return context, skipped + + +def _urlopen(request, timeout): + """urllib.request.urlopen for the plugin's API calls. Uses Python's + default TLS context unless that cannot be built because of the Windows + certificate store (see above); checked once per process.""" + global _store_tls_context, _store_certs_skipped + if _store_tls_context is _STORE_TLS_UNSET: + with _store_tls_lock: + if _store_tls_context is _STORE_TLS_UNSET: + try: + context, skipped = _context_without_unreadable_store_certs() + except Exception as e: + debug_log(f"TLS: certificate store check failed: {type(e).__name__}") + context, skipped = None, 0 + if context is not None: + debug_log(f"TLS: the Windows certificate store has {skipped} certificate(s) " + "OpenSSL cannot read; using the store without them") + _store_certs_skipped = skipped + _store_tls_context = context + if _store_tls_context is None: + return urllib.request.urlopen(request, timeout=timeout) + return urllib.request.urlopen(request, timeout=timeout, context=_store_tls_context) + + def _probe_anthropic(timeout: float = 5.0) -> bool: req = urllib.request.Request(_anthropic_base_url() + "/", method="HEAD") try: - with urllib.request.urlopen(req, timeout=timeout): + with _urlopen(req, timeout): return True except urllib.error.HTTPError: return True # got a status code → connected @@ -484,9 +570,7 @@ def _fetch_newest_opus() -> Optional[str]: url, headers=_build_auth_headers(use_token, betas=()), method="GET", ) try: - with urllib.request.urlopen( - request, timeout=_REVIEW_MODEL_LOOKUP_TIMEOUT, - ) as response: + with _urlopen(request, _REVIEW_MODEL_LOOKUP_TIMEOUT) as response: listing = json.loads( response.read(_REVIEW_MODEL_LISTING_MAX_BYTES).decode("utf-8") ) @@ -975,7 +1059,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, headers=headers, method="POST", ) - with urllib.request.urlopen(request, timeout=120) as response: + with _urlopen(request, 120) as response: response_body = response.read().decode("utf-8") response_data = json.loads(response_body) _record_usage(response_data.get("usage") or {}, diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index f48f66c1..39578a1c 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -86,7 +86,7 @@ from _base import ( # noqa: E402,F401 _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, _USAGE_CONTEXT, _log_usage, - state_dir as _resolve_state_dir, + launcher_probe_metrics, state_dir as _resolve_state_dir, write_hook_output as _write_hook_output, llm_reviews_switched_off, agent_sdk_installed, ) @@ -202,6 +202,13 @@ MAX_STOP_HOOK_FIRINGS = int(os.environ.get("MAX_STOP_HOOK_FIRINGS", "3")) # diff; unbounded diffs burn tokens and risk 400 on context length. MAX_DIFF_FILES = int(os.environ.get("MAX_DIFF_FILES", "30")) +# Changed source paths past which the Stop review is skipped before any diff. +# A set this large is a repo at $HOME or an unignored cache, not edits; no +# platform takes that many paths in one git command, and only resolving them +# takes seconds. Paths the review never reads (an unignored node_modules) do +# not count: they must not hide the one edited source file beside them. +MAX_REVIEW_SET_PATHS = int(os.environ.get("MAX_REVIEW_SET_PATHS", "100000")) + # Appended to all exit(2) guidance so the asyncRewake auto-turn doesn't # cause the model to abandon the user's original request. CONTINUATION_SUFFIX = ( @@ -213,10 +220,14 @@ 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 all others: the first a row over CC's key -# cap loses, whenever they were set. +# 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() + # Reviewer context diagnostics from llm.agentic_review, most useful first. _REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls") @@ -303,6 +314,10 @@ def emit_metrics( # Diagnostic keys go last, so they are the first dropped when a row is # over CC's key cap and never displace an existing key. tail = {} + if llm._store_certs_skipped: + # The Windows certificate store held entries OpenSSL cannot read and + # the plugin's API calls ran on the store without them. + tail["tls_store_skipped"] = llm._store_certs_skipped if usage or "review_ms" in metrics or metrics.get("review_failed"): # Review rows say whether the plugin's calls went through a gateway, # so the error rate behind gateways can be read per plugin version. @@ -317,6 +332,7 @@ def emit_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} if rewake_summary: @@ -515,7 +531,10 @@ def record_pending_warnings(session_id, file_path, rule_names): def sweep_pending_warnings(session_id): """ Stop-hook final sweep. Re-read every file in pending_warnings, re-check - patterns, and return (fixed, unresolved, unresolved_mask). Clears state. + patterns, and return (fixed, unresolved, unresolved_mask, fired_mask). + fired_mask has a bit for every built-in rule that matched an edit since + the last sweep (whether or not its reminder was shown again), so the two + masks give, per rule, fired and still matching. Clears state. A file that's been deleted counts as fixed — the dangerous code is gone. Never raises — this is telemetry and must not break the Stop hook. """ @@ -523,18 +542,24 @@ def sweep_pending_warnings(session_id): try: pending = state.get("pending_warnings") if not isinstance(pending, dict) or not pending: - return 0, 0, 0 + return 0, 0, 0, 0 by_file = {} for key in pending: if not isinstance(key, str) or ":" not in key: continue fp, _, rule = key.rpartition(":") + if fp.endswith(":user"): + # User rules are named "user:<name>"; keep them apart + # from a built-in rule of the same name. + fp, rule = fp[:-len(":user")], "user:" + rule by_file.setdefault(fp, set()).add(rule) unresolved = [] + fired = set() fixed = 0 for fp, rules in by_file.items(): + fired |= rules try: with open(fp, "r", errors="replace") as f: still_matching = {r for r, _ in check_patterns(fp, f.read())} @@ -550,13 +575,14 @@ def sweep_pending_warnings(session_id): # Filter to known rules so a renamed/removed rule in old state # doesn't KeyError rule_names_to_mask. known = [r for r in unresolved if r in _RULE_NAME_TO_ID] - return fixed, len(unresolved), rule_names_to_mask(known) + return (fixed, len(unresolved), rule_names_to_mask(known), + rule_names_to_mask(fired)) except Exception as e: debug_log(f"sweep_pending_warnings failed: {e}") - return 0, 0, 0 + return 0, 0, 0, 0 result = with_locked_state(session_id, _sweep) - return result if result is not None else (0, 0, 0) + return result if result is not None else (0, 0, 0, 0) # ===================================================================== # Git baseline management @@ -2372,13 +2398,25 @@ def handle_stop_hook(input_data): # Sweep pattern-warning outcomes (pure local work; stop_hook_active is # already guaranteed False here so no double-count guard needed). sweep = {} - warn_fixed, warn_unresolved, warn_unresolved_mask = sweep_pending_warnings(session_id) + (warn_fixed, warn_unresolved, warn_unresolved_mask, + warn_fired_mask) = sweep_pending_warnings(session_id) if warn_fixed or warn_unresolved: sweep = { "warn_fixed": warn_fixed, "warn_unresolved": warn_unresolved, "warn_unresolved_mask": warn_unresolved_mask, } + # The two masks also ride the tail, so the reviewed rows below, which + # leave `sweep` or its mask out, carry them when there is room under the + # key cap. Per rule they give how often it fired and how often the + # flagged code was still there at Stop. warn_fired_mask goes after + # warn_unresolved_mask: a row cut at the cap loses it first, and a row + # without it is left out of the per-rule read instead of counting its + # rules as fixed. + if warn_unresolved_mask: + _TAIL_METRICS["warn_unresolved_mask"] = warn_unresolved_mask + if warn_fired_mask: + _TAIL_METRICS["warn_fired_mask"] = warn_fired_mask v2_metrics = {} @@ -2504,6 +2542,12 @@ def handle_stop_hook(input_data): debug_log("Stop hook: empty review set") _skip(9, touched_paths_count=len(touched_paths)) debug_log(f"Stop hook: review_set={len(review_paths)} base={diff_base[:12]} dirty_now={v2_metrics['dirty_now_count']} changed_since={v2_metrics['changed_since_count']}") + if (len(review_paths) > MAX_REVIEW_SET_PATHS + and sum(_is_reviewable_source(os.path.relpath(p, repo_root)) + for p in review_paths) > MAX_REVIEW_SET_PATHS): + debug_log(f"Stop hook: pathological review set (more than " + f"{MAX_REVIEW_SET_PATHS} paths), skipping") + _skip(8) # Run from repo_root so the toplevel-relative review_paths resolve. # Diff CONTENT against the turn-start stash (baseline_sha) so the LLM # sees only this-turn edits — diffing against HEAD includes the user's @@ -2515,7 +2559,8 @@ def handle_stop_hook(input_data): content_base = baseline_sha or diff_base diff_output = get_git_diff(repo_root, content_base, full_context=False, paths=review_paths, untracked_paths=untracked) - if diff_output is None and content_base != diff_base: + if (diff_output is None and content_base != diff_base + and "gave_up" not in gitutil._path_list_too_long): 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) @@ -2532,6 +2577,12 @@ def handle_stop_hook(input_data): baseline_sha = "HEAD" if not diff_output or not diff_output.strip(): + if "gave_up" in gitutil._path_list_too_long: + debug_log("Stop hook: changed paths do not fit the git commands, skipping") + _skip(8) + if "none_reviewable" in gitutil._path_list_too_long: + debug_log("Stop hook: no source code files among the changed paths") + _skip(7) debug_log("Stop hook: no changes since baseline") _skip(6) @@ -2935,6 +2986,7 @@ def main(): "rule_id": int(_RULE_NAME_TO_ID.get(raw_names[0], -1)), "rule_mask": rule_names_to_mask(raw_names), **({"pv": _PV} if _PV else {}), + **_LAUNCHER_METRICS, } if all_guidance: output["hookSpecificOutput"] = { diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh index a02c7d6c..e0c2730e 100755 --- a/plugins/security-guidance/hooks/sg-python.sh +++ b/plugins/security-guidance/hooks/sg-python.sh @@ -106,7 +106,7 @@ probe() { exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}")' "$SG_TARGET" 2>/dev/null } -# Use as `v=$(probe ...) || { note_unreadable "<name>"; continue; }`. +# Use as `ask ... || { note_unreadable "<name>"; continue; }` (see ask below). note_unreadable() { [ $? -eq 3 ] && sg_unreadable="$sg_unreadable|$1|" return 0 @@ -119,6 +119,49 @@ on_path() { command -v "$1" >/dev/null 2>&1 } +# How long the probes took, for the launcher_probe_max_ms / launcher_probe_ms +# metrics the hook reports. Measurement only: `ask` is `v=$(probe ...)` with a +# clock around it, and changes neither which interpreter runs nor how long a +# probe may take. EPOCHREALTIME needs bash 5; older bash (macOS /bin/bash) only +# has whole seconds, where a difference of 1 can be a few milliseconds: there +# a single probe counts from 2 s, and the total is first probe to last. +unset SG_LAUNCHER_PROBE_MS SG_LAUNCHER_PROBE_MAX_MS +sg_probe_ms=0 +sg_probe_max_ms=0 +sg_probe_first="" +sg_coarse="" +sg_clock() { + # Sets $sg_now (ms) without starting a process. + case "${EPOCHREALTIME:-}" in + [0-9]*[.,][0-9][0-9][0-9][0-9][0-9][0-9]) # the decimal point follows the locale + sg_now=${EPOCHREALTIME//[!0-9]/} + sg_now=$((10#$sg_now / 1000)) ;; + *) + sg_coarse=1 + sg_now=$((SECONDS * 1000)) ;; + esac +} +ask() { + # Sets $v; same exit status as probe. + local rc=0 t0 ms + sg_clock; t0=$sg_now + [ -n "$sg_probe_first" ] || sg_probe_first=$t0 + v=$(probe "$@") || rc=$? + sg_clock; ms=$((sg_now - t0)) + if [ -n "$sg_coarse" ]; then + [ "$ms" -ge 2000 ] || ms=0 + sg_probe_ms=$((sg_now - sg_probe_first)) + [ "$sg_probe_ms" -ge 2000 ] || sg_probe_ms=0 + elif [ "$ms" -gt 0 ]; then + sg_probe_ms=$((sg_probe_ms + ms)) + fi + [ "$ms" -le "$sg_probe_max_ms" ] || sg_probe_max_ms=$ms + if [ "$sg_probe_ms" -gt 0 ]; then + export SG_LAUNCHER_PROBE_MS=$sg_probe_ms SG_LAUNCHER_PROBE_MAX_MS=$sg_probe_max_ms + fi + return $rc +} + # True iff arg is a "M.m" version string >= 3.10. claude_agent_sdk requires # Python >= 3.10; below that, pip install fails ("No matching distribution") # and the LLM-powered review (Stop / commit / push) silently no-ops while @@ -139,7 +182,7 @@ is_sdk_compatible() { # than this list are pass 2b. for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do on_path "$cmd" || continue - v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; } + ask "$cmd" || { note_unreadable "$cmd"; continue; } v=${v%$'\r'} if is_sdk_compatible "$v"; then exec "$cmd" "$@" @@ -154,7 +197,7 @@ for cmd in "python3" "python" "py -3"; do # shellcheck disable=SC2086 on_path $cmd || continue # shellcheck disable=SC2086 - v=$(probe $cmd) || { note_unreadable "$cmd"; continue; } + ask $cmd || { note_unreadable "$cmd"; continue; } v=${v%$'\r'} if is_sdk_compatible "$v"; then # shellcheck disable=SC2086 @@ -229,7 +272,7 @@ sg_tried="|" for cmd in "${sg_candidates[@]}"; do case "$sg_tried" in *"|$cmd|"*) continue ;; esac sg_tried="$sg_tried$cmd|" - v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; } + ask "$cmd" || { note_unreadable "$cmd"; continue; } v=${v%$'\r'} if is_sdk_compatible "$v"; then exec "$cmd" "$@" |
