diff options
| author | Claude <noreply@anthropic.com> | 2026-10-20 22:36:29 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-20 22:36:29 +0000 |
| commit | 6d4e17c8c4d45de2eba6dce119e56fff18ae43b1 (patch) | |
| tree | 701885afff4bfa63b7dbf1b7c8af7492e9aa90a0 /plugins/security-guidance/hooks | |
| parent | d2919136660832d06d5260677b256033c7dbdbda (diff) | |
| parent | beecef224291d252a87f58c5e83df28d15fe3450 (diff) | |
Merge branch 'main' into mhegazy/sg-launcher-probe-timingmhegazy/sg-launcher-probe-timing
Diffstat (limited to 'plugins/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 53 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 148 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/ensure_agent_sdk.py | 136 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 388 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 365 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 317 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/sg-python.sh | 21 |
7 files changed, 1278 insertions, 150 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index 0ec54e35..e5959e68 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -5,6 +5,7 @@ This module exists so that ``patterns``/``session_state``/``gitutil`` can use ``debug_log`` without importing ``security_reminder_hook`` (which would be a circular import). It must stay free of any other intra-plugin imports. """ +import glob import json import os import re @@ -33,11 +34,53 @@ def state_dir(): """ explicit = os.environ.get("SECURITY_WARNINGS_STATE_DIR") if explicit: - return os.path.expanduser(explicit) - cc_config = os.environ.get("CLAUDE_CONFIG_DIR") - if cc_config: - return os.path.expanduser(os.path.join(cc_config, "security")) - return os.path.expanduser("~/.claude/security") + d = explicit + elif os.environ.get("CLAUDE_CONFIG_DIR"): + d = os.path.join(os.environ["CLAUDE_CONFIG_DIR"], "security") + else: + d = "~/.claude/security" + return os.path.abspath(os.path.expanduser(d)) + + +def llm_reviews_switched_off(): + """True when the environment turns off every review that calls a model: + the kill switch (SECURITY_GUIDANCE_DISABLE=1 / ENABLE_SECURITY_REMINDER=0), + ENABLE_CODE_SECURITY_REVIEW=0, or ENABLE_STOP_REVIEW=0 together with + ENABLE_COMMIT_REVIEW=0. Nothing loads the agent SDK then, so nothing + should install it. Same reading of each variable as + security_reminder_hook.py.""" + env = os.environ.get + if env("SECURITY_GUIDANCE_DISABLE", "").strip().lower() in ("1", "true", "yes", "on"): + return True + if env("ENABLE_SECURITY_REMINDER", "1") == "0": + return True + if env("ENABLE_CODE_SECURITY_REVIEW", "1") == "0": + return True + return env("ENABLE_STOP_REVIEW", "1") == "0" and env("ENABLE_COMMIT_REVIEW", "1") == "0" + + +def agent_sdk_site_dirs(state_dir): + """Directories under the state dir that ensure_agent_sdk.py installs the + agent SDK into and llm.py adds to sys.path: the venv's site-packages + (POSIX `lib/pythonX.Y/site-packages`, Windows `Lib/site-packages`) and + the flat `pip install --target` fallback.""" + venv_root = os.path.join(state_dir, "agent-sdk-venv") + return ( + glob.glob(os.path.join(venv_root, "lib", "python*", "site-packages")) + + glob.glob(os.path.join(venv_root, "Lib", "site-packages")) + + [os.path.join(state_dir, "agent-sdk-libs")] + ) + + +def agent_sdk_installed(state_dir): + """True iff one of those directories holds a finished install of the SDK: + its package and the metadata pip writes once the package is unpacked. A + file check only, no import.""" + return any( + os.path.isfile(os.path.join(d, "claude_agent_sdk", "__init__.py")) + and glob.glob(os.path.join(d, "claude_agent_sdk-*.dist-info")) + for d in agent_sdk_site_dirs(state_dir) + ) # Debug log file. Lives under the plugin state dir (default ~/.claude/security/) diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index f2d9dbe4..d3dd2a51 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -8,6 +8,7 @@ to work without retargeting. """ import os import subprocess +import sys import time from _base import debug_log, _PV @@ -17,6 +18,7 @@ from gitutil import ( _git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index, ) from session_state import with_locked_state +from extensibility import _same_dir # ===================================================================== @@ -96,6 +98,10 @@ def consume_stop_state(session_id, clear=True): "touched_paths": list(state.get("touched_paths", [])), "baseline_sha": state.get("baseline_sha"), "head_at_capture": state.get("head_at_capture"), + # Where and when the prompt hook captured it; see baseline_origin. + "baseline_root": state.get("baseline_root"), + "prompt_at": state.get("prompt_at"), + "baseline_kept": state.get("baseline_kept") or 0, "untracked_at_baseline": ( dict(state["untracked_at_baseline"]) if isinstance(state.get("untracked_at_baseline"), dict) else {} @@ -107,8 +113,17 @@ def consume_stop_state(session_id, clear=True): # State lost or overwritten since the last Stop (session_state). "state_resets": state.get("state_resets", 0), "state_overwrites": state.get("state_overwrites", 0), + "baseline_fail": state.get("baseline_fail") or 0, } + # touched_paths is cleared per Stop, but one baseline can be + # reviewed by several Stops (rewakes). turn_touched keeps every path + # recorded since the baseline; only telemetry reads it. + turn = list(dict.fromkeys( + [p for p in state.get("turn_touched", []) if isinstance(p, str)] + + snap["touched_paths"]))[-200:] + snap["turn_touched"] = turn if clear: + state["turn_touched"] = turn state["touched_paths"] = [] state.pop("reviewed_diff_hash", None) state.pop("state_resets", None) @@ -117,12 +132,70 @@ def consume_stop_state(session_id, clear=True): return with_locked_state(session_id, _snap) or { "touched_paths": [], "baseline_sha": None, "head_at_capture": None, - "untracked_at_baseline": {}, + "untracked_at_baseline": {}, "baseline_root": None, "prompt_at": None, + "baseline_kept": 0, "fire_count": 0, "fire_count_expired": False, "previous_findings": [], "reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0, + "baseline_fail": 0, "turn_touched": [], } +# Path names compare without case where the filesystem usually does. +_FOLD_CASE = os.name == "nt" or sys.platform == "darwin" + + +def _rel_in_repo(real_root, path): + """`path` relative to the repo root (a real path), or None when it lies + outside the repo.""" + real = os.path.realpath(path) + try: + rel = os.path.relpath(real, real_root) + except ValueError: # another drive + return None + if rel == os.pardir or rel.startswith(os.pardir + os.sep): + return None + return rel.casefold() if _FOLD_CASE else rel + + +def touched_scope(repo_root, cwd, touched_paths): + """Where the paths the session's edit tools wrote since the baseline lie: + (scope, repo-relative paths inside the repo). scope: 0 none recorded, + 1 all inside the reviewed repo, 2 some outside, 3 all outside. Relative + paths are read against `cwd`. The list holds the newest 200 paths, so + this is approximate past that. Telemetry only.""" + root = os.path.realpath(repo_root) + inside, outside = set(), 0 + for p in touched_paths: + rel = _rel_in_repo(root, os.path.join(cwd or root, p)) + if rel is None: + outside += 1 + else: + inside.add(rel) + if not touched_paths: + return 0, inside + if not outside: + return 1, inside + return (2 if inside else 3), inside + + +def review_scope_code(repo_root, scope, inside, files, base_fail): + """One number, for telemetry only, saying how a Stop review relates to + what the session's edit tools wrote since the baseline: + + base_fail * 100000 + scope * 10000 + min(untouched, 9999) + + scope and inside: from touched_scope. untouched: how many of `files` + (repo-root-relative or absolute) no edit tool wrote. base_fail: 0 the + review diffed against a real turn-start snapshot, 1 and 2 see + last_baseline_fail, 3 there was no usable snapshot. Packed into one key + and sent even when 0, so a row without it was cut by the metrics key cap + or had no repo.""" + root = os.path.realpath(repo_root) + untouched = sum(1 for f in files + if _rel_in_repo(root, os.path.join(root, f)) not in inside) + return int(base_fail or 0) * 100000 + scope * 10000 + min(untouched, 9999) + + def record_reviewed_diff(session_id, diff_hash): def _save(state): state["reviewed_diff_hash"] = diff_hash @@ -153,6 +226,48 @@ def restore_unreviewed_stop_state(session_id, paths, baseline_sha): with_locked_state(session_id, _restore) +# state["baseline_kept"]: why a prompt left an earlier turn's baseline in +# place. Only telemetry reads it. +KEPT_NO_CAPTURE = 1 # it could not capture one (not a repo, or git failed) +KEPT_UNREVIEWED = 2 # the previous turn's edits were never reviewed + +# baseline_origin() values that mean "captured in another checkout". +FOREIGN_ORIGINS = (1, 2, 3) + + +def baseline_origin(repo_root, baseline_sha, baseline_root): + """Where the session's baseline was captured, relative to the checkout a + Stop review is about to read (`repo_root`): + + 0 that checkout (or the origin was not recorded) + 1 another worktree of the same repository + 2 another repository + 3 another folder, which is gone or cannot be read as a checkout + 4 there is no baseline + + `baseline_root` is the repo root the prompt hook stored beside the SHA.""" + if not baseline_sha: + return 4 + if not baseline_root or not isinstance(baseline_root, str): + return 0 + if _same_dir(baseline_root, repo_root): + return 0 + if not os.path.isdir(baseline_root): + return 3 + here, there = _git_dir(repo_root), _git_dir(baseline_root) + if not here or not there: + return 3 + return 1 if _same_dir(here, there) else 2 + + +def baseline_origin_metric(origin, kept): + """The `bl_origin` number on Stop rows: baseline_origin, plus 10 or 20 + (KEPT_*) when the baseline is an earlier turn's.""" + if origin == 4 or kept not in (KEPT_NO_CAPTURE, KEPT_UNREVIEWED): + return origin + return origin + 10 * kept + + def get_baseline_file_content(session_id, file_path, cwd): """Get the content of a file at the baseline SHA. Returns None if unavailable. @@ -186,6 +301,14 @@ def get_baseline_file_content(session_id, file_path, cwd): return None +# How the last capture_git_baseline call got its SHA: 0 a real snapshot, +# 1 `stash create` failed and HEAD was returned, 2 no index copy and HEAD was +# returned. With 1 or 2 the next Stop review cannot tell the turn's changes +# from uncommitted work that was already there. Stored with baseline_sha. +# Telemetry only. +last_baseline_fail = 0 + + def capture_git_baseline(cwd): """ Capture a git ref representing the current working tree state. @@ -212,6 +335,8 @@ 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 + last_baseline_fail = 0 try: # Check if HEAD exists (i.e., repo has at least one commit) head_check = subprocess.run( @@ -233,6 +358,10 @@ def capture_git_baseline(cwd): cwd=cwd, capture_output=True, timeout=15, env=env ) sha = (result.stdout or b"").decode("utf-8", errors="replace").strip() + if not sha and result.returncode != 0: + last_baseline_fail = 1 + else: + last_baseline_fail = 2 if sha: return sha @@ -605,7 +734,8 @@ def _list_untracked(cwd): debug_log(f"_list_untracked error: {e}") return {} -def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_baseline=None): +def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_baseline=None, + since_ns=None): """v2 diff strategy: derive the review set from git state alone. review_set = (files dirty vs current HEAD, plus files committed this turn @@ -620,6 +750,10 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel A file is excluded only if it was untracked at baseline AND its mtime is unchanged — an in-place edit during the turn is still reviewed. + since_ns: for a checkout the prompt hook took no baseline or snapshot of + (the turn moved into it), the time the turn began. A dirty or untracked + file last written before then was already that way and is left out. + Known limitation: a Bash-only turn that's interrupted before Stop fires leaves touched_paths empty, so the next UPS re-baselines past those edits. v1 never reviews Bash-only turns at all, so v2 is no worse there. @@ -662,6 +796,16 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel return max(st.st_mtime_ns, st.st_ctime_ns) < capped_at_ns - _CAPPED_BASELINE_SLACK_NS preexisting_unchanged = {p for p in untracked if _unchanged_since_baseline(p)} + if since_ns: + def _written_before_turn(p): + try: + st = os.stat(os.path.join(repo, p)) + except OSError: + return False + return max(st.st_mtime_ns, st.st_ctime_ns) < since_ns - _CAPPED_BASELINE_SLACK_NS + + preexisting_unchanged |= {p for p in untracked if _written_before_turn(p)} + tracked_dirty = {p for p in tracked_dirty if not _written_before_turn(p)} new_untracked = untracked - preexisting_unchanged dirty_now = tracked_dirty | new_untracked diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index c74c40f0..d3aaf96b 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -31,6 +31,25 @@ from _base import ( launcher_probe_metrics, portable_output, state_dir as _resolve_state_dir, write_hook_output, ) +from _base import llm_reviews_switched_off + + +def _spawn_cwd() -> str: + """Working directory for every Python this file starts. + + `python -c` and `python -m` put the working directory first on the import + path, and hooks run in the user's repository, so a repository file named + `claude_agent_sdk.py`, `venv.py` or `pip.py` would be imported in place + of the real module. The state dir is the plugin's own (the venv is built + there, so the interpreter can reach it); the plugin folder is the + fallback when it can't be created. + """ + d = _resolve_state_dir() + try: + os.makedirs(d, exist_ok=True) + return d + except OSError: + return str(Path(__file__).resolve().parent.parent) # Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry. NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python @@ -58,6 +77,9 @@ SKIP_COOLDOWN = 9 # a recent build was signal-killed (memory pressure) — no # repro confirmed the dominant Linux BUILD_FAILED is a # SIGKILL/SIGSEGV of the memory-heavy venv+pip subprocess # (rc<0, empty streams). See #2154 follow-up. +SKIP_REVIEWS_OFF = 10 # the environment turns off every review that would + # load the SDK (kill switch included), so nothing is + # installed. See #5331. # How long to skip rebuilds after a signal kill. Retries at most once per # window so a machine whose memory frees up still recovers (just not every @@ -314,7 +336,7 @@ def _probe_has_pip() -> bool: try: r = subprocess.run( [sys.executable, "-m", "pip", "--version"], - capture_output=True, timeout=10, + capture_output=True, timeout=10, cwd=_spawn_cwd(), ) return r.returncode == 0 except Exception: @@ -395,6 +417,20 @@ def _pip_err_from_stderr(stderr_b): return f"other:{tail}" if tail else "other" +# A package directory that has lost its files still imports, as a namespace +# package, so a bare `import claude_agent_sdk` calls an emptied install +# healthy and it is never rebuilt. A real install has a __file__; the probe +# exits with _PROBE_EMPTIED when there is none. See #6612. +_PROBE_EMPTIED = 3 +_SDK_IMPORT_PROBE = ( + "import sys, claude_agent_sdk; " + f"sys.exit(0 if getattr(claude_agent_sdk, '__file__', None) else {_PROBE_EMPTIED})" +) + +# Set by main() when the venv's probe exited with _PROBE_EMPTIED. +_venv_was_emptied = False + + def _target_dir(state_dir) -> Path: return Path(state_dir) / "agent-sdk-libs" @@ -410,9 +446,9 @@ def _target_sdk_importable(state_dir) -> bool: try: r = subprocess.run( [sys.executable, "-c", - "import sys; sys.path.insert(0, sys.argv[1]); import claude_agent_sdk", + "import sys; sys.path.insert(0, sys.argv[1]); " + _SDK_IMPORT_PROBE, str(target)], - capture_output=True, timeout=10, + capture_output=True, timeout=10, cwd=_spawn_cwd(), ) return r.returncode == 0 except Exception: @@ -437,7 +473,7 @@ def _build_via_target(state_dir) -> tuple[int, str, str]: "--target", str(target), "--upgrade", "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir", "claude-agent-sdk"], - capture_output=True, timeout=120, check=True, + capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(), ) return BUILT_TARGET, "", "" except subprocess.CalledProcessError as e: @@ -456,6 +492,79 @@ def _build_via_target(state_dir) -> tuple[int, str, str]: return BUILD_FAILED, "pip_target", f"exc:{type(e).__name__}" +def _near_git_repo() -> bool: + """Whether the session's directory is in a git work tree (a `.git` entry + here or above) or directly holds one (a workspace of repositories). The + reviews the SDK serves only run on a repository.""" + try: + top = d = os.path.abspath(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()) + while True: + if os.path.exists(os.path.join(d, ".git")): + return True + parent = os.path.dirname(d) + if parent == d: + break + d = parent + with os.scandir(top) as entries: + for i, entry in enumerate(entries): + if i >= 500: + return True # too large to say; not counted + if entry.is_dir() and os.path.exists(os.path.join(entry.path, ".git")): + return True + return False + except OSError: + return True + + +def _venv_python_version(venv) -> int: + """The Python the venv was built with, as major*100+minor (312), read + from its pyvenv.cfg; 0 if unknown.""" + try: + for line in (Path(venv) / "pyvenv.cfg").read_text(errors="replace").splitlines(): + key, _, value = line.partition("=") + if key.strip() in ("version", "version_info"): + major, minor = value.strip().split(".")[:2] + return int(major) * 100 + int(minor) + except (OSError, ValueError): + pass + return 0 + + +def _install_context_metrics(outcome, state_dir) -> dict: + """Counts that size open questions about the private SDK install; no + behaviour depends on them. Only when set, and the first three only on + rows where the install exists. + + sdk_no_creds / sdk_no_git: the session holds the install while the + reviews it serves cannot run, for lack of model credentials or of a git + repository. Should the build wait for those? See #5331. + + sdk_venv_py: the venv was built by another Python version than the one + running the hooks, which is the one that loads it; its compiled + dependencies do not load there. See #5706. + + sdk_venv_emptied: the venv's SDK package directory had lost its files + and this run went on to rebuild it, whatever the outcome. See #6612.""" + out = {} + if _venv_was_emptied: + out["sdk_venv_emptied"] = 1 + if outcome not in (NOOP_VENV, BUILT, BUILT_TARGET, NOOP_TARGET): + return out + try: + import llm + if not llm.HAS_API_CREDENTIALS: + out["sdk_no_creds"] = 1 + except Exception: + pass + if not _near_git_repo(): + out["sdk_no_git"] = 1 + if outcome == NOOP_VENV: + built_by = _venv_python_version(Path(state_dir) / "agent-sdk-venv") + if built_by and built_by != sys.version_info[0] * 100 + sys.version_info[1]: + out["sdk_venv_py"] = built_by + return out + + def _sdk_on_syspath() -> bool: # find_spec is ~10ms; actually importing the SDK pulls in # transitive deps and costs ~800ms — too heavy for a @@ -484,6 +593,15 @@ def main() -> tuple[int, str, str]: err_phase / err_kind are non-empty only on BUILD_FAILED — they let telemetry split bootstrap failures by root cause. """ + global _venv_was_emptied + _venv_was_emptied = False + # The SDK only serves the LLM reviews. With those switched off, or the + # whole plugin (SECURITY_GUIDANCE_DISABLE=1), a venv of a few hundred MB + # would be built for code that never runs, and the notice below would + # advertise a reviewer the user turned off. See #5331. + if llm_reviews_switched_off(): + return SKIP_REVIEWS_OFF, "", "" + # Honesty check (fixes the misleading NOOP_VENV in #2071): the SDK # requires Python >=3.10 and uses 3.10+ syntax (match statements, # PEP 604 unions). On a 3.9 hook interpreter we CANNOT import it no @@ -536,11 +654,12 @@ def main() -> tuple[int, str, str]: if venv_py.exists(): try: r = subprocess.run( - [str(venv_py), "-c", "import claude_agent_sdk"], - capture_output=True, timeout=10, + [str(venv_py), "-c", _SDK_IMPORT_PROBE], + capture_output=True, timeout=10, cwd=_spawn_cwd(), ) if r.returncode == 0: return NOOP_VENV, "", "" + _venv_was_emptied = r.returncode == _PROBE_EMPTIED except Exception: pass # broken venv; rebuild below @@ -573,7 +692,7 @@ def main() -> tuple[int, str, str]: err_phase = "venv" subprocess.run( [sys.executable, "-m", "venv", "--clear", str(venv)], - capture_output=True, timeout=60, check=True, + capture_output=True, timeout=60, check=True, cwd=_spawn_cwd(), ) # Some machines route pip through a private registry; we # don't pass --index-url here so we inherit that default. Outside @@ -597,7 +716,7 @@ def main() -> tuple[int, str, str]: [str(venv_py), "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir", "claude-agent-sdk"], - capture_output=True, timeout=120, check=True, + capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(), ) return BUILT, "", "" except subprocess.CalledProcessError as e: @@ -849,6 +968,7 @@ if __name__ == "__main__": # HOOK_PY_INCOMPATIBLE (whose "py_3.9" err_kind otherwise collapses to # err=99, losing the version). Cheap — no subprocess, just sys.version_info. metrics["sdk_hook_py"] = sys.version_info[0] * 100 + sys.version_info[1] + metrics.update(_install_context_metrics(outcome, _resolve_state_dir())) pv = _plugin_version_int() if pv: metrics["pv"] = pv diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index bc4d753b..4177a573 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -18,6 +18,9 @@ import contextlib import os import re import subprocess +import tempfile +import threading +import time from _base import debug_log @@ -48,11 +51,27 @@ GIT_CMD = [ "-c", "diff.noprefix=false", "-c", "diff.srcPrefix=a/", "-c", "diff.dstPrefix=b/", + # A directory with its own `.git` inside the work tree (a submodule, a + # 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. + "-c", "diff.ignoreSubmodules=all", + "-c", "diff.submodule=short", ] +# diff.ignoreSubmodules is a default that the repository's own settings for +# one submodule (.gitmodules, submodule.<name>.ignore) override. The option +# cannot be overridden. Pass it to every `git status` and work-tree `git diff`. +IGNORE_SUBMODULES = "--ignore-submodules=all" + SAFE_GIT_CONFIG = ( ("core.fsmonitor", "false"), ("core.hooksPath", "/dev/null"), + ("diff.ignoreSubmodules", "all"), + ("diff.submodule", "short"), ) # The hook's git runs in the background beside the session's own git. Without @@ -448,8 +467,11 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths): # `git status` and here would silently drop ALL untracked files # from the diff. --ignore-missing only works with --dry-run, so # filter to surviving paths (lexists so dangling symlinks count). + # A nested repository (`dir/`) would be added as a submodule + # entry; see diff.ignoreSubmodules in GIT_CMD. surviving = [p for p in untracked_paths - if os.path.lexists(os.path.join(cwd, p))] + if not p.endswith("/") + and os.path.lexists(os.path.join(cwd, p))] add_args = ["--"] + surviving if surviving else None else: add_args = None @@ -487,6 +509,41 @@ def _git_toplevel(cwd): return None +def _git_toplevel_and_head(cwd): + """(repo root, HEAD SHA) for `cwd` from one git call, or (None, None) + when git cannot give both (not a work tree, no commits).""" + try: + r = subprocess.run( + [*GIT_CMD, "rev-parse", "--show-toplevel", "HEAD"], + cwd=cwd, capture_output=True, timeout=5, + ) + except (subprocess.TimeoutExpired, FileNotFoundError, OSError): + return None, None + if r.returncode != 0: + return None, None + # See #2099: the first line is a PATH, so decode the bytes manually. + top, _, head = r.stdout.decode("utf-8", errors="replace").strip().rpartition("\n") + return (top.strip() or None), (head.strip() or None) + + +def _git_head_at(cwd, epoch): + """The SHA this checkout's HEAD pointed at just before `epoch` (seconds), + read from its own reflog. A checkout created after `epoch` answers with + the commit it was created at. None when git cannot say (no reflog).""" + try: + # Reflog times are whole seconds: ask for the second before, so a + # commit made in the same second as `epoch` counts as after it. + r = subprocess.run( + [*GIT_CMD, "rev-parse", "--verify", "-q", f"HEAD@{{@{int(epoch) - 1}}}"], + cwd=cwd, capture_output=True, timeout=5, + ) + except (subprocess.TimeoutExpired, FileNotFoundError, OSError, + TypeError, ValueError, OverflowError): + return None + sha = r.stdout.decode("utf-8", errors="replace").strip() + return sha if r.returncode == 0 and sha else None + + def _git_dir(repo_root): """Absolute shared `.git` directory for repo_root. @@ -673,7 +730,7 @@ def _git_name_only(cwd, base, include_untracked=False): def _run(env): # core.quotePath=false comes from GIT_CMD globally (see definition). result = subprocess.run( - [*GIT_CMD, "diff", "--name-only", "-z", base], + [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-only", "-z", base], cwd=cwd, capture_output=True, timeout=30, env=env, ) @@ -714,7 +771,7 @@ def _git_status_porcelain(cwd): try: # core.quotePath=false comes from GIT_CMD globally (see definition). r = subprocess.run( - [*GIT_CMD, "status", "--porcelain=v1", "-uall", "-z"], + [*GIT_CMD, "status", IGNORE_SUBMODULES, "--porcelain=v1", "-uall", "-z"], cwd=cwd, capture_output=True, timeout=30, ) if r.returncode != 0: @@ -732,7 +789,10 @@ def _git_status_porcelain(cwd): continue xy, path = e[:2], e[3:] if xy == "??": - untracked.add(path) + # With -uall only a nested repository is listed as `dir/`. + # It is not a file to review; see diff.ignoreSubmodules. + if not path.endswith("/"): + untracked.add(path) else: tracked.add(path) # Rename/copy entries are XY old\0new\0 — second NUL field is @@ -766,6 +826,264 @@ def _is_ancestor(cwd, maybe_ancestor, descendant): return False +_DEFAULT_FILE_DIFF_BYTES = 4 * 1024 * 1024 +_LATE_FILE_DIFF_BYTES = 256 * 1024 +_LAST_FILE_DIFF_BYTES = 96 * 1024 + + +def _file_diff_cap(): + """SG_MAX_FILE_DIFF_BYTES, or the default when it is unset, not a number + or not positive. Never below what a late file keeps, which is well above + what the review prompt takes of one file.""" + try: + n = int(os.environ.get("SG_MAX_FILE_DIFF_BYTES", "")) + except ValueError: + return _DEFAULT_FILE_DIFF_BYTES + if n <= 0: + return _DEFAULT_FILE_DIFF_BYTES + return max(n, _LATE_FILE_DIFF_BYTES) + + +# How much of one file's diff the Stop review keeps while it reads git's +# output: this much from the start of the file's section, and as much again +# of the added lines after that. The review prompt takes far less of a file +# (DIFF_PER_FILE_BYTES); the rest is for filter_preexisting_from_diff, which +# needs the removed and the added side of a rewritten file. +MAX_FILE_DIFF_BYTES = _file_diff_cap() +# Past this much kept in total, a further file keeps _LATE_FILE_DIFF_BYTES +# the same two ways; past four times as much, _LAST_FILE_DIFF_BYTES from its +# start, which is still more than the review prompt takes of one file. +MAX_KEPT_DIFF_BYTES = 4 * MAX_FILE_DIFF_BYTES +_SECTION_MARK = b"\ndiff --git " +_MAX_HEADER_BYTES = 64 * 1024 +_CUT_MARK = b"\\ [cut by security-guidance: the rest of this file's diff was not read]\n" + +# What the last get_git_diff read, for the Stop hook's metrics: bytes of git +# output, reviewable files whose diff was cut and the bytes cut from them, +# and diffs that hit the timeout during this hook run. +_diff_read = {"bytes": 0, "cut_files": 0, "cut_bytes": 0, "timeouts": 0} + + +class _DiffKeeper: + """Takes `git diff` output as it arrives and keeps only what the review + can use: the header line of every file, and a bounded part of each file + parse_diff_into_files would keep. A turn that wrote large data files no + longer puts their whole diff in memory.""" + + def __init__(self): + self.parts = [] + self.kept = 0 + self.seen = 0 + self.cut_files = 0 + self.cut_bytes = 0 + # Unhandled input. Starts as a newline that is not git's, so a header + # at the very start of the output is found like any other. + self._pending = b"\n" + self._at_start = True + self._reviewable = True + self._room = self._added_room = MAX_FILE_DIFF_BYTES + self._cut = False + self._ends_nl = True + # Past the cut: whether the next byte starts a line, and whether the + # line being read is an added one. + self._bol = True + self._in_added = False + + def feed(self, data): + buf = self._pending + data + pos = 0 + while True: + i = buf.find(_SECTION_MARK, pos) + if i < 0: + # Hold back a tail that could be the start of a header. + end = max(pos, len(buf) - len(_SECTION_MARK) + 1) + self._keep(buf, pos, end) + self._pending = buf[end:] + return + j = buf.find(b"\n", i + 1) + if j < 0 and len(buf) - i <= _MAX_HEADER_BYTES: + # The header line is not complete yet. + self._keep(buf, pos, i) + self._pending = buf[i:] + return + self._keep(buf, pos, i + 1) + if j >= 0: + self._begin(buf[i + 1:j]) + pos = i + 1 + + def _begin(self, header): + """A new file's section starts with this `diff --git ` line.""" + self._end_section() + text = header[len(_SECTION_MARK) - 1:].decode("utf-8", errors="replace") + paths = _parse_diff_header(text) + # A section the parser drops, or whose header it cannot read and only + # counts, keeps its header line. + self._reviewable = bool(paths) and _section_is_reviewable( + paths[1] or paths[0], paths[0]) + if not self._reviewable: + self._room, self._added_room = len(header) + 1, 0 + elif self.kept > 4 * MAX_KEPT_DIFF_BYTES: + self._room, self._added_room = max(len(header) + 1, _LAST_FILE_DIFF_BYTES), 0 + elif self.kept > MAX_KEPT_DIFF_BYTES: + self._room = self._added_room = max(len(header) + 1, _LATE_FILE_DIFF_BYTES) + else: + self._room = self._added_room = MAX_FILE_DIFF_BYTES + self._cut = False + + def _end_section(self): + if not self._ends_nl: + # Cut inside a line: end it, so what follows starts a line. + self._append(b"\n") + if self._cut: + self._append(_CUT_MARK) + + def _append(self, piece): + self.parts.append(piece) + self.kept += len(piece) + self._ends_nl = piece.endswith(b"\n") + + def _keep(self, buf, start, end): + if self._at_start and end > start: + self._at_start = False + start += 1 + n = end - start + if n <= 0: + return + self.seen += n + take = min(n, self._room) + if take: + self._append(buf[start:start + take]) + self._room -= take + if take == n or not self._reviewable: + return + if not self._cut: + self._cut = True + self.cut_files += 1 + self._bol = self._ends_nl + self._in_added = False + self.cut_bytes += n - take - self._keep_added(buf, start + take, end) + + def _keep_added(self, buf, pos, end): + """Past a file's cut, keep its added lines only, up to as much again. + A rewritten file lists every removed line before the first added one, + and the review is about the added ones. Returns the bytes kept.""" + kept = 0 + run = -1 # where a run of added lines not yet appended starts + while pos < end and self._added_room > 0: + if self._bol: + self._bol = False + self._in_added = buf.startswith(b"+", pos) + if self._in_added and run < 0 and not self._ends_nl: + self._append(b"\n") + if not self._in_added: + if run >= 0: + self._append(buf[run:pos]) + run = -1 + nxt = buf.find(b"\n+", pos, end) + if nxt < 0: + self._bol = buf.endswith(b"\n", pos, end) + break + pos = nxt + 1 + self._bol = True + continue + nl = buf.find(b"\n", pos, end) + stop = end if nl < 0 else nl + 1 + take = min(stop - pos, self._added_room) + if run < 0: + run = pos + self._added_room -= take + kept += take + self._bol = nl >= 0 + if pos + take < stop: + self._append(buf[run:pos + take]) + run = -1 + pos = stop + if run >= 0: + self._append(buf[run:pos]) + return kept + + def result(self): + self._keep(self._pending, 0, len(self._pending)) + self._pending = b"" + self._end_section() + self._cut = False + return b"".join(self.parts) + + +def _run_diff_bounded(cmd, timeout, **kwargs): + """subprocess.run(cmd, capture_output=True, timeout=timeout) for a + `git diff`, except that stdout goes through _DiffKeeper instead of being + held whole.""" + keeper = _DiffKeeper() + deadline = time.monotonic() + timeout + try: + err = tempfile.TemporaryFile() + except OSError: + err = None + try: + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stderr=err if err is not None else subprocess.DEVNULL, + **kwargs) + failed = [] + given_up = [] + + def _read(): + try: + while not given_up: + chunk = p.stdout.read1(65536) + if not chunk or given_up: + break + keeper.feed(chunk) + except BaseException as e: + failed.append(e) + + # Read on a thread, so the timeout holds even while something git + # started still has the pipe open after git itself is gone. + reader = threading.Thread(target=_read, daemon=True) + timed_out = False + try: + try: + reader.start() + except RuntimeError as e: + failed.append(e) + else: + reader.join(timeout) + timed_out = reader.is_alive() + if timed_out or failed: + p.kill() + try: + returncode = p.wait(max(deadline - time.monotonic(), 0.1)) + except subprocess.TimeoutExpired: + timed_out = True + finally: + if timed_out or failed or p.returncode is None: + # The reader may be left waiting on a pipe something else + # holds: it keeps nothing more, and the pipe stays its. + given_up.append(True) + p.kill() + p.wait() + if reader.ident is not None: + reader.join(1) + if not reader.is_alive(): + p.stdout.close() + _diff_read["bytes"] += keeper.seen + if timed_out: + _diff_read["timeouts"] += 1 + raise subprocess.TimeoutExpired(cmd, timeout) + if failed: + raise OSError(f"reading the diff failed: {failed[0]!r}") + stdout = keeper.result() + _diff_read["cut_files"] += keeper.cut_files + _diff_read["cut_bytes"] += keeper.cut_bytes + stderr = b"" + if err is not None: + err.seek(0) + stderr = err.read(4096) + return subprocess.CompletedProcess(cmd, returncode, stdout, stderr) + finally: + if err is not None: + err.close() + def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_paths=None): """ @@ -781,6 +1099,9 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa cwd; absolute paths are converted, paths outside cwd are dropped). `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. """ pathspec = _diff_pathspec(cwd, paths) if paths and not pathspec: @@ -791,17 +1112,18 @@ 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", "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec + cmd = [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec + _diff_read.update(bytes=0, cut_files=0, cut_bytes=0) try: if untracked_paths is not None and not untracked_paths: # Nothing to `add -N`, and the diff only reads the index. - result = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=30) + 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 = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=30, env=env) + 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 @@ -874,9 +1196,12 @@ _SSH_PRIVATE_KEY_BASENAMES = frozenset(( 'id_ed25519_sk', 'id_xmss', )) _PRIVATE_KEY_NAME_SUFFIXES = ('_rsa', '_dsa', '_ecdsa', '_ed25519') +# `.credentials.json` and `.claude.json` are Claude Code's own files: sign-in +# tokens, a saved API key, MCP server secrets. Claude Code rewrites them as it +# runs, so they show up as changed when its config directory is a git repo. _CREDENTIAL_BASENAMES = frozenset(( 'credentials', '.netrc', '.pgpass', '.npmrc', '.pypirc', - '.git-credentials', '.dockercfg', + '.git-credentials', '.dockercfg', '.credentials.json', '.claude.json', )) # chezmoi encodes a target file's attributes as stacked name prefixes # (`private_dot_netrc`, `encrypted_private_token`); `dot_` stands for a @@ -934,6 +1259,42 @@ def _is_secret_shaped(file_path): return False +# Data files whose name says they hold secrets (`secrets.yml`, +# `client_secret.json`). They are reviewed like any other data file; the Stop +# hook only counts how many are in its review set (never the names), to show +# how common they are. +_SECRET_NAMED_STEMS = frozenset(( + 'secret', 'secrets', 'credential', 'credentials', + 'client_secret', 'client_secrets', 'client-secret', 'client-secrets', + 'service-account', 'service_account', 'serviceaccount', + 'service-account-key', 'service_account_key', 'serviceaccountkey', +)) +_SECRET_NAMED_DATA_EXTENSIONS = frozenset(( + '.json', '.yaml', '.yml', '.toml', '.properties', '.tfvars', +)) +# `secrets.example.yml` is a placeholder and `secrets.enc.yaml` is ciphertext. +_NOT_SECRET_NAME_PARTS = frozenset(( + 'example', 'sample', 'template', 'tmpl', 'dist', 'schema', + 'enc', 'encrypted', 'sops', +)) + + +def _is_secret_named(file_path): + base = os.path.basename(file_path.replace("\\", "/")).lower() + parts = base.lstrip('.').split('.') + if len(parts) < 2 or '.' + parts[-1] not in _SECRET_NAMED_DATA_EXTENSIONS: + return False + if _NOT_SECRET_NAME_PARTS.intersection(parts[1:-1]): + return False + stem = parts[0] + # Google's OAuth download is `client_secret_<client id>.json`. + return stem in _SECRET_NAMED_STEMS or stem.startswith('client_secret_') + + +def count_secret_named(diff_files): + return sum(1 for file_path, _ in diff_files if _is_secret_named(file_path)) + + # Path tokens that bump a file's review priority when a commit exceeds # MAX_DIFF_FILES and we have to pick a subset. These are exactly the surfaces # single-shot and agentic reviews disagree on most (auth, routing, IPC, @@ -1116,6 +1477,13 @@ def _parse_diff_header(header): _unparsed_diff_headers = set() +def _section_is_reviewable(file_path, old_path): + """Whether a diff section is sent for review: a source file, and not one + renamed away from a secret-shaped name, which still carries the secret's + content.""" + return _is_reviewable_source(file_path) and not _skip_secret_shaped(old_path) + + def _iter_diff_sections(diff_output): """Yield (new_path, old_path, lines after the header line) per file section.""" for section in _DIFF_SECTION_RE.split(diff_output)[1:]: @@ -1137,7 +1505,7 @@ def extract_file_paths_from_diff(diff_output): return [ file_path for file_path, old_path, _ in _iter_diff_sections(diff_output) - if _is_reviewable_source(file_path) and not _skip_secret_shaped(old_path) + if _section_is_reviewable(file_path, old_path) ] @@ -1153,7 +1521,7 @@ def parse_diff_into_files(diff_output): for file_path, old_path, lines in _iter_diff_sections(diff_output): # Filter to source code files only. A rename away from a secret-shaped # name still carries the secret's content, so the old name counts too. - if not _is_reviewable_source(file_path) or _skip_secret_shaped(old_path): + if not _section_is_reviewable(file_path, old_path): continue # Extract the diff content (from first @@ onwards) diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 9fe8640c..76d04c54 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -17,12 +17,12 @@ Two reassignable globals here are read by handlers in ``_last_review_truncated_bytes``. Handlers reference them as ``llm.X`` (not via ``from``-import) so they observe reassignment. """ -import glob import hashlib import json import logging import os import re +import subprocess import sys import tempfile import threading @@ -30,12 +30,12 @@ import time import traceback import urllib.parse import urllib.request -from typing import Optional, Tuple, Dict, Any, List +from typing import Optional, Tuple, Dict, Any, List, Callable import extensibility import review_api -from _base import debug_log, _record_usage, _record_http_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir # noqa: F401 -from session_state import with_locked_state +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 session_state import load_state, with_locked_state from gitutil import git_config_env, SAFE_GIT_CONFIG @@ -59,17 +59,13 @@ def _inject_agent_sdk_venv_into_syspath(state_dir): fails with `ModuleNotFoundError: pywintypes` and the agentic reviewer falls back to single-shot silently. Replicate what site.py would do. """ - venv_root = os.path.join(state_dir, "agent-sdk-venv") - candidates = ( - glob.glob(os.path.join(venv_root, "lib", "python*", "site-packages")) - + glob.glob(os.path.join(venv_root, "Lib", "site-packages")) - # `pip install --target` fallback (ensure_agent_sdk BUILT_TARGET, used - # when venv can't bootstrap pip): a FLAT layout — packages sit directly - # in agent-sdk-libs/, not under a site-packages subdir. See #2154 - # follow-up. The pywin32 .pth bootstrap below applies here too (target - # installs don't process .pth at runtime, same as a manual venv insert). - + [os.path.join(state_dir, "agent-sdk-libs")] - ) + # `agent-sdk-libs` is the `pip install --target` fallback + # (ensure_agent_sdk BUILT_TARGET, used when venv can't bootstrap pip): a + # FLAT layout, packages sit directly in it, not under a site-packages + # subdir. See #2154 follow-up. The pywin32 .pth bootstrap below applies + # there too (target installs don't process .pth at runtime, same as a + # manual venv insert). + candidates = agent_sdk_site_dirs(state_dir) added = False for sp in candidates: if not os.path.isdir(sp) or sp in sys.path: @@ -322,10 +318,12 @@ def _custom_headers() -> List[Tuple[str, str]]: def gateway_cfg() -> int: - """How the plugin's own API calls are routed, for telemetry: bit 1 when + """How the plugin's reviews are routed, for telemetry: bit 1 when ANTHROPIC_BASE_URL names a host other than api.anthropic.com, bit 2 when - at least one ANTHROPIC_CUSTOM_HEADERS line is sent. 0 when neither. A - number only: no host, header name or value.""" + at least one ANTHROPIC_CUSTOM_HEADERS line is sent, bit 4 when reviews + run through the user's claude on a Claude apps gateway sign-in (see + gateway_review_cli). 0 when none. A number only: no host, header name + or value.""" cfg = 0 base = _anthropic_base_url() try: @@ -336,6 +334,8 @@ def gateway_cfg() -> int: cfg |= 1 if any(name.lower() != "anthropic-beta" for name, _ in _custom_headers()): cfg |= 2 + if _gateway_cli: + cfg |= 4 return cfg @@ -558,16 +558,17 @@ def _write_review_model_cache(path, endpoint_key, model, now): def default_review_model() -> str: """Model for a review the user hasn't pinned with SECURITY_REVIEW_MODEL. - 3P providers go through the Agent SDK, so the CLI alias does the work. - 1P and gateways get the newest Opus the endpoint lists, looked up at most - once per _REVIEW_MODEL_TTL_SECONDS; _PINNED_REVIEW_MODEL when the lookup - can't answer. Never raises. + 3P providers and Claude apps gateway sign-ins go through the Agent SDK, + so the CLI alias does the work. 1P and LLM gateways set with + ANTHROPIC_BASE_URL get the newest Opus the endpoint lists, looked up at + most once per _REVIEW_MODEL_TTL_SECONDS; _PINNED_REVIEW_MODEL when the + lookup can't answer. Never raises. """ global _review_model_memo explicit = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() if explicit: return explicit - if _is_3p_provider(): + if _is_3p_provider() or _gateway_cli: return _CLI_OPUS_ALIAS if not HAS_API_CREDENTIALS: return _PINNED_REVIEW_MODEL @@ -591,16 +592,165 @@ def default_review_model() -> str: return _review_model_memo -def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None): +# A session signed in to a Claude apps gateway with /login gives hooks no +# credential, but a child `claude` restores that sign-in by itself, so reviews +# can run through the user's CLI without a credential entering this process. + +# `claude auth status` may wait for a settings helper script an administrator +# configured, which Claude Code gives 10 s by default. +_GATEWAY_CHECK_TIMEOUT_S = 15 +_GATEWAY_STATE_KEY = "gateway_sign_in" +# The CLI that reviews for a signed-in gateway session, "" when this process +# decided not to use the gateway route, None before it has decided. +_gateway_cli: Optional[str] = None +# True when this process asked the CLI about the sign-in and got no usable +# answer: the reviews are skipped, but the session may well be signed in. +_gateway_check_unanswered = False +# True once a review through the gateway route ran out of time. What makes +# it do so (a rejected sign-in, a gateway that cannot be reached) does not +# depend on the model, so the Sonnet attempt is not made after it. +_gateway_review_timed_out = False + + +def _user_cli_path() -> Optional[str]: + """The user's own `claude`: SG_AGENTIC_CLI_PATH if set ("" selects the + SDK's bundled CLI), else the first of the absolute paths below that + exists, else None.""" + cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") + if cli_path is not None: + return cli_path + # CLAUDE_CODE_EXECPATH is the absolute path to the running CC binary + # itself (e.g. ~/.local/share/claude/versions/2.1.x — that's the binary, + # not a directory). Claude Code sets it for the Bash tool's shells, not for + # hooks, so hooks usually find the CLI at a fixed path below. We do NOT + # fall back to shutil.which("claude") because the hook's cwd is the + # user's (potentially attacker-supplied) repo, and Windows shutil.which + # searches cwd first — a checked-in ./claude.exe would get spawned. + # Absolute-path probes only. + for p in ( + os.environ.get("CLAUDE_CODE_EXECPATH"), + os.path.expanduser("~/.local/bin/claude"), + "/root/.local/bin/claude", + # Claude Code Remote container install path. + "/opt/claude-code/bin/claude", + ): + if p and os.path.isfile(p): + return p + return None + + +def _tolerate_unknown_sdk_messages() -> None: + """Make the SDK's message parser pass unknown message types through + instead of raising: a CLI newer than the SDK emits types the SDK does not + know (e.g. rate_limit_event).""" + try: + from claude_agent_sdk._internal import message_parser as _mp + import claude_agent_sdk._internal.client as _sdk_client + from claude_agent_sdk import SystemMessage as _SysMsg + + _orig_parse = _mp.parse_message + if getattr(_orig_parse, "_sg_tolerant", False): + return + + def _tolerant(data): + try: + return _orig_parse(data) + except Exception: + return _SysMsg(subtype=data.get("type", "unknown"), data=data) + + _tolerant._sg_tolerant = True + _mp.parse_message = _tolerant + _sdk_client.parse_message = _tolerant + except Exception: + pass + + +def _gateway_signed_in(cli: str) -> Optional[bool]: + """Whether `cli auth status --json` reports a session signed in to a + Claude apps gateway. None when the CLI gave no usable answer (an error, a + timeout, or output that is not a JSON object).""" + try: + # A process the CLI starts can keep stdout open after the CLI exits; + # reading a pipe would then wait out the timeout and lose the answer. + with tempfile.TemporaryFile() as out: + subprocess.run( + [cli, "auth", "status", "--json"], stdin=subprocess.DEVNULL, + stdout=out, stderr=subprocess.DEVNULL, + env={**os.environ, **_agentic_spawn_env()}, + cwd=os.path.expanduser("~"), + timeout=_GATEWAY_CHECK_TIMEOUT_S, check=False, + ) + out.seek(0) + status = json.loads(out.read(64 * 1024)) + except Exception as e: + debug_log(f"gateway check: no usable answer from {cli} ({type(e).__name__})") + return None + if not isinstance(status, dict): + debug_log("gateway check: answer was not a JSON object") + return None + provider, logged_in = status.get("apiProvider"), status.get("loggedIn") + debug_log(f"gateway check: apiProvider={str(provider)[:40]!r} loggedIn={repr(logged_in)[:10]}") + # A managed machine that names a gateway but was never signed in also + # reports "gateway". + return provider == "gateway" and logged_in is True + + +def gateway_review_cli(session_id) -> Optional[str]: + """The CLI to review through when the plugin has no credential but the + session is signed in to a Claude apps gateway; None otherwise. A yes or + no from the CLI is kept for the rest of the session, so signing in or + out mid-session takes effect in the next one. When the CLI gives no + usable answer, nothing is saved, so the next hook asks again.""" + global _gateway_cli, _gateway_check_unanswered + if _gateway_cli is not None: + return _gateway_cli or None + cli = _user_cli_path() or "" + ok = None + # No skip for CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, as on Bedrock and Vertex: + # the gateway docs suggest setting it, and the review goes through the + # gateway like the session's own requests. + if not os.path.isabs(cli): + debug_log("gateway check: skipped, SG_AGENTIC_CLI_PATH is not a full path" + if "SG_AGENTIC_CLI_PATH" in os.environ + else "gateway check: skipped, no claude at ~/.local/bin/claude or the other " + "usual full paths (SG_AGENTIC_CLI_PATH can name one)") + else: + cached = load_state(session_id).get(_GATEWAY_STATE_KEY) + if (isinstance(cached, dict) and cached.get("cli") == cli + and isinstance(cached.get("ok"), bool)): + ok = cached["ok"] + debug_log(f"gateway check: using this session's saved answer (signed in: {ok})") + else: + ok = _gateway_signed_in(cli) + _gateway_check_unanswered = ok is None + if ok is not None: + def _save(state): + state[_GATEWAY_STATE_KEY] = {"cli": cli, "ok": ok} + with_locked_state(session_id, _save) + _gateway_cli = cli if ok else "" + return _gateway_cli or None + + +def can_review(session_id) -> bool: + """True when the plugin has a credential, or has none but the session is + signed in to a Claude apps gateway. Call it before reviewing: the review + takes the gateway route only after it has said yes in this process.""" + return HAS_API_CREDENTIALS or gateway_review_cli(session_id) is not None + + +def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, + cli_path=None): """Single-turn SDK call as a substitute for the HTTP _call_claude path on - 3P providers. Uses the same `output_format` JSON-schema contract so the - return value shape is identical (parsed dict or None). + 3P providers, and, with `cli_path` set, for a session signed in to a + Claude apps gateway. Uses the same `output_format` JSON-schema contract so + the return value shape is identical (parsed dict or None). No tools (see _only_tools_args) — the security review only needs structured output, not Read/Grep/Glob. Single turn keeps cost predictable. """ - global _last_call_claude_http_error + global _last_call_claude_http_error, _gateway_review_timed_out _last_call_claude_http_error = None + route = "gateway" if cli_path else "3P" try: import asyncio as _asyncio @@ -625,13 +775,16 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) query, ) except Exception as e: - debug_log(f"3P sdk-single-turn: SDK unavailable ({e})") + debug_log(f"{route} sdk-single-turn: SDK unavailable ({e})") _last_call_claude_http_error = -1 _record_http_error(-1) return None _send_sdk_logs_to_debug_log() - cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None + if cli_path: + _tolerate_unknown_sdk_messages() + else: + cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None default_model = default_review_model() chosen_model = model or default_model @@ -639,6 +792,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) # error (auth missing, model id wrong, etc.) in the debug log instead # of just "exit code 1". _captured_stderr: List[str] = [] + # HTTP statuses (or "no response") the CLI said it retried an API request after. + _retried_after: set = set() async def _arun(): opts = ClaudeAgentOptions( @@ -671,31 +826,46 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) structured = msg.structured_output _record_usage(getattr(msg, "usage", None) or {}, chosen_model, cost_usd=getattr(msg, "total_cost_usd", None)) + elif getattr(msg, "subtype", None) == "api_retry": + data = getattr(msg, "data", None) + status = data.get("error_status") if isinstance(data, dict) else None + _retried_after.add(str(status) if isinstance(status, int) else "no response") return structured # 60s ceiling: a single review request on a healthy 3P endpoint completes # in 5-15s; >60s means the child claude is hung (e.g. user has the 3P env # var set but no provider creds → child waits for an auth that never # comes). Bound the wait so a misconfigured 3P session doesn't stall the - # whole hook. - try: - result = _asyncio.run(_asyncio.wait_for(_arun(), timeout=60)) + # whole hook. A gateway review gets the 120 s a direct HTTP review gets. + timeout_s = 120 if route == "gateway" else 60 + + def _log_child_stderr(): if _captured_stderr: - debug_log(f"3P sdk-single-turn child stderr ({len(_captured_stderr)} lines):") + debug_log(f"{route} sdk-single-turn child stderr ({len(_captured_stderr)} lines):") for _l in _captured_stderr[:20]: debug_log(f" | {_l.rstrip()}") + + try: + result = _run_inner_cli( + lambda: _asyncio.run(_asyncio.wait_for(_arun(), timeout=timeout_s)), + _captured_stderr) + _log_child_stderr() return result except _asyncio.TimeoutError: - debug_log("3P sdk-single-turn: timeout after 60s") + # The CLI retries a refused or unreachable API by itself and reports + # each retry in its output, not on stderr. + debug_log(f"{route} sdk-single-turn: timeout after {timeout_s}s" + + (f"; the CLI's API requests were retried after status " + f"{', '.join(sorted(_retried_after))}" if _retried_after else "")) + _log_child_stderr() + if route == "gateway": + _gateway_review_timed_out = True _last_call_claude_http_error = -1 _record_http_error(-1) return None except Exception as e: - debug_log(f"3P sdk-single-turn: query failed ({e})") - if _captured_stderr: - debug_log(f"3P sdk-single-turn child stderr ({len(_captured_stderr)} lines):") - for _l in _captured_stderr[:20]: - debug_log(f" | {_l.rstrip()}") + debug_log(f"{route} sdk-single-turn: query failed ({e})") + _log_child_stderr() _last_call_claude_http_error = -1 _record_http_error(-1) return None @@ -734,6 +904,13 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, max_tokens=max_tokens, model=model) if not HAS_API_CREDENTIALS: + if _gateway_cli: + # Signed in to a Claude apps gateway: the user's CLI reviews with + # its own stored sign-in (see gateway_review_cli). + if cacheable_prefix: + prompt = cacheable_prefix + "\n\n" + prompt + return _call_claude_via_sdk(prompt, output_schema, max_tokens=max_tokens, + model=model, cli_path=_gateway_cli) return None global _auth_prefer_token @@ -891,6 +1068,9 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, explicit = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() primary = default_review_model() + # Through the user's CLI, the alias gives the Sonnet id the user's own + # sessions use on the gateway, including any ANTHROPIC_DEFAULT_SONNET_MODEL. + fallback = "sonnet" if _gateway_cli else "claude-sonnet-4-6" if not _dual_or_enabled(): # Single-call path. Reuse the same sonnet-fallback retry as a dual_or @@ -898,10 +1078,10 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget, max_tokens=max_tokens, model=primary, retry_5xx=False, cacheable_prefix=cacheable_prefix) - if r is None and not explicit: + if r is None and not explicit and not _gateway_review_timed_out: debug_log(f"single: {primary} failed, falling back to sonnet") r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget, - max_tokens=max_tokens, model="claude-sonnet-4-6", + max_tokens=max_tokens, model=fallback, retry_5xx=True, cacheable_prefix=cacheable_prefix) return r @@ -909,10 +1089,10 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget, max_tokens=max_tokens, model=primary, retry_5xx=False, cacheable_prefix=cacheable_prefix) - if r is None and not explicit: + if r is None and not explicit and not _gateway_review_timed_out: debug_log(f"dual_or: {primary} leg failed, falling back to sonnet") r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget, - max_tokens=max_tokens, model="claude-sonnet-4-6", + max_tokens=max_tokens, model=fallback, retry_5xx=True, cacheable_prefix=cacheable_prefix) return r @@ -1202,7 +1382,7 @@ def analyze_code_security(files: List[Tuple[str, str]], is_diff: bool = False, p """ _review_status.failed = False _review_status.status = None - if not HAS_API_CREDENTIALS or not files: + if not (HAS_API_CREDENTIALS or _gateway_cli) or not files: return None, [] # Build language context from file extensions @@ -1419,7 +1599,42 @@ def _only_tools_args(tools: Tuple[str, ...] = ()) -> Dict[str, Optional[str]]: the permission mode that CLI starts in. Passed as CLI flags because not every Agent SDK build that can run a review has a `tools` option. """ - return {"tools": ",".join(tools), "strict-mcp-config": None} + args: Dict[str, Optional[str]] = {"tools": ",".join(tools)} + if _send_strict_mcp: + args["strict-mcp-config"] = None + else: + # The servers an administrator delivers still start; their tools are + # kept from the reviewer. + args["disallowedTools"] = "mcp__*" + return args + + +# Claude Code exits at startup when given --strict-mcp-config on a machine +# whose administrator delivers the MCP servers (managed-mcp.json). The flag +# is sent until an inner CLI refuses it. +_send_strict_mcp = True + + +def _names_strict_mcp_flag(stderr_line: Any) -> bool: + return "--strict-mcp-config" in str(stderr_line) + + +def _run_inner_cli(start: Callable[[], Any], stderr_lines: List[str]) -> Any: + """start() runs one inner CLI to its result; stderr_lines receives what + that CLI writes to stderr. A start the CLI refused over + --strict-mcp-config is made once more without the flag, and the flag is + left out for the rest of this process.""" + global _send_strict_mcp + del stderr_lines[:] + try: + return start() + except Exception: + if not any(_names_strict_mcp_flag(l) for l in stderr_lines): + raise + _send_strict_mcp = False + debug_log("inner CLI refused --strict-mcp-config; starting it again without the flag") + del stderr_lines[:] + return start() def _agentic_spawn_env() -> Dict[str, str]: @@ -1440,6 +1655,9 @@ def _agentic_spawn_env() -> Dict[str, str]: is the only credential. """ env = { + # Policy settings can enable this plugin inside the reviewing CLI too; + # its hooks there must not start reviews of their own. + "SECURITY_GUIDANCE_DISABLE": "1", "FALLBACK_FOR_ALL_PRIMARY_MODELS": "1", "CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR": "", "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR": "", @@ -1593,59 +1811,26 @@ def _agentic_review( # `[Request interrupted by user]` and gives up). The CLI that launched # this hook is by definition >= the plugin's tested floor, so it's # always at least as capable. - # - # CLAUDE_CODE_EXECPATH is the absolute path to the running CC binary - # itself (e.g. ~/.local/share/claude/versions/2.1.x — that's the binary, - # not a directory). It is the exact CLI that loaded this hook. We do NOT - # fall back to shutil.which("claude") because the hook's cwd is the - # user's (potentially attacker-supplied) repo, and Windows shutil.which - # searches cwd first — a checked-in ./claude.exe would get spawned. - # Absolute-path probes only. - # - # Also monkeypatch the SDK's message parser to tolerate unknown message - # types (newer CLI emits rate_limit_event which older SDK raises on). - cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") - if cli_path is None: - for p in ( - os.environ.get("CLAUDE_CODE_EXECPATH"), - os.path.expanduser("~/.local/bin/claude"), - "/root/.local/bin/claude", - # Claude Code Remote container install path. CLAUDE_CODE_EXECPATH - # is not exported to hook subprocesses there, so without this - # candidate cli_path resolves to None and the SDK uses its - # bundled CLI — which lags the running CC by builds. - "/opt/claude-code/bin/claude", - ): - if p and os.path.isfile(p): - cli_path = p - break + cli_path = _gateway_cli or _user_cli_path() if cli_path: - try: - from claude_agent_sdk._internal import message_parser as _mp - import claude_agent_sdk._internal.client as _sdk_client - from claude_agent_sdk import SystemMessage as _SysMsg - - _orig_parse = _mp.parse_message - - def _tolerant(data): - try: - return _orig_parse(data) - except Exception: - return _SysMsg(subtype=data.get("type", "unknown"), data=data) - - _mp.parse_message = _tolerant - _sdk_client.parse_message = _tolerant - except Exception: - pass + _tolerate_unknown_sdk_messages() # Without a callback the inner CLI writes to this hook's stderr, which # Claude Code shows Claude as the review notice. Log it instead. child_stderr_lines = [0] + # Lines of the current start that name --strict-mcp-config (_run_inner_cli). + flag_refusals: List[str] = [] def _child_stderr_metric() -> Dict[str, int]: return {"child_stderr": child_stderr_lines[0]} if child_stderr_lines[0] else {} def _on_child_stderr(line: str) -> None: + if _names_strict_mcp_flag(line): + # Not counted: where the flag is refused, every review gets this + # line once, from the start that is then made again. + flag_refusals.append(str(line)) + debug_log(f"agentic reviewer's CLI stderr | {str(line).rstrip()}") + return child_stderr_lines[0] += 1 metrics["child_stderr"] = child_stderr_lines[0] if child_stderr_lines[0] <= 20: @@ -1756,7 +1941,9 @@ def _agentic_review( def _run(system: str, prompt: str, *, schema: Dict[str, Any] ) -> Tuple[Optional[Dict[str, Any]], int, Optional[str]]: - return _asyncio.run(_arun(system, prompt, schema=schema)) + return _run_inner_cli( + lambda: _asyncio.run(_arun(system, prompt, schema=schema)), + flag_refusals) # Stage 1: investigate — SDK enforces _FINDINGS_SCHEMA and retries the # agent on mismatch, so `inv` is either a validated dict or None. diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 27b82c3e..c72e3620 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -49,7 +49,9 @@ Other: - SECURITY_REVIEW_MODEL: Model for LLM review (default: the newest Opus) - ANTHROPIC_API_KEY: Required for LLM-based reviews - ANTHROPIC_AUTH_TOKEN: Alternative to API key — OAuth access token sent as Bearer auth. - Claude Code passes this automatically for OAuth-authenticated users. + Claude Code passes this to the plugin's hooks for signed-in users, unless + telemetry or nonessential traffic is turned off. With neither, the LLM + reviews are skipped and the user is told once (see README, Credentials). """ try: @@ -86,6 +88,7 @@ from _base import ( # noqa: E402,F401 _USAGE_CONTEXT, _log_usage, launcher_probe_metrics, state_dir as _resolve_state_dir, write_hook_output as _write_hook_output, + llm_reviews_switched_off, agent_sdk_installed, ) import extensibility # noqa: E402 from patterns import ( # noqa: E402,F401 @@ -102,6 +105,7 @@ from gitutil import ( # noqa: E402,F401 GIT_CMD, apply_safe_git_env, remove_copies_on_termination, _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, _detect_main_branch, _git_reflog_recent_commits, _git_name_only, _git_status_porcelain, _is_ancestor, get_git_diff, SOURCE_CODE_EXTENSIONS, SOURCE_CODE_BASENAMES, @@ -121,6 +125,9 @@ from diffstate import ( # noqa: E402,F401 _reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas, _full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight, UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set, + touched_scope, review_scope_code, + baseline_origin, baseline_origin_metric, FOREIGN_ORIGINS, + KEPT_NO_CAPTURE, KEPT_UNREVIEWED, ) from reporesolve import ( # noqa: E402,F401 RES_NONE, RES_CWD, RES_COMMAND, RES_SHA_SCAN, RES_TOUCHED_PATHS, RES_HINT, @@ -128,6 +135,7 @@ from reporesolve import ( # noqa: E402,F401 toplevel_from_command, repo_containing_commit, scan_roots, resolve_repo_root, save_repo_hint, load_repo_hint, ) +import diffstate # noqa: E402 module ref for last_baseline_fail import gitutil # noqa: E402 module ref for per-run counters import llm # noqa: E402 module ref for reassignable globals (_last_call_claude_http_error etc.) from llm import ( # noqa: E402,F401 @@ -300,6 +308,10 @@ def emit_metrics( cfg = llm.gateway_cfg() if cfg: tail["gateway_cfg"] = cfg + if not llm._send_strict_mcp: + # An inner CLI refused --strict-mcp-config (a machine with a + # managed-mcp.json) and the review was started again without it. + tail["strict_mcp_off"] = 1 tail.update(_TAIL_METRICS) tail.update(_LAUNCHER_METRICS) metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} @@ -318,6 +330,81 @@ def emit_metrics( out["systemMessage"] = system_message _write_hook_output(out) + +def _llm_review_off(session_id): + """Why no LLM review can run: (log text, extra metrics), or None.""" + if not ENABLE_CODE_SECURITY_REVIEW: + return "LLM review disabled", {} + if not llm.can_review(session_id): + return ("no API credentials and no Claude apps gateway sign-in", + {"no_creds": True}) + return None + + +# Claude Code hands a signed-in user's credentials to this plugin's hooks, +# but not in a session started with one of these set. +_NO_CREDENTIALS_NOTICE_INTERVAL_SEC = 7 * 24 * 3600 + + +def _credential_withholding_env_vars(): + names = [v for v in ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", + "DISABLE_TELEMETRY") if os.environ.get(v)] + if os.environ.get("DO_NOT_TRACK", "").strip().lower() in ( + "1", "true", "yes", "on"): + names.append("DO_NOT_TRACK") + return names + + +def _no_credentials_notice(file_path, session_id): + """Text telling the user the LLM reviews are not running, or None. + + With no credential and no Claude apps gateway sign-in, every Stop, + commit and push review is skipped, and nothing else tells the user. + Returned for an edit inside a git repo (the reviews only look at those), + at most once a week per install: the marker file in the state dir holds + the time of the last notice, or of the last check that found the reviews + running through a Claude apps gateway sign-in. A marker that can't be + written means no notice rather than one on every edit. The caller is the + Edit/Write hook because the review hooks run in the background, where + Claude Code does not show a systemMessage. + """ + import time as _time + try: + marker = os.path.join(_resolve_state_dir(), ".no_credentials_notice") + try: + age = _time.time() - os.path.getmtime(marker) + if 0 <= age < _NO_CREDENTIALS_NOTICE_INTERVAL_SEC: + return None + except OSError: + pass + if not _git_toplevel(os.path.dirname(os.path.abspath(file_path))): + return None + os.makedirs(os.path.dirname(marker), exist_ok=True) + with open(marker, "w"): + pass + # In a session signed in to a Claude apps gateway the reviews do run, + # through the user's claude (llm.gateway_review_cli). `claude auth + # status` runs only after the marker is written, so an edit waits for + # it at most once a week. + if llm.can_review(session_id): + return None + except OSError: + return None + withheld_by = _credential_withholding_env_vars() + if withheld_by: + why = ("Claude Code does not pass your sign-in to plugins while " + + " or ".join(withheld_by) + " is set") + else: + why = "No Anthropic credentials were passed to the plugin's hooks" + rest = (", so only the pattern warnings on edits are active" + if ENABLE_PATTERN_RULES else "") + return ( + "security-guidance: the AI security review of your changes is not " + f"running. {why}{rest}. See \"Credentials\" in the plugin README. " + "Set ENABLE_CODE_SECURITY_REVIEW=0 to turn the review off and hide " + "this notice, which is shown at most once a week." + ) + # ===================================================================== # State management # ===================================================================== @@ -476,11 +563,30 @@ def sweep_pending_warnings(session_id): # Pattern matching # ===================================================================== +def _notebook_cell_sources(content): + """Cell sources of a saved notebook, or None when content is not one (a + single cell's source, say).""" + if not isinstance(content, str) or not content.lstrip("\ufeff \t\r\n").startswith("{"): + return None + try: + sources = [cell.get("source", "") for cell in json.loads(content.lstrip("\ufeff"))["cells"]] + return "\n".join(src if isinstance(src, str) else "".join(src) for src in sources) + except Exception: + return None + def check_patterns(file_path, content): """Check if file path or content matches any security patterns. Returns ALL matches.""" normalized_path = file_path.lstrip("/") matches = [] + # A saved notebook is JSON: its string escapes hide code from the rules + # ("\nos.system(" has no word boundary) and its outputs can run to + # megabytes. Check the cells as written instead. + if normalized_path.endswith(".ipynb"): + cell_sources = _notebook_cell_sources(content) + if cell_sources is not None: + content = cell_sources + for pattern in list(SECURITY_PATTERNS) + extensibility.user_patterns(): # path_filter is a gate: when present, the rule only applies to # matching paths. Distinct from path_check, which is itself a @@ -519,7 +625,7 @@ def check_patterns(file_path, content): return matches -def extract_content_from_input(tool_name, tool_input): +def extract_content_from_input(tool_name, tool_input, tool_response=None): """Extract content to check from tool input based on tool type.""" if tool_name == "Write": return tool_input.get("content", "") @@ -530,12 +636,29 @@ def extract_content_from_input(tool_name, tool_input): if edits: return " ".join(edit.get("new_string", "") for edit in edits) return "" + elif tool_name == "NotebookEdit": + # A deleted cell adds no code. A failed edit comes back as an error + # in the response, with the notebook unchanged. + if tool_input.get("edit_mode") == "delete": + return "" + if isinstance(tool_response, dict) and tool_response.get("error"): + return "" + new_source = tool_input.get("new_source", "") + return new_source if isinstance(new_source, str) else "" return "" # ===================================================================== # Hook handlers # ===================================================================== +def _store_baseline_fail(state, fail): + """Keep diffstate.last_baseline_fail next to the baseline_sha it describes.""" + if fail: + state["baseline_fail"] = fail + else: + state.pop("baseline_fail", None) + + def handle_user_prompt_submit(input_data): """ Handle UserPromptSubmit — capture git baseline SHA. @@ -579,14 +702,25 @@ 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 + # come back empty. + no_repo = False if not sha and not _git_toplevel(cwd): hint = load_repo_hint(session_id) if hint: debug_log(f"UPS: cwd is not a git repo; using repo hint {hint!r}") cwd = hint sha, untracked_now = _capture(cwd) - head = _git_rev_parse_head(cwd) + else: + no_repo = True + baseline_fail = diffstate.last_baseline_fail + # The repo root rides on the same git call as HEAD. + root, head = (None, None) if no_repo else _git_toplevel_and_head(cwd) + if sha and not head: + head = _git_rev_parse_head(cwd) # If the previous turn's Stop hook never ran (user interrupt, follow-up # during work, tool-reject, model crash, maxTurns, PostToolUse block…), @@ -609,10 +743,27 @@ def handle_user_prompt_submit(input_data): # untracked file in the tree as written this turn. if untracked_now is not None and "untracked_at_baseline" not in state: state["untracked_at_baseline"] = untracked_now + # Once a prompt failed to capture, the baseline is old whatever + # later prompts did. + state["baseline_kept"] = ( + KEPT_NO_CAPTURE + if not sha or state.get("baseline_kept") == KEPT_NO_CAPTURE + else KEPT_UNREVIEWED) return if sha: state["baseline_sha"] = sha state["head_at_capture"] = head + state.pop("turn_touched", None) + _store_baseline_fail(state, baseline_fail) + # A Stop review that ends up in another checkout does not use + # this baseline. + state["baseline_root"] = root + state.pop("baseline_kept", None) + elif state.get("baseline_sha"): + state["baseline_kept"] = KEPT_NO_CAPTURE + # When the turn began: what a Stop review in another checkout has + # to go on. + state["prompt_at"] = captured_at # untracked_at_baseline is independent of whether the stash produced # a SHA, so compute_v2_review_set's preexisting-untracked exclusion # works in untracked-only trees. None means no snapshot was taken @@ -620,7 +771,10 @@ def handle_user_prompt_submit(input_data): # baseline. if untracked_now is None: state.pop("untracked_at_baseline", None) - else: + elif not no_repo: + # no_repo: the earlier baseline stays (above), and so does the + # snapshot that belongs to it. An empty one in its place would + # make every untracked file in that repo look new. state["untracked_at_baseline"] = untracked_now with_locked_state(session_id, _save) @@ -1142,6 +1296,12 @@ def _review_failure_reason(status): if llm._is_3p_provider(): return ("provider", "the review through the cloud provider got no answer", "The plugin's log has the provider's error.") + if llm._gateway_cli: + pinned = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() + return ("gateway", "the review through Claude Code on the Claude apps gateway returned no result", + "The plugin's log has the reason. If it says the sign-in has expired, run /login again." + + (f" SECURITY_REVIEW_MODEL ({pinned}) may also name a model the gateway does " + "not serve." if pinned else "")) if status == 401: return ("auth", "the API rejected the plugin's credentials (HTTP 401)", f"The sign-in may have expired or been revoked{gateway}.") @@ -1334,9 +1494,10 @@ def handle_commit_review_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 32, **_base}) sys.exit(0) - if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS: - debug_log("Commit review: LLM review disabled or no API credentials") - emit_metrics({"skipped": True, "skip_reason": 22, **_base}) + off = _llm_review_off(session_id) + if off: + debug_log(f"Commit review: {off[0]}") + emit_metrics({"skipped": True, "skip_reason": 22, **off[1], **_base}) sys.exit(0) if not ensure_anthropic_reachable(): @@ -1802,8 +1963,9 @@ def handle_push_sweep_posttooluse(input_data): if interrupted: emit_metrics({"skipped": True, "skip_reason": 21, **_base}) sys.exit(0) - if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS: - emit_metrics({"skipped": True, "skip_reason": 22, **_base}) + off = _llm_review_off(session_id) + if off: + emit_metrics({"skipped": True, "skip_reason": 22, **off[1], **_base}) sys.exit(0) if not cwd: emit_metrics({"skipped": True, "skip_reason": 25, **_base}) @@ -2140,6 +2302,14 @@ def handle_push_sweep_posttooluse(input_data): hook_event_name="PostToolUse") sys.exit(2) +def _stop_diff_truncated(): + """Bytes of reviewable diff the Stop review did not send: cut while + reading git's output, plus what the prompt caps dropped after that. + As the metric to emit, or nothing when there were none.""" + n = llm._last_review_truncated_bytes + gitutil._diff_read["cut_bytes"] + return {"diff_truncated": n} if n else {} + + def handle_stop_hook(input_data): """ Handle the Stop hook — final security check using git diff. @@ -2224,9 +2394,12 @@ def handle_stop_hook(input_data): debug_log(f"Stop hook: already fired {fire_count} times (max {MAX_STOP_HOOK_FIRINGS}), skipping") _skip(2) - if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS: - debug_log("Stop hook: LLM review disabled or no API credentials") - _skip(3) + off = _llm_review_off(session_id) + if off: + debug_log(f"Stop hook: {off[0]}") + # When the sign-in check gave no answer, this turn's changes are kept + # for the next Stop review. + _skip(3, restore=llm._gateway_check_unanswered, **off[1]) # Stop-hook-only kill switch — placed after consume_stop_state so # touched_paths is still cleared each turn (a disabled Stop hook that @@ -2263,10 +2436,58 @@ def handle_stop_hook(input_data): save_repo_hint(session_id, repo_cwd) cwd = repo_cwd + # The baseline belongs to the checkout the prompt hook captured it in. + # When the turn ends in another one (the session entered a worktree, or + # the edits were in a different repo), it says nothing about what changed + # here: this checkout's older commits would look like commits made this + # turn, and its files would be diffed against the other checkout's. Use + # what this checkout can say for itself instead: its own HEAD when the + # turn began (from its reflog) for commits, HEAD for file contents, and + # file times for which uncommitted files were already there. + origin = None + if repo_cwd: + try: + origin = baseline_origin(repo_cwd, snap_baseline, snap["baseline_root"]) + except Exception as e: + debug_log(f"Stop hook: baseline origin check failed: {e}") + foreign_baseline = origin in FOREIGN_ORIGINS + since_ns = None + if foreign_baseline: + at = snap["prompt_at"] + at = at if isinstance(at, (int, float)) and 0 < at < 1e11 else None + baseline_sha = None + head_at_capture = _git_head_at(repo_cwd, at) if at else None + untracked_at_baseline = {} + since_ns = int(at * 1e9) if at else None + debug_log(f"Stop hook: baseline {str(snap_baseline)[:12]} is from another " + f"checkout (origin {origin}); this one was at " + f"{str(head_at_capture)[:12]} when the turn began") + review_paths, diff_base, repo_root, untracked, v2_metrics = compute_v2_review_set( - cwd, baseline_sha, head_at_capture, untracked_at_baseline + cwd, baseline_sha, head_at_capture, untracked_at_baseline, since_ns=since_ns ) + # Sent even when 0, once git status has worked. + if origin is not None and v2_metrics.get("dirty_now_count", -1) >= 0: + _TAIL_METRICS["bl_origin"] = baseline_origin_metric(origin, snap["baseline_kept"]) + v2_metrics = {**res_metrics, **v2_metrics} + # Count-only view of how the review set relates to what the session's + # edit tools wrote. Only when a repo was read; never fails the review. + def _note_scope(files): + try: + if "scope" not in _scope: + _scope["scope"] = touched_scope( + repo_root, input_data.get("cwd", ""), snap["turn_touched"]) + # -1: the stored baseline could not be used in this repo. + fail = (3 if v2_metrics.get("changed_since_count") == -1 + else snap.get("baseline_fail")) + _TAIL_METRICS["review_scope"] = review_scope_code( + repo_root, *_scope["scope"], files, fail) + except Exception as e: + debug_log(f"review scope telemetry skipped: {e}") + _scope = {} + if v2_metrics.get("dirty_now_count", -1) >= 0: + _note_scope(review_paths) if not review_paths: debug_log("Stop hook: empty review set") _skip(9, touched_paths_count=len(touched_paths)) @@ -2286,6 +2507,13 @@ 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), + ("diff_cut_files", gitutil._diff_read["cut_files"]), + ("diff_timeout", gitutil._diff_read["timeouts"])): + if _v: + _TAIL_METRICS[_k] = _v # filter_preexisting_from_diff needs a resolvable pre-turn ref; fall # back to HEAD when UPS never captured a baseline (print mode). if not baseline_sha: @@ -2325,8 +2553,13 @@ def handle_stop_hook(input_data): # Filter out pre-existing content from file rewrites diff_files = filter_preexisting_from_diff(diff_files, cwd, baseline_sha) + if "scope" in _scope: + _note_scope([fp for fp, _ in diff_files]) debug_log(f"Stop hook: reviewing {len(diff_files)} changed files (standard diff)") + secret_named = gitutil.count_secret_named(diff_files) + if secret_named: + _TAIL_METRICS["secret_named_reviewed"] = secret_named import time as _time stop_review_start = _time.time() @@ -2371,7 +2604,12 @@ def handle_stop_hook(input_data): ] # Update baseline so next stop hook iteration only sees new changes new_sha = None if is_subagent else capture_git_baseline(cwd) + new_base_fail = diffstate.last_baseline_fail new_untracked_baseline = _list_untracked(cwd) if new_sha else None + # After a baseline from another checkout, the rest of it is replaced + # too, below. + new_head = (_git_rev_parse_head(cwd) + if new_sha and foreign_baseline and not head_at_capture else None) def _record_fire(state): if is_subagent: @@ -2396,6 +2634,14 @@ def handle_stop_hook(input_data): if new_sha: state["baseline_sha"] = new_sha state["untracked_at_baseline"] = new_untracked_baseline + _store_baseline_fail(state, new_base_fail) + state["baseline_root"] = repo_root + state.pop("baseline_kept", None) + if foreign_baseline: + # The stored HEAD is the other checkout's. Keep the one + # this review used, so a later Stop this turn still sees + # commits made (or amended) here since the prompt. + state["head_at_capture"] = head_at_capture or new_head with_locked_state(session_id, _record_fire) if new_sha: @@ -2423,8 +2669,7 @@ def handle_stop_hook(input_data): "touched_paths_count": len(touched_paths), "review_ms": review_ms, "fire_index": fire_index, - **({"diff_truncated": llm._last_review_truncated_bytes} - if llm._last_review_truncated_bytes else {}), + **_stop_diff_truncated(), **({"repo_resolution": repo_res} if res_metrics else {}), **sweep_trimmed, **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} @@ -2461,8 +2706,7 @@ def handle_stop_hook(input_data): "review_ms": review_ms, "fire_index": fire_index, **({"api_error": llm._last_call_claude_http_error} if llm._last_call_claude_http_error is not None else {}), - **({"diff_truncated": llm._last_review_truncated_bytes} - if llm._last_review_truncated_bytes else {}), + **_stop_diff_truncated(), **v2_metrics, **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} if gitutil._unparsed_diff_headers else {}), @@ -2487,12 +2731,15 @@ def _maybe_bootstrap_agent_sdk_async(): is idempotent and O_EXCL-locked, so concurrent/repeat spawns are safe; the throttle file only avoids spawning dozens of subprocesses during the build window. No-ops in ~10ms on local installs (SDK already - importable). + importable, or already installed under the state dir, which is not on + sys.path here) and when the environment turns the LLM reviews off. """ try: import importlib.util if importlib.util.find_spec("claude_agent_sdk") is not None: return + if llm_reviews_switched_off() or agent_sdk_installed(_resolve_state_dir()): + return import time as _t try: if _t.time() - os.path.getmtime(_SDK_BOOTSTRAP_THROTTLE) < 300: @@ -2625,7 +2872,8 @@ def main(): record_touched_path(session_id, file_path) - content = extract_content_from_input(tool_name, tool_input) + content = extract_content_from_input( + tool_name, tool_input, input_data.get("tool_response")) all_guidance = [] raw_pattern_matches = [] @@ -2665,9 +2913,10 @@ def main(): # rule_id: RuleId of the first raw match (values stay small/enumerable in telemetry) # rule_mask: bitmask of ALL raw matches — POPCOUNT gives raw hit count, # (mask >> N) & 1 tests for a specific rule + output = {} if raw_pattern_matches: raw_names = [r for r, _ in raw_pattern_matches] - output = {"metrics": { + output["metrics"] = { "pattern_hits": len(all_guidance), # User-defined patterns (rule_name="user:*") have no static # RuleId; emit -1 so the metrics pipeline can distinguish. @@ -2675,21 +2924,21 @@ def main(): "rule_mask": rule_names_to_mask(raw_names), **({"pv": _PV} if _PV else {}), **_LAUNCHER_METRICS, - }} - if all_guidance: - output["hookSpecificOutput"] = { - "hookEventName": "PostToolUse", - "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), - } + } + if all_guidance: + output["hookSpecificOutput"] = { + "hookEventName": "PostToolUse", + "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), + } + # The LLM reviews are on but can't run: say so. + if (ENABLE_CODE_SECURITY_REVIEW and not HAS_API_CREDENTIALS + and (ENABLE_STOP_REVIEW or COMMIT_REVIEW_ENABLED + or PUSH_SWEEP_ENABLED)): + notice = _no_credentials_notice(file_path, session_id) + if notice: + output["systemMessage"] = notice + if output: _write_hook_output(output) - elif all_guidance: - # Defensive: pattern rules disabled but guidance somehow set (shouldn't happen) - print(json.dumps({ - "hookSpecificOutput": { - "hookEventName": "PostToolUse", - "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), - } - })) sys.exit(0) diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh index 97387901..e0c2730e 100755 --- a/plugins/security-guidance/hooks/sg-python.sh +++ b/plugins/security-guidance/hooks/sg-python.sh @@ -178,7 +178,8 @@ is_sdk_compatible() { # Pass 1 — try minor-versioned binaries in descending order. These are only # present if the user explicitly installed them (Homebrew / python.org / pyenv), # so picking one here always upgrades over the system `python3`. Highest -# available wins; the user doesn't have to PATH-prefer it. +# of these wins; the user doesn't have to PATH-prefer it. Releases newer +# than this list are pass 2b. for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do on_path "$cmd" || continue ask "$cmd" || { note_unreadable "$cmd"; continue; } @@ -208,6 +209,22 @@ for cmd in "python3" "python" "py -3"; do esac done +# Pass 2b — minor versions newer than the pass 1 list, so a machine whose +# only SDK-compatible Python is a recent release (system `python3` 3.9 next to +# Homebrew's python3.14) is not left on pass 3. Tried only when nothing +# above is compatible: an interpreter that already works is never traded for +# a newer one, which may not have the SDK or wheels for its dependencies yet. +# Oldest first for the same reason. Missing names cost no process (on_path). +# See #4907, #5024. +for cmd in "python3.14" "python3.15" "python3.16" "python3.17" "python3.18" "python3.19"; do + on_path "$cmd" || continue + v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; } + v=${v%$'\r'} + if is_sdk_compatible "$v"; then + exec "$cmd" "$@" + fi +done + # Pass 3 — fallback to any Python 3, even <3.10. Pattern-based checks # (PostToolUse regex on Edit/Write) only need 3.6+ and are useful on their # own; the SDK-dependent paths will detect the version mismatch and degrade @@ -280,7 +297,7 @@ if [ -n "$sg_unreadable" ]; then exit 1 fi echo "security-guidance: no working Python 3 interpreter found." >&2 -echo " tried: python3.13, python3.12, python3.11, python3.10, python3, python, py -3" >&2 +echo " tried: python3.13 to python3.10, python3, python, py -3, python3.14 to python3.19" >&2 echo " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2 echo " on macOS, install Python 3.10+ via Homebrew (\`brew install python\`)" >&2 exit 1 |
