diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-18 16:46:37 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-18 16:46:37 +0000 |
| commit | ded17af4aac57cbe4f3b027dc46a5c338f41afa9 (patch) | |
| tree | e5f2969916c9f19232f229ae53a939fc03e7c70b /plugins | |
| parent | 84f3cd05382d6c190fc0b09ca2cd2f4d5432e7f6 (diff) | |
| parent | ea10b213686c90bb1984b2016937310e05336cf3 (diff) | |
Merge remote-tracking branch 'origin/main' into mhegazy/sg-stop-pathspec
Diffstat (limited to 'plugins')
31 files changed, 3973 insertions, 307 deletions
diff --git a/plugins/security-guidance/.claude-plugin/plugin.json b/plugins/security-guidance/.claude-plugin/plugin.json index e8e66df7..b3fd1749 100644 --- a/plugins/security-guidance/.claude-plugin/plugin.json +++ b/plugins/security-guidance/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "security-guidance", - "version": "2.0.13", + "version": "2.0.14", "description": "Security review for Claude-generated code. Pattern-based warnings on edits, LLM-powered diff review on Stop, and an agentic commit reviewer that catches injection, XSS, SSRF, hardcoded secrets, and 25+ other vulnerability classes.", "author": { "name": "David Dworken", diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index 58736a85..b8a67ed4 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -58,6 +58,14 @@ SECURITY_REVIEW_MODEL=claude-opus-5-5 | `ENABLE_STOP_REVIEW=0` | on | Disable only the Stop-hook diff review, keeping commit/push reviews. Useful for multi-agent / shared-worktree setups where another agent can move HEAD between a worker's turns | | `ENABLE_COMMIT_REVIEW=0` | on | Disable layer 3 (agentic commit review) | +### Hook output for other hosts + +```bash +SECURITY_GUIDANCE_PORTABLE_OUTPUT=1 # default: detected +``` + +The hooks' JSON output carries two fields that only Claude Code reads (`metrics` and `rewakeSummary`), and the SessionStart hook prints a separate `{"async": ...}` line first. A host that validates hook output against a closed schema rejects them. In portable mode they are left out, so every hook prints one JSON object with only the standard fields (`decision`, `reason`, `systemMessage`, `hookSpecificOutput`), and the SessionStart hook runs to completion before the host continues. It turns on by itself when the host passes `PLUGIN_ROOT` and does not identify itself as Claude Code; set the variable to `1` or `0` to force it either way. + ### Higher-recall mode ```bash @@ -70,7 +78,7 @@ Runs two parallel review calls and unions the findings. Catches a few percentage Drop a `claude-security-guidance.md` in any of: -- `~/.claude/claude-security-guidance.md` — user-wide rules +- `~/.claude/claude-security-guidance.md` — user-wide rules (when `CLAUDE_CONFIG_DIR` is set, the same file in that directory is read too) - `<project>/.claude/claude-security-guidance.md` — project rules, intended to be committed - `<project>/.claude/claude-security-guidance.local.md` — local overrides, intended to be `.gitignore`'d @@ -95,10 +103,25 @@ The plugin sends data to a model endpoint to perform its reviews. Specifically, Where that data goes depends on your Claude Code configuration: - **Default (Anthropic API / subscription):** sent to `api.anthropic.com` and handled under Anthropic's [Commercial Terms](https://www.anthropic.com/legal/commercial-terms) and [Privacy Policy](https://www.anthropic.com/legal/privacy). -- **LLM gateway** (`ANTHROPIC_BASE_URL` set): sent to your gateway URL instead. The gateway operator's terms apply. +- **LLM gateway** (`ANTHROPIC_BASE_URL` set): sent to your gateway URL instead, with the headers in `ANTHROPIC_CUSTOM_HEADERS` (except `anthropic-beta`). The gateway operator's terms apply. - **3rd-party providers** (Bedrock / Vertex / Foundry / Mantle): sent to your configured provider endpoint. The provider's data-handling terms apply (e.g., AWS / GCP / Azure). -The plugin writes its own debug log to `~/.claude/security/log.txt` (override with `SECURITY_GUIDANCE_DEBUG_LOG`). The log contains diffstate metadata and finding categories — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded. +The plugin writes its own debug log to `~/.claude/security/log.txt` (override with `SECURITY_GUIDANCE_DEBUG_LOG`). The log contains diffstate metadata, finding categories, the Agent SDK's own warnings and errors, and up to 20 lines per review that the agentic reviewer's inner Claude Code prints to stderr — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded. + +### Review usage and cost + +The LLM reviews use your API path, so they cost tokens (or subscription usage) on top of your own session. The default reviewer is the newest Opus model. On the Anthropic API path the diff review on Stop calls the API directly, so it does not appear in Claude Code's own cost figures or transcripts. After each review the plugin writes one line to its debug log: + +``` +Review usage: review=stop session=<session id> model=claude-opus-5-5 calls=1 in=31994 out=3250 cache_read=0 cache_write=0 est_cost_usd=0.1930 +``` + +- `review` is `stop`, `commit` or `push`; `session` is the Claude Code session that triggered it. +- `calls` counts API requests for the diff review and reviewer runs for the agentic commit/push review, where `model` is the model that was asked for (`opus` by default). +- `est_cost_usd` is an estimate at list prices, not a bill: on a subscription the review counts against your usage limits instead. A trailing `~` means the model had no entry in the plugin's price table and a default rate was used. A review cut short (timeout, session exit) may not be counted. +- The log rotates at 1 MB, so copy these lines out if you need a longer history. + +To spend less, set `SECURITY_REVIEW_MODEL` (diff review) and `SG_AGENTIC_MODEL` (commit/push review) to a cheaper model, or turn reviews off (see [Enabling/disabling layers](#enablingdisabling-layers)). ## Limitations @@ -108,7 +131,7 @@ This is a best-effort assistive tool, not a guarantee. Treat findings as suggest **Plugin doesn't seem to fire** — check that `~/.claude/claude-security-guidance.md` (or hook activity) shows in debug logs. Run Claude Code with `--debug-file /tmp/claude/debug.txt` and grep for `security_reminder_hook`. The plugin also writes its own log to `~/.claude/security/log.txt`. -**Review never finds anything** — verify your API path works. On 3P providers, if you set `SECURITY_REVIEW_MODEL`, check it is a provider-specific id your account can invoke. On LLM gateways, check the gateway's logs for `POST /v1/messages` traffic from the plugin. +**Review never finds anything** — verify your API path works. When a commit or push review gets no usable answer from the model, Claude is told once per session for each kind of review and failure (for example "Commit security review did not complete: …"), and the reason is logged. If a commit whose review failed is pushed later from Claude Code, the push review checks it. On 3P providers, if you set `SECURITY_REVIEW_MODEL`, check it is a provider-specific id your account can invoke. On LLM gateways, check the gateway's logs for `POST /v1/messages` traffic from the plugin. **Too many false positives** — set `SECURITY_REVIEW_MODEL` to a cheaper model (`claude-sonnet-5-5`) and re-evaluate; if precision is the priority, stay on the default. diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index 44b205f0..1daa6642 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -7,6 +7,7 @@ circular import). It must stay free of any other intra-plugin imports. """ import json import os +import re import threading from datetime import datetime @@ -94,6 +95,47 @@ PROVENANCE_BANNER = ( ) +# Output that only Claude Code reads: the `metrics` and `rewakeSummary` fields, +# and the separate `{"async": ...}` line an async hook prints first. Other hosts +# that run this plugin's hooks can validate hook output against a closed schema +# and reject the whole output over a field or a second line they do not know, +# which shows up as a hook error. +_CLAUDE_CODE_OUTPUT_FIELDS = ("metrics", "rewakeSummary") + + +def _detect_portable_output(): + forced = os.environ.get("SECURITY_GUIDANCE_PORTABLE_OUTPUT", "").strip().lower() + if forced in ("1", "true", "yes", "on"): + return True + if forced in ("0", "false", "no", "off"): + return False + if os.environ.get("CLAUDECODE") or os.environ.get("CLAUDE_CODE_ENTRYPOINT"): + return False + return bool(os.environ.get("PLUGIN_ROOT")) + + +# Decided once, from the environment the host started the hook with: code the +# hook runs in-process later can set these variables itself. +_PORTABLE_OUTPUT = _detect_portable_output() + + +def portable_output(): + """True when stdout should carry only the standard hook output fields. + + SECURITY_GUIDANCE_PORTABLE_OUTPUT=1 or =0 forces it on or off. Otherwise it + is on only when the host passes PLUGIN_ROOT and does not identify itself as + Claude Code, so Claude Code and direct invocations are unchanged.""" + return _PORTABLE_OUTPUT + + +def write_hook_output(out): + """Print one hook output line. In portable mode the Claude Code only + fields are left out; what remains (possibly `{}`) is still valid output.""" + if portable_output(): + out = {k: v for k, v in out.items() if k not in _CLAUDE_CODE_OUTPUT_FIELDS} + print(json.dumps(out), flush=True) + + def _read_plugin_version_int(): """Encode plugin.json version "M.m.p" as M*10000 + m*100 + p so it fits the bool|number metrics constraint. Returns 0 if unreadable.""" @@ -127,6 +169,10 @@ _USAGE = { # reported it manually. "http_err_last": 0, # most recent HTTP error code this invocation "http_err_count": 0, # total HTTP errors (4xx + 5xx + network) + # For the usage log line only: model ids as recorded (the requested alias + # on the Agent SDK path), and whether any call had no price-table entry. + "models": [], + "default_priced": False, } _USAGE_LOCK = threading.Lock() @@ -163,12 +209,15 @@ def _record_usage(usage, model, cost_usd=None): cw = int(u.get("cache_creation_input_tokens") or 0) except (TypeError, ValueError): return + default_priced = False if cost_usd is None: pin, pout = _PRICE_DEFAULT + default_priced = True m = (model or "").lower() for k, v in sorted(_PRICE_PER_MTOK.items(), key=lambda kv: -len(kv[0])): if m.startswith(k): pin, pout = v + default_priced = False break cost_usd = (i * pin + o * pout + cr * pin * 0.1 + cw * pin * 1.25) / 1_000_000 with _USAGE_LOCK: @@ -178,6 +227,10 @@ def _record_usage(usage, model, cost_usd=None): _USAGE["cw"] += cw _USAGE["cost"] += float(cost_usd or 0.0) _USAGE["n"] += 1 + _USAGE["default_priced"] = _USAGE["default_priced"] or default_priced + name = re.sub(r"[^A-Za-z0-9_.:/@-]", "_", str(model or ""))[:80] + if name and name not in _USAGE["models"]: + _USAGE["models"].append(name) def _record_http_error(status): @@ -204,6 +257,36 @@ def _record_http_error(status): _USAGE["http_err_count"] += 1 +# Set by main() and the review handlers: which review this invocation runs +# and for which Claude Code session, so the usage log line can be attributed. +_USAGE_CONTEXT = {"session_id": "", "review": "stop"} + + +def _log_usage(usage): + """Write this invocation's review usage to the debug log. + + `usage` is a `_usage_metrics()` snapshot, the same numbers that go out + with the hook's metrics. The raw-HTTP review leaves no Claude Code + transcript and no OpenTelemetry event; without this line nothing on the + machine records what it used. `est_cost_usd` is that same rollup: list + prices (the inner CLI's own figure on the Agent SDK path), `~` appended + when a model had no price-table entry and the default rate was used. + """ + if not usage.get("api_calls"): + return + with _USAGE_LOCK: + models = ",".join(_USAGE["models"]) or "-" + approx = "~" if _USAGE["default_priced"] else "" + debug_log( + f"Review usage: review={_USAGE_CONTEXT.get('review') or '-'} " + f"session={_USAGE_CONTEXT.get('session_id') or '-'} " + f"model={models} calls={usage['api_calls']} " + f"in={usage['tok_in']} out={usage['tok_out']} " + f"cache_read={usage['tok_cache_r']} cache_write={usage['tok_cache_w']} " + f"est_cost_usd={usage['cost_usd']:.4f}{approx}" + ) + + 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 be839212..f2d9dbe4 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 time from _base import debug_log, _PV from gitutil import ( @@ -103,17 +104,22 @@ def consume_stop_state(session_id, clear=True): "fire_count_expired": expired and state.get("stop_hook_fire_count", 0) > 0, "previous_findings": [] if findings_expired else list(state.get("previous_findings", [])), "reviewed_diff_hash": state.get("reviewed_diff_hash"), + # State lost or overwritten since the last Stop (session_state). + "state_resets": state.get("state_resets", 0), + "state_overwrites": state.get("state_overwrites", 0), } if clear: state["touched_paths"] = [] state.pop("reviewed_diff_hash", None) + state.pop("state_resets", None) + state.pop("state_overwrites", None) return snap return with_locked_state(session_id, _snap) or { "touched_paths": [], "baseline_sha": None, "head_at_capture": None, "untracked_at_baseline": {}, "fire_count": 0, "fire_count_expired": False, "previous_findings": [], - "reviewed_diff_hash": None, + "reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0, } @@ -198,7 +204,8 @@ def capture_git_baseline(cwd): NOTE: `git stash create` does NOT capture untracked files. UPS pairs this SHA with a `_list_untracked()` snapshot stored as `untracked_at_baseline`, and `compute_v2_review_set` subtracts that set so pre-existing untracked - files are not reviewed as Claude-authored. + files are not reviewed as Claude-authored. UPS takes no snapshot while the + Stop review, its only reader, is switched off. """ # stdout is a SHA so text=True is safe on stdout, but a non-ASCII # filename in `git stash create`'s STDERR warning (e.g. a worktree @@ -279,14 +286,19 @@ def capture_git_baseline(cwd): _REVIEWED_SHAS_BASENAME = "sg-reviewed-shas" _REVIEWED_SHAS_CAP = 500 +def _is_full_sha(sha): + return len(sha) == 40 and all(c in "0123456789abcdef" for c in sha) + + def _reviewed_shas_path(repo_root): gd = _git_dir(repo_root) return os.path.join(gd, _REVIEWED_SHAS_BASENAME) if gd else None -def _load_reviewed_shas(repo_root): +def _load_reviewed_shas(repo_root, _gd=None): """Set of full 40-hex shas previously reviewed in this clone.""" - p = _reviewed_shas_path(repo_root) + p = (os.path.join(_gd, _REVIEWED_SHAS_BASENAME) if _gd + else _reviewed_shas_path(repo_root)) if not p or not os.path.exists(p): return set() out = set() @@ -294,7 +306,7 @@ def _load_reviewed_shas(repo_root): with open(p, "r") as f: for line in f: sha = line.split("\t", 1)[0].strip() - if len(sha) == 40 and all(c in "0123456789abcdef" for c in sha): + if _is_full_sha(sha): out.add(sha) except OSError: pass @@ -346,11 +358,194 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0): pass +# ─── in-flight review markers ─────────────────────────────────────────────── +# +# A commit or push review records its shas only once it has a verdict, which +# is minutes after it starts. A review that starts in between (the push right +# after a commit, the next commit's reflog scan) would send the same commits +# through a second full review. So a review first takes an exclusive flock on +# `sg-inflight-<sha>`, next to the reviewed-shas file, and holds it until its +# process ends; other reviews leave a locked commit to it. The kernel drops +# the lock however the holder dies, so a killed review blocks nobody. Without +# flock (native Windows Python, some network filesystems) there are no +# markers and nothing changes. + +_INFLIGHT_PREFIX = "sg-inflight-" +# A marker file nobody holds (a killed review's) is removed once this old. +_INFLIGHT_GC_AGE_S = 3600 +_inflight_held = {} + + +def _full_shas(repo_root, shas): + """Resolve abbreviated commit refs to full 40-hex shas; drops unresolved.""" + out = [] + for s in shas: + try: + r = subprocess.run( + [*GIT_CMD, "rev-parse", "--verify", "-q", s], + cwd=repo_root, capture_output=True, timeout=5, + ) + except (subprocess.TimeoutExpired, FileNotFoundError, OSError): + continue + if r.returncode == 0: + out.append(r.stdout.decode("utf-8", errors="replace").strip()) + return out + + +def _flock_nb(fd, exclusive): + """True when the lock was taken, False when another process holds it. + Raises OSError when the file cannot be locked at all.""" + import errno + import fcntl + try: + fcntl.flock(fd, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB) + return True + except OSError as e: + if e.errno in (errno.EWOULDBLOCK, errno.EAGAIN): + return False + raise + + +def _release_inflight(): + for p, fd in list(_inflight_held.items()): + try: + os.unlink(p) + except OSError: + pass + try: + os.close(fd) + except OSError: + pass + _inflight_held.clear() + + +def _sweep_inflight(gd): + """Remove old marker files no review holds.""" + import time as _time + cutoff = _time.time() - _INFLIGHT_GC_AGE_S + for name in os.listdir(gd): + p = os.path.join(gd, name) + if not name.startswith(_INFLIGHT_PREFIX) or p in _inflight_held: + continue + try: + if os.path.getmtime(p) > cutoff: + continue + fd = os.open(p, os.O_RDWR) + except OSError: + continue + try: + if _flock_nb(fd, exclusive=True): + os.unlink(p) + except OSError: + pass + os.close(fd) + + +def _mark_inflight(repo_root, shas): + """Claim `shas` (full 40-hex) for the review this process is about to + run, until the process ends. Best-effort; never raises. A commit another + live review holds stays with that review.""" + try: + import fcntl # noqa: F401 + gd = _git_dir(repo_root) + if not gd: + return + _sweep_inflight(gd) + for sha in shas: + p = os.path.join(gd, _INFLIGHT_PREFIX + sha) + if not _is_full_sha(sha) or p in _inflight_held: + continue + fd = os.open(p, os.O_RDWR | os.O_CREAT, 0o600) + try: + # The inode check: a holder unlinks its marker when it ends, + # and a lock on that unlinked file would claim nothing. + held = (_flock_nb(fd, exclusive=True) + and os.fstat(fd).st_ino == os.stat(p).st_ino) + except OSError: + # Cannot lock here at all: leave no file that reads as held. + os.close(fd) + os.unlink(p) + return + if not held: + os.close(fd) + continue + if not _inflight_held: + import atexit + atexit.register(_release_inflight) + _inflight_held[p] = fd + os.utime(p) + except Exception: + pass + + +def _load_inflight_shas(repo_root, shas, _gd=None): + """Which of `shas` another live review in this clone holds right now.""" + out = set() + try: + import fcntl # noqa: F401 + except ImportError: + return out + gd = _gd or _git_dir(repo_root) + if not gd: + return out + for sha in shas: + p = os.path.join(gd, _INFLIGHT_PREFIX + sha) + if not _is_full_sha(sha) or p in _inflight_held: + continue + try: + fd = os.open(p, os.O_RDONLY) + except OSError: + continue + try: + # Shared, so two reviews asking at once do not look like a + # holder to each other. + if not _flock_nb(fd, exclusive=False): + out.add(sha) + except OSError: + pass + os.close(fd) + return out + + +def _reviewed_after_inflight(repo_root, push_range, max_wait_s, poll_s=1.0): + """The reviewed-sha set for a push of `push_range` (oldest first), read + once no other review is still running on the commit the push review + would start from, or after `max_wait_s`. Returns (reviewed, waited_s).""" + import time as _time + gd = _git_dir(repo_root) + start = _time.monotonic() + waited = False + reviewed = _load_reviewed_shas(repo_root, _gd=gd) + while gd: + # Only the first unreviewed commit matters: if nobody is reviewing + # it, the push review covers everything from there on anyway. + first = next((s for s in push_range if s not in reviewed), None) + if first is None: + break + # In-flight before reviewed: a review that ends between the two + # reads then shows up as reviewed rather than as neither. + busy = _load_inflight_shas(repo_root, [first], _gd=gd) + reviewed = _load_reviewed_shas(repo_root, _gd=gd) + if first in reviewed: + continue + if not busy or _time.monotonic() - start >= max_wait_s: + break + waited = True + _time.sleep(poll_s) + return reviewed, (_time.monotonic() - start) if waited else 0.0 + + # ===================================================================== # v2 review-set computation (Stop hook) # ===================================================================== UNTRACKED_BASELINE_CAP = 2000 +# Set in a snapshot that hit the cap, to the time the listing started. NUL +# cannot occur in a path, so the key never collides with a file. +UNTRACKED_CAPPED_AT_KEY = "\0capped_at_ns" +# Coarse filesystem timestamps (1 s on ext3, 2 s on FAT) can stamp a file +# created just after the snapshot as slightly older than it. +_CAPPED_BASELINE_SLACK_NS = 2_000_000_000 def _list_untracked(cwd): @@ -377,6 +572,7 @@ def _list_untracked(cwd): the holdouts.""" try: repo = _git_toplevel(cwd) or cwd + started_ns = time.time_ns() # core.quotePath=false comes from GIT_CMD globally (see gitutil.py). r = subprocess.run( [*GIT_CMD, "ls-files", "--others", "--exclude-standard", "-z"], @@ -397,6 +593,10 @@ def _list_untracked(cwd): out[p] = 0 if len(out) >= UNTRACKED_BASELINE_CAP: debug_log(f"_list_untracked: capped at {UNTRACKED_BASELINE_CAP}") + # The files past the cap are not recorded one by one. Record + # when the snapshot was taken so the Stop hook can still tell + # them from files created or edited during the turn. + out[UNTRACKED_CAPPED_AT_KEY] = started_ns break return out except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: @@ -442,14 +642,24 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel if tracked_dirty is None: return [], "HEAD", repo, [], {"dirty_now_count": -1, "changed_since_count": -1, "review_set_count": 0} + capped_at_ns = untracked_at_baseline.get(UNTRACKED_CAPPED_AT_KEY) + def _unchanged_since_baseline(p): base_mtime = untracked_at_baseline.get(p) - if base_mtime is None: - return False try: - return os.stat(os.path.join(repo, p)).st_mtime_ns == base_mtime + st = os.stat(os.path.join(repo, p)) except OSError: return False + if base_mtime is not None: + return st.st_mtime_ns == base_mtime + if not capped_at_ns: + return False + # The snapshot stopped at the cap, so this file may simply be one it + # never reached. Without this, every pre-existing file past the cap + # looks new on every turn and the same files are reviewed again and + # again. A file created or edited during the turn has a later mtime + # or ctime than the snapshot; anything older was already there. + 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)} new_untracked = untracked - preexisting_unchanged diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index f5d016db..059f3825 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -27,7 +27,7 @@ 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 state_dir as _resolve_state_dir +from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output # Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry. NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python @@ -765,7 +765,11 @@ if __name__ == "__main__": # SessionStart runs before the user's first prompt; doing this in the # background means the first commit-review of the session usually finds # the venv ready. - print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True) + # + # Not printed in portable mode: a host that reads stdout as one JSON + # document rejects a second line, and runs this hook to completion anyway. + if not portable_output(): + print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True) t0 = time.perf_counter() try: outcome, err_phase, err_kind = main() @@ -845,6 +849,10 @@ if __name__ == "__main__": pv = _plugin_version_int() if pv: metrics["pv"] = pv + # See sg-python.sh pass 4: started by real path, the PATH names could + # not read the plugin files. + if os.environ.get("SG_LAUNCHER_FALLBACK") == "1": + metrics["launcher_fallback"] = 1 response: dict[str, object] = {"metrics": metrics} # One-time user-visible notice when the agentic reviewer is dead on # arrival. Uses hookSpecificOutput.additionalContext (SessionStart's @@ -859,4 +867,4 @@ if __name__ == "__main__": "additionalContext": notice, } response["systemMessage"] = notice - print(json.dumps(response), flush=True) + write_hook_output(response) diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index a9c7f8fe..cb3e0a8d 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -12,11 +12,13 @@ Two extensibility points, both additive only: Discovery, in precedence order (matching CLAUDE.md / settings.json): - ``~/.claude/<name>`` (user) + - ``$CLAUDE_CONFIG_DIR/<name>`` (user, when set to another directory) - ``<cwd>/.claude/<name>`` (project, committed) - ``<cwd>/.claude/<name>.local.<ext>`` (project local, gitignored) Managed delivery via ``managed-settings.json`` is not yet supported. -Org admins can still push files to ``~/.claude/`` via MDM/GPO. +Org admins can still push files to ``~/.claude/`` (or the directory +``CLAUDE_CONFIG_DIR`` names) via MDM/GPO. Trust model: - The ``.md`` is repo-controlled and goes into the USER prompt (not system), @@ -89,11 +91,32 @@ def user_patterns() -> List[Dict[str, Any]]: # ── claude-security-guidance.md ─────────────────────────────────────────────────────── +def _user_config_dirs() -> List[str]: + """User-level config directories. ``~/.claude`` always, so a file placed + there keeps loading; then ``CLAUDE_CONFIG_DIR`` when it names another + directory. Empty is treated as not set, as in ``_base.state_dir``.""" + dirs = [os.path.expanduser(os.path.join("~", ".claude"))] + configured = (os.environ.get("CLAUDE_CONFIG_DIR") or "").strip() + if configured: + configured = os.path.expanduser(configured) + if _same_dir(configured, dirs[0]): + return dirs + dirs.append(configured) + return dirs + + +def _same_dir(a: str, b: str) -> bool: + try: + return os.path.samefile(a, b) + except OSError: + return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b)) + + def _config_paths(cwd: Optional[str], basename: str) -> List[Tuple[str, str]]: """Existing config file paths, lowest precedence first (so concat reads in precedence order user → project → project-local). Truncation is done on the concatenated string, so lowest-precedence content is dropped last.""" - paths = [("User", os.path.expanduser(os.path.join("~", ".claude", basename)))] + paths = [("User", os.path.join(d, basename)) for d in _user_config_dirs()] if cwd: paths.append(("Project", os.path.join(cwd, ".claude", basename))) # claude-security-guidance.local.md / security-patterns.local.yaml diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 5ef8a8db..aceb9071 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -44,6 +44,13 @@ GIT_CMD = [ # content same) rewrites the index under index.lock, GIT_OPTIONAL_LOCKS or # not. Off, every diff here only reads the index, so none needs a copy. "-c", "diff.autoRefreshIndex=false", + # The diff parsers read `diff --git a/<old> b/<new>` headers. A user's + # diff.mnemonicPrefix (c/ w/ i/), diff.noprefix or diff.srcPrefix / + # diff.dstPrefix changes that shape, and every file would be dropped. + "-c", "diff.mnemonicPrefix=false", + "-c", "diff.noprefix=false", + "-c", "diff.srcPrefix=a/", + "-c", "diff.dstPrefix=b/", ] SAFE_GIT_CONFIG = ( @@ -937,6 +944,77 @@ SKIP_FILE_SUFFIXES = ( '.lock', '_pb2.py', '.pb.go', ) +# Files that hold secrets by naming convention are never sent for review. The +# review covers everything dirty in the work tree, including files the user +# changed and Claude never opened, so a key file or an encrypted dotfile source +# would otherwise leave the machine in the review request. The list is kept to +# names that are secret stores by convention; ordinary source such as +# `private_api.py` or `id_generator.py` stays reviewable. +_SSH_PRIVATE_KEY_BASENAMES = frozenset(( + 'id_rsa', 'id_dsa', 'id_ecdsa', 'id_ecdsa_sk', 'id_ed25519', + 'id_ed25519_sk', 'id_xmss', +)) +_PRIVATE_KEY_NAME_SUFFIXES = ('_rsa', '_dsa', '_ecdsa', '_ed25519') +_CREDENTIAL_BASENAMES = frozenset(( + 'credentials', '.netrc', '.pgpass', '.npmrc', '.pypirc', + '.git-credentials', '.dockercfg', +)) +# chezmoi encodes a target file's attributes as stacked name prefixes +# (`private_dot_netrc`, `encrypted_private_token`); `dot_` stands for a +# leading dot. +_CHEZMOI_ATTR_PREFIXES = ( + 'after_', 'before_', 'create_', 'empty_', 'encrypted_', 'exact_', + 'executable_', 'external_', 'literal_', 'modify_', 'once_', 'onchange_', + 'private_', 'readonly_', 'remove_', 'run_', 'symlink_', +) +# An `encrypted_` source keeps its target's name, so `encrypted_store.py` could +# be either ciphertext or code about encryption. Treat it as ciphertext only +# when it has no extension or a data-file one. +_ENCRYPTED_DATA_EXTENSIONS = frozenset(( + '', '.json', '.yaml', '.yml', '.toml', '.properties', '.tfvars', +)) + + +# Paths skipped as secret-shaped during this hook run. The Stop hook reports +# the count (never the names) so the skip can be watched in telemetry. +_secret_shaped_skipped = set() + + +def _skip_secret_shaped(file_path): + if not _is_secret_shaped(file_path): + return False + _secret_shaped_skipped.add(file_path) + return True + + +def _is_secret_shaped(file_path): + base = os.path.basename(file_path.replace("\\", "/")).lower() + target = base + encrypted = False + stripped = True + while stripped: + stripped = False + for prefix in _CHEZMOI_ATTR_PREFIXES: + if target.startswith(prefix) and len(target) > len(prefix): + target = target[len(prefix):] + encrypted = encrypted or prefix == 'encrypted_' + stripped = True + break + if target.startswith('dot_'): + target = '.' + target[4:] + ext = os.path.splitext(target)[1] + if encrypted and ext in _ENCRYPTED_DATA_EXTENSIONS: + return True + for name in {base, target}: + if name.startswith('.env'): + return True + if name in _SSH_PRIVATE_KEY_BASENAMES or name in _CREDENTIAL_BASENAMES: + return True + if '.' not in name and name.endswith(_PRIVATE_KEY_NAME_SUFFIXES): + return True + return False + + # 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, @@ -1014,6 +1092,8 @@ def _is_reviewable_source(file_path): norm = "/" + file_path.replace("\\", "/") if any(("/" + p) in norm for p in SKIP_PATH_PATTERNS): return False + if _skip_secret_shaped(file_path): + return False if file_path.endswith(SKIP_FILE_SUFFIXES): return False ext = os.path.splitext(file_path)[1].lower() @@ -1043,32 +1123,103 @@ def _is_reviewable_source(file_path): return False +# A file's section starts at a `diff --git ` line. Inside a section every line +# of file content carries a `+`, `-` or space prefix, so only a real header can +# start a line with it; source text that merely contains the words cannot. +_DIFF_SECTION_RE = re.compile(r'^diff --git ', re.MULTILINE) +_UNQUOTED_HEADER_RE = re.compile(r'^a/(.+?) b/(.+)$') +_C_ESCAPES = { + 'a': b'\a', 'b': b'\b', 'f': b'\f', 'n': b'\n', 'r': b'\r', 't': b'\t', + 'v': b'\v', '\\': b'\\', '"': b'"', +} + + +def _read_quoted_path(text, start): + """Decode the C-quoted path whose opening quote is at text[start]. + Returns (path, index after the closing quote), or None if unterminated.""" + out = bytearray() + i = start + 1 + while i < len(text): + c = text[i] + if c == '"': + return out.decode("utf-8", errors="replace"), i + 1 + if c == '\\' and i + 1 < len(text): + n = text[i + 1] + if n in _C_ESCAPES: + out += _C_ESCAPES[n] + i += 2 + continue + octal = re.match(r'[0-7]{1,3}', text[i + 1:i + 4]) + if octal: + out.append(int(octal.group(0), 8) & 0xFF) + i += 1 + len(octal.group(0)) + continue + out += c.encode("utf-8") + i += 1 + return None + + +def _parse_diff_header(header): + """(old_path, new_path) from the text after `diff --git `, or None. + + core.quotePath=false keeps non-ASCII names raw, but git still C-quotes a + name that contains a double quote, a backslash or a control character: + `"a/we\\"ird.py" "b/we\\"ird.py"`. Either side can be quoted on its own. + """ + old = new = None + if header.startswith('"'): + first = _read_quoted_path(header, 0) + if not first: + return None + old, end = first + rest = header[end:].lstrip(' ') + if rest.startswith('"'): + second = _read_quoted_path(rest, 0) + new = second[0] if second else None + else: + new = rest + elif header.endswith('"') and ' "b/' in header: + split_at = header.index(' "b/') + old = header[:split_at] + second = _read_quoted_path(header, split_at + 1) + new = second[0] if second else None + else: + m = _UNQUOTED_HEADER_RE.match(header) + return (m.group(1), m.group(2)) if m else None + if not old or not new or not old.startswith('a/') or not new.startswith('b/'): + return None + return old[2:], new[2:] + + +# Section headers that could not be parsed during this hook run; that file is +# left out of the review. The Stop hook reports the count so a header shape +# this parser misses shows up in telemetry instead of passing silently. +_unparsed_diff_headers = set() + + +def _iter_diff_sections(diff_output): + """Yield (new_path, old_path, lines after the header line) per file section.""" + for section in _DIFF_SECTION_RE.split(diff_output)[1:]: + lines = section.split('\n') + paths = _parse_diff_header(lines[0]) + if paths: + yield paths[1] or paths[0], paths[0], lines[1:] + else: + _unparsed_diff_headers.add(lines[0]) + + def extract_file_paths_from_diff(diff_output): """ Extract file paths from unified diff output (without content). Only includes files with source code extensions. - Returns a list of file paths. """ if not diff_output or not diff_output.strip(): return [] - paths = [] - file_diffs = diff_output.split("diff --git ") - - for file_diff in file_diffs: - if not file_diff.strip(): - continue - lines = file_diff.split('\n') - header_match = re.match(r'^a/(.+?) b/(.+)$', lines[0]) - if not header_match: - continue - file_path = header_match.group(2) or header_match.group(1) or '' - if not _is_reviewable_source(file_path): - continue - paths.append(file_path) - - return paths - + 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) + ] def parse_diff_into_files(diff_output): @@ -1080,28 +1231,16 @@ def parse_diff_into_files(diff_output): return [] files = [] - file_diffs = diff_output.split("diff --git ") - - for file_diff in file_diffs: - if not file_diff.strip(): - continue - - # Extract filename from first line: "a/path/to/file b/path/to/file" - lines = file_diff.split('\n') - header_match = re.match(r'^a/(.+?) b/(.+)$', lines[0]) - if not header_match: - continue - - file_path = header_match.group(2) or header_match.group(1) or '' - - # Filter to source code files only - if not _is_reviewable_source(file_path): + 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): continue # Extract the diff content (from first @@ onwards) diff_lines = [] in_hunks = False - for line in lines[1:]: + for line in lines: if line.startswith('@@'): in_hunks = True if in_hunks: diff --git a/plugins/security-guidance/hooks/hooks.json b/plugins/security-guidance/hooks/hooks.json index a4723026..eef54730 100644 --- a/plugins/security-guidance/hooks/hooks.json +++ b/plugins/security-guidance/hooks/hooks.json @@ -37,58 +37,26 @@ { "type": "command", "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git commit:*)", + "if": "Bash(git*commit*)", "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" + "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", + "rewakeSummary": "Security review found issues" }, { "type": "command", "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git -C * commit *)", + "if": "Bash(git*push*)", "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" + "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", + "rewakeSummary": "Security review found issues" }, { "type": "command", "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git push:*)", + "if": "Bash(gt *)", "asyncRewake": true, - "rewakeMessage": "Background security review of pushed commits not yet reviewed — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Push security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git -C * push*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of pushed commits not yet reviewed — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Push security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(gt create:*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(gt modify:*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(gt submit:*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of pushed commits not yet reviewed — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Push security review found issues" + "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", + "rewakeSummary": "Security review found issues" } ], "matcher": "Bash" diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 3c1eb5e3..9fe8640c 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -20,11 +20,15 @@ Two reassignable globals here are read by handlers in import glob import hashlib import json +import logging import os import re import sys import tempfile +import threading import time +import traceback +import urllib.parse import urllib.request from typing import Optional, Tuple, Dict, Any, List @@ -153,6 +157,24 @@ CLAUDE_CODE_SYSTEM_PROMPT = "You are a Claude agent, built on Anthropic's Claude # each call. None = no error; int = HTTP status code; -1 = network/timeout; _last_call_claude_http_error = None +# Outcome of this thread's last analyze_code_security call. Per thread because +# the commit review's race runs that call on a thread of its own. +_review_status = threading.local() + + +def last_review_failed() -> bool: + """True when this thread's last analyze_code_security call got no verdict + from the model (every call failed, or the reply could not be read), which + a caller must not treat as "nothing found".""" + return getattr(_review_status, "failed", False) + + +def last_review_status() -> Optional[int]: + """A copy of the module-wide _last_call_claude_http_error, taken when this + thread's last analyze_code_security call got no verdict (an overlapping call + on another thread can change the global); None if the reply was unreadable.""" + return getattr(_review_status, "status", None) + # ===================================================================== # Outbound connectivity probe @@ -267,6 +289,56 @@ def _cap_files_for_prompt(files): _auth_prefer_token = False +# A valid HTTP header name (an RFC 9110 token). +_HEADER_NAME = re.compile(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+") +_custom_header_lines_skipped = set() + + +def _custom_headers() -> List[Tuple[str, str]]: + """ANTHROPIC_CUSTOM_HEADERS as (name, value) pairs, parsed the way Claude + Code parses it: one `Name: Value` per line, split at the first colon, + trimmed, lines with no name dropped. Lines http.client cannot send (an + invalid name, a carriage return or non-Latin-1 text in the value) are + skipped. Values are never logged: they are often credentials.""" + pairs = [] + raw = os.environ.get("ANTHROPIC_CUSTOM_HEADERS", "") + for number, line in enumerate(re.split(r"\r?\n", raw), 1): + name, sep, value = line.partition(":") + name, value = name.strip(), value.strip() + if not sep or not name: + continue + try: + value.encode("latin-1") + sendable = bool(_HEADER_NAME.fullmatch(name)) and "\r" not in value + except UnicodeEncodeError: + sendable = False + if not sendable: + if number not in _custom_header_lines_skipped: + _custom_header_lines_skipped.add(number) + debug_log(f"ANTHROPIC_CUSTOM_HEADERS: skipped line {number}, not a valid HTTP header") + continue + pairs.append((name, value)) + return pairs + + +def gateway_cfg() -> int: + """How the plugin's own API calls 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.""" + cfg = 0 + base = _anthropic_base_url() + try: + host = (urllib.parse.urlsplit(base).hostname or "").lower() + except ValueError: + host = "" + if base and host != "api.anthropic.com": + cfg |= 1 + if any(name.lower() != "anthropic-beta" for name, _ in _custom_headers()): + cfg |= 2 + return cfg + + def _build_auth_headers(use_token, betas=("structured-outputs-2025-11-13",)): betas = list(betas) headers = { @@ -278,6 +350,18 @@ def _build_auth_headers(use_token, betas=("structured-outputs-2025-11-13",)): betas.append("oauth-2025-04-20") else: headers["x-api-key"] = ANTHROPIC_API_KEY + for name, value in _custom_headers(): + lowered = name.lower() + if lowered == "anthropic-beta": + # Not sent: the review needs none of the user's betas, and Claude + # Code drops anthropic-beta lines when the organization's + # compliance policy disables experimental betas. + continue + # As in Claude Code, a custom line wins over a header of the same + # name that the plugin set, including the credential header. + for existing in [k for k in headers if k.lower() == lowered]: + del headers[existing] + headers[name] = value if betas: headers["anthropic-beta"] = ",".join(betas) return headers @@ -512,8 +596,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) 3P providers. Uses the same `output_format` JSON-schema contract so the return value shape is identical (parsed dict or None). - No tools (`allowed_tools=[]`) — the security review only needs structured - output, not Read/Grep/Glob. Single turn keeps cost predictable. + 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 _last_call_claude_http_error = None @@ -546,6 +630,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) _record_http_error(-1) return None + _send_sdk_logs_to_debug_log() cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None default_model = default_review_model() chosen_model = model or default_model @@ -560,6 +645,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) system_prompt=CLAUDE_CODE_SYSTEM_PROMPT, cli_path=cli_path, allowed_tools=[], + extra_args=_only_tools_args(), setting_sources=[], max_turns=2, model=chosen_model, @@ -1111,7 +1197,11 @@ def analyze_code_security(files: List[Tuple[str, str]], is_diff: bool = False, p previous_findings: list of category strings from earlier stop hook firings this turn, used to prompt the reviewer to verify those issues were actually fixed. Returns (formatted guidance string or None, list of vuln dicts with severity/category). + Also returns (None, []) when the model gave no verdict; last_review_failed() + tells the two apart. """ + _review_status.failed = False + _review_status.status = None if not HAS_API_CREDENTIALS or not files: return None, [] @@ -1229,11 +1319,21 @@ Respond with a JSON object. If vulnerabilities are found, set hasVulnerabilities } prompt += extensibility.guidance_block() - analysis = _call_claude_dual_or(prompt, output_schema, - bool_key="hasVulnerabilities", - list_key="vulnerabilities", - cacheable_prefix=_CODE_REVIEW_RUBRIC) - if not analysis or not analysis.get("hasVulnerabilities") or not analysis.get("vulnerabilities"): + try: + analysis = _call_claude_dual_or(prompt, output_schema, + bool_key="hasVulnerabilities", + list_key="vulnerabilities", + cacheable_prefix=_CODE_REVIEW_RUBRIC) + except Exception as e: + debug_log(f"LLM code review: call raised {type(e).__name__}: {e}") + analysis = None + # A reply without the schema's required flag is not a verdict either. + if not isinstance(analysis, dict) or "hasVulnerabilities" not in analysis: + _review_status.failed = True + _review_status.status = _last_call_claude_http_error + debug_log("LLM code review: no verdict from the model") + return None, [] + if not analysis.get("hasVulnerabilities") or not analysis.get("vulnerabilities"): debug_log("LLM code review: no vulnerabilities found") return None, [] @@ -1279,6 +1379,49 @@ _FINDINGS_SCHEMA = review_api.FINDINGS_SCHEMA _SURVIVED_SCHEMA = review_api.SURVIVED_SCHEMA +class _DebugLogHandler(logging.Handler): + def emit(self, record): + try: + text = record.getMessage() + if record.exc_info: + text += " | " + "".join( + traceback.format_exception_only(*record.exc_info[:2])).strip() + except Exception: + return # never handleError(): it prints to stderr + debug_log(f"agent sdk: {text}") + + +_sdk_log_lock = threading.Lock() + + +def _send_sdk_logs_to_debug_log() -> None: + """Route the Agent SDK's own log records to the debug log, and stop them + propagating. With no handler, Python prints its errors to this hook's + stderr, which Claude Code shows Claude as the review notice.""" + sdk_logger = logging.getLogger("claude_agent_sdk") + with _sdk_log_lock: + if not any(isinstance(h, _DebugLogHandler) for h in sdk_logger.handlers): + sdk_logger.addHandler(_DebugLogHandler()) + sdk_logger.propagate = False + + +# The agentic reviewer reads a diff it must not trust, so it gets +# file-reading tools and nothing else. +_REVIEWER_TOOLS = ("Read", "Grep", "Glob") + + +def _only_tools_args(tools: Tuple[str, ...] = ()) -> Dict[str, Optional[str]]: + """extra_args that make `tools` the inner CLI's whole tool set. + + allowed_tools only pre-approves tools. Without these flags the inner CLI + still offers every Claude Code tool (shell, file edits, web, subagents) + and any configured MCP server, and whether a call to one runs is left to + 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} + + def _agentic_spawn_env() -> Dict[str, str]: """opts.env for the SDK-spawned inner `claude` CLI. @@ -1301,11 +1444,11 @@ def _agentic_spawn_env() -> Dict[str, str]: "CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR": "", "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR": "", "CLAUDE_CODE_INCLUDE_PARTIAL_MESSAGES": "", - # Neutralize git config/env hijack vectors so an allowlisted - # `git diff/log/show` cannot be turned into RCE via diff.external, - # core.pager, core.sshCommand, or an inherited GIT_* var. The agentic - # session only needs read-only history inspection; it never needs an - # external diff driver, a pager, or a remote. + # Neutralize git config/env hijack vectors so a `git diff/log/show` + # cannot be turned into RCE via diff.external, core.pager, + # core.sshCommand, or an inherited GIT_* var. The inner CLI has no + # shell tool (see _only_tools_args); this stays as a second line of + # defence should it ever run git. "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_EXTERNAL_DIFF": "", @@ -1327,13 +1470,46 @@ def _agentic_spawn_env() -> Dict[str, str]: return env +# The tools the agentic reviewer is given to look around the repo. +_REVIEWER_FILE_TOOLS = ("Read", "Grep", "Glob") + + +def _agentic_context_dir(repo_dir: str) -> str: + """The directory the agentic reviewer runs in.""" + return os.environ.get("SG_AGENTIC_CONTEXT_DIR") or repo_dir + + def agentic_review( repo_dir: str, diff_files: List[Tuple[str, str]], touched_paths: List[str], ) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]: + """Run the two-stage agentic review (_agentic_review) and add reviewer + context diagnostics to its metrics. Counts only, no paths: + + rv_cwd_gone 1 = the directory the reviewer runs in was missing + before the review, 2 = it went missing during it + rv_tool_err Read/Grep/Glob calls that came back as errors + rv_tool_calls Read/Grep/Glob calls made + + The counts cover all stages of the review. Keys are left out when 0.""" + context_dir = _agentic_context_dir(repo_dir) + gone = 0 if os.path.isdir(context_dir) else 1 + ctx = {"rv_tool_err": 0, "rv_tool_calls": 0} + guidance, vulns, metrics = _agentic_review(repo_dir, diff_files, touched_paths, ctx) + if not gone and not os.path.isdir(context_dir): + gone = 2 + ctx_m = {"rv_cwd_gone": gone, **ctx} + return guidance, vulns, {**metrics, **{k: v for k, v in ctx_m.items() if v}} + + +def _agentic_review( + repo_dir: str, diff_files: List[Tuple[str, str]], touched_paths: List[str], + ctx: Dict[str, int], +) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]: """Two-stage Agent-SDK review: investigate (Read/Grep/Glob over the repo) then a self-refute filter pass. Returns (guidance_or_None, vulns, metrics). On SDK unavailability returns (None, [], {"agentic_fallback": - reason}) so the caller can fall back to the single-shot path.""" + reason}) so the caller can fall back to the single-shot path. Adds to + the `ctx` counters (see agentic_review) as the reviewer makes tool calls.""" import time as _t # Note: do NOT pop ANTHROPIC_AUTH_TOKEN from os.environ here. The race @@ -1377,6 +1553,7 @@ def agentic_review( debug_log(f"agentic_review: SDK unavailable ({e}); falling back") return None, [], {"agentic_fallback": f"import:{type(e).__name__}"} + _send_sdk_logs_to_debug_log() # Overridable via SG_AGENTIC_MODEL. model = os.environ.get("SG_AGENTIC_MODEL") or _CLI_OPUS_ALIAS max_turns = int(os.environ.get("SG_AGENTIC_MAX_TURNS", "18")) @@ -1384,7 +1561,7 @@ def agentic_review( # eval harness it's a temp dir with ONLY touched_paths — the agent can't # trace cross-file data flow. The harness sets SG_AGENTIC_CONTEXT_DIR to a # full repo (worktree at the commit, or the live clone at HEAD). - context_dir = os.environ.get("SG_AGENTIC_CONTEXT_DIR") or repo_dir + context_dir = _agentic_context_dir(repo_dir) context_note = "" if context_dir != repo_dir: context_note = ( @@ -1461,6 +1638,21 @@ def agentic_review( except Exception: pass + # 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] + + 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: + child_stderr_lines[0] += 1 + metrics["child_stderr"] = child_stderr_lines[0] + if child_stderr_lines[0] <= 20: + debug_log(f"agentic reviewer's CLI stderr | {str(line).rstrip()}") + elif child_stderr_lines[0] == 21: + debug_log("agentic reviewer's CLI stderr | (further lines not logged)") + async def _arun(system: str, prompt: str, *, schema: Dict[str, Any], turns: Optional[int] = None ) -> Tuple[Optional[Dict[str, Any]], int, Optional[str]]: @@ -1472,12 +1664,10 @@ def agentic_review( system_prompt=system, cwd=context_dir, cli_path=cli_path, - allowed_tools=["Read", "Grep", "Glob"], - # Read/Grep/Glob within cwd are auto-approved in default - # permission mode, so bypassPermissions is unnecessary (and - # would trip our own agent-permission-bypass guidance). Leaving - # permission_mode unset means an accidental future addition of - # a write/exec tool to allowed_tools is caught by the gate. + # Pre-approved, and the only tools the reviewer has: no + # permission mode can then let it write, run or fetch anything. + allowed_tools=list(_REVIEWER_TOOLS), + extra_args=_only_tools_args(_REVIEWER_TOOLS), setting_sources=[], max_turns=turns if turns is not None else max_turns, model=model, @@ -1517,6 +1707,7 @@ def agentic_review( # the review run end-to-end; the others are belt-and-suspenders # for the same fd-passing pattern. env=_agentic_spawn_env(), + stderr=_on_child_stderr, ) n = 0 structured: Optional[Dict[str, Any]] = None @@ -1533,9 +1724,16 @@ def agentic_review( yield {"type": "user", "message": {"role": "user", "content": prompt}} + # Blocks are matched by shape so older SDK builds need no extra import. + file_tool_ids = set() async for msg in query(prompt=_once(), options=opts): if isinstance(msg, AssistantMessage): n += 1 + for b in getattr(msg, "content", None) or []: + if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS + and getattr(b, "id", None)): + file_tool_ids.add(b.id) + ctx["rv_tool_calls"] += 1 elif isinstance(msg, ResultMessage): subtype = msg.subtype if msg.structured_output is not None: @@ -1545,6 +1743,15 @@ def agentic_review( # the price-table estimate. getattr guards older SDK builds. _record_usage(getattr(msg, "usage", None) or {}, model, cost_usd=getattr(msg, "total_cost_usd", None)) + else: + # Tool results come back as user messages. + content = getattr(msg, "content", None) + if isinstance(content, list): + ctx["rv_tool_err"] += sum( + 1 for b in content + if getattr(b, "is_error", None) is True + and getattr(b, "tool_use_id", None) in file_tool_ids + ) return structured, n, subtype def _run(system: str, prompt: str, *, schema: Dict[str, Any] @@ -1568,12 +1775,14 @@ def agentic_review( f"{json.dumps(inv, indent=2) if inv else '<none>'}") except Exception as e: debug_log(f"agentic_review: investigate failed ({e}); falling back") - return None, [], {"agentic_fallback": f"investigate:{type(e).__name__}"} + return None, [], {"agentic_fallback": f"investigate:{type(e).__name__}", + **_child_stderr_metric()} metrics["investigate_ms"] = int((_t.time() - t0) * 1000) metrics["investigate_turns"] = inv_turns if inv is None: reason = inv_subtype or "no_structured_output" - return None, [], {"agentic_fallback": f"investigate:{reason}"} + return None, [], {"agentic_fallback": f"investigate:{reason}", + **_child_stderr_metric()} # Keep medium-severity candidates through self-refute — that pass is the # real precision gate, and the model's investigate-stage severity rating # is conservative (it defaults to "medium"). Filtering to high/critical diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 6b885e64..946fddcf 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -83,7 +83,9 @@ from _base import ( # noqa: E402,F401 PROVENANCE_TAG, PROVENANCE_BANNER, _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, + write_hook_output as _write_hook_output, ) import extensibility # noqa: E402 from patterns import ( # noqa: E402,F401 @@ -117,6 +119,7 @@ from diffstate import ( # noqa: E402,F401 get_baseline_file_content, capture_git_baseline, _REVIEWED_SHAS_BASENAME, _REVIEWED_SHAS_CAP, _reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas, + _full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight, UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set, ) from reporesolve import ( # noqa: E402,F401 @@ -125,6 +128,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 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 ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, HAS_API_CREDENTIALS, @@ -204,6 +208,20 @@ CONTINUATION_SUFFIX = ( "response." ) +# Extra keys emit_metrics appends to every row this invocation emits. +_TAIL_METRICS: Dict[str, Any] = {} + +# Reviewer context diagnostics from llm.agentic_review, most useful first. +_REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls") + + +def _note_reviewer_context(agentic_metrics): + """Queue the agentic reviewer's context diagnostics for this row.""" + for key in _REVIEWER_CONTEXT_KEYS: + if agentic_metrics.get(key): + _TAIL_METRICS[key] = agentic_metrics[key] + + def emit_metrics( metrics, rewake_summary=None, @@ -234,31 +252,22 @@ def emit_metrics( task-notification one-liner. Must be in the same JSON line as the metrics because CC stops scanning stdout after the first {-prefixed line. - `additional_context` (asyncRewake findings): model-visible guidance text. - Delivery channel depends on `hook_event_name` because CC's hook-output - contract is NOT symmetric across events: - - - PostToolUse (commit-review, push-sweep): surfaced via the modern - hookSpecificOutput.additionalContext protocol. `PostToolUse` is a - member of CC's hookSpecificOutput discriminated union - (coreSchemas.ts), so the JSON validates and metrics/rewakeSummary - are consumed. See #1375 / #1783 for why this replaced the legacy - stderr + exit(2) shape for PostToolUse. - - - Stop / SubagentStop: there is NO `Stop` member in that union, so - emitting hookSpecificOutput{hookEventName:"Stop"} makes the whole - line fail isSyncHookJSONOutput validation — which on the asyncRewake - path silently drops metrics AND rewakeSummary, and (because the - legacy stderr write was removed) leaks the raw JSON to the model as - the rewake body. CC's asyncRewake delivery actually reads - `stderr || stdout` for the model-visible body and only scans stdout - JSON for metrics+rewakeSummary — it never reads additionalContext - on this path. So for Stop we use the documented clean pattern: - guidance on stderr, valid JSON (metrics + rewakeSummary + - top-level decision/reason) on stdout. The top-level decision:"block" - + reason also covers the sync-fallback path (single-shot `claude -p`, - where asyncRewake degrades to a sync Stop hook that reads - decision/reason). See #2159. + `additional_context` (asyncRewake findings, exit-2 callers only): + model-visible guidance text, written to stderr for every event. CC's + asyncRewake delivery reads `stderr || stdout` for the model-visible body + and only scans stdout JSON for metrics+rewakeSummary — it never reads + additionalContext on this path. stdout keeps one valid JSON line so + metrics + rewakeSummary survive: + + - Stop / SubagentStop: also top-level decision:"block" + reason, for + the sync-fallback path (single-shot `claude -p`, where asyncRewake + degrades to a sync Stop hook that reads decision/reason). There is + no `Stop` member in CC's hookSpecificOutput union, so that field + must not be used here. + + - PostToolUse (commit-review, push-sweep): stderr only. In the + sync-fallback path CC shows the model an exit-2 PostToolUse hook's + stderr, so additionalContext would repeat the text. Empty/None additional_context emits neither channel (back-compat for metrics-only callers). @@ -269,40 +278,47 @@ def emit_metrics( surface; systemMessage adds a per-fire override when the static rewakeMessage isn't specific enough for the finding being shown. - `hook_event_name` (used only when additional_context is set): selects the - delivery channel above. Defaults to "PostToolUse" (commit-review and + `hook_event_name` (used only when additional_context is set): whether to + add decision/reason as above. Defaults to "PostToolUse" (commit-review and push-sweep are the most common callers); handle_stop_hook passes "Stop". """ + _log_usage(_usage_metrics()) head = {} if _PV and "pv" not in metrics: head["pv"] = _PV - head.update(_usage_metrics()) + # sg-python.sh could only start this interpreter by its real path: the + # names on PATH were launcher aliases that cannot read the plugin files. + if os.environ.get("SG_LAUNCHER_FALLBACK") == "1": + head["launcher_fallback"] = 1 + usage = _usage_metrics() + head.update(usage) if head: metrics = {**head, **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 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. + cfg = llm.gateway_cfg() + if cfg: + tail["gateway_cfg"] = cfg + tail.update(_TAIL_METRICS) + metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} out = {"metrics": metrics} if rewake_summary: out["rewakeSummary"] = rewake_summary if additional_context: + # Guidance on stderr, the asyncRewake body channel (`stderr || stdout`). + sys.stderr.write(additional_context) + sys.stderr.flush() if hook_event_name in ("Stop", "SubagentStop"): - # Stop is NOT in CC's hookSpecificOutput union — emitting it there - # fails schema validation and drops metrics+rewakeSummary (#2159). - # Clean pattern: guidance on stderr (the asyncRewake body channel, - # delivered via `stderr || stdout`), top-level decision/reason for - # the sync-fallback path. stdout JSON stays valid so metrics + - # rewakeSummary survive. - sys.stderr.write(additional_context) - sys.stderr.flush() + # Sync-fallback path for Stop reads decision/reason. out["decision"] = "block" out["reason"] = additional_context - else: - # PostToolUse et al. — valid union member; modern protocol. - out["hookSpecificOutput"] = { - "hookEventName": hook_event_name, - "additionalContext": additional_context, - } if system_message: out["systemMessage"] = system_message - print(json.dumps(out), flush=True) + _write_hook_output(out) # ===================================================================== # State management @@ -540,29 +556,38 @@ def handle_user_prompt_submit(input_data): sys.exit(0) session_id = input_data.get("session_id", "default") - # stash-create and ls-files both walk the worktree (~2-5s each in a very - # large repo). Run them concurrently so UPS latency stays ≈ max(both). - import concurrent.futures as _cf - with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, cwd) - _f_ut = _ex.submit(_list_untracked, cwd) - sha = _f_sha.result() - # Always capture the untracked snapshot. `git stash create` returns - # empty when there are no TRACKED changes, but pre-existing untracked - # files still need to be excluded from the next Stop's review_set — - # otherwise an untracked-only working tree gets every untracked file - # reviewed on every turn until something tracked is dirtied. - untracked_now = _f_ut.result() or {} + # The untracked snapshot has one reader: the Stop-hook diff review, which + # skips before reading it when either of these switches is off (see + # handle_stop_hook). Listing the worktree on every prompt then buys + # nothing, so only the stash baseline (still read by the Write pattern + # filter) is captured. + snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW + + def _capture(repo_cwd): + if not snapshot_untracked: + return capture_git_baseline(repo_cwd), None + # stash-create and ls-files both walk the worktree (~2-5s each in a + # very large repo). Run them concurrently so UPS latency stays + # ≈ max(both). + import concurrent.futures as _cf + with _cf.ThreadPoolExecutor(max_workers=2) as _ex: + _f_sha = _ex.submit(capture_git_baseline, repo_cwd) + _f_ut = _ex.submit(_list_untracked, repo_cwd) + # Taken whether or not the stash produced a SHA. `git stash + # create` returns empty when there are no TRACKED changes, but + # pre-existing untracked files still need to be excluded from the + # next Stop's review_set — otherwise an untracked-only working + # tree gets every untracked file reviewed on every turn until + # something tracked is dirtied. + return _f_sha.result(), _f_ut.result() or {} + + sha, untracked_now = _capture(cwd) 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 - with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, cwd) - _f_ut = _ex.submit(_list_untracked, cwd) - sha = _f_sha.result() - untracked_now = _f_ut.result() or {} + sha, untracked_now = _capture(cwd) head = _git_rev_parse_head(cwd) # If the previous turn's Stop hook never ran (user interrupt, follow-up @@ -581,14 +606,24 @@ def handle_user_prompt_submit(input_data): # we still need to capture a baseline. if state.get("touched_paths") and state.get("baseline_sha"): preserved["value"] = True + # A baseline captured while the Stop review was off has no + # snapshot beside it. Without one the next Stop would take every + # 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 return if sha: state["baseline_sha"] = sha state["head_at_capture"] = head # untracked_at_baseline is independent of whether the stash produced - # a SHA — write it unconditionally so compute_v2_review_set's - # preexisting-untracked exclusion works in untracked-only trees. - state["untracked_at_baseline"] = untracked_now + # a SHA, so compute_v2_review_set's preexisting-untracked exclusion + # works in untracked-only trees. None means no snapshot was taken + # (Stop review off): drop the previous one, which belongs to an older + # baseline. + if untracked_now is None: + state.pop("untracked_at_baseline", None) + else: + state["untracked_at_baseline"] = untracked_now with_locked_state(session_id, _save) if preserved["value"]: @@ -683,26 +718,33 @@ _COMMIT_DIFFSTAT_PATTERNS = [ # or trailing hook output isn't picked up and fed to `git show`. _COMMIT_SHA_RE = re.compile(r'^\[[^\]]*?\b([0-9a-f]{7,40})\]', re.MULTILINE) -# Regex matching `git commit` commands. Mirrors Claude Code's own commit -# detection — it does NOT tolerate `git -c k=v commit` global options, which -# keeps this hook aligned with CC's commit attribution on what counts as a -# commit. +# Regex matching `git commit` commands, global options included (see below). # # Also matches `gt create` and `gt modify` — Graphite's stacked-PR wrapper # around git. `gt create` produces a new commit (mapped to git commit # semantics); `gt modify` amends the current commit (mapped to git commit -# --amend, also flagged by _GIT_AMEND_RE below). The hooks.json matcher -# widening for `gt create:*` / `gt modify:*` / `gt submit:*` ships in the -# same change set — without that widening this regex change is dead code -# because the hook subprocess never spawns for gt invocations. See #2048. +# --amend, also flagged by _GIT_AMEND_RE below). hooks.json has a +# `Bash(gt *)` entry so the hook subprocess spawns for gt invocations. +# +# Global options allowed between `git` and the subcommand, shared by +# _GIT_COMMIT_RE and _GIT_PUSH_RE: `-C <path>`, `-c key=val`, `--opt=val`, +# the long options that take a separate value, and flags that take none +# (`--no-pager`, `-p`). A value may be quoted in part (`-c user.name="A B"`). +_GIT_OPT_VALUE = r'''(?:[^\s"']|"[^"]*"|'[^']*')+''' +_GIT_VALUE_OPTS = r'git-dir|work-tree|namespace|config-env|attr-source' +_GIT_GLOBAL_OPTS = ( + r'(?:\s+-[Cc]\s+' + _GIT_OPT_VALUE + + r'|\s+--[^\s=]+=' + _GIT_OPT_VALUE + + r'|\s+--(?:' + _GIT_VALUE_OPTS + r')\s+' + _GIT_OPT_VALUE + # `--help` / `--version` run no subcommand. + + r'|\s+(?:--(?!(?:' + _GIT_VALUE_OPTS + r'|help|version)\s)[^\s=]+|-[pP])(?=\s))*' +) _GIT_COMMIT_RE = re.compile( - # `git -C <path>` and `git -c key=val` global options are allowed between - # `git` and `commit` (mirrors the long-standing tolerance in - # _GIT_PUSH_RE). Without this, `git -C /repo commit` is silently dropped - # by the handler — see #2089's secondary finding. The gt branch has no - # global-option layer to worry about. - r'\bgit(?:\s+-[Cc]\s+(?:"[^"]*"|\'[^\']*\'|[^\s"\']\S*)|\s+--[^\s=]+=\S+' - r'|\s+--(?:git-dir|work-tree)\s+\S+)*\s+commit\b' + # Without the global-option tolerance, `git -C /repo commit` is silently + # dropped by the handler — see #2089's secondary finding. The gt branch + # has no global-option layer to worry about. + # `(?!-)`: not the plumbing commands `git commit-graph` / `git commit-tree`. + r'\bgit' + _GIT_GLOBAL_OPTS + r'\s+commit\b(?!-)' r'|\bgt\s+(?:create|modify)\b' ) # Match either the `--amend` flag (with the leading whitespace boundary @@ -727,11 +769,9 @@ COMMIT_REVIEW_RATE_WINDOW_S = int( # ─── push-sweep ───────────────────────────────────────────────────────────── # # Mirrors Claude Code's own push-command matching — tolerates `git -C <p>` / -# `git -c k=v` global options. The hooks.json `Bash(git push:*)` matcher -# (subcommand prefix) doesn't, but those forms are rare in practice -# and the python only ever runs after CC's matcher fired, so this regex is a -# defensive re-gate, not a widening — `git -C path push` won't reach python -# unless chained with a plain `git push` in the same compound command. +# `git -c k=v` global options, as the hooks.json `Bash(git*push*)` matcher +# does. That matcher also lets through e.g. `git stash push`; this regex is +# what decides whether the command is a push. # # `gh pr create` is intentionally NOT a separate hooks.json matcher: gh runs # `git push` as a child process, which CC's matcher doesn't observe (it sees @@ -739,14 +779,13 @@ COMMIT_REVIEW_RATE_WINDOW_S = int( # entry would buy minimal extra coverage (sessions that push only via gh) at # the cost of an extra python spawn on every `... && gh pr create` compound # (the common case). Those sessions are caught on their next standalone `git push`. -# Matches `git push` (with optional `-c k=v` / `-C path` global options -# CC's hooks.json matcher doesn't tolerate) OR `gt submit` — Graphite's +# Matches `git push` (with optional `-c k=v` / `-C path` global options) +# OR `gt submit` — Graphite's # stacked-PR push command. gt submit forwards to `git push` internally, # but the bash hook fires on Claude's top-level command so we need to # recognize gt submit at the matcher level. See #2048. _GIT_PUSH_RE = re.compile( - r'(?:\bgit(?:\s+-[cC]\s+(?:"[^"]*"|\'[^\']*\'|[^\s"\']\S*)|\s+--[^\s=]+=\S+' - r'|\s+--(?:git-dir|work-tree)\s+\S+)*\s+push\b|\bgt\s+submit\b)' + r'(?:\bgit' + _GIT_GLOBAL_OPTS + r'\s+push\b|\bgt\s+submit\b)' ) # `git push` stdout: "abc1234..def5678 branch -> branch" (or `+abc..def` on @@ -763,12 +802,20 @@ _PUSH_RANGE_RE = re.compile( MAX_PUSH_SWEEP_FILES = int(os.environ.get("SG_PUSH_SWEEP_MAX_FILES", "30")) MAX_PUSH_SWEEP_RANGE = int(os.environ.get("SG_PUSH_SWEEP_MAX_RANGE", "50")) PUSH_SWEEP_REPORT_CAP = int(os.environ.get("SG_PUSH_SWEEP_REPORT_CAP", "3")) +# How long a push review waits for a commit review that is still running on +# the pushed commits, before reviewing them itself. Longer than the agentic +# race delay, so a commit review that fell back to single-shot can finish. +try: + INFLIGHT_WAIT_S = int(os.environ.get("SG_INFLIGHT_WAIT_S", "") or 240) +except ValueError: + INFLIGHT_WAIT_S = 240 def _claim_bash_hook_once(input_data): """De-dupe across hooks.json `if` matchers firing for the same Bash call. - `git commit -m x && git push` matches both `Bash(git commit:*)` and - `Bash(git push:*)` `if` configs → CC spawns this script twice with the + `git commit -m x && git push` matches both `Bash(git*commit*)` and + `Bash(git*push*)` `if` configs, and a command CC cannot parse runs every + `if` config → CC spawns this script more than once with the SAME `tool_use_id`. The first spawn atomically creates a sentinel under `.git/`; subsequent spawns see it and exit early. Avoids redundant LLM calls (and the redundant asyncRewake) on compound commands. @@ -899,6 +946,17 @@ def _push_section(bash_output): section = section[:end] return section +def _push_in_output(bash_output): + """True when Bash output shows a git push that updated a remote branch.""" + section = _push_section(bash_output or "") + if not section.lstrip("\n").startswith("To "): + return False + return bool(_PUSH_RANGE_RE.search(section)) or "[new branch]" in section + +# Only words the failed-review notice; `gh pr create` alone is not routed to +# the push review. +_MAY_PUSH_VIA_GH_RE = re.compile(r"\bgh\s+pr\s+create\b") + def _detect_prev_upstream(repo_root, bash_output): """Where the remote was BEFORE this push. @@ -962,6 +1020,13 @@ def is_commit_review_enabled(): COMMIT_REVIEW_ENABLED = is_commit_review_enabled() +# Seconds from the start of a commit or push review's race after which +# neither side waits for the other any longer; well inside Claude Code's +# 10-minute hook timeout. +_RACE_MAX_WAIT_S = 480 +# api_error for a race that hit that deadline with no verdict. +_RACE_TIMED_OUT = -2 + def _agentic_review_with_race( repo_root: str, diff_files: List[Tuple[str, str]], @@ -971,8 +1036,12 @@ def _agentic_review_with_race( """Race the agentic reviewer against a delayed single-shot fallback. Agentic starts at t=0. After SG_AGENTIC_RACE_DELAY_S (default 180s), the - single-shot diff reviewer also starts. Whichever finishes first wins. If - agentic finishes before the delay elapses, the fallback never runs. + single-shot diff reviewer also starts. Whichever finishes first wins, + except that a single-shot review with no verdict waits for agentic up to + _RACE_MAX_WAIT_S from the start, and that if agentic fails after the + fallback started, the fallback's result (or, past the deadline, no + verdict) is returned so the caller never starts another review. If agentic + finishes before the delay, the fallback never runs. Metrics added: race_winner : 1 = agentic won, 2 = fallback won (CC accepts only @@ -980,8 +1049,8 @@ def _agentic_review_with_race( race_delay_s : the configured delay race_started : 1 if the fallback was actually launched, else 0 - Only the commit-review handler calls this — external harnesses invoke - agentic_review() directly and are unaffected. SG_AGENTIC_NO_RACE=1 + Only the commit-review and push-sweep handlers call this — external + harnesses invoke agentic_review() directly and are unaffected. SG_AGENTIC_NO_RACE=1 disables the race for any other caller that wants pure agentic. """ import queue as _queue @@ -994,6 +1063,10 @@ def _agentic_review_with_race( delay_s = int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180")) q: "_queue.Queue[Tuple[str, Any]]" = _queue.Queue(maxsize=1) fallback_started = _th.Event() + fallback_done = _th.Event() + agentic_done = _th.Event() + fallback_result: Dict[str, Any] = {} + deadline = _t.monotonic() + _RACE_MAX_WAIT_S def _agentic() -> None: try: @@ -1004,33 +1077,136 @@ def _agentic_review_with_race( q.put_nowait(("agentic", r)) except _queue.Full: pass + agentic_done.set() def _fallback() -> None: _t.sleep(delay_s) - if not q.empty(): + if agentic_done.is_set(): return # agentic finished within the delay — never start fallback fallback_started.set() + result = (None, [], {"agentic": False, "review_failed": True, "api_error": None}) try: g, v = analyze_code_security( diff_files, is_diff=True, previous_findings=previous_findings ) - except Exception as e: # pragma: no cover - g, v = None, [] - try: - q.put_nowait(("fallback", (g, v, {"agentic": False}))) - except _queue.Full: + # Read on this thread: the outcome is per thread. + failed = llm.last_review_failed() + result = (g, v, {"agentic": False, "review_failed": failed, + "api_error": llm.last_review_status() if failed else None}) + except Exception: # pragma: no cover pass + finally: + fallback_result["r"] = result + fallback_done.set() + if result[2]["review_failed"]: + # A failed fallback does not win: the agentic review's inner + # CLI may still get a verdict where direct calls cannot. + agentic_done.wait(timeout=max(0.0, deadline - _t.monotonic())) + try: + q.put_nowait(("fallback", result)) + except _queue.Full: + pass _th.Thread(target=_agentic, daemon=True).start() _th.Thread(target=_fallback, daemon=True).start() winner, (g, v, m) = q.get() - m = dict(m) # don't mutate the callee's metrics dict + # What the agentic run saw of its directory is kept when the fallback's + # result replaces it below. + reviewer_context = ( + {k: m[k] for k in _REVIEWER_CONTEXT_KEYS if k in m} if winner == "agentic" else {} + ) + if winner == "agentic" and m.get("agentic_fallback") and fallback_started.is_set(): + # The caller would rerun the single-shot review the fallback has + # already started; use its result instead. + if fallback_done.wait(timeout=max(0.0, deadline - _t.monotonic())): + winner, (g, v, m) = "fallback", fallback_result["r"] + else: + winner, (g, v, m) = "fallback", (None, [], { + "agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT}) + m = {**m, **reviewer_context} # a copy: don't mutate the callee's metrics dict m["race_winner"] = 1 if winner == "agentic" else 2 m["race_delay_s"] = delay_s m["race_started"] = 1 if fallback_started.is_set() else 0 return g, v, m +def _review_failure_reason(status): + """(failure type, reason, likely cause or "") for a review with no verdict. + + `status` is llm.last_review_status(): an HTTP status, -1 for a network + error or timeout, None when the reply could not be read; or + _RACE_TIMED_OUT. + """ + gateway = (", or an LLM gateway may need its key in ANTHROPIC_CUSTOM_HEADERS" + if os.environ.get("ANTHROPIC_BASE_URL") else "") + if status == _RACE_TIMED_OUT: + return ("timeout", "the review did not finish in time", "") + 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 status == 401: + return ("auth", "the API rejected the plugin's credentials (HTTP 401)", + f"The sign-in may have expired or been revoked{gateway}.") + if status == 403: + return ("auth", "the API refused access (HTTP 403)", + f"The account may lack access to the review model{gateway}.") + if status == 429 or (isinstance(status, int) and status >= 500): + return ("busy", f"the API was busy or unavailable (HTTP {status})", + "This is usually temporary.") + if status == -1: + return ("network", "the model could not be reached (network error or timeout)", "") + if isinstance(status, int): + pinned = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() + return ("request", f"the API refused the request (HTTP {status})", + f"SECURITY_REVIEW_MODEL ({pinned}) may name a model this account " + "cannot use." if pinned else "") + return ("reply", "the model's reply could not be read", "") + + +def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): + """End a commit ("Commit") or push ("Push") review that got no verdict. + + Never reports the code as clean. Tells Claude once per session for each + kind of review and failure; repeats are only logged. `pushed` ("yes", + "maybe" or "no"): whether the commit's own command also pushed it. Exits. + """ + failure, reason, cause = _review_failure_reason(status) + debug_log(f"{kind} review: got no verdict ({reason}); not marked reviewed") + metrics = {"review_failed": True, + **({"api_error": status} if status is not None else {}), + **metrics, "vulns_found": 0} + # A commit its own command pushed gets its own notice: no later push + # re-checks it. + told_key = f"review_failed:{kind}:{failure}" + (":pushed" if pushed == "yes" else "") + if not atomic_check_and_mark_warning(session_id, told_key): + emit_metrics(metrics) + sys.exit(0) + subject = "this push" if kind == "Push" else "this commit" + if kind == "Push": + after = ("It was for the pushed commits not already reviewed when they " + "were committed, and a later push will not re-check them.") + elif pushed == "yes": + after = "The same command pushed it, so a later push will not re-check it." + elif not PUSH_SWEEP_ENABLED: + after = "" + elif pushed == "maybe": + after = ("If the same command pushed it, a later push will not re-check " + "it; otherwise a later push from Claude Code will.") + else: + after = "If it is pushed later from Claude Code, the push review will check it." + notice = " ".join(part for part in ( + f"The security review of {subject} did not complete: {reason}.", cause, after, + f"Tell the user this in one sentence, and that details are in {DEBUG_LOG_FILE}.", + ) if part) + # The notice goes on stderr: Claude Code shows Claude an asyncRewake + # hook's stderr, else its stdout, which carries the metrics line. + sys.stderr.write(PROVENANCE_BANNER + "\n\n" + notice + "\n") + sys.stderr.flush() + emit_metrics(metrics, + rewake_summary=(f"{kind} security review did not complete: {reason}. " + f"Log: {DEBUG_LOG_FILE}")) + sys.exit(2) + def handle_commit_review_posttooluse(input_data): """PostToolUse handler for Bash — reviews git commits for security issues. @@ -1042,15 +1218,17 @@ def handle_commit_review_posttooluse(input_data): the Stop hook won't re-flag the same (filePath, vulnerableCode) pair. """ session_id = input_data.get("session_id", "default") + _USAGE_CONTEXT["review"] = "commit" tool_input = input_data.get("tool_input", {}) tool_response = input_data.get("tool_response", {}) cwd = input_data.get("cwd", "") command = tool_input.get("command", "") if not isinstance(command, str) or not _GIT_COMMIT_RE.search(command): - # Defensive only — hooks.json's `"if": "Bash(git commit:*)"` is the - # real gate so CC never spawns python3 for ls/grep/etc. This catches - # cases where CC's command matching fails open and spawns the hook anyway. + # hooks.json's `"if": "Bash(git*commit*)"` only keeps CC from + # spawning python3 for ls/grep/etc. It lets through other git commands + # with "commit" in them (`git merge --no-commit`), and CC runs the hook + # anyway when it cannot parse the command; this regex decides. sys.exit(0) debug_log(f"Commit review: detected git commit in command") @@ -1119,8 +1297,13 @@ def handle_commit_review_posttooluse(input_data): _root = repo_root _fresh, _stale = _git_reflog_recent_commits(_root) if _fresh: + # Commits an earlier call's review is still working on are that + # review's: it records them when it has a verdict. (Read before + # the reviewed set, so one that ends in between counts as reviewed.) + _inflight = _load_inflight_shas(_root, _fresh) _already = _load_reviewed_shas(_root) - _reflog_shas = [s for s in _fresh if s not in _already] + _reflog_shas = [s for s in _fresh + if s not in _already and s not in _inflight] if _reflog_shas: commit_succeeded = True debug_log( @@ -1132,8 +1315,9 @@ def handle_commit_review_posttooluse(input_data): # Fresh commit(s) in reflog but all already in # sg-reviewed-shas — likely a Bash retry or the commit was # reviewed via a prior fire. Correct to skip; sub=2 lets telemetry - # split this from genuine fails. - _skip_21_sub = 2 + # split this from genuine fails. sub=5: at least one is still + # being reviewed by an earlier call. + _skip_21_sub = 5 if any(s not in _already for s in _fresh) else 2 elif _stale: _skip_21_sub = 3 # commit entries exist but all >120s old else: @@ -1393,6 +1577,10 @@ def handle_commit_review_posttooluse(input_data): previous_findings = with_locked_state(session_id, _read_previous) or [] + # Tell a push review (or the next commit's reflog scan) that these commits + # are being reviewed, so it does not start a second review of them. + _mark_inflight(repo_root, _full_shas(repo_root, shas)) + review_start = _time.time() agentic_metrics: Dict[str, Any] = {} @@ -1402,43 +1590,35 @@ def handle_commit_review_posttooluse(input_data): repo_root, diff_files, rel_touched, previous_findings ) agentic_metrics.update(_am) + if _am.get("child_stderr"): + # Lines the inner CLI wrote to stderr during the review: how often + # the condition that used to replace the findings body occurs. Not + # counted when the single-shot fallback wins the race. + _TAIL_METRICS["child_stderr"] = _am["child_stderr"] + _note_reviewer_context(agentic_metrics) + review_failed = bool(agentic_metrics.get("review_failed")) + api_status = agentic_metrics.get("api_error") # Fall back to single-shot only on agentic FAILURE (SDK/investigate # crash). If agentic completed and returned 0 findings, trust that. if agentic_metrics.get("agentic_fallback"): concrete_guidance, vulns = analyze_code_security( diff_files, is_diff=True, previous_findings=previous_findings ) + review_failed = llm.last_review_failed() + api_status = llm.last_review_status() else: concrete_guidance, vulns = analyze_code_security( diff_files, is_diff=True, previous_findings=previous_findings ) - - # push-sweep state: record this commit as reviewed (full 40-hex sha) so a - # later `git push` can advance its diff base past it. Recorded here — after - # the review ran but before any exit path — so it's marked regardless of - # whether findings were emitted. `shas` holds abbreviated refs from - # `[branch sha]`; resolve to full so set-membership in the push-sweep is - # exact. Best-effort; failures here never block the review result. - try: - full_shas = [] - for s in shas: - # See #2099: drop text=True; decode manually for cp1252 safety. - r = subprocess.run( - [*GIT_CMD, "rev-parse", "--verify", "-q", s], - cwd=repo_root, capture_output=True, timeout=5, - ) - if r.returncode == 0: - full_shas.append(r.stdout.decode("utf-8", errors="replace").strip()) - _append_reviewed_shas(repo_root, full_shas, vulns_found=len(vulns or [])) - except Exception: - pass + review_failed = llm.last_review_failed() + api_status = llm.last_review_status() review_ms = int((_time.time() - review_start) * 1000) # `survived` is the raw self-refute count BEFORE the high/critical-only # severity filter; `survived_after_sev` is the count the user actually # sees. Include `survived_after_sev` ONLY when the filter actually # dropped candidates — otherwise it's redundant with `survived` and eats - # into CC's 10-key emit cap, pushing files_reviewed/review_ms out of the + # into CC's metric-key cap, pushing files_reviewed/review_ms out of the # emitted metrics. # # CC accepts only booleans and finite numbers as metric values. @@ -1474,6 +1654,36 @@ def handle_commit_review_posttooluse(input_data): else {} ) + if review_failed: + # Not marked reviewed, so a later push review from Claude Code still + # covers it. + _exit_review_failed("Commit", session_id, { + **_base, **_agentic_m, + "files_reviewed": len(diff_files), "review_ms": review_ms, + }, api_status, pushed=( + "yes" if _push_in_output(bash_output) + else "maybe" if _GIT_PUSH_RE.search(command) or _MAY_PUSH_VIA_GH_RE.search(command) + else "no")) + + # push-sweep state: record this commit as reviewed (full 40-hex sha) so a + # later `git push` can advance its diff base past it. Recorded only after a + # review that got a verdict, whether or not it found anything. `shas` holds abbreviated refs from + # `[branch sha]`; resolve to full so set-membership in the push-sweep is + # exact. Best-effort; failures here never block the review result. + try: + full_shas = [] + for s in shas: + # See #2099: drop text=True; decode manually for cp1252 safety. + r = subprocess.run( + [*GIT_CMD, "rev-parse", "--verify", "-q", s], + cwd=repo_root, capture_output=True, timeout=5, + ) + if r.returncode == 0: + full_shas.append(r.stdout.decode("utf-8", errors="replace").strip()) + _append_reviewed_shas(repo_root, full_shas, vulns_found=len(vulns or [])) + except Exception: + pass + if not concrete_guidance: debug_log("Commit review: no security issues found") emit_metrics({ @@ -1531,9 +1741,8 @@ def handle_commit_review_posttooluse(input_data): sev[s] += 1 # Rebuild guidance from new_vulns only — concrete_guidance from the LLM - # still lists deduped entries. Pass via additional_context so CC surfaces - # the reason via hookSpecificOutput.additionalContext instead of empty - # stdout (#1783) / stderr-only "json output validation failed" (#1375). + # still lists deduped entries. emit_metrics writes it to stderr, the body + # of the asyncRewake notice. _commit_guidance = (PROVENANCE_BANNER + "\n\n" + _format_vulns_guidance(new_vulns) + CONTINUATION_SUFFIX + "\n") @@ -1548,8 +1757,6 @@ def handle_commit_review_posttooluse(input_data): # exit(2) is preserved per the asyncRewake protocol — it's what CC # uses as the "force fix" signal that triggers the rewakeMessage flow. - # The stderr.write was removed; additional_context above now carries - # the same text via the modern JSON channel. See #1358/#1375/#1783. sys.exit(2) def handle_push_sweep_posttooluse(input_data): @@ -1576,6 +1783,7 @@ def handle_push_sweep_posttooluse(input_data): command = tool_input.get("command", "") or "" cwd = input_data.get("cwd") session_id = input_data.get("session_id", "") + _USAGE_CONTEXT["review"] = "push" bash_output = ( (tool_response.get("stdout", "") or "") + "\n" @@ -1583,9 +1791,8 @@ def handle_push_sweep_posttooluse(input_data): ) interrupted = tool_response.get("interrupted", False) - # Re-gate: hooks.json `if` matched, but confirm with the broader regex - # (defensive — `git -C`/`-c` forms won't reach here via the hooks.json - # prefix matcher alone, but a compound with a plain `git push` would). + # Re-gate: hooks.json `if` matched (or CC could not parse the command + # and ran every entry), so confirm with the regex. if not _GIT_PUSH_RE.search(command): sys.exit(0) @@ -1728,13 +1935,27 @@ def handle_push_sweep_posttooluse(input_data): "pushed": len(push_range)}) sys.exit(0) - reviewed = _load_reviewed_shas(repo_root) + # A commit review that is still running on these commits records them + # once it has a verdict. Wait for it instead of reviewing the same diff a + # second time; if it ends without one, they are reviewed here. + reviewed, _waited = _reviewed_after_inflight( + repo_root, push_range, INFLIGHT_WAIT_S) + _wait_m = {} + if _waited: + _wait_m = {"inflight_wait_s": max(1, int(round(_waited)))} + debug_log(f"Push sweep: waited {_waited:.0f}s for a running commit review") base, tail = _compute_push_sweep_base(prev_upstream, push_range, reviewed) prefix_advanced = len(push_range) - len(tail) if base is None: debug_log("Push sweep: every pushed commit already reviewed") emit_metrics({**_base, "pushed": len(push_range), "unreviewed": 0, - "prefix_advanced": prefix_advanced}) + "prefix_advanced": prefix_advanced, **_wait_m}) + sys.exit(0) + if _waited and head and _git_rev_parse_head(repo_root) != head: + # Same guard as above: the diff and the reviewer's file reads are + # both taken at HEAD, and HEAD left the pushed tip during the wait. + debug_log("Push sweep: HEAD moved while waiting, skipping") + emit_metrics({"skipped": True, "skip_reason": 44, **_base, **_wait_m}) sys.exit(0) debug_log(f"Push sweep: range={len(push_range)} prefix_advanced=" @@ -1787,6 +2008,8 @@ def handle_push_sweep_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 23, **_base}) sys.exit(0) + _mark_inflight(repo_root, tail) + import time as _time now = _time.time() previous_findings = with_locked_state( @@ -1802,16 +2025,32 @@ def handle_push_sweep_posttooluse(input_data): concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race( repo_root, diff_files, rel_touched, previous_findings ) + if agentic_metrics.get("child_stderr"): + _TAIL_METRICS["child_stderr"] = agentic_metrics["child_stderr"] + _note_reviewer_context(agentic_metrics) + review_failed = bool(agentic_metrics.get("review_failed")) + api_status = agentic_metrics.get("api_error") if agentic_metrics.get("agentic_fallback"): concrete_guidance, vulns = analyze_code_security( diff_files, is_diff=True, previous_findings=previous_findings ) + review_failed = llm.last_review_failed() + api_status = llm.last_review_status() else: concrete_guidance, vulns = analyze_code_security( diff_files, is_diff=True, previous_findings=previous_findings ) + review_failed = llm.last_review_failed() + api_status = llm.last_review_status() agentic_metrics = {} review_ms = int((_time.time() - review_start) * 1000) + if review_failed: + # Not marked reviewed. A later push does not re-check these commits: + # its range starts from the new upstream. + _exit_review_failed("Push", session_id, { + **_base, "pushed": len(push_range), "unreviewed": len(tail), + "files_reviewed": len(diff_files), "review_ms": review_ms, + }, api_status) # The tail is now covered by this net-diff review. _append_reviewed_shas(repo_root, tail, vulns_found=len(vulns or [])) @@ -1820,20 +2059,21 @@ def handle_push_sweep_posttooluse(input_data): session_id, vulns or [], prompted=_finding_keys(previous_findings) ) - # Metrics — keep within the 10-key cap; agentic sub-metrics are dropped + # Metrics — keep within CC's metric-key cap; agentic sub-metrics are dropped # here in favour of the push-sweep funnel keys (telemetry can join on session_id # to the per-commit fires for agentic detail). rewake_summary must ride # this line (CC reads only the first {-prefixed stdout line); the emit # is deferred to the two exit points below so the with-vulns path can - # also pass additional_context in the same JSON line (#1375/#1783) — - # the by-design "CC keeps only the first JSON line" constraint means - # we can't emit twice. Builds the shared metrics dict here; vulns path + # also pass additional_context in the same emit_metrics call — the + # by-design "CC keeps only the first JSON line" constraint means we + # can't emit twice. Builds the shared metrics dict here; vulns path # adds additional_context, no-vulns path emits as-is. _push_metrics = { **_base, "pushed": len(push_range), "unreviewed": len(tail), "prefix_advanced": prefix_advanced, "vulns_found": len(new_vulns), "files_reviewed": len(diff_files), "review_ms": review_ms, **({"deduped": n_deduped} if n_deduped else {}), + **_wait_m, } _push_rewake_summary = _format_vulns_summary(new_vulns, prefix="Push security review found") @@ -1893,9 +2133,9 @@ def handle_push_sweep_posttooluse(input_data): else: guidance = concrete_guidance or _format_vulns_guidance(reported) or "" # Emit metrics + additional_context together — single JSON line is the - # contract CC's hook parser expects. exit(2) preserved as the asyncRewake - # "force fix" trigger (see comment near handle_commit_review_posttooluse). - # See #1358 / #1375 / #1783. + # contract CC's hook parser expects; the guidance itself goes to stderr. + # exit(2) preserved as the asyncRewake "force fix" trigger (see comment + # near handle_commit_review_posttooluse). emit_metrics(_push_metrics, rewake_summary=_push_rewake_summary, additional_context=(PROVENANCE_BANNER + "\n\n" + guidance + CONTINUATION_SUFFIX + "\n"), @@ -1941,6 +2181,13 @@ def handle_stop_hook(input_data): head_at_capture = snap["head_at_capture"] untracked_at_baseline = snap.get("untracked_at_baseline") or {} previous_findings = snap["previous_findings"] + # Only when it happened: state lost to an unreadable file, and saves that + # overwrote another hook's (possible only without locking). SubagentStop + # does not clear them, so it does not report them either. + if not is_subagent: + for _k in ("state_resets", "state_overwrites"): + if isinstance(snap.get(_k), int) and snap[_k] > 0: + _TAIL_METRICS[_k] = snap[_k] # Sweep pattern-warning outcomes (pure local work; stop_hook_active is # already guaranteed False here so no double-count guard needed). @@ -1965,6 +2212,10 @@ def handle_stop_hook(input_data): "skipped": True, "skip_reason": reason, "fire_index": fire_count + 1, "diff_strategy_v2": True, **v2_metrics, **extra, **sweep, + **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} + if gitutil._unparsed_diff_headers else {}), + **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} + if gitutil._secret_shaped_skipped else {}), }) sys.exit(0) @@ -2165,11 +2416,9 @@ def handle_stop_hook(input_data): # untracked_baseline_n is the signal for whether the UPS-time # untracked-snapshot capture actually ran. sweep_trimmed = {k: v for k, v in sweep.items() if k != "warn_unresolved_mask"} - # Pass guidance via additional_context so CC surfaces the findings via - # hookSpecificOutput.additionalContext instead of stderr-only (which - # was the cause of "json output validation failed" / empty-reason UI in - # #1375 / #1783). exit(2) preserved as the asyncRewake "force fix" - # signal — that's the documented mechanism. See #1358 / #1375 / #1783. + # Guidance goes to stderr plus top-level decision/reason (see + # emit_metrics). exit(2) preserved as the asyncRewake "force fix" + # signal — that's the documented mechanism. emit_metrics({ "vulns_found": len(vulns), "untracked_baseline_n": len(untracked_at_baseline), @@ -2184,26 +2433,33 @@ def handle_stop_hook(input_data): if llm._last_review_truncated_bytes else {}), **({"repo_resolution": repo_res} if res_metrics else {}), **sweep_trimmed, + **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} + if gitutil._unparsed_diff_headers else {}), + **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} + if gitutil._secret_shaped_skipped else {}), }, rewake_summary=_format_vulns_summary(vulns), additional_context=(PROVENANCE_BANNER + "\n\n" + concrete_guidance + CONTINUATION_SUFFIX + "\n"), hook_event_name=hook_event_name) sys.exit(2) - if llm._last_call_claude_http_error is not None: - debug_log(f"Stop hook: API call failed with status {llm._last_call_claude_http_error}") + stop_review_failed = llm.last_review_failed() + if stop_review_failed: + debug_log(f"Stop hook: review got no verdict " + f"({_review_failure_reason(llm.last_review_status())[1]})") restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline) else: debug_log("Stop hook: no security issues found") if is_subagent: record_reviewed_diff(session_id, diff_hash) - # CC truncates metrics to 10 keys by - # insertion order. The previous **sweep,**v2_metrics tail meant the 3 - # v2_metrics keys were always sliced off this most-common path, so the - # diff-strategy diagnostics never reached telemetry. Drop sweep here (it's - # PostToolUse-warning state, orthogonal to diff-strategy comparison). - # 6 base + optional api_error + 3 v2_metrics = ≤10. + # CC keeps the first 20 metric keys (10 in older versions), in insertion + # order, after the pv and usage keys emit_metrics puts first. The previous + # **sweep,**v2_metrics tail meant the 3 v2_metrics keys were always sliced + # off this most-common path, so the diff-strategy diagnostics never reached + # telemetry. Drop sweep here (it's PostToolUse-warning state, orthogonal to + # diff-strategy comparison). emit_metrics({ + **({"review_failed": True} if stop_review_failed else {}), "vulns_found": 0, "diff_strategy_v2": True, "files_reviewed": len(diff_files), @@ -2214,6 +2470,10 @@ def handle_stop_hook(input_data): **({"diff_truncated": llm._last_review_truncated_bytes} if llm._last_review_truncated_bytes else {}), **v2_metrics, + **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} + if gitutil._unparsed_diff_headers else {}), + **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} + if gitutil._secret_shaped_skipped else {}), }) sys.exit(0) @@ -2287,6 +2547,7 @@ def main(): sys.exit(0) session_id = input_data.get("session_id", "default") + _USAGE_CONTEXT["session_id"] = re.sub(r"[^A-Za-z0-9_.-]", "_", str(session_id))[:80] tool_name = input_data.get("tool_name", "") tool_input = input_data.get("tool_input", {}) hook_event_name = input_data.get("hook_event_name", "") @@ -2318,11 +2579,15 @@ def main(): # Handle PostToolUse[Bash] — commit review or push sweep (asyncRewake). # - # hooks.json has two `if` configs under the Bash matcher (`git commit:*` - # and `git push:*`). CC evaluates each `if` independently and spawns this + # hooks.json has three `if` configs under the Bash matcher (`git*commit*`, + # `git*push*` and `gt *`), kept to one per kind because CC runs EVERY + # entry when it cannot parse the command (loops, some substitutions): one + # entry per spelling meant one python per entry on those calls. CC + # evaluates each `if` independently and spawns this # script ONCE PER MATCH — so `git commit -m x && git push` spawns python # twice with the same command string and the same tool_use_id. The python - # cannot tell which `if` fired it. + # cannot tell which `if` fired it, which is also why the three entries + # share one rewakeMessage. # # Routing therefore MUST check commit FIRST so that compound commit+push # commands continue to hit commit-review (the pre-existing behaviour) on @@ -2345,7 +2610,7 @@ def main(): # Another spawn for this same tool_use_id already claimed the # work (compound matched multiple `if` configs). Emit a single # metric so telemetry can count how often the de-dupe kicks in. - print(json.dumps({"metrics": {"bash_hook_dedup": True}}), flush=True) + _write_hook_output({"metrics": {"bash_hook_dedup": True}}) sys.exit(0) if _GIT_COMMIT_RE.search(cmd): handle_commit_review_posttooluse(input_data) @@ -2421,7 +2686,7 @@ def main(): "hookEventName": "PostToolUse", "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), } - print(json.dumps(output)) + _write_hook_output(output) elif all_guidance: # Defensive: pattern rules disabled but guidance somehow set (shouldn't happen) print(json.dumps({ diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py index 8dbadfd2..c8045532 100644 --- a/plugins/security-guidance/hooks/session_state.py +++ b/plugins/security-guidance/hooks/session_state.py @@ -17,6 +17,7 @@ except ImportError: import json import os import re +import tempfile from datetime import datetime from _base import debug_log, state_dir as _state_dir @@ -47,7 +48,7 @@ def get_lock_file(session_id): def cleanup_old_state_files(): - """Remove state files and lock files older than 30 days.""" + """Remove state files, lock files and leftover temporary files older than 30 days.""" try: state_dir = _state_dir() if not os.path.exists(state_dir): @@ -58,7 +59,7 @@ def cleanup_old_state_files(): for filename in os.listdir(state_dir): if filename.startswith("security_warnings_state_") and ( - filename.endswith(".json") or filename.endswith(".lock") + filename.endswith((".json", ".lock", ".tmp")) ): file_path = os.path.join(state_dir, filename) try: @@ -96,25 +97,79 @@ def load_state(session_id): if isinstance(data, dict): data.setdefault("shown_warnings", []) return data - except (json.JSONDecodeError, IOError, KeyError, TypeError): + except FileNotFoundError: + return {"shown_warnings": []} + except (ValueError, IOError, KeyError, TypeError): + # ValueError: not JSON, or bytes that do not decode. pass - return {"shown_warnings": []} + # The file is there but cannot be used, so everything the session had + # recorded is gone. Leave a mark for the Stop hook to report: a flag, not + # a count, since an earlier mark is lost with the rest. + debug_log(f"State file {state_file} is unreadable, starting from an empty state") + return {"shown_warnings": [], "state_resets": 1} + + +# Windows still writes the state file in place: a rename there is refused +# while another process has the file open and can make a concurrent open fail, +# and hooks run without a state lock on Windows (see with_locked_state). +_RENAME_INTO_PLACE = os.name != "nt" + + +def _write_then_rename(state_file, state): + """Write `state` to a temporary file and rename it over `state_file`. + Returns False, with nothing changed, when this directory does not allow + it; any other failure raises OSError and leaves the state file as it was.""" + tmp = None + try: + fd, tmp = tempfile.mkstemp( + dir=os.path.dirname(state_file), + prefix=os.path.basename(state_file) + ".", suffix=".tmp") + with os.fdopen(fd, "w") as f: + json.dump(state, f) + os.replace(tmp, state_file) + return True + except BaseException as e: + if tmp: + try: + os.unlink(tmp) + except OSError: + pass + if isinstance(e, PermissionError): + return False + raise def save_state(session_id, state): - """Save the full state dict to file.""" + """Save the full state dict to file. + + The new contents go to a temporary file that is then renamed over the + state file, so a hook killed part-way through a save (a timeout, an + interrupt) leaves the previous state. Written in place it left a truncated + file, which load_state reads as an empty state: the turn baseline, touched + paths and shown warnings were lost. + """ state_file = get_state_file(session_id) try: state_dir = os.path.dirname(state_file) if state_dir: os.makedirs(state_dir, exist_ok=True) + if _RENAME_INTO_PLACE and _write_then_rename(state_file, state): + return with open(state_file, "w") as f: json.dump(state, f) except (IOError, OSError) as e: debug_log(f"Failed to save state file {state_file}: {e}") +def _raw_state(state_file): + try: + with open(state_file, "rb") as f: + return f.read() + except OSError: + return None + + def with_locked_state(session_id, callback): """ Execute callback with exclusive access to the state file. @@ -132,8 +187,15 @@ def with_locked_state(session_id, callback): if fcntl is None: # No file locking available (Windows) — run without locking + state_file = get_state_file(session_id) + before = _raw_state(state_file) state = load_state(session_id) result = callback(state) + if _raw_state(state_file) != before: + # Another hook changed the state after it was read here, and this + # save is about to drop that change. Count how often it happens; + # the Stop hook reports the count. + state["state_overwrites"] = state.get("state_overwrites", 0) + 1 save_state(session_id, state) return result diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh index 9cf8cc07..f1b9d68c 100755 --- a/plugins/security-guidance/hooks/sg-python.sh +++ b/plugins/security-guidance/hooks/sg-python.sh @@ -33,6 +33,10 @@ set -e # changing it from inside the interpreter has no effect. export PYTHONUTF8=1 +# Set to 1 below only when the interpreter had to be found by its real path +# (pass 4); the hook reports it as the `launcher_fallback` metric. +unset SG_LAUNCHER_FALLBACK + # Git Bash / MSYS on Windows hands script paths to this shim in POSIX form # (`/c/Users/...`). When we exec a Windows `python.exe` (which we do on # Windows since `python3` is the Microsoft Store stub), python interprets the @@ -41,14 +45,30 @@ export PYTHONUTF8=1 # fails with ENOENT, and every Edit/Write/MultiEdit tool use blocks until the # session restarts. See anthropics/claude-plugins-official#2043. # -# Fix: convert absolute path args to native Windows form via `cygpath -w` -# before exec. `cygpath` is a Git Bash builtin; it's absent on macOS/Linux, -# where the `command -v` guard makes this a no-op. `cygpath -w` is idempotent -# for already-Windows paths so the rare mixed-form case is safe. +# Fix: convert absolute path args to native Windows form before exec. +# `cygpath` ships with Git Bash; it's absent on macOS/Linux, where the +# `command -v` guard makes this a no-op. `cygpath -w` is idempotent for +# already-Windows paths so the rare mixed-form case is safe. +# +# Under Git Bash every $(...) is a new Windows process, and this shim runs on +# every hook, so drive paths (`/c/Users/...`, where the plugin lives) are +# converted in-shell. Git Bash and MSYS2 (OSTYPE=msys) mount drives at +# /<letter>; anything else (`/tmp`, `/usr`, Cygwin's /cygdrive) needs cygpath +# to resolve. See #6470. if command -v cygpath >/dev/null 2>&1; then + sg_drive_mounts="" + case "${OSTYPE:-}" in msys*) sg_drive_mounts=1 ;; esac converted=() for a in "$@"; do case "$a" in + /[A-Za-z]/*) + if [ -n "$sg_drive_mounts" ]; then + drive="${a:1:1}" + rest="${a:3}" + converted+=("${drive^^}:\\${rest//\//\\}") + else + converted+=("$(cygpath -w "$a")") + fi ;; /*) converted+=("$(cygpath -w "$a")") ;; *) converted+=("$a") ;; esac @@ -56,10 +76,47 @@ if command -v cygpath >/dev/null 2>&1; then set -- "${converted[@]}" fi +# The hook script the chosen interpreter has to run (already in native form). +SG_TARGET="" +case "${1:-}" in + ""|-*) ;; + *) SG_TARGET="$1" ;; +esac + +# Names whose interpreter runs but cannot see the hook script ("|"-separated). +sg_unreadable="" + probe() { # $1..N: the interpreter command (may be multi-word like `py -3`) - # Writes "<major>.<minor>" to stdout and exits 0 iff at least Python 3. - "$@" -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")' 2>/dev/null + # Writes "<major>.<minor>" to stdout and exits 0 iff it is at least + # Python 3 AND it can read the hook script; exits 3 if it cannot. + # + # The second half matters on Windows: an interpreter started through a + # packaged launcher alias (Microsoft Store Python, Python Install Manager; + # the python/python3/py entries under ...\Microsoft\WindowsApps) runs with + # a different view of %APPDATA% than the process that started it. It + # answers `-c` fine, then fails on the script with "can't open file ... + # [Errno 2]" and exit code 2 -- and exit 2 from an asyncRewake hook wakes + # the model, whose reply runs the Stop hook again: an endless loop that + # never reviewed anything. See #6251, #5781. + # + # Only for `$(probe ...)`: the `exec` replaces that subshell instead of + # forking a second process from it. + [ "${BASH_SUBSHELL:-0}" -gt 0 ] || return 1 + 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; }`. +note_unreadable() { + [ $? -eq 3 ] && sg_unreadable="$sg_unreadable|$1|" + return 0 +} + +# True iff the command's executable is on PATH ($1 of a possibly multi-word +# command like `py -3`). A builtin lookup: `$(probe ...)` costs a process even +# when the interpreter does not exist, so missing names are skipped first. +on_path() { + command -v "$1" >/dev/null 2>&1 } # True iff arg is a "M.m" version string >= 3.10. claude_agent_sdk requires @@ -80,7 +137,9 @@ is_sdk_compatible() { # so picking one here always upgrades over the system `python3`. Highest # available wins; the user doesn't have to PATH-prefer it. for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do - v=$(probe "$cmd") || continue + on_path "$cmd" || continue + v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; } + v=${v%$'\r'} if is_sdk_compatible "$v"; then exec "$cmd" "$@" fi @@ -89,13 +148,21 @@ done # Pass 2 — bare interpreters, but only if SDK-compatible. Covers Linux distros # that ship 3.10+ as the default `python3`, and Windows where `python` / # `py -3` resolves to the user's python.org install. +sg_older="" # first of these that is a readable Python 3 below 3.10 for cmd in "python3" "python" "py -3"; do # shellcheck disable=SC2086 - v=$(probe $cmd) || continue + on_path $cmd || continue + # shellcheck disable=SC2086 + v=$(probe $cmd) || { note_unreadable "$cmd"; continue; } + v=${v%$'\r'} if is_sdk_compatible "$v"; then # shellcheck disable=SC2086 exec $cmd "$@" fi + # Anything that successfully reported a "M.m" string. + case "$v" in + [0-9]*.[0-9]*) [ -n "$sg_older" ] || sg_older="$cmd" ;; + esac done # Pass 3 — fallback to any Python 3, even <3.10. Pattern-based checks @@ -103,18 +170,72 @@ done # own; the SDK-dependent paths will detect the version mismatch and degrade # inside the Python code. Without this fallback, the entire plugin would # stop working on default macOS, which is a regression vs today. +if [ -n "$sg_older" ]; then + # shellcheck disable=SC2086 + exec $sg_older "$@" +fi + +# Pass 4 — nothing above could run the hook script. If that is because the +# names on PATH resolve to packaged launcher aliases that cannot see the +# plugin directory (see probe), the same interpreter usually works when it is +# started by its real path instead of through the alias. Candidates: +# - every further python3/python on PATH, by full path (a regular install +# often sits behind the alias in PATH order; the first match is the one +# the bare name resolved to above), +# - the real executable each alias reports as sys.executable. +# The list is built before the loop that execs, and from a here-document: a +# redirect around that loop would become the hook's stdin. +sg_candidates=() +for name in "python3" "python"; do + first=1 + while IFS= read -r c; do + if [ -n "$first" ]; then first=""; continue; fi + [ -n "$c" ] && sg_candidates+=("$c") + done <<EOF +$(type -ap "$name" 2>/dev/null) +EOF +done for cmd in "python3" "python" "py -3"; do + case "$sg_unreadable" in *"|$cmd|"*) ;; *) continue ;; esac # shellcheck disable=SC2086 - v=$(probe $cmd) || continue - # Accept anything that successfully reported a "M.m" string. + c=$($cmd -c 'import sys; print(sys.executable)' 2>/dev/null) || continue + c=${c%$'\r'} # native Windows Python prints CRLF + [ -n "$c" ] || continue + if command -v cygpath >/dev/null 2>&1; then + c=$(cygpath -u "$c" 2>/dev/null) || continue + fi + sg_candidates+=("$c") +done +export SG_LAUNCHER_FALLBACK=1 +sg_fallback="" +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; } + v=${v%$'\r'} + if is_sdk_compatible "$v"; then + exec "$cmd" "$@" + fi case "$v" in - [0-9]*.[0-9]*) - # shellcheck disable=SC2086 - exec $cmd "$@" - ;; + [0-9]*.[0-9]*) [ -n "$sg_fallback" ] || sg_fallback="$cmd" ;; esac done +if [ -n "$sg_fallback" ]; then + exec "$sg_fallback" "$@" +fi +# Exit 1, never 2: on an asyncRewake hook exit 2 means "the review has +# findings, wake the model", and a launcher failure is not a finding. +if [ -n "$sg_unreadable" ]; then + echo "security-guidance: found Python, but it cannot read the hook script (missing, or not visible to Python), so no security checks ran." >&2 + echo " hook script: $SG_TARGET" >&2 + echo " on Windows this happens when python, python3 and py are Microsoft Store or Python Install Manager aliases;" >&2 + echo " install Python from https://python.org and put it ahead of ...\\Microsoft\\WindowsApps in PATH" >&2 + # No Python to report it, so the launcher emits the metric itself. + echo '{"metrics": {"launcher_unreadable": 1}}' + 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 " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2 diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index 2cf4dd1c..998401c2 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -128,7 +128,8 @@ def hook_env(tmp_path, stub_api): "CLAUDE_PROJECT_DIR", "HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", - "CLAUDE_CODE_USE_FOUNDRY")} + "CLAUDE_CODE_USE_FOUNDRY", + "PLUGIN_ROOT", "SECURITY_GUIDANCE_PORTABLE_OUTPUT")} env.update(GIT_ENV) env.update({ "SECURITY_WARNINGS_STATE_DIR": str(state), @@ -212,3 +213,81 @@ def ups_payload(cwd, session_id="s1"): "prompt": "hi", "cwd": str(cwd), } + + +# ── a local Anthropic-compatible endpoint the hook can be pointed at ────── + +class _Gateway(http.server.BaseHTTPRequestHandler): + """An Anthropic-compatible endpoint. With `required` set it answers 401 + unless that header arrives, like a LiteLLM proxy keyed on a custom header.""" + + def _handle(self): + n = int(self.headers.get("Content-Length") or 0) + if n: + self.rfile.read(n) + srv = self.server + srv.requests.append((self.command, self.path, {k.lower(): v for k, v in self.headers.items()})) + name, value = srv.required or (None, None) + if name and self.headers.get(name) != value: + return self._send(401, {"type": "error", "error": { + "type": "authentication_error", "message": "Invalid proxy server token"}}) + if srv.status != 200: + return self._send(srv.status, {"type": "error", "error": {"type": "api_error"}}) + if self.command == "GET": + return self._send(200, {"data": [{"id": "claude-opus-5-5"}], "has_more": False}) + text = (srv.reply if srv.reply is not None else json.dumps( + {"hasVulnerabilities": bool(srv.vulns), "vulnerabilities": srv.vulns})) + self._send(200, { + "id": "msg_stub", "type": "message", "role": "assistant", + "model": "stub", "stop_reason": "end_turn", + "content": [{"type": "text", "text": text}], + "usage": {"input_tokens": 1, "output_tokens": 1}, + }) + + do_GET = do_POST = do_HEAD = _handle + + def _send(self, status, payload): + body = json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *a): + pass + + +@pytest.fixture +def gateway(): + srv = http.server.HTTPServer(("127.0.0.1", 0), _Gateway) + srv.requests, srv.required, srv.status, srv.reply, srv.vulns = [], None, 200, None, [] + threading.Thread(target=srv.serve_forever, daemon=True).start() + try: + yield srv + finally: + srv.shutdown() + + +@pytest.fixture +def env(hook_env, gateway): + e = dict(hook_env) + e["ANTHROPIC_BASE_URL"] = f"http://127.0.0.1:{gateway.server_port}" + e.pop("SECURITY_REVIEW_MODEL", None) + return e + + +@pytest.fixture +def failing_inner_cli(tmp_path): + """An inner CLI that prints a warning on stderr and exits 1; the review + then falls back to a single-shot call.""" + cli = tmp_path / "claude" + cli.write_text("#!/bin/sh\necho 'claude.ai connectors are disabled' >&2\nexit 1\n") + cli.chmod(0o755) + return str(cli) + + +@pytest.fixture +def agentic_env(env, failing_inner_cli): + pytest.importorskip("claude_agent_sdk") + return {**env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli} diff --git a/plugins/security-guidance/tests/test_custom_headers.py b/plugins/security-guidance/tests/test_custom_headers.py new file mode 100644 index 00000000..fe019d52 --- /dev/null +++ b/plugins/security-guidance/tests/test_custom_headers.py @@ -0,0 +1,95 @@ +"""ANTHROPIC_CUSTOM_HEADERS reach every call the plugin makes.""" +from conftest import ( + STUB_VULN, VULN_PY, edit_payload, metrics_of, run_hook, stop_payload, ups_payload, +) + +import llm + +GATEWAY_KEY = ("x-litellm-api-key", "Bearer sk-gateway") + + +class TestCustomHeaders: + def test_parsed_like_claude_code(self, monkeypatch): + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", + "x-litellm-api-key: Bearer sk-1\r\n" + "X-Tenant: acme:eu \n" + "no colon here\n" + ": no name\n" + "\n" + "X-Empty:") + assert llm._custom_headers() == [ + ("x-litellm-api-key", "Bearer sk-1"), ("X-Tenant", "acme:eu"), ("X-Empty", ""), + ] + + def test_unsendable_lines_are_skipped(self, monkeypatch): + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", + "bad name: x\nX-Ok: 1\nX-Uni: caf\u00e9\u2603\nX-Cr: a\rb") + assert llm._custom_headers() == [("X-Ok", "1")] + + def test_sent_with_the_plugin_credentials(self, monkeypatch): + monkeypatch.setattr(llm, "ANTHROPIC_AUTH_TOKEN", "oauth") + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "x-litellm-api-key: k") + h = llm._build_auth_headers(use_token=True) + assert h["x-litellm-api-key"] == "k" + assert h["Authorization"] == "Bearer oauth" + + def test_custom_line_wins_over_the_same_header(self, monkeypatch): + monkeypatch.setattr(llm, "ANTHROPIC_AUTH_TOKEN", "oauth") + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "authorization: Bearer gw") + h = llm._build_auth_headers(use_token=True) + assert [v for k, v in h.items() if k.lower() == "authorization"] == ["Bearer gw"] + + def test_custom_beta_lines_are_not_sent(self, monkeypatch): + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "anthropic-beta: extra-1\nX-Ok: 1") + h = llm._build_auth_headers(use_token=False) + assert h["anthropic-beta"] == "structured-outputs-2025-11-13" + assert h["X-Ok"] == "1" + + def test_without_custom_headers_only_the_plugin_headers_are_sent(self, monkeypatch): + monkeypatch.delenv("ANTHROPIC_CUSTOM_HEADERS", raising=False) + assert set(llm._build_auth_headers(use_token=False)) == { + "Content-Type", "anthropic-version", "x-api-key", "anthropic-beta"} + + def test_stop_review_reaches_a_header_keyed_gateway(self, env, gateway, workspace): + """Every plugin call (model lookup and review) carries the gateway + key, and the review finds the vuln.""" + _, repo = workspace + gateway.required = GATEWAY_KEY + gateway.vulns = [STUB_VULN] + e = {**env, "ANTHROPIC_CUSTOM_HEADERS": f"{GATEWAY_KEY[0]}: {GATEWAY_KEY[1]}"} + run_hook(ups_payload(repo), e) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py", VULN_PY), e) + rc, so, se = run_hook(stop_payload(repo), e) + assert rc == 2, (so, se) + assert "command_injection" in se + assert metrics_of(so)["gateway_cfg"] == 3 # custom base URL and custom headers + calls = [(m, p.split("?")[0]) for m, p, _ in gateway.requests] + assert ("GET", "/v1/models") in calls and ("POST", "/v1/messages") in calls + for method, path, headers in gateway.requests: + if path.startswith("/v1/"): + assert headers.get(GATEWAY_KEY[0]) == GATEWAY_KEY[1], (method, path) + + def test_gateway_cfg_is_a_number_with_no_names_or_values(self, monkeypatch): + monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False) + monkeypatch.delenv("ANTHROPIC_CUSTOM_HEADERS", raising=False) + assert llm.gateway_cfg() == 0 + for same_host in ("https://api.anthropic.com/", "https://API.anthropic.com:443"): + monkeypatch.setenv("ANTHROPIC_BASE_URL", same_host) + assert llm.gateway_cfg() == 0 + monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://gw.example.com") + assert llm.gateway_cfg() == 1 + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "anthropic-beta: extra-1") + assert llm.gateway_cfg() == 1 # beta lines are not sent + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "X-Ok: 1") + assert llm.gateway_cfg() == 3 + monkeypatch.delenv("ANTHROPIC_BASE_URL") + assert llm.gateway_cfg() == 2 + + def test_gateway_cfg_is_left_out_when_no_api_call_was_made(self, env, gateway, workspace): + """Only rows that made API calls carry gateway_cfg.""" + _, repo = workspace + rc, so, se = run_hook(stop_payload(repo), env) + assert rc == 0, (so, se) + row = metrics_of(so) + assert row["skipped"] is True and "gateway_cfg" not in row diff --git a/plugins/security-guidance/tests/test_diff_parsing.py b/plugins/security-guidance/tests/test_diff_parsing.py new file mode 100644 index 00000000..7665a064 --- /dev/null +++ b/plugins/security-guidance/tests/test_diff_parsing.py @@ -0,0 +1,99 @@ +import os +import subprocess + +from conftest import GIT_ENV, git, make_repo + +import gitutil + +VULN = "import os\nos.system(input())\n" + + +def staged_diff(repo): + r = subprocess.run( + [*gitutil.GIT_CMD, "diff", "--cached", "--no-color"], cwd=repo, + capture_output=True, env={**os.environ, **GIT_ENV}, + ) + assert r.returncode == 0, r.stderr + return r.stdout.decode("utf-8", errors="replace") + + +def stage(tmp_path, files): + repo = make_repo(tmp_path / "repo") + for name, content in files.items(): + (repo / name).write_text(content) + git(repo, "add", "-A") + return staged_diff(repo) + + +class TestEmbeddedHeaderText: + SOURCE = ( + 'HEADER = """\n' + "diff --git a/other.py b/other.py\n" + '"""\n' + "import os\n" + "os.system(input()) # AFTER_EMBEDDED_HEADER\n" + ) + + def test_content_after_embedded_header_text_is_kept(self, tmp_path): + files = dict(gitutil.parse_diff_into_files(stage(tmp_path, {"embed.py": self.SOURCE}))) + assert list(files) == ["embed.py"] + assert "AFTER_EMBEDDED_HEADER" in files["embed.py"] + + def test_embedded_header_text_adds_no_path(self, tmp_path): + diff = stage(tmp_path, {"embed.py": self.SOURCE}) + assert gitutil.extract_file_paths_from_diff(diff) == ["embed.py"] + + def test_following_file_is_still_parsed(self, tmp_path): + diff = stage(tmp_path, {"embed.py": self.SOURCE, "z_next.py": VULN}) + assert [p for p, _ in gitutil.parse_diff_into_files(diff)] == ["embed.py", "z_next.py"] + + +class TestQuotedPaths: + def test_names_git_quotes_are_reviewed(self, tmp_path): + names = ['we"ird.py', "tab\there.py", "back\\slash.py", "café.py", "plain.py"] + diff = stage(tmp_path, {n: VULN for n in names}) + assert '"a/we\\"ird.py"' in diff # git did quote it + parsed = gitutil.parse_diff_into_files(diff) + assert sorted(p for p, _ in parsed) == sorted(names) + assert all("os.system" in c for _, c in parsed) + assert sorted(gitutil.extract_file_paths_from_diff(diff)) == sorted(names) + + def test_rename_to_a_quoted_name(self, tmp_path): + repo = make_repo(tmp_path / "repo", {"plain.py": VULN * 20}) + git(repo, "mv", "plain.py", 'qu"ote.py') + (repo / 'qu"ote.py').write_text(VULN * 20 + "eval(input())\n") + git(repo, "add", "-A") + diff = staged_diff(repo) + assert 'a/plain.py "b/qu\\"ote.py"' in diff + assert [p for p, _ in gitutil.parse_diff_into_files(diff)] == ['qu"ote.py'] + + def test_octal_escapes_decode_as_utf8(self): + header = '"a/caf\\303\\251.py" "b/caf\\303\\251.py"' + assert gitutil._parse_diff_header(header) == ("café.py", "café.py") + + def test_unterminated_quote_is_skipped(self): + assert gitutil._parse_diff_header('"a/x.py b/x.py') is None + + +class TestCommitOutput: + def test_git_show_preamble_is_ignored(self, tmp_path): + repo = make_repo(tmp_path / "repo") + (repo / "app.py").write_text(VULN) + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "diff --git a/fake.py b/fake.py") + r = subprocess.run( + [*gitutil.GIT_CMD, "show", "-p", "--no-color", "HEAD", "--"], cwd=repo, + capture_output=True, env={**os.environ, **GIT_ENV}, + ) + parsed = gitutil.parse_diff_into_files(r.stdout.decode()) + assert [p for p, _ in parsed] == ["app.py"] + + +def test_unparsed_headers_are_counted_for_telemetry(): + import gitutil + gitutil._unparsed_diff_headers.clear() + diff = 'diff --git "a/x.py b/x.py\n@@ -0,0 +1 @@\n+x = 1\n' + assert gitutil.parse_diff_into_files(diff) == [] + assert gitutil.extract_file_paths_from_diff(diff) == [] + assert len(gitutil._unparsed_diff_headers) == 1 + gitutil._unparsed_diff_headers.clear() diff --git a/plugins/security-guidance/tests/test_diff_prefix_config.py b/plugins/security-guidance/tests/test_diff_prefix_config.py new file mode 100644 index 00000000..ce2a8017 --- /dev/null +++ b/plugins/security-guidance/tests/test_diff_prefix_config.py @@ -0,0 +1,70 @@ +"""A user's diff prefix settings must not hide files from the reviews.""" +import os +import subprocess + +import pytest + +from conftest import ( + GIT_ENV, VULN_PY, commit_file, bash_payload, git, make_repo, metrics_of, + run_hook, stop_payload, ups_payload, +) + +import gitutil + +PREFIX_CONFIGS = [ + ("diff.mnemonicPrefix", "true"), + ("diff.noprefix", "true"), + ("diff.srcPrefix", "x/"), + ("diff.dstPrefix", "y/"), +] + + +@pytest.fixture +def git_env(monkeypatch): + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + + +@pytest.mark.parametrize("key,value", PREFIX_CONFIGS) +class TestParsers: + def test_work_tree_diff(self, tmp_path, git_env, key, value): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + git(repo, "config", key, value) + (repo / "app.py").write_text("x = 1\ny = 2\n") + diff = gitutil.get_git_diff(str(repo), "HEAD") + assert [f for f, _ in gitutil.parse_diff_into_files(diff)] == ["app.py"] + assert gitutil.extract_file_paths_from_diff(diff) == ["app.py"] + + def test_commit_diff(self, tmp_path, git_env, key, value): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + git(repo, "config", key, value) + commit_file(repo, "app.py", "x = 1\ny = 2\n") + show = subprocess.run( + [*gitutil.GIT_CMD, "show", "-p", "--no-color", "HEAD", "--"], + cwd=repo, capture_output=True, + ).stdout.decode("utf-8", errors="replace") + assert [f for f, _ in gitutil.parse_diff_into_files(show)] == ["app.py"] + diff = gitutil._git_diff_range(str(repo), "HEAD~1") + assert [f for f, _ in gitutil.parse_diff_into_files(diff)] == ["app.py"] + + +@pytest.mark.parametrize("key,value", PREFIX_CONFIGS[:2]) +class TestWholeHook: + def test_stop_review_runs(self, tmp_path, hook_env, stub_api, key, value): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + git(repo, "config", key, value) + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + rc, so, se = run_hook(stop_payload(repo), hook_env) + m = metrics_of(so) + assert m.get("skip_reason") is None, m + assert stub_api.calls + + +class TestWholeHookCommit: + def test_commit_review_runs_with_noprefix(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + git(repo, "config", "diff.noprefix", "true") + sha, out = commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", stdout=out), hook_env) + assert metrics_of(so).get("skip_reason") != 30 diff --git a/plugins/security-guidance/tests/test_findings_delivery.py b/plugins/security-guidance/tests/test_findings_delivery.py new file mode 100644 index 00000000..0989ed4b --- /dev/null +++ b/plugins/security-guidance/tests/test_findings_delivery.py @@ -0,0 +1,88 @@ +"""Findings reach Claude on the channel Claude Code reads for an asyncRewake +hook (`stderr || stdout`, never additionalContext).""" +import json +import sys +import types + +from conftest import ( + STUB_VULN, VULN_PY, bash_payload, commit_file, metrics_of, run_hook, +) + +import llm +import security_reminder_hook as hook + + +def _rewake_body(stdout, stderr): + """What Claude Code shows Claude for an exit-2 asyncRewake hook: stderr, + else stdout.""" + return stderr or stdout + + +def _commit(repo, env, content=VULN_PY, session_id="s1"): + sha, out = commit_file(repo, "app.py", content) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out, + session_id=session_id), env) + return sha, rc, so, se + + +class TestAgenticReviewerOn: + def test_findings_not_replaced_by_the_inner_cli_warning(self, agentic_env, gateway, workspace): + _, repo = workspace + gateway.vulns = [STUB_VULN] + sha, rc, so, se = _commit(repo, agentic_env) + assert rc == 2, (so, se) + assert metrics_of(so)["agentic_fallback"] == 2 + assert metrics_of(so)["child_stderr"] >= 1 # the warning was counted, not shown + body = _rewake_body(so, se) + assert "command_injection" in body + assert "connectors are disabled" not in body + assert "Fatal error in message reader" not in body # the SDK's own log line + + +class TestFindingsReachClaude: + def test_commit_findings_are_the_rewake_body(self, env, gateway, workspace): + _, repo = workspace + gateway.vulns = [STUB_VULN] + sha, rc, so, se = _commit(repo, env) + assert rc == 2 + body = _rewake_body(so, se) + assert "Security Review: Potential vulnerabilities detected" in body + assert "command_injection" in body + out = json.loads(so.strip().splitlines()[-1]) + assert out["metrics"]["vulns_found"] == 1 + assert out["rewakeSummary"].startswith("Commit security review found") + assert "hookSpecificOutput" not in out # not repeated where the sync path would show it twice + + def test_stop_findings_also_go_in_decision_and_reason(self, capsys): + hook.emit_metrics({"vulns_found": 1}, additional_context="FINDINGS", hook_event_name="Stop") + cap = capsys.readouterr() + assert cap.err == "FINDINGS" + out = json.loads(cap.out) + assert out["decision"] == "block" and out["reason"] == "FINDINGS" + + def test_agentic_review_captures_the_inner_cli_stderr(self, monkeypatch, tmp_path, capfd): + spawned = [] + + class ClaudeAgentOptions: + def __init__(self, **kwargs): + self.kwargs = kwargs + spawned.append(kwargs) + + class ResultMessage: + subtype, usage, total_cost_usd = "success", {}, 0.0 + structured_output = {"findings": []} + + async def query(prompt, options): + # What the inner CLI prints on stderr; with a callback set the SDK + # pipes it to the callback instead of the hook's own stderr. + options.kwargs["stderr"]("claude.ai connectors are disabled") + yield ResultMessage() + + sdk = types.ModuleType("claude_agent_sdk") + sdk.ClaudeAgentOptions, sdk.ResultMessage, sdk.query = ClaudeAgentOptions, ResultMessage, query + sdk.AssistantMessage = type("AssistantMessage", (), {}) + monkeypatch.setitem(sys.modules, "claude_agent_sdk", sdk) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "") + llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + assert callable(spawned[0].get("stderr")) + assert "connectors" not in capfd.readouterr().err diff --git a/plugins/security-guidance/tests/test_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py new file mode 100644 index 00000000..4e00c608 --- /dev/null +++ b/plugins/security-guidance/tests/test_inflight_reviews.py @@ -0,0 +1,248 @@ +"""A commit still under review is not sent through a second review.""" +import contextlib +import json +import os +import subprocess +import sys +import time + +import pytest + +from conftest import ( + HOOK_SCRIPT, bash_payload, commit_file, git, make_repo, metrics_of, run_hook, +) + +import diffstate + +pytest.importorskip("fcntl") + +_HOLD = ( + "import fcntl, os, sys, time\n" + "fd = os.open(sys.argv[1], os.O_RDWR | os.O_CREAT, 0o600)\n" + "fcntl.flock(fd, fcntl.LOCK_EX)\n" + "print('held', flush=True)\n" + "time.sleep(float(sys.argv[2]))\n" +) + + +@contextlib.contextmanager +def _held_by_another_review(repo, sha, seconds=60): + """A marker on `sha` that a live process holds, as a running review does.""" + marker = repo / ".git" / f"sg-inflight-{sha}" + p = subprocess.Popen([sys.executable, "-c", _HOLD, str(marker), str(seconds)], + stdout=subprocess.PIPE, text=True) + try: + assert p.stdout.readline().strip() == "held" + yield marker + finally: + p.kill() + p.wait() + p.stdout.close() + + +@contextlib.contextmanager +def _hook_in_background(payload, env): + p = subprocess.Popen( + [sys.executable, str(HOOK_SCRIPT)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, env=env, + ) + try: + p.stdin.write(json.dumps(payload)) + p.stdin.close() + yield p + finally: + if p.poll() is None: + p.kill() + p.wait() + p.stdout.close() + + +def _repo_with_remote(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + remote = tmp_path / "remote.git" + git(tmp_path, "init", "-q", "--bare", str(remote)) + git(repo, "remote", "add", "origin", str(remote)) + git(repo, "push", "-q", "-u", "origin", "main") + return repo, remote + + +def _markers(repo): + return [n for n in os.listdir(repo / ".git") if n.startswith("sg-inflight-")] + + +def _wait_until(cond, what, timeout=20): + end = time.time() + timeout + while time.time() < end: + if cond(): + return + time.sleep(0.05) + raise AssertionError(f"timed out waiting for {what}") + + +def _reviews(stub_api): + return [c for c in stub_api.calls if c.endswith("/v1/messages")] + + +def _commit_and_push(repo, remote): + base = git(repo, "rev-parse", "HEAD").strip() + sha, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + git(repo, "push", "-q", "origin", "main") + push_out = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n" + return base, sha, commit_out, push_out + + +def test_push_right_after_commit_runs_one_review(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base, sha, commit_out, push_out = _commit_and_push(repo, remote) + stub_api.delay = 6 + with _hook_in_background(bash_payload(repo, "git commit -m change", commit_out), + hook_env) as commit: + _wait_until(lambda: _markers(repo), "the commit review's marker") + rc, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), hook_env) + commit.wait(timeout=60) + + m = metrics_of(so) + assert rc == 0 and m["push_sweep"] is True + assert m["pushed"] == 1 and m["unreviewed"] == 0 + assert m.get("inflight_wait_s", 0) >= 1 + assert len(_reviews(stub_api)) == 1 + assert sha in diffstate._load_reviewed_shas(str(repo)) + assert _markers(repo) == [] + + +def test_push_reviews_commit_whose_review_died(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base, sha, _, push_out = _commit_and_push(repo, remote) + with _held_by_another_review(repo, sha): + pass # killed: its marker file stays, its lock does not + assert _markers(repo) == [f"sg-inflight-{sha}"] + rc, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), hook_env) + + m = metrics_of(so) + assert m["unreviewed"] == 1 and "inflight_wait_s" not in m + assert len(_reviews(stub_api)) == 1 + assert _markers(repo) == [] + + +def test_push_reviews_commit_whose_review_ended_without_a_verdict(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base, sha, _, push_out = _commit_and_push(repo, remote) + with _held_by_another_review(repo, sha, seconds=3): + rc, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), hook_env) + + m = metrics_of(so) + assert m["unreviewed"] == 1 + assert m["files_reviewed"] == 1 and len(_reviews(stub_api)) == 1 + assert sha in diffstate._load_reviewed_shas(str(repo)) + + +def test_push_stops_waiting_after_the_limit(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base, sha, _, push_out = _commit_and_push(repo, remote) + env = {**hook_env, "SG_INFLIGHT_WAIT_S": "2"} + with _held_by_another_review(repo, sha): + rc, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), env) + + m = metrics_of(so) + assert m["unreviewed"] == 1 and m["inflight_wait_s"] >= 2 + assert len(_reviews(stub_api)) == 1 + + +def test_push_does_not_wait_when_an_earlier_commit_needs_review_anyway(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base = git(repo, "rev-parse", "HEAD").strip() + commit_file(repo, "outside.py", "def o(x):\n return x\n") + sha, _ = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + git(repo, "push", "-q", "origin", "main") + push_out = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n" + with _held_by_another_review(repo, sha): + rc, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), hook_env) + + m = metrics_of(so) + assert m["pushed"] == 2 and m["unreviewed"] == 2 and "inflight_wait_s" not in m + assert m["files_reviewed"] == 2 + + +def test_push_does_not_record_the_range_when_head_moves_during_the_wait(tmp_path, hook_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + base, sha, _, push_out = _commit_and_push(repo, remote) + env = {**hook_env, "SG_INFLIGHT_WAIT_S": "10"} + with _held_by_another_review(repo, sha): + with _hook_in_background(bash_payload(repo, "git push origin main", push_out), + env) as push: + time.sleep(5) + git(repo, "checkout", "-q", "-b", "elsewhere", base) + so = push.stdout.read() + push.wait(timeout=60) + + m = metrics_of(so) + assert m["skip_reason"] == 44 and m.get("inflight_wait_s", 0) >= 1 + assert _reviews(stub_api) == [] + assert sha not in diffstate._load_reviewed_shas(str(repo)) + + +def test_next_quiet_commit_leaves_a_running_review_its_commit(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + commit_file(repo, "a.py", "def a(x):\n return x\n") + stub_api.delay = 6 + with _hook_in_background(bash_payload(repo, "git commit -q -m a"), hook_env) as first: + _wait_until(lambda: _markers(repo), "the first review's marker") + commit_file(repo, "b.py", "def b(x):\n return x\n") + rc, so, _ = run_hook(bash_payload(repo, "git commit -q -m b"), hook_env) + first.wait(timeout=60) + + m = metrics_of(so) + assert m["sha_via_reflog"] is True and m["reflog_shas_n"] == 1 + assert m["files_reviewed"] == 1 + assert _markers(repo) == [] + + +def test_marker_is_not_taken_from_a_live_review(tmp_path): + repo = make_repo(tmp_path / "repo") + sha = git(repo, "rev-parse", "HEAD").strip() + with _held_by_another_review(repo, sha) as marker: + diffstate._mark_inflight(str(repo), [sha]) + assert diffstate._inflight_held == {} + assert diffstate._load_inflight_shas(str(repo), [sha]) == {sha} + assert diffstate._load_inflight_shas(str(repo), [sha]) == set() + assert marker.exists() # fresh leftovers stay; old ones are removed + old = time.time() - diffstate._INFLIGHT_GC_AGE_S - 5 + os.utime(marker, (old, old)) + diffstate._mark_inflight(str(repo), []) + assert not marker.exists() + + +def test_no_marker_is_left_where_files_cannot_be_locked(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo") + sha = git(repo, "rev-parse", "HEAD").strip() + + def no_locks(fd, exclusive): + raise OSError(37, "No locks available") + monkeypatch.setattr(diffstate, "_flock_nb", no_locks) + diffstate._mark_inflight(str(repo), [sha]) + assert _markers(repo) == [] and diffstate._inflight_held == {} + (repo / ".git" / f"sg-inflight-{sha}").write_text("") + assert diffstate._load_inflight_shas(str(repo), [sha]) == set() + + +def test_own_marker_is_held_until_released(tmp_path): + repo = make_repo(tmp_path / "repo") + sha = git(repo, "rev-parse", "HEAD").strip() + diffstate._mark_inflight(str(repo), [sha, "not-a-sha"]) + marker = repo / ".git" / f"sg-inflight-{sha}" + try: + assert _markers(repo) == [marker.name] + assert diffstate._load_inflight_shas(str(repo), [sha]) == set() + probe = ( + "import sys; sys.path.insert(0, sys.argv[1]); import diffstate; " + "print(sorted(diffstate._load_inflight_shas(sys.argv[2], [sys.argv[3]])))" + ) + seen = subprocess.run( + [sys.executable, "-c", probe, os.path.dirname(diffstate.__file__), str(repo), sha], + capture_output=True, text=True).stdout.strip() + assert seen == str([sha]) + reviewed, waited = diffstate._reviewed_after_inflight(str(repo), [sha], 5) + assert reviewed == set() and waited == 0.0 + finally: + diffstate._release_inflight() + assert not marker.exists() diff --git a/plugins/security-guidance/tests/test_launcher_process_count.py b/plugins/security-guidance/tests/test_launcher_process_count.py new file mode 100644 index 00000000..f22fd680 --- /dev/null +++ b/plugins/security-guidance/tests/test_launcher_process_count.py @@ -0,0 +1,158 @@ +"""sg-python.sh starts as few processes as it can before it runs the hook. + +Under Git Bash every command substitution is a new Windows process, and the +launcher runs on every hook, so probing interpreters that are not installed, +probing the same one twice, or calling cygpath for a plain drive path is paid +on each Edit, prompt and Stop. See #6470. + +Interpreters and cygpath are emulated with shell scripts, so these tests need +a POSIX shell. +""" +import shutil +import subprocess +import sys + +import pytest + +from conftest import HOOKS_DIR + +pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers") + +SHIM = HOOKS_DIR / "sg-python.sh" +BASH = shutil.which("bash") or "/bin/bash" + +# Logs each start; answers the probe with a fixed version, else prints its argv. +PYTHON = """#!{bash} +if [ "${{1:-}}" = "-c" ] || [ "${{1:-}} ${{2:-}}" = "-3 -c" ]; then + echo "${{0##*/}} probe" >> '{log}'; printf '{version}{eol}'; exit 0 +fi +echo "${{0##*/}} $*" >> '{log}' +printf 'ran:%s\\n' "${{0##*/}}"; printf 'arg:%s\\n' "$@" +""" +# ${x^^} in the launcher's Git Bash branch needs bash 4; stock macOS has 3.2. +BASH_MAJOR = int(subprocess.run([BASH, "-c", "echo ${BASH_VERSINFO[0]}"], capture_output=True, + text=True).stdout.strip() or 0) + +# The Microsoft Store placeholder: on PATH, starts, does nothing. +STUB = """#!{bash} +echo "${{0##*/}} probe" >> '{log}' +exit 49 +""" +CYGPATH = """#!{bash} +echo "cygpath $*" >> '{log}' +echo "CYGPATH($2)" +""" + + +@pytest.fixture +def box(tmp_path): + (tmp_path / "bin").mkdir() + (tmp_path / "log").write_text("") + return tmp_path + + +def _add(box, name, template, version="", crlf=False): + p = box / "bin" / name + p.write_text(template.format(bash=BASH, log=box / "log", version=version, + eol="\\r\\n" if crlf else "\\n")) + p.chmod(0o755) + + +def _run(box, *args, ostype="linux-gnu", trace=False): + cmd = [BASH] + (["-x"] if trace else []) + [str(SHIM), *args] + return subprocess.run(cmd, input="", capture_output=True, text=True, timeout=60, + env={"PATH": str(box / "bin"), "HOME": "/", "OSTYPE": ostype}) + + +def _starts(box): + return (box / "log").read_text().splitlines() + + +def test_only_installed_interpreters_are_probed(box): + _add(box, "python", PYTHON, "3.12") + r = _run(box, "hook.py", trace=True) + assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"] + # xtrace marks what runs in a subshell with "++": only the one probe did. + probes = [line for line in r.stderr.splitlines() if line.startswith("++ probe ")] + assert probes == ["++ probe python"] + assert _starts(box) == ["python probe", "python hook.py"] + + +def test_store_placeholder_still_falls_through_to_python(box): + _add(box, "python3", STUB) + _add(box, "python", PYTHON, "3.13") + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"] + assert _starts(box) == ["python3 probe", "python probe", "python hook.py"] + + +def test_python_below_3_10_is_probed_once(box): + _add(box, "python3", PYTHON, "3.9") + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:python3", "arg:hook.py"] + assert _starts(box) == ["python3 probe", "python3 hook.py"] + + +def test_first_older_python_wins_when_none_is_3_10(box): + _add(box, "python3", PYTHON, "3.8") + _add(box, "python", PYTHON, "3.9") + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:python3", "arg:hook.py"] + + +def test_newer_python_under_a_later_name_beats_an_older_python3(box): + _add(box, "python3", PYTHON, "3.9") + _add(box, "python", PYTHON, "3.12") + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"] + + +def test_py_launcher_is_still_a_candidate(box): + _add(box, "py", PYTHON, "3.12") + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:py", "arg:-3", "arg:hook.py"] + assert _starts(box) == ["py probe", "py -3 hook.py"] + + +def test_crlf_version_output_does_not_cost_further_probes(box): + # Native Windows Python may print CRLF; 3.12 must still read as 3.10+. + _add(box, "python", PYTHON, "3.12", crlf=True) + _add(box, "py", PYTHON, "3.12", crlf=True) + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"] + assert _starts(box) == ["python probe", "python hook.py"] + + +@pytest.mark.skipif(BASH_MAJOR < 4, reason="needs bash 4+, as Git Bash has") +@pytest.mark.parametrize("posix, native", [ + ("/c/Users/me/.claude/hooks/hook.py", "C:\\Users\\me\\.claude\\hooks\\hook.py"), + ("/d/a b/hook.py", "D:\\a b\\hook.py"), + ("/c/", "C:\\"), +]) +def test_drive_paths_are_converted_without_cygpath(box, posix, native): + _add(box, "cygpath", CYGPATH) + _add(box, "python", PYTHON, "3.12") + rest = ["--flag", "rel/path", "C:\\already\\native", "C:/d/mixed"] + r = _run(box, posix, *rest, ostype="msys") + assert r.stdout.splitlines() == ["ran:python", "arg:" + native] + ["arg:" + a for a in rest] + assert not [s for s in _starts(box) if s.startswith("cygpath")] + + +@pytest.mark.parametrize("ostype, posix", [ + ("msys", "/tmp/hook.py"), # a mount point, not a drive + ("msys", "/usr/bin"), + ("msys", "/c"), + ("msys", "//server/share/hook.py"), + ("cygwin", "/c/Users/me/hook.py"), # drives live under /cygdrive there +]) +def test_other_absolute_paths_still_go_through_cygpath(box, ostype, posix): + _add(box, "cygpath", CYGPATH) + _add(box, "python", PYTHON, "3.12") + r = _run(box, posix, ostype=ostype) + assert r.stdout.splitlines() == ["ran:python", "arg:CYGPATH(%s)" % posix] + + +def test_paths_are_left_alone_without_cygpath(box): + _add(box, "python3", PYTHON, "3.12") + r = _run(box, "/c/Users/me/hook.py", ostype="msys") + assert r.stdout.splitlines() == ["ran:python3", "arg:/c/Users/me/hook.py"] diff --git a/plugins/security-guidance/tests/test_launcher_unreadable_script.py b/plugins/security-guidance/tests/test_launcher_unreadable_script.py new file mode 100644 index 00000000..d963eaa0 --- /dev/null +++ b/plugins/security-guidance/tests/test_launcher_unreadable_script.py @@ -0,0 +1,192 @@ +"""sg-python.sh never hands the hook script to an interpreter that cannot see it. + +On Windows, python/python3/py can be packaged launcher aliases whose +interpreter answers `-c` but has no view of the plugin directory. Running the +hook with one fails with CPython's "can't open file" and exit code 2, which an +asyncRewake hook reports to the model as review findings, on every Stop. + +The aliases are emulated with shell wrappers around the real interpreter, so +these tests need a POSIX shell. +""" +import json +import os +import shutil +import subprocess +import sys + +import pytest + +from conftest import HOOKS_DIR, metrics_of, run_hook, stop_payload + +pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers") + +SHIM = HOOKS_DIR / "sg-python.sh" +BASH = shutil.which("bash") or "/bin/bash" +REAL = os.path.realpath(sys.executable) + +# Echoes its stdin and exits 2, like a hook that has findings to report. +HOOK = ( + "import os, sys\n" + "print('fallback=' + os.environ.get('SG_LAUNCHER_FALLBACK', ''))\n" + "sys.stderr.write('ran:' + sys.stdin.read())\nsys.exit(2)\n" +) + +ALIAS = """#!{bash} +# A packaged alias: `-c` works, files under HIDE are invisible. +HIDE='{hide}'; REAL='{real}' +if [ "${{1:-}}" = "-c" ]; then + code="$2"; shift 2 + out=$("$REAL" -c "import os as _o, sys as _s +_f = _o.path.isfile +_o.path.isfile = lambda p, _f=_f: False if str(p).startswith('$HIDE') else _f(p) +if '{sealed}': _s.executable = '$0' +$code" "$@"); rc=$? + [ -n "$out" ] && printf '%s{eol}' "$out" + exit $rc +fi +case "${{1:-}}" in + "$HIDE"/*) echo "python: can't open file '$1': [Errno 2] No such file or directory" >&2; exit 2 ;; +esac +exec "$REAL" "$@" +""" + + +def _alias(bindir, name, hide, sealed=False, crlf=False): + bindir.mkdir(parents=True, exist_ok=True) + p = bindir / name + p.write_text(ALIAS.format(bash=BASH, hide=hide, real=REAL, sealed="1" if sealed else "", + eol="\\r\\n" if crlf else "\\n")) + p.chmod(0o755) + + +def _run(path_dirs, script, payload='{"k": 1}'): + return subprocess.run( + [BASH, str(SHIM), str(script)], input=payload, capture_output=True, text=True, timeout=60, + env={"PATH": os.pathsep.join(str(d) for d in path_dirs), "HOME": os.environ.get("HOME", "/")}, + ) + + +@pytest.fixture +def plugin(tmp_path): + d = tmp_path / "plugin" / "hooks" + d.mkdir(parents=True) + (d / "hook.py").write_text(HOOK) + return d + + +def test_alias_is_replaced_by_the_interpreter_it_reports(plugin, tmp_path): + for name in ("python3", "python"): + _alias(tmp_path / "alias", name, plugin) + r = _run([tmp_path / "alias"], plugin / "hook.py") + assert "can't open file" not in r.stderr + # The hook ran, read its payload, and its own exit code came through. + assert r.stderr == 'ran:{"k": 1}' + assert r.returncode == 2 + assert r.stdout.strip() == "fallback=1" + + +def test_regular_interpreter_is_not_marked_as_fallback(plugin, tmp_path): + (tmp_path / "real").mkdir() + os.symlink(REAL, tmp_path / "real" / "python3") + r = subprocess.run( + [BASH, str(SHIM), str(plugin / "hook.py")], input="{}", capture_output=True, text=True, timeout=60, + env={"PATH": str(tmp_path / "real"), "HOME": "/", "SG_LAUNCHER_FALLBACK": "1"}, + ) + assert r.returncode == 2 + assert r.stdout.strip() == "fallback=" + + +def test_regular_install_later_on_path_is_used(plugin, tmp_path): + _alias(tmp_path / "alias", "python3", plugin, sealed=True) + (tmp_path / "real").mkdir() + os.symlink(REAL, tmp_path / "real" / "python3") + r = _run([tmp_path / "alias", tmp_path / "real"], plugin / "hook.py") + assert r.stderr == 'ran:{"k": 1}' + assert r.returncode == 2 + + +def test_regular_install_under_another_name_is_used(plugin, tmp_path): + _alias(tmp_path / "alias", "python3", plugin, sealed=True) + (tmp_path / "real").mkdir() + os.symlink(REAL, tmp_path / "real" / "python") + r = _run([tmp_path / "alias", tmp_path / "real"], plugin / "hook.py") + assert r.stderr == 'ran:{"k": 1}' + assert r.returncode == 2 + + +def test_no_interpreter_can_see_the_script_is_not_reported_as_findings(plugin, tmp_path): + for name in ("python3", "python"): + _alias(tmp_path / "alias", name, plugin, sealed=True) + r = _run([tmp_path / "alias"], plugin / "hook.py") + assert r.returncode == 1 + assert "can't open file" not in r.stderr + assert "cannot read the hook script" in r.stderr + assert str(plugin / "hook.py") in r.stderr + assert metrics_of(r.stdout) == {"launcher_unreadable": 1} + + +def test_missing_script_is_not_reported_as_findings(plugin, tmp_path): + (tmp_path / "real").mkdir() + os.symlink(REAL, tmp_path / "real" / "python3") + r = _run([tmp_path / "real"], plugin / "gone.py") + assert r.returncode == 1 + assert "can't open file" not in r.stderr + + +def test_no_python_keeps_its_own_message(plugin, tmp_path): + (tmp_path / "empty").mkdir() + r = _run([tmp_path / "empty"], plugin / "hook.py") + assert r.returncode == 1 + assert "no working Python 3 interpreter found" in r.stderr + + +def test_unusable_python_keeps_the_no_interpreter_message(plugin, tmp_path): + # Runs, but is not Python 3: nothing says the script is unreadable. + d = tmp_path / "old" + d.mkdir() + (d / "python").write_text("#!%s\nexit 1\n" % BASH) + (d / "python").chmod(0o755) + r = _run([d], plugin / "hook.py") + assert r.returncode == 1 + assert "no working Python 3 interpreter found" in r.stderr + + +def test_alias_with_crlf_output_is_still_resolved(plugin, tmp_path): + # Native Windows Python prints CRLF; the reported path must survive that. + _alias(tmp_path / "alias", "python3", plugin, crlf=True) + r = _run([tmp_path / "alias"], plugin / "hook.py") + assert r.stderr == 'ran:{"k": 1}' + assert r.returncode == 2 + + +@pytest.mark.skipif(shutil.which("git") is None, reason="needs git") +def test_real_hook_runs_through_an_alias_only_path(tmp_path): + for name in ("python3", "python"): + _alias(tmp_path / "alias", name, HOOKS_DIR) + payload = json.dumps({"hook_event_name": "UserPromptSubmit", "session_id": "launcher-test", + "cwd": str(tmp_path), "prompt": "hello"}) + # git only: its directory usually holds a regular python3 as well. + git_dir = tmp_path / "git" + git_dir.mkdir() + os.symlink(shutil.which("git"), git_dir / "git") + r = subprocess.run( + [BASH, str(SHIM), str(HOOKS_DIR / "security_reminder_hook.py")], + input=payload, capture_output=True, text=True, timeout=120, + env={"PATH": os.pathsep.join([str(tmp_path / "alias"), str(git_dir)]), "HOME": str(tmp_path), + "SECURITY_GUIDANCE_DEBUG_LOG": str(tmp_path / "debug.log")}, + ) + assert r.returncode == 0, r.stderr + assert "hook_event=UserPromptSubmit" in (tmp_path / "debug.log").read_text() + + +@pytest.mark.parametrize("flag", ["1", None]) +def test_hook_reports_launcher_fallback(workspace, hook_env, flag): + env = dict(hook_env) + env.pop("SG_LAUNCHER_FALLBACK", None) + if flag: + env["SG_LAUNCHER_FALLBACK"] = flag + rc, out, _ = run_hook(stop_payload(workspace), env) + assert rc == 0 + m = metrics_of(out) + assert m is not None + assert m.get("launcher_fallback") == (1 if flag else None) diff --git a/plugins/security-guidance/tests/test_portable_output.py b/plugins/security-guidance/tests/test_portable_output.py new file mode 100644 index 00000000..cad2052c --- /dev/null +++ b/plugins/security-guidance/tests/test_portable_output.py @@ -0,0 +1,181 @@ +import json +import os +import subprocess +import sys + +import pytest + +from conftest import ( + HOOKS_DIR, STUB_VULN, VULN_PY, edit_payload, metrics_of, run_hook, stop_payload, ups_payload, +) + +# What a host with a closed hook output schema accepts. +STOP_FIELDS = {"continue", "decision", "reason", "stopReason", "suppressOutput", "systemMessage"} +POST_TOOL_USE_FIELDS = STOP_FIELDS | {"hookSpecificOutput"} +HOST_MARKERS = ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "PLUGIN_ROOT", + "SECURITY_GUIDANCE_PORTABLE_OUTPUT") + + +def _env(hook_env, **extra): + env = {k: v for k, v in hook_env.items() if k not in HOST_MARKERS} + env.update(extra) + return env + + +def _objects(stdout): + lines = [l for l in stdout.splitlines() if l.strip()] + return [json.loads(l) for l in lines] + + +def _review_with_finding(workspace, env, stub_api): + ws, repo = workspace + stub_api.vulns = [STUB_VULN] + run_hook(ups_payload(repo), env) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env) + return run_hook(stop_payload(repo), env) + + +class TestOtherHost: + def test_stop_skip_path_prints_only_standard_fields(self, workspace, hook_env): + ws, repo = workspace + rc, so, se = run_hook(stop_payload(repo), _env(hook_env, PLUGIN_ROOT=str(ws))) + assert rc == 0 + assert _objects(so) == [{}] + + def test_stop_finding_keeps_the_block_and_the_guidance(self, workspace, hook_env, stub_api): + rc, so, se = _review_with_finding(workspace, _env(hook_env, PLUGIN_ROOT="/p"), stub_api) + (out,) = _objects(so) + assert set(out) <= STOP_FIELDS, out + assert out["decision"] == "block" + assert "command_injection" in out["reason"] + assert "command_injection" in se + + def test_pattern_warning_keeps_the_guidance(self, workspace, hook_env): + ws, repo = workspace + env = _env(hook_env, PLUGIN_ROOT="/p") + (repo / "app.py").write_text(VULN_PY) + rc, so, se = run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env) + assert rc == 0 + (out,) = _objects(so) + assert set(out) <= POST_TOOL_USE_FIELDS, out + assert out["hookSpecificOutput"]["additionalContext"] + + def test_kill_switch_path(self, workspace, hook_env): + ws, repo = workspace + env = _env(hook_env, PLUGIN_ROOT="/p", SECURITY_GUIDANCE_DISABLE="1") + rc, so, se = run_hook(stop_payload(repo), env) + assert rc == 0 + assert all(set(o) <= STOP_FIELDS for o in _objects(so)) + + + def test_mode_is_not_changed_by_the_hook_process_itself(self, hook_env): + code = ("import os, _base\n" + "os.environ['CLAUDE_CODE_ENTRYPOINT'] = 'sdk-py'\n" + "_base.write_hook_output({'metrics': {'x': 1}, 'reason': 'r'})\n") + r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, + cwd=HOOKS_DIR, env=_env(hook_env, PLUGIN_ROOT="/p"), timeout=60) + assert _objects(r.stdout) == [{"reason": "r"}], r.stderr + + +class TestClaudeCodeUnchanged: + @pytest.mark.parametrize("extra", [ + {}, + {"PLUGIN_ROOT": "/p", "CLAUDECODE": "1"}, + {"PLUGIN_ROOT": "/p", "CLAUDE_CODE_ENTRYPOINT": "cli"}, + {"PLUGIN_ROOT": "/p", "SECURITY_GUIDANCE_PORTABLE_OUTPUT": "0"}, + ]) + def test_metrics_and_summary_are_still_sent(self, workspace, hook_env, stub_api, extra): + rc, so, se = _review_with_finding(workspace, _env(hook_env, **extra), stub_api) + (out,) = _objects(so) + assert out["metrics"]["vulns_found"] == 1 + assert out["rewakeSummary"] + assert out["decision"] == "block" + + def test_forced_on_under_claude_code(self, workspace, hook_env): + ws, repo = workspace + env = _env(hook_env, CLAUDECODE="1", SECURITY_GUIDANCE_PORTABLE_OUTPUT="1") + rc, so, se = run_hook(stop_payload(repo), env) + assert metrics_of(so) is None and _objects(so) == [{}] + + +# SessionStart runs ensure_agent_sdk.py. The wrapper picks the branch without +# installing anything: whether the SDK looks importable, and whether the +# interpreter looks older than the SDK supports. +SESSION_START_FIELDS = STOP_FIELDS | {"hookSpecificOutput"} +_BOOTSTRAP = """ +import importlib.util, os, runpy, sys +script, sdk, old_py = sys.argv[1:4] +sys.path.insert(0, os.path.dirname(script)) +real = importlib.util.find_spec +def find_spec(name, *a, **k): + if name == "claude_agent_sdk": + return object() if sdk == "present" else None + return real(name, *a, **k) +importlib.util.find_spec = find_spec +class V(tuple): + major, minor = property(lambda s: s[0]), property(lambda s: s[1]) +sys.version_info = V(((3, 9, 6) if old_py == "old" else (3, 12, 0)) + ("final", 0)) +sys.argv = [script] +runpy.run_path(script, run_name="__main__") +""" + + +def _session_start(tmp_path, branch, **extra): + state = tmp_path / "state" + state.mkdir(exist_ok=True) + sdk, old_py = "absent", "new" + if branch == "noop": + sdk = "present" + elif branch == "concurrent_build": + (state / "agent-sdk-venv.building").touch() + elif branch == "failure": + (tmp_path / "file").write_text("") + state = tmp_path / "file" / "state" + elif branch == "notice": + old_py = "old" + env = {k: v for k, v in os.environ.items() if k not in HOST_MARKERS} + env.update(SECURITY_WARNINGS_STATE_DIR=str(state), HOME=str(tmp_path), + PYTHONDONTWRITEBYTECODE="1", **extra) + r = subprocess.run( + [sys.executable, "-c", _BOOTSTRAP, str(HOOKS_DIR / "ensure_agent_sdk.py"), sdk, old_py], + input="{}", capture_output=True, text=True, env=env, timeout=60, + ) + return r.returncode, r.stdout, r.stderr + + +SESSION_START_BRANCHES = ["noop", "concurrent_build", "failure", "notice"] + + +class TestSessionStartOtherHost: + @pytest.mark.parametrize("branch", SESSION_START_BRANCHES) + def test_one_document_with_only_standard_fields(self, tmp_path, branch): + rc, so, se = _session_start(tmp_path, branch, PLUGIN_ROOT="/p") + assert rc == 0 and se == "" + out = json.loads(so) # the whole stream is one JSON document + assert set(out) <= SESSION_START_FIELDS, out + assert (out != {}) == (branch == "notice") + + def test_notice_is_kept(self, tmp_path): + rc, so, se = _session_start(tmp_path, "notice", PLUGIN_ROOT="/p") + out = json.loads(so) + assert "Python" in out["systemMessage"] + assert out["hookSpecificOutput"] == { + "hookEventName": "SessionStart", "additionalContext": out["systemMessage"]} + + +class TestSessionStartClaudeCodeUnchanged: + @pytest.mark.parametrize("branch,outcome", [ + ("noop", 0), ("concurrent_build", 5), ("failure", 3), ("notice", 6)]) + @pytest.mark.parametrize("extra", [ + {}, + {"PLUGIN_ROOT": "/p", "CLAUDECODE": "1"}, + {"PLUGIN_ROOT": "/p", "SECURITY_GUIDANCE_PORTABLE_OUTPUT": "0"}, + ]) + def test_async_line_then_metrics(self, tmp_path, branch, outcome, extra): + rc, so, se = _session_start(tmp_path, branch, **extra) + assert rc == 0 + first, second = _objects(so) + assert first == {"async": True, "asyncTimeout": 180000} + assert second["metrics"]["sdk_bootstrap"] == outcome + assert ("systemMessage" in second) == (branch == "notice") diff --git a/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py b/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py new file mode 100644 index 00000000..be0fc1ee --- /dev/null +++ b/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py @@ -0,0 +1,169 @@ +import json +import os +import shutil + +import pytest + +from conftest import ( + VULN_PY, edit_payload, make_repo, metrics_of, run_hook, stop_payload, ups_payload, +) + +OFF_SWITCHES = [ + pytest.param({"ENABLE_STOP_REVIEW": "0"}, id="stop-review-off"), + pytest.param({"ENABLE_CODE_SECURITY_REVIEW": "0"}, id="all-reviews-off"), +] +OLD = "import os\nos.system(cmd)\n" + + +@pytest.fixture +def on(hook_env, tmp_path): + """hook_env with the Stop review on, and a `git` first on PATH that + records each call before running it.""" + shim = tmp_path / "bin" + shim.mkdir() + log = tmp_path / "git.log" + log.write_text("") + (shim / "git").write_text( + f'#!/bin/sh\nprintf \'%s\\n\' "$*" >> "{log}"\nexec "{shutil.which("git")}" "$@"\n') + (shim / "git").chmod(0o755) + env = {k: v for k, v in hook_env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"} + env.update(HOME=str(tmp_path), PATH=f"{shim}{os.pathsep}{hook_env['PATH']}", + GIT_CALLS=str(log)) + return env + + +def _listed_untracked(env): + with open(env["GIT_CALLS"]) as f: + return any("ls-files --others" in line for line in f) + + +def _state(env, session_id="s1"): + path = os.path.join(env["SECURITY_WARNINGS_STATE_DIR"], + f"security_warnings_state_{session_id}.json") + with open(path) as f: + return json.load(f) + + +def _repo(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": OLD}) + (repo / "notes.txt").write_text("scratch\n") + return repo + + +def _write_payload(cwd, file_path, content, session_id="s1"): + return { + "session_id": session_id, + "hook_event_name": "PostToolUse", + "tool_name": "Write", + "tool_input": {"file_path": str(file_path), "content": content}, + "tool_response": {}, + "cwd": str(cwd), + } + + +def _reviewed(stub_api): + n = len(stub_api.calls) + del stub_api.calls[:] + return n > 0 + + +pytestmark = pytest.mark.skipif(os.name == "nt", reason="the git recorder is a sh script") + + +class TestPrompt: + def test_review_on_takes_the_snapshot(self, tmp_path, on): + repo = _repo(tmp_path) + rc, _, _ = run_hook(ups_payload(repo), on) + assert rc == 0 + assert _listed_untracked(on) + assert list(_state(on)["untracked_at_baseline"]) == ["notes.txt"] + + @pytest.mark.parametrize("off", OFF_SWITCHES) + def test_review_off_does_not_list_the_worktree(self, tmp_path, on, off): + repo = _repo(tmp_path) + rc, _, _ = run_hook(ups_payload(repo), {**on, **off}) + assert rc == 0 + assert not _listed_untracked(on) + assert "untracked_at_baseline" not in _state(on) + + @pytest.mark.parametrize("off", OFF_SWITCHES) + def test_review_off_write_filter_still_knows_what_was_there(self, tmp_path, on, off): + """The stash baseline is still captured: a full-file Write that keeps + a risky call from before the prompt is not reported as new.""" + repo = _repo(tmp_path) + env = {**on, **off, "CLAUDE_PROJECT_DIR": str(repo)} + (repo / "app.py").write_text(OLD + "# edited before the prompt\n") + run_hook(ups_payload(repo), env) + + _rc, out, _ = run_hook(_write_payload(repo, repo / "app.py", OLD + "print('x')\n"), env) + assert "additionalContext" not in out + _rc, out, _ = run_hook(_write_payload( + repo, repo / "app.py", OLD + "import pickle\npickle.loads(data)\n"), env) + assert "pickle" in out and "os.system" not in out + + def test_review_off_uses_the_repo_hint_without_listing(self, tmp_path, on): + repo = _repo(tmp_path) + outside = tmp_path / "not-a-repo" + outside.mkdir() + (repo / "app.py").write_text(VULN_PY) + # The hint a commit review that resolved the repo leaves behind. + with open(os.path.join(on["SECURITY_WARNINGS_STATE_DIR"], + "security_warnings_state_s1.json"), "w") as f: + json.dump({"shown_warnings": [], "repo_root_hint": str(repo)}, f) + rc, _, _ = run_hook(ups_payload(outside), {**on, "ENABLE_STOP_REVIEW": "0"}) + assert rc == 0 + assert not _listed_untracked(on) + assert _state(on).get("baseline_sha") + + def test_review_off_drops_the_snapshot_of_an_older_baseline(self, tmp_path, on): + repo = _repo(tmp_path) + run_hook(ups_payload(repo), on) + assert "untracked_at_baseline" in _state(on) + run_hook(ups_payload(repo), {**on, "ENABLE_STOP_REVIEW": "0"}) + assert "untracked_at_baseline" not in _state(on) + + +class TestTurn: + def test_review_on_reviews_only_new_untracked_files(self, tmp_path, on, stub_api): + repo = _repo(tmp_path) + (repo / "old_vuln.py").write_text(VULN_PY) + run_hook(ups_payload(repo), on) + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["skip_reason"] == 9 # empty review set + assert not _reviewed(stub_api) + + run_hook(ups_payload(repo), on) + (repo / "new_vuln.py").write_text(VULN_PY) + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["files_reviewed"] == 1 + assert _reviewed(stub_api) + + @pytest.mark.parametrize("off", OFF_SWITCHES) + def test_review_switched_back_on_at_the_next_prompt(self, tmp_path, on, stub_api, off): + """Old untracked files are not reviewed as this turn's work.""" + repo = _repo(tmp_path) + (repo / "old_vuln.py").write_text(VULN_PY) + run_hook(ups_payload(repo), {**on, **off}) + run_hook(stop_payload(repo), {**on, **off}) + + run_hook(ups_payload(repo), on) + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["skip_reason"] == 9 + assert not _reviewed(stub_api) + + def test_review_switched_back_on_after_an_interrupted_turn(self, tmp_path, on, stub_api): + """The interrupted turn's baseline is kept, so its edit is reviewed, + and the old untracked file beside it is not.""" + off = {**on, "ENABLE_STOP_REVIEW": "0"} + repo = _repo(tmp_path) + (repo / "old_vuln.py").write_text(VULN_PY) + run_hook(ups_payload(repo), off) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py"), off) # no Stop: interrupted + baseline = _state(on)["baseline_sha"] + + run_hook(ups_payload(repo), on) + assert _state(on)["baseline_sha"] == baseline + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["files_reviewed"] == 1 + assert _reviewed(stub_api) diff --git a/plugins/security-guidance/tests/test_repo_resolution.py b/plugins/security-guidance/tests/test_repo_resolution.py index 8bcf24b9..30c94a7c 100644 --- a/plugins/security-guidance/tests/test_repo_resolution.py +++ b/plugins/security-guidance/tests/test_repo_resolution.py @@ -191,6 +191,10 @@ class TestRegexes: "git -c core.editor=true -C sub commit --amend", "git --git-dir=x/.git --work-tree=x commit -m x", "git --git-dir x/.git commit -m x", + "git --no-pager commit -m x", + "git -p --no-optional-locks -c user.name=x --bare commit -m x", + 'git -c user.name="First Last" -c user.email=a@b.c commit -S -m x', + "git --git-dir='a b/.git' --namespace ns commit -m x", "cd sub && git commit -m x", "gt create -m x", ]) @@ -199,16 +203,29 @@ class TestRegexes: @pytest.mark.parametrize("cmd", [ "git push", "git -C sub push origin main", 'git -C "a b" push', - "git --work-tree x push -u origin HEAD", "gt submit", + "git --work-tree x push -u origin HEAD", "git --no-pager push", + 'git -c http.extraHeader="X-A: b" push', "git --config-env http.extraheader=TOK push", "gt submit", ]) def test_push_re(self, cmd): assert hook._GIT_PUSH_RE.search(cmd) - @pytest.mark.parametrize("cmd", ["git status", "git log --oneline", "echo commit"]) + @pytest.mark.parametrize("cmd", ["git status", "git log --oneline", "echo commit", + "git commit-graph write --reachable", "git commit-tree HEAD^{tree}", + "git log --grep commit", "git stash push", + "git log --oneline commit", "git --no-pager log --grep commit", + "git merge --no-commit topic", "git --git-dir commit status", + "git --namespace commit log", "git --help commit", + 'git -c user.name="commit status']) def test_commit_re_negative(self, cmd): assert not hook._GIT_COMMIT_RE.search(cmd) - @pytest.mark.parametrize("unit", ['-c "a"', "-c 'a'", "--no-a=b", "--a=b=c=d", "--git-dir x"]) + @pytest.mark.parametrize("cmd", ["git stash push", "git log --grep push", "git commit-graph write", + "git --no-pager stash push", "git --no-pager log push"]) + def test_push_re_negative(self, cmd): + assert not hook._GIT_PUSH_RE.search(cmd) + + @pytest.mark.parametrize("unit", ['-c "a"', "-c 'a'", "--no-a=b", "--a=b=c=d", "--git-dir x", + "--no-pager", "-p", '-c a="b c"', "--namespace x"]) @pytest.mark.parametrize("regex,verb", [("_GIT_COMMIT_RE", "commit"), ("_GIT_PUSH_RE", "push")]) def test_global_option_prefix_is_linear(self, regex, verb, unit): cre = getattr(hook, regex) @@ -228,11 +245,19 @@ class TestHooksJson: assert stop["command"].endswith('security_reminder_hook.py"') assert stop["asyncRewake"] is True bash = [g for g in cfg["hooks"]["PostToolUse"] if g.get("matcher") == "Bash"][0] - ifs = {h.get("if") for h in bash["hooks"]} - assert {"Bash(git commit:*)", "Bash(git push:*)", "Bash(git -C * commit *)", - "Bash(git -C * push*)", "Bash(gt create:*)", "Bash(gt modify:*)", - "Bash(gt submit:*)"} <= ifs - + # One entry per kind, not per spelling: when Claude Code cannot parse + # a command it runs every entry, so each extra entry is one more process. + assert [h.get("if") for h in bash["hooks"]] == [ + "Bash(git*commit*)", "Bash(git*push*)", "Bash(gt *)"] + assert all(h["asyncRewake"] is True and h["rewakeMessage"] for h in bash["hooks"]) + + @pytest.mark.parametrize("cmd", ["git stash push", "git commit-graph write --reachable", + "git log --grep commit", "gt log"]) + def test_other_commands_the_if_patterns_let_through_do_nothing(self, workspace, hook_env, stub_api, cmd): + ws, repo = workspace + commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, cmd, ""), hook_env) + assert rc == 0 and so.strip() == "" and not stub_api.calls def _read_state(env): diff --git a/plugins/security-guidance/tests/test_review_outcomes.py b/plugins/security-guidance/tests/test_review_outcomes.py new file mode 100644 index 00000000..887ff9c0 --- /dev/null +++ b/plugins/security-guidance/tests/test_review_outcomes.py @@ -0,0 +1,298 @@ +"""A review that got no verdict is never reported as clean.""" +import json +import time + +import pytest + +from conftest import ( + STUB_VULN, VULN_PY, bash_payload, commit_file, edit_payload, git, + metrics_of, run_hook, stop_payload, ups_payload, +) + +import llm +import security_reminder_hook as hook + + +def _reviewed(repo): + p = repo / ".git" / "sg-reviewed-shas" + return p.read_text() if p.exists() else "" + + +def _rewake_body(stdout, stderr): + """What Claude Code shows Claude for an exit-2 asyncRewake hook: stderr, + else stdout.""" + return stderr or stdout + + +def _commit(repo, env, content=VULN_PY, session_id="s1"): + sha, out = commit_file(repo, "app.py", content) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out, + session_id=session_id), env) + return sha, rc, so, se + + +class TestFailedReviewIsNotClean: + def test_commit_left_unreviewed_and_user_told(self, env, gateway, workspace): + _, repo = workspace + gateway.status = 401 + sha, rc, so, se = _commit(repo, env) + m = metrics_of(so) + assert m["review_failed"] is True and m["api_error"] == 401 and m["vulns_found"] == 0 + assert sha not in _reviewed(repo) + assert rc == 2 + body = _rewake_body(so, se) + assert ("The security review of this commit did not complete: " + "the API rejected the plugin's credentials (HTTP 401).") in body + assert "ANTHROPIC_CUSTOM_HEADERS" in body # ANTHROPIC_BASE_URL is set + assert "If it is pushed later from Claude Code, the push review will check it." in body + assert "log.txt" in body + summary = json.loads(so.strip().splitlines()[-1])["rewakeSummary"] + assert summary.startswith("Commit security review did not complete: " + "the API rejected the plugin's credentials (HTTP 401). Log: ") + + def test_commit_pushed_by_the_same_command(self, env, gateway, workspace): + """The push hook does not run for `git commit && git push`, so no later + push review covers this commit.""" + _, repo = workspace + gateway.status = 401 + sha, out = commit_file(repo, "app.py", VULN_PY) + out += f"To /srv/remote.git\n 1111111..{sha[:7]} main -> main\n" + rc, so, se = run_hook(bash_payload(repo, "git commit -m change && git push", out), env) + assert rc == 2 + assert "The same command pushed it, so a later push will not re-check it." in se + assert "If it is pushed later" not in se + + @pytest.mark.parametrize("command", [ + 'git commit -m "retry git push on 403"', # push only in the message + "git commit -m change && git push", # push rejected or output hidden + ]) + def test_push_in_the_command_without_push_output(self, env, gateway, workspace, command): + _, repo = workspace + gateway.status = 401 + sha, out = commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, command, out), env) + assert rc == 2 + assert "The same command pushed it" not in se + assert ("If the same command pushed it, a later push will not re-check it; " + "otherwise a later push from Claude Code will.") in se + + def test_told_once_per_session_for_each_kind_of_failure(self, env, gateway, workspace): + _, repo = workspace + gateway.status = 401 + _commit(repo, env) + sha2, rc, so, se = _commit(repo, env, VULN_PY + "# 2\n") + assert rc == 0 and se == "" + assert metrics_of(so)["review_failed"] is True + assert sha2 not in _reviewed(repo) + gateway.status = 503 # a different kind of failure is still told + sha3, rc, so, se = _commit(repo, env, VULN_PY + "# 3\n") + assert rc == 2 and "busy or unavailable (HTTP 503)" in se + assert sha3 not in _reviewed(repo) + + def test_unreadable_reply_is_a_failed_review(self, env, gateway, workspace): + _, repo = workspace + gateway.reply = "I can't help with that." + sha, rc, so, se = _commit(repo, env) + assert metrics_of(so)["review_failed"] is True + assert sha not in _reviewed(repo) + + def test_reply_without_the_verdict_flag_is_a_failed_review(self, env, gateway, workspace): + _, repo = workspace + gateway.reply = json.dumps({"findings": []}) + sha, rc, so, se = _commit(repo, env) + assert metrics_of(so)["review_failed"] is True + assert sha not in _reviewed(repo) + + def test_unexpected_error_in_the_call_is_a_failed_review(self, monkeypatch): + def boom(*a, **k): + raise ConnectionResetError("dropped") + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) + monkeypatch.setattr(llm, "_call_claude_dual_or", boom) + assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, []) + assert llm.last_review_failed() + + def test_pushed_commit_is_told_after_an_unpushed_one(self, env, gateway, workspace): + _, repo = workspace + gateway.status = 401 + _commit(repo, env) + sha, out = commit_file(repo, "app.py", VULN_PY + "# 2\n") + out += "To github.com:o/r.git\n 1111111..2222222 main -> main\n" + rc, so, se = run_hook(bash_payload(repo, "git commit -am x && git push", out), env) + assert rc == 2 and "The same command pushed it" in se + + def test_clean_review_still_marks_the_commit(self, env, gateway, workspace): + _, repo = workspace + sha, rc, so, se = _commit(repo, env) + m = metrics_of(so) + assert rc == 0 and "review_failed" not in m and m["vulns_found"] == 0 + assert sha in _reviewed(repo) + + def test_push_sweep_leaves_the_range_unreviewed(self, env, gateway, workspace, tmp_path): + """Also told after a commit review failed the same way: a failed push + review is not re-checked later, so it has its own notice.""" + ws, repo = workspace + remote = tmp_path / "remote.git" + git(ws, "init", "-q", "--bare", str(remote)) + git(repo, "remote", "add", "origin", str(remote)) + git(repo, "push", "-q", "-u", "origin", "main") + base = git(repo, "rev-parse", "HEAD").strip() + gateway.status = 401 + sha, rc, so, se = _commit(repo, env) + assert rc == 2 + git(repo, "push", "-q", "origin", "main") + push_stdout = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n" + rc, so, se = run_hook(bash_payload(repo, "git push origin main", push_stdout), env) + m = metrics_of(so) + assert m["push_sweep"] is True and m["review_failed"] is True, m + assert sha not in _reviewed(repo) + assert rc == 2 + assert "The security review of this push did not complete" in se + assert ("It was for the pushed commits not already reviewed when they were " + "committed, and a later push will not re-check them.") in se + + def test_subagent_review_failure_keeps_the_diff_unreviewed(self, env, gateway, workspace): + """A SubagentStop review that finds nothing records its diff as + reviewed; one that got no verdict must not, or it is never retried.""" + _, repo = workspace + gateway.reply = "not json" + run_hook(ups_payload(repo), env) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env) + rc, so, se = run_hook(stop_payload(repo, event="SubagentStop"), env) + assert rc == 0, (so, se) + gateway.reply, gateway.vulns = None, [STUB_VULN] + rc, so, se = run_hook(stop_payload(repo, event="SubagentStop"), env) + assert rc == 2 and "command_injection" in se, (so, se) + + @pytest.fixture + def race(self, monkeypatch): + """Runs the race with the fallback starting at once; agentic_review + and the single-shot review are stand-ins.""" + calls = [] + monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0") + monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False) + + def failing_single_shot(*a, **k): + calls.append("single_shot") + llm._review_status.failed = True + return None, [] + + monkeypatch.setattr(hook, "analyze_code_security", failing_single_shot) + + def run(agentic): + monkeypatch.setattr(hook, "agentic_review", agentic) + llm._review_status.failed = False + result = hook._agentic_review_with_race("/nonexistent", [("a.py", "+x")], ["a.py"], []) + assert llm.last_review_failed() is False # the flag stays on its own thread + return result + run.calls = calls + return run + + def test_failed_fallback_waits_for_agentic(self, race): + """Direct calls can fail where the agentic reviewer's CLI works (it + may hold a credential the direct calls lack); its verdict must count.""" + def slow_agentic(*a, **k): + time.sleep(1) + return None, [], {"agentic": True} + + g, v, m = race(slow_agentic) + assert m["race_winner"] == 1 and not m.get("review_failed") + + def test_both_failing_reports_the_fallback_once(self, race): + def failing_agentic(*a, **k): + time.sleep(1) + return None, [], {"agentic_fallback": "investigate:ProcessError"} + + g, v, m = race(failing_agentic) + assert m["race_winner"] == 2 and m["review_failed"] is True + assert "agentic_fallback" not in m # the caller must not rerun it + assert race.calls == ["single_shot"] + + def test_no_fallback_after_agentic_finished(self, race, monkeypatch): + """Once agentic has answered, the delayed fallback never starts, even + after the caller has taken agentic's result off the queue.""" + monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "1") + + def quick_failing_agentic(*a, **k): + return None, [], {"agentic_fallback": "investigate:ProcessError"} + + g, v, m = race(quick_failing_agentic) + assert m["race_winner"] == 1 + time.sleep(1.5) + assert race.calls == [] + + def test_agentic_failing_while_the_fallback_overruns(self, race, monkeypatch): + """Past the deadline the race reports no verdict instead of letting the + caller start yet another review.""" + monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 2) + + def slow_single_shot(*a, **k): + race.calls.append("single_shot") + time.sleep(10) + return None, [] + + monkeypatch.setattr(hook, "analyze_code_security", slow_single_shot) + + def failing_agentic(*a, **k): + time.sleep(0.5) + return None, [], {"agentic_fallback": "investigate:ProcessError"} + + t0 = time.monotonic() + g, v, m = race(failing_agentic) + assert time.monotonic() - t0 < 5 + assert m["review_failed"] is True and m["api_error"] == hook._RACE_TIMED_OUT + assert "agentic_fallback" not in m + assert hook._review_failure_reason(m["api_error"])[1] == "the review did not finish in time" + + def test_failed_fallback_stops_waiting_at_the_deadline(self, race, monkeypatch): + monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 1) + + def hung_agentic(*a, **k): + time.sleep(30) + + g, v, m = race(hung_agentic) + assert m["race_winner"] == 2 and m["review_failed"] is True + + +class TestFailureReason: + @pytest.mark.parametrize("status,failure,reason", [ + (401, "auth", "the API rejected the plugin's credentials (HTTP 401)"), + (403, "auth", "the API refused access (HTTP 403)"), + (529, "busy", "the API was busy or unavailable (HTTP 529)"), + (-1, "network", "the model could not be reached (network error or timeout)"), + (404, "request", "the API refused the request (HTTP 404)"), + (None, "reply", "the model's reply could not be read"), + ]) + def test_first_party(self, monkeypatch, status, failure, reason): + for var in llm._PROVIDER_ENV_VARS: + monkeypatch.delenv(var, raising=False) + assert hook._review_failure_reason(status)[:2] == (failure, reason) + + def test_cloud_provider(self, monkeypatch): + monkeypatch.setenv("CLAUDE_CODE_USE_BEDROCK", "1") + for status in (-1, None): + assert hook._review_failure_reason(status)[:2] == ( + "provider", "the review through the cloud provider got no answer") + + def test_causes_name_only_settings_in_use(self, monkeypatch): + for var in llm._PROVIDER_ENV_VARS: + monkeypatch.delenv(var, raising=False) + monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False) + monkeypatch.delenv("SECURITY_REVIEW_MODEL", raising=False) + assert "ANTHROPIC_CUSTOM_HEADERS" not in hook._review_failure_reason(401)[2] + assert hook._review_failure_reason(404)[2] == "" + monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://gateway") + monkeypatch.setenv("SECURITY_REVIEW_MODEL", "claude-x") + assert "ANTHROPIC_CUSTOM_HEADERS" in hook._review_failure_reason(401)[2] + assert "SECURITY_REVIEW_MODEL (claude-x)" in hook._review_failure_reason(404)[2] + + +class TestAgenticReviewerOn: + def test_failed_review_is_not_clean(self, agentic_env, gateway, workspace): + _, repo = workspace + gateway.status = 401 + sha, rc, so, se = _commit(repo, agentic_env) + m = metrics_of(so) + assert m["review_failed"] is True and m["agentic_fallback"] == 2, m + assert sha not in _reviewed(repo) + assert rc == 2 and "HTTP 401" in se diff --git a/plugins/security-guidance/tests/test_review_usage_log.py b/plugins/security-guidance/tests/test_review_usage_log.py new file mode 100644 index 00000000..bca87d51 --- /dev/null +++ b/plugins/security-guidance/tests/test_review_usage_log.py @@ -0,0 +1,116 @@ +"""Each LLM review leaves one usage line in the plugin's debug log.""" +import re + +from conftest import ( + VULN_PY, bash_payload, commit_file, edit_payload, git, metrics_of, run_hook, + stop_payload, ups_payload, +) + +USAGE = re.compile( + r"Review usage: review=(\w+) session=(\S+) model=(\S+) calls=(\d+) " + r"in=(\d+) out=(\d+) cache_read=(\d+) cache_write=(\d+) est_cost_usd=(\d+\.\d{4}~?)$" +) + + +def _usage_lines(env): + log = env["SECURITY_GUIDANCE_DEBUG_LOG"] + try: + text = open(log).read() + except FileNotFoundError: + return [] + return [m.groups() for m in map(USAGE.search, text.splitlines()) if m] + + +def _env(hook_env, tmp_path): + return {**hook_env, "SECURITY_GUIDANCE_DEBUG_LOG": str(tmp_path / "log.txt"), + "SECURITY_REVIEW_MODEL": "claude-opus-5-5"} + + +def test_stop_review_logs_its_usage_with_the_session(workspace, hook_env, tmp_path): + _, repo = workspace + env = _env(hook_env, tmp_path) + run_hook(ups_payload(repo, session_id="sess-1"), env) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py", VULN_PY, session_id="sess-1"), env) + assert _usage_lines(env) == [] + rc, so, _ = run_hook(stop_payload(repo, session_id="sess-1"), env) + + m = metrics_of(so) + assert m["api_calls"] == 1 + # "stub" is not in the price table, so the estimate is marked. + assert _usage_lines(env) == [ + ("stop", "sess-1", "stub", "1", "1", "1", "0", "0", f"{m['cost_usd']:.4f}~"), + ] + + +def test_commit_review_logs_review_commit(workspace, hook_env, tmp_path): + _, repo = workspace + env = _env(hook_env, tmp_path) + _, out = commit_file(repo, "app.py", VULN_PY) + run_hook(bash_payload(repo, "git commit -m change", out, session_id="sess 2/x"), env) + + lines = _usage_lines(env) + assert len(lines) == 1 + assert lines[0][:2] == ("commit", "sess_2_x") and lines[0][3] == "1" + + +def test_no_line_when_no_review_ran(workspace, hook_env, tmp_path): + _, repo = workspace + env = _env(hook_env, tmp_path) + run_hook(ups_payload(repo), env) + run_hook(stop_payload(repo), env) + assert _usage_lines(env) == [] + + +def test_failed_request_logs_no_usage(workspace, hook_env, stub_api, tmp_path): + _, repo = workspace + env = _env(hook_env, tmp_path) + stub_api.status = 400 + _, out = commit_file(repo, "app.py", VULN_PY) + run_hook(bash_payload(repo, "git commit -m change", out), env) + assert _usage_lines(env) == [] + + +def test_push_review_logs_review_push(workspace, hook_env, tmp_path): + _, repo = workspace + env = _env(hook_env, tmp_path) + remote = tmp_path / "remote.git" + git(tmp_path, "init", "-q", "--bare", str(remote)) + git(repo, "remote", "add", "origin", str(remote)) + git(repo, "push", "-q", "-u", "origin", "main") + base = git(repo, "rev-parse", "HEAD").strip() + sha, _ = commit_file(repo, "app.py", VULN_PY) + git(repo, "push", "-q", "origin", "main") + out = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n" + run_hook(bash_payload(repo, "git push origin main", out), env) + + lines = _usage_lines(env) + assert len(lines) == 1 and lines[0][0] == "push" + + +def test_line_carries_the_same_numbers_as_the_metrics(tmp_path, monkeypatch): + import _base + logged = [] + monkeypatch.setattr(_base, "debug_log", logged.append) + monkeypatch.setattr(_base, "_USAGE", { + "in": 0, "out": 0, "cr": 0, "cw": 0, "cost": 0.0, "n": 0, + "http_err_last": 0, "http_err_count": 0, "models": [], "default_priced": False, + }) + monkeypatch.setattr(_base, "_USAGE_CONTEXT", {"session_id": "abc", "review": "stop"}) + _base._log_usage(_base._usage_metrics()) + assert logged == [] + + _base._record_usage({"input_tokens": 31994, "output_tokens": 3250, + "cache_read_input_tokens": 7, "cache_creation_input_tokens": 9}, + "claude-opus-5-5") + _base._record_usage({"input_tokens": 1, "output_tokens": 1}, "opus", cost_usd=0.5) + _base._record_usage({"input_tokens": 1, "output_tokens": 1}, + "bad model\nReview usage: forged") + usage = _base._usage_metrics() + _base._log_usage(usage) + assert logged == [ + "Review usage: review=stop session=abc " + "model=claude-opus-5-5,opus,bad_model_Review_usage:_forged calls=3 " + f"in=31996 out=3252 cache_read=7 cache_write=9 est_cost_usd={usage['cost_usd']:.4f}~" + ] + assert usage["cost_usd"] > 0.69 diff --git a/plugins/security-guidance/tests/test_reviewer_context_metrics.py b/plugins/security-guidance/tests/test_reviewer_context_metrics.py new file mode 100644 index 00000000..c0dfb491 --- /dev/null +++ b/plugins/security-guidance/tests/test_reviewer_context_metrics.py @@ -0,0 +1,178 @@ +"""The agentic reviewer reports, as counts only, how its Read/Grep/Glob calls +went and whether the directory it ran in was still there.""" +import json +import os +import shutil +import sys +import types + +import pytest + +import llm +import security_reminder_hook as hook + + +class _ToolUse: + def __init__(self, id, name): + self.id, self.name, self.input = id, name, {} + + +class _ToolResult: + def __init__(self, tool_use_id, is_error=None): + self.tool_use_id, self.is_error, self.content = tool_use_id, is_error, "" + + +@pytest.fixture +def sdk(monkeypatch, tmp_path): + """Stand-in for claude_agent_sdk whose reviewer replays `script.messages` + and then returns no findings. Like the SDK, it cannot start in a + directory that does not exist.""" + script = types.SimpleNamespace(messages=[], before_result=lambda: None) + + class ClaudeAgentOptions: + def __init__(self, **kwargs): + self.kwargs = kwargs + + class AssistantMessage: + def __init__(self, *content): + self.content = list(content) + + class UserMessage: + def __init__(self, content): + self.content = content + + class ResultMessage: + subtype, usage, total_cost_usd = "success", {}, 0.0 + structured_output = {"findings": []} + + async def query(prompt, options): + if not os.path.isdir(options.kwargs["cwd"]): + raise RuntimeError("Working directory does not exist") + for m in script.messages: + yield m + script.before_result() + yield ResultMessage() + + mod = types.ModuleType("claude_agent_sdk") + mod.ClaudeAgentOptions, mod.ResultMessage, mod.query = ClaudeAgentOptions, ResultMessage, query + mod.AssistantMessage = AssistantMessage + monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "") + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + for var in ("SG_AGENTIC_CONTEXT_DIR", "SG_AGENTIC_DEBUG_DIR", "SG_AGENTIC_MODEL"): + monkeypatch.delenv(var, raising=False) + script.assistant, script.user = AssistantMessage, UserMessage + return script + + +def _review(repo): + return llm.agentic_review(str(repo), [("a.py", "+x = 1\n")], ["a.py"])[2] + + +class TestAgenticReview: + def test_clean_review_counts_calls_and_no_errors(self, sdk, tmp_path): + sdk.messages = [sdk.assistant(_ToolUse("t1", "Read")), + sdk.user([_ToolResult("t1", is_error=False)])] + m = _review(tmp_path) + assert m["rv_tool_calls"] == 1 + assert "rv_tool_err" not in m and "rv_cwd_gone" not in m + + def test_errored_file_tool_results_are_counted(self, sdk, tmp_path): + sdk.messages = [ + sdk.assistant(_ToolUse("t1", "Read")), + sdk.user([_ToolResult("t1", is_error=True)]), + sdk.assistant(_ToolUse("t2", "Glob"), _ToolUse("t3", "Grep")), + sdk.user([_ToolResult("t2", is_error=True), _ToolResult("t3", is_error=False)]), + sdk.user("plain text"), + ] + m = _review(tmp_path) + assert (m["rv_tool_calls"], m["rv_tool_err"]) == (3, 2) + + def test_other_tools_are_not_counted(self, sdk, tmp_path): + # A rejected structured-output attempt or a denied tool is not a + # sign of missing context. + sdk.messages = [ + sdk.assistant(_ToolUse("t1", "StructuredOutput"), _ToolUse("t2", "Bash")), + sdk.user([_ToolResult("t1", is_error=True), _ToolResult("t2", is_error=True)]), + ] + m = _review(tmp_path) + assert "rv_tool_calls" not in m and "rv_tool_err" not in m + + def test_directory_missing_before_the_review(self, sdk, tmp_path): + m = _review(tmp_path / "removed") + assert m["agentic_fallback"].startswith("investigate:") + assert m["rv_cwd_gone"] == 1 + + def test_directory_removed_during_the_review(self, sdk, tmp_path): + repo = tmp_path / "wt" + repo.mkdir() + sdk.messages = [sdk.assistant(_ToolUse("t1", "Read")), + sdk.user([_ToolResult("t1", is_error=True)])] + sdk.before_result = lambda: shutil.rmtree(repo) + m = _review(repo) + assert (m["rv_cwd_gone"], m["rv_tool_err"]) == (2, 1) + + def test_counts_survive_a_failed_investigate(self, sdk, tmp_path, monkeypatch): + async def query(prompt, options): + yield sdk.assistant(_ToolUse("t1", "Read")) + yield sdk.user([_ToolResult("t1", is_error=True)]) + raise RuntimeError("inner CLI exited") + + monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query) + m = _review(tmp_path) + assert m["agentic_fallback"].startswith("investigate:") + assert (m["rv_tool_calls"], m["rv_tool_err"]) == (1, 1) + + +class TestEmittedRow: + @pytest.fixture(autouse=True) + def _clean_tail(self, monkeypatch): + monkeypatch.setattr(hook, "_TAIL_METRICS", {}) + + def _row(self, capsys): + return json.loads(capsys.readouterr().out)["metrics"] + + def test_context_keys_come_last_in_priority_order(self, capsys): + hook._note_reviewer_context( + {"rv_tool_calls": 4, "rv_tool_err": 2, "rv_cwd_gone": 2, "investigate_turns": 5}) + hook.emit_metrics({"vulns_found": 0, "review_ms": 10}) + keys = list(self._row(capsys)) + assert keys[-5:] == ["vulns_found", "review_ms", "rv_cwd_gone", "rv_tool_err", "rv_tool_calls"] + + def test_zero_or_absent_keys_are_left_out(self, capsys): + hook._note_reviewer_context({"rv_tool_calls": 3, "rv_tool_err": 0}) + hook.emit_metrics({"vulns_found": 0}) + row = self._row(capsys) + assert row["rv_tool_calls"] == 3 + assert "rv_tool_err" not in row and "rv_cwd_gone" not in row + + def test_failed_review_row_keeps_vulns_found_ahead_of_context_keys(self, capsys): + hook._note_reviewer_context({"rv_cwd_gone": 1}) + with pytest.raises(SystemExit): + hook._exit_review_failed("Commit", "s1", {"files_reviewed": 1}, 500) + keys = list(self._row(capsys)) + assert keys.index("vulns_found") < keys.index("rv_cwd_gone") == len(keys) - 1 + + +class TestRace: + def test_context_kept_when_the_fallback_result_replaces_a_failed_agentic_run(self, monkeypatch): + import time + + def agentic(*a): + time.sleep(0.3) # fails after the fallback has started + return None, [], {"agentic_fallback": "investigate:RuntimeError", + "rv_cwd_gone": 2, "rv_tool_err": 4, "rv_tool_calls": 5} + + monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0") + monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False) + monkeypatch.setattr(hook, "agentic_review", agentic) + + def single_shot(*a, **k): + time.sleep(0.6) + return None, [] + + monkeypatch.setattr(hook, "analyze_code_security", single_shot) + monkeypatch.setattr(hook.llm, "last_review_failed", lambda: False) + _, _, m = hook._agentic_review_with_race("/nonexistent", [("a.py", "+x")], ["a.py"], []) + assert m["race_winner"] == 2 and m["agentic"] is False + assert (m["rv_cwd_gone"], m["rv_tool_err"], m["rv_tool_calls"]) == (2, 4, 5) diff --git a/plugins/security-guidance/tests/test_reviewer_tools.py b/plugins/security-guidance/tests/test_reviewer_tools.py new file mode 100644 index 00000000..3e2aa86c --- /dev/null +++ b/plugins/security-guidance/tests/test_reviewer_tools.py @@ -0,0 +1,84 @@ +"""The inner Claude Code the plugin starts for a review gets only the tools +the review needs.""" +import sys +import types + +import pytest + +import llm + +READ_ONLY = {"tools": "Read,Grep,Glob", "strict-mcp-config": None} +NO_TOOLS = {"tools": "", "strict-mcp-config": None} + + +def test_tool_flags(): + assert llm._only_tools_args(("Read", "Grep", "Glob")) == READ_ONLY + assert llm._only_tools_args() == NO_TOOLS + + +def test_flags_reach_the_command_line_of_the_installed_sdk(): + sdk = pytest.importorskip("claude_agent_sdk") + transport = pytest.importorskip( + "claude_agent_sdk._internal.transport.subprocess_cli") + opts = sdk.ClaudeAgentOptions( + cli_path="claude", allowed_tools=["Read", "Grep", "Glob"], + extra_args=llm._only_tools_args(llm._REVIEWER_TOOLS)) + cmd = transport.SubprocessCLITransport(prompt="x", options=opts)._build_command() + assert cmd[cmd.index("--tools") + 1] == "Read,Grep,Glob" + assert cmd.count("--tools") == 1 and "--strict-mcp-config" in cmd + + +@pytest.fixture +def sdk(monkeypatch, tmp_path): + """Stand-in for claude_agent_sdk that records each spawn's options. The + first agentic stage reports one finding, later stages keep it.""" + spawned = [] + + class ClaudeAgentOptions: + def __init__(self, **kwargs): + self.kwargs = kwargs + + class ResultMessage: + subtype, usage, total_cost_usd = "success", {}, 0.0 + + def __init__(self, structured_output): + self.structured_output = structured_output + + async def query(prompt, options): + spawned.append(options.kwargs) + if len(spawned) == 1: + yield ResultMessage({"hasVulnerabilities": False, "vulnerabilities": [], + "findings": [{ + "filePath": "a.py", "category": "c", "vulnerableCode": "x = 1", + "explanation": "e", "fix": "f", "severity": "high"}]}) + else: + yield ResultMessage({"findings": [], "survived": [0]}) + + mod = types.ModuleType("claude_agent_sdk") + mod.ClaudeAgentOptions, mod.ResultMessage, mod.query = ClaudeAgentOptions, ResultMessage, query + mod.AssistantMessage = type("AssistantMessage", (), {}) + monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "") + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + for var in ("CONTEXT_DIR", "DEBUG_DIR", "MODEL", "ITER2", "FILTER", "NO_ADJUDICATE", + "DIFF_INTERSECT", "EXCLUDE_MEDIUM", "MAX_TURNS"): + monkeypatch.delenv("SG_AGENTIC_" + var, raising=False) + return spawned + + +def test_every_agentic_stage_gets_only_the_read_tools(sdk, tmp_path): + _, vulns, _ = llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + assert len(vulns) == 1 + # investigate, second investigate pass, refute + assert len(sdk) == 3 + for opts in sdk: + assert opts["extra_args"] == READ_ONLY + assert opts["allowed_tools"] == ["Read", "Grep", "Glob"] + assert "permission_mode" not in opts + + +def test_single_turn_sdk_review_gets_no_tools(sdk): + schema = {"type": "object", "properties": {}} + assert llm._call_claude_via_sdk("review this", schema) is not None + assert len(sdk) == 1 + assert sdk[0]["extra_args"] == NO_TOOLS and sdk[0]["allowed_tools"] == [] diff --git a/plugins/security-guidance/tests/test_secret_shaped_paths.py b/plugins/security-guidance/tests/test_secret_shaped_paths.py new file mode 100644 index 00000000..bfd5180d --- /dev/null +++ b/plugins/security-guidance/tests/test_secret_shaped_paths.py @@ -0,0 +1,95 @@ +import os +import subprocess + +import pytest + +from conftest import ( + GIT_ENV, git, make_repo, metrics_of, run_hook, stop_payload, ups_payload, +) + +import gitutil + + +@pytest.mark.parametrize("path", [ + "dot_config/private_example/encrypted_private_token", + "encrypted_private_dot_netrc", + "home/encrypted_config.yaml", + "id_ed25519", + ".ssh/id_rsa", + "private_dot_ssh/private_id_ecdsa", + "deploy_rsa", + "keys/github_ed25519", + ".env.production.json", + ".env.local.yaml", + "config/dot_env.toml", + "private_dot_netrc", + "dot_aws/credentials", + "Deploy_RSA", +]) +def test_secret_shaped_names_are_not_reviewable(path): + assert gitutil._is_secret_shaped(path) + assert not gitutil._is_reviewable_source(path) + + +@pytest.mark.parametrize("path", [ + "src/private_api.py", + "src/id_generator.py", + "lib/encrypted_store.py", + "crypto/rsa.py", + "auth/sign_rsa.go", + "app/credentials.py", + "scripts/run_migrations.sh", + "dot_product.py", + "config/environment.json", + "bin/deploy", + "Dockerfile.dev", + "executable_backup.sh", +]) +def test_ordinary_source_stays_reviewable(path): + assert not gitutil._is_secret_shaped(path) + assert gitutil._is_reviewable_source(path) + + +def _staged_diff(repo): + r = subprocess.run( + [*gitutil.GIT_CMD, "diff", "--cached", "--no-color", "-M"], cwd=repo, + capture_output=True, env={**os.environ, **GIT_ENV}, + ) + assert r.returncode == 0, r.stderr + return r.stdout.decode("utf-8", errors="replace") + + +def test_secret_content_is_left_out_of_the_parsed_diff(tmp_path): + repo = make_repo(tmp_path / "repo") + (repo / "encrypted_private_token").write_text("CIPHERTEXT_BODY\n") + (repo / "id_ed25519").write_text("PRIVATE_KEY_BODY\n") + (repo / ".env.production.json").write_text('{"API_KEY": "ENV_SECRET_BODY"}\n') + (repo / "app.py").write_text("import os\nos.system(input())\n") + git(repo, "add", "-A") + diff = _staged_diff(repo) + parsed = gitutil.parse_diff_into_files(diff) + assert [p for p, _ in parsed] == ["app.py"] + assert "_BODY" not in "".join(c for _, c in parsed) + assert gitutil.extract_file_paths_from_diff(diff) == ["app.py"] + + +def test_rename_away_from_a_secret_name_is_left_out(tmp_path): + body = "".join(f"KEY_{i}=SECRET_VALUE_{i}\n" for i in range(30)) + repo = make_repo(tmp_path / "repo", {"deploy_rsa": body}) + git(repo, "mv", "deploy_rsa", "notes.sh") + (repo / "notes.sh").write_text(body + "KEY_NEW=SECRET_VALUE_NEW\n") + git(repo, "add", "-A") + diff = _staged_diff(repo) + assert "rename from deploy_rsa" in diff + assert gitutil.parse_diff_into_files(diff) == [] + assert gitutil.extract_file_paths_from_diff(diff) == [] + + +def test_stop_hook_reports_how_many_files_it_left_out(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo") + run_hook(ups_payload(repo), hook_env) + (repo / "id_ed25519").write_text("-----BEGIN OPENSSH PRIVATE KEY-----\n") + (repo / ".env.local").write_text("TOKEN=abc\n") + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + assert metrics_of(stdout).get("secret_shaped_skipped") == 2 + assert stub_api.calls == [] diff --git a/plugins/security-guidance/tests/test_state_file.py b/plugins/security-guidance/tests/test_state_file.py new file mode 100644 index 00000000..0d3a56b0 --- /dev/null +++ b/plugins/security-guidance/tests/test_state_file.py @@ -0,0 +1,197 @@ +import json +import os +import signal +import subprocess +import sys +import time + +import pytest + +from conftest import HOOKS_DIR, make_repo, metrics_of, run_hook, stop_payload, ups_payload + +import session_state as ss + + +@pytest.fixture +def state_dir(tmp_path, monkeypatch): + d = tmp_path / "state" + d.mkdir() + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d)) + monkeypatch.delenv("CLAUDE_CODE_REMOTE_SESSION_ID", raising=False) + # Keep the legacy lock-file sweep and the debug log out of the real home. + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setattr(ss, "debug_log", lambda _msg: None) + return d + + +def _seed(session_id="s1"): + ss.with_locked_state(session_id, lambda st: st.update( + baseline_sha="a" * 40, touched_paths=["x.py"], + untracked_at_baseline={f"dir/file_{i:05d}.py": i for i in range(1500)})) + + +def _on_disk(state_dir, session_id="s1"): + return json.loads((state_dir / f"security_warnings_state_{session_id}.json").read_text()) + + +def _leftovers(state_dir): + return sorted(p.name for p in state_dir.iterdir() if p.name.endswith(".tmp")) + + +_MARK_ONE = ( + "import sys; sys.path.insert(0, sys.argv[1]); import session_state as s; " + "s.with_locked_state('s1', lambda st: st['shown_warnings'].append(sys.argv[2]))" +) + +# A save that dies half-way through writing, as a hook killed on timeout does. +_KILLED_MID_SAVE = """ +import json, os, signal, sys +sys.path.insert(0, sys.argv[1]) +import session_state as s +def dump(obj, f, **kw): + data = json.dumps(obj) + f.write(data[:len(data) // 2]); f.flush() + os.kill(os.getpid(), signal.SIGKILL) +s.json.dump = dump +s.with_locked_state('s1', lambda st: st['touched_paths'].append('y.py')) +""" + + +@pytest.mark.skipif(os.name == "nt", reason="rename into place is not used on Windows") +class TestSaveIsAtomic: + def test_a_save_killed_part_way_keeps_the_previous_state(self, state_dir): + _seed() + r = subprocess.run([sys.executable, "-c", _KILLED_MID_SAVE, str(HOOKS_DIR)], + env=dict(os.environ)) + assert r.returncode == -signal.SIGKILL + state = ss.load_state("s1") + assert state["baseline_sha"] == "a" * 40 + assert state["touched_paths"] == ["x.py"] + assert len(state["untracked_at_baseline"]) == 1500 + assert "state_resets" not in state + + def test_no_temporary_file_is_left_behind(self, state_dir): + _seed() + ss.with_locked_state("s1", lambda st: st["touched_paths"].append("y.py")) + assert _on_disk(state_dir)["touched_paths"] == ["x.py", "y.py"] + assert _leftovers(state_dir) == [] + + def test_state_that_cannot_be_written_leaves_the_file_alone(self, state_dir): + _seed() + with pytest.raises(TypeError): + ss.save_state("s1", {"shown_warnings": [], "bad": object()}) + assert _on_disk(state_dir)["baseline_sha"] == "a" * 40 + assert _leftovers(state_dir) == [] + + def test_writes_in_place_where_the_directory_refuses_a_rename(self, state_dir, monkeypatch): + _seed() + + def refuse(_src, _dst): + raise PermissionError("rename refused") + monkeypatch.setattr(ss.os, "replace", refuse) + ss.with_locked_state("s1", lambda st: st["touched_paths"].append("y.py")) + assert _on_disk(state_dir)["touched_paths"] == ["x.py", "y.py"] + assert _leftovers(state_dir) == [] + + def test_a_full_disk_leaves_the_previous_state(self, state_dir, monkeypatch): + _seed() + + def full(_obj, f, **_kw): + f.write('{"shown_warn') + raise OSError(28, "No space left on device") + monkeypatch.setattr(ss.json, "dump", full) + ss.save_state("s1", {"shown_warnings": []}) + assert _on_disk(state_dir)["baseline_sha"] == "a" * 40 + assert _leftovers(state_dir) == [] + + def test_in_place_where_rename_is_not_used(self, state_dir, monkeypatch): + monkeypatch.setattr(ss, "_RENAME_INTO_PLACE", False) + monkeypatch.setattr(ss.os, "replace", lambda *_a: pytest.fail("renamed")) + _seed() + assert _on_disk(state_dir)["touched_paths"] == ["x.py"] + + +@pytest.mark.skipif(ss.fcntl is None, reason="needs file locking") +def test_concurrent_writers_all_land(state_dir): + """Eight hooks marking one warning each at the same moment keep all eight.""" + for _round in range(5): + (state_dir / "security_warnings_state_s1.json").unlink(missing_ok=True) + procs = [subprocess.Popen([sys.executable, "-c", _MARK_ONE, str(HOOKS_DIR), f"k{i}"], + env=dict(os.environ)) for i in range(8)] + assert [p.wait() for p in procs] == [0] * 8 + assert sorted(_on_disk(state_dir)["shown_warnings"]) == [f"k{i}" for i in range(8)] + assert _leftovers(state_dir) == [] + + +class TestStateLossIsCounted: + def test_missing_file_is_a_fresh_state(self, state_dir): + assert ss.load_state("s1") == {"shown_warnings": []} + + @pytest.mark.parametrize("content", [ + b"", b'{"baseline_sha": "abc", "touched_pa', b"42", b'{"baseline_sha": "\xff\xfe"}']) + def test_unreadable_file_is_counted(self, state_dir, content): + (state_dir / "security_warnings_state_s1.json").write_bytes(content) + assert ss.load_state("s1") == {"shown_warnings": [], "state_resets": 1} + + def test_overwriting_another_hooks_save_is_counted_without_locking( + self, state_dir, monkeypatch): + monkeypatch.setattr(ss, "fcntl", None) + _seed() + assert "state_overwrites" not in _on_disk(state_dir) + + def slow_hook(state): + # Another hook saves while this one is between its read and write. + time.sleep(0.01) + ss.save_state("s1", {**state, "touched_paths": ["x.py", "other.py"]}) + state["shown_warnings"].append("k") + ss.with_locked_state("s1", slow_hook) + after = _on_disk(state_dir) + assert after["state_overwrites"] == 1 + assert after["touched_paths"] == ["x.py"] # the other hook's save was lost + + def test_a_concurrent_save_of_the_same_state_is_not_counted(self, state_dir, monkeypatch): + monkeypatch.setattr(ss, "fcntl", None) + _seed() + + def reader(state): + ss.save_state("s1", dict(state)) # another hook that only read + return state["baseline_sha"] + assert ss.with_locked_state("s1", reader) == "a" * 40 + assert "state_overwrites" not in _on_disk(state_dir) + + def test_stop_reports_the_counts_once(self, tmp_path, hook_env): + repo = make_repo(tmp_path / "repo") + hook_env = {k: v for k, v in hook_env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"} + state_file = os.path.join(hook_env["SECURITY_WARNINGS_STATE_DIR"], + "security_warnings_state_s1.json") + run_hook(ups_payload(repo), hook_env) + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + m = metrics_of(stdout) + assert "state_resets" not in m and "state_overwrites" not in m + + with open(state_file, "w") as f: + f.write('{"baseline_sha": "abc", "touched_pa') + run_hook(ups_payload(repo), hook_env) + with open(state_file) as f: + state = json.load(f) + state["state_overwrites"] = 3 + with open(state_file, "w") as f: + json.dump(state, f) + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + m = metrics_of(stdout) + assert (m["state_resets"], m["state_overwrites"]) == (1, 3) + + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + m = metrics_of(stdout) + assert "state_resets" not in m and "state_overwrites" not in m + + +def test_cleanup_removes_old_temporary_files(state_dir): + old = state_dir / "security_warnings_state_s1.json.a1b2c3.tmp" + new = state_dir / "security_warnings_state_s2.json.a1b2c3.tmp" + old.write_text("{}") + new.write_text("{}") + long_ago = time.time() - 31 * 24 * 60 * 60 + os.utime(old, (long_ago, long_ago)) + ss.cleanup_old_state_files() + assert not old.exists() and new.exists() diff --git a/plugins/security-guidance/tests/test_untracked_cap.py b/plugins/security-guidance/tests/test_untracked_cap.py new file mode 100644 index 00000000..00fd4015 --- /dev/null +++ b/plugins/security-guidance/tests/test_untracked_cap.py @@ -0,0 +1,85 @@ +import os +import time + +from conftest import make_repo, metrics_of, run_hook, stop_payload, ups_payload + +import diffstate + +SRC = "import os\nos.system(input())\n" + + +def _review(repo, snapshot): + paths, _base, root, _untracked, metrics = diffstate.compute_v2_review_set( + str(repo), None, None, snapshot) + return sorted(os.path.relpath(p, root) for p in paths), metrics + + +class TestCappedSnapshot: + def _repo(self, tmp_path, monkeypatch, n=30, cap=10): + monkeypatch.setattr(diffstate, "UNTRACKED_BASELINE_CAP", cap) + monkeypatch.setattr(diffstate, "_CAPPED_BASELINE_SLACK_NS", 20_000_000) + repo = make_repo(tmp_path / "repo") + for i in range(n): + (repo / f"old_{i:03d}.py").write_text(SRC) + time.sleep(0.1) + return repo + + def test_snapshot_records_when_it_was_capped(self, tmp_path, monkeypatch): + repo = self._repo(tmp_path, monkeypatch) + before = time.time_ns() + snap = diffstate._list_untracked(str(repo)) + assert before <= snap[diffstate.UNTRACKED_CAPPED_AT_KEY] <= time.time_ns() + assert len(snap) == 10 + 1 + + def test_uncapped_snapshot_has_no_marker(self, tmp_path, monkeypatch): + repo = self._repo(tmp_path, monkeypatch, n=5) + assert diffstate.UNTRACKED_CAPPED_AT_KEY not in diffstate._list_untracked(str(repo)) + + def test_files_past_the_cap_are_not_reviewed_when_untouched(self, tmp_path, monkeypatch): + repo = self._repo(tmp_path, monkeypatch) + snap = diffstate._list_untracked(str(repo)) + review, metrics = _review(repo, snap) + assert review == [] + assert metrics["preexisting_untracked_excluded"] == 30 + + def test_new_and_edited_files_past_the_cap_are_reviewed(self, tmp_path, monkeypatch): + repo = self._repo(tmp_path, monkeypatch) + snap = diffstate._list_untracked(str(repo)) + time.sleep(0.1) + (repo / "zz_new.py").write_text(SRC) + (repo / "old_025.py").write_text(SRC + "eval(input())\n") + (repo / "old_003.py").write_text(SRC + "eval(input())\n") # inside the cap + review, _ = _review(repo, snap) + assert review == ["old_003.py", "old_025.py", "zz_new.py"] + + def test_file_moved_in_with_an_old_mtime_is_reviewed(self, tmp_path, monkeypatch): + repo = self._repo(tmp_path, monkeypatch) + snap = diffstate._list_untracked(str(repo)) + time.sleep(0.1) + new = repo / "zz_extracted.py" + new.write_text(SRC) + os.utime(new, (1_600_000_000, 1_600_000_000)) # as tar or cp -p would leave it + review, _ = _review(repo, snap) + assert review == ["zz_extracted.py"] + + +def test_stop_hook_does_not_re_review_files_past_the_cap(tmp_path, hook_env, stub_api): + """More untracked files than the snapshot holds: the same old files must + not be sent for review turn after turn (#6407).""" + repo = make_repo(tmp_path / "repo") + n_files = diffstate.UNTRACKED_BASELINE_CAP + 60 + for i in range(n_files): + (repo / f"old_{i:05d}.py").write_text(SRC) + time.sleep(2.2) # older than the snapshot by more than the timestamp slack + + for _turn in range(2): + run_hook(ups_payload(repo), hook_env) + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + # Telemetry: a count above the cap is how this path shows up. + assert metrics_of(stdout)["preexisting_untracked_excluded"] == n_files + assert stub_api.calls == [] + + run_hook(ups_payload(repo), hook_env) + (repo / "zz_new.py").write_text(SRC) + run_hook(stop_payload(repo), hook_env) + assert len([c for c in stub_api.calls if "messages" in c]) == 1 diff --git a/plugins/security-guidance/tests/test_user_config_dir.py b/plugins/security-guidance/tests/test_user_config_dir.py new file mode 100644 index 00000000..7c8a1245 --- /dev/null +++ b/plugins/security-guidance/tests/test_user_config_dir.py @@ -0,0 +1,98 @@ +"""User-level claude-security-guidance.md and security-patterns files are +found in the directory CLAUDE_CONFIG_DIR names, as well as in ~/.claude.""" +import json +import os + +import pytest + +import extensibility + +MARKER = "MARKER_POLICY_LINE" +PATTERNS = {"patterns": [{"rule_name": "marker_rule", "substrings": ["x"], "reminder": "r"}]} + + +@pytest.fixture +def home(tmp_path, monkeypatch): + h = tmp_path / "home" + h.mkdir() + monkeypatch.setenv("HOME", str(h)) + monkeypatch.setenv("USERPROFILE", str(h)) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + return h + + +def write_user_files(d, marker=MARKER, rule="marker_rule"): + d.mkdir(parents=True, exist_ok=True) + (d / "claude-security-guidance.md").write_text(f"- {marker}\n") + patterns = {"patterns": [dict(PATTERNS["patterns"][0], rule_name=rule)]} + (d / "security-patterns.json").write_text(json.dumps(patterns)) + + +def load(): + extensibility.load_for_session(None) + return extensibility.guidance_block(), [r["ruleName"] for r in extensibility.user_patterns()] + + +def test_files_in_configured_dir_are_loaded(home, monkeypatch): + cfg = home / ".claude-work" + write_user_files(cfg) + monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(cfg)) + guidance, rules = load() + assert MARKER in guidance + assert rules == ["user:marker_rule"] + + +def test_default_dir_still_loaded_when_config_dir_is_set(home, monkeypatch): + write_user_files(home / ".claude") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(home / ".claude-work")) + guidance, rules = load() + assert MARKER in guidance + assert rules == ["user:marker_rule"] + + +def test_both_dirs_loaded_default_first(home, monkeypatch): + write_user_files(home / ".claude", marker="FROM_DEFAULT", rule="default_rule") + cfg = home / ".claude-work" + write_user_files(cfg, marker="FROM_CONFIGURED", rule="configured_rule") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(cfg)) + guidance, rules = load() + assert guidance.index("FROM_DEFAULT") < guidance.index("FROM_CONFIGURED") + assert rules == ["user:default_rule", "user:configured_rule"] + + +@pytest.mark.parametrize("spelling", ["{home}/.claude", "{home}/.claude/", "~/.claude", "{home}/link"]) +def test_config_dir_naming_the_default_dir_is_read_once(home, monkeypatch, spelling): + write_user_files(home / ".claude") + os.symlink(home / ".claude", home / "link") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", spelling.format(home=home)) + guidance, rules = load() + assert guidance.count(MARKER) == 1 + assert rules == ["user:marker_rule"] + + +@pytest.mark.parametrize("value", ["", " "]) +def test_empty_config_dir_is_not_set(home, monkeypatch, value): + write_user_files(home / ".claude") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", value) + assert extensibility._user_config_dirs() == [str(home / ".claude")] + guidance, rules = load() + assert guidance.count(MARKER) == 1 + + +def test_tilde_in_config_dir_is_expanded(home, monkeypatch): + write_user_files(home / ".claude-work") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", "~/.claude-work") + guidance, _ = load() + assert MARKER in guidance + + +def test_project_files_unchanged(home, monkeypatch, tmp_path): + cfg = home / ".claude-work" + write_user_files(cfg, marker="FROM_USER") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(cfg)) + proj = tmp_path / "proj" + write_user_files(proj / ".claude", marker="FROM_PROJECT", rule="project_rule") + extensibility.load_for_session(str(proj)) + guidance = extensibility.guidance_block() + assert guidance.index("FROM_USER") < guidance.index("FROM_PROJECT") + assert [r["ruleName"] for r in extensibility.user_patterns()] == ["user:marker_rule", "user:project_rule"] |
