diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-14 12:18:32 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-14 12:18:32 +0000 |
| commit | d876712c3801b10bb1258da9b8f71fa7b41320e4 (patch) | |
| tree | 1e731f205e59d6f90032c4b5cc22a000e28d1272 /plugins | |
| parent | 26eea79bd04d30a6b38f3a4c89f4596c44a91128 (diff) | |
| parent | 641d925db5a662e72f8650cb1b7670a59dab1abc (diff) | |
Merge remote-tracking branch 'origin/main' into mhegazy/sg-portable-hook-output
# Conflicts:
# plugins/security-guidance/hooks/security_reminder_hook.py
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/README.md | 6 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 124 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 158 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 358 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/conftest.py | 78 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_custom_headers.py | 95 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_diff_parsing.py | 99 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_findings_delivery.py | 88 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_review_outcomes.py | 298 |
9 files changed, 1163 insertions, 141 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index b3d16f18..61bd2449 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -103,10 +103,10 @@ 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. ## Limitations @@ -116,7 +116,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/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 2036b45e..93b7a87e 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -962,32 +962,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, 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], 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, _ in _iter_diff_sections(diff_output) + if _is_reviewable_source(file_path) + ] def parse_diff_into_files(diff_output): @@ -999,20 +1070,7 @@ 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 '' - + for file_path, lines in _iter_diff_sections(diff_output): # Filter to source code files only if not _is_reviewable_source(file_path): continue @@ -1020,7 +1078,7 @@ def parse_diff_into_files(diff_output): # 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/llm.py b/plugins/security-guidance/hooks/llm.py index 3c1eb5e3..3f7607c6 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 @@ -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 @@ -1111,7 +1196,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 +1318,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 +1378,32 @@ _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 + + def _agentic_spawn_env() -> Dict[str, str]: """opts.env for the SDK-spawned inner `claude` CLI. @@ -1377,6 +1502,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")) @@ -1461,6 +1587,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]]: @@ -1517,6 +1658,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 @@ -1568,12 +1710,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 0326d1f2..71e0c73e 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -125,6 +125,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, @@ -229,6 +230,10 @@ def _write_hook_output(out): print(json.dumps(out), flush=True) +# Extra keys emit_metrics appends to every row this invocation emits. +_TAIL_METRICS: Dict[str, Any] = {} + + def emit_metrics( metrics, rewake_summary=None, @@ -259,31 +264,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). @@ -294,37 +290,39 @@ 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". """ head = {} if _PV and "pv" not in metrics: head["pv"] = _PV - head.update(_usage_metrics()) + 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 _write_hook_output(out) @@ -924,6 +922,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. @@ -987,6 +996,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]], @@ -996,8 +1012,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 @@ -1005,8 +1025,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 @@ -1019,6 +1039,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: @@ -1029,33 +1053,131 @@ 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() + 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 = dict(m) # 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. @@ -1427,43 +1549,34 @@ 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"] + 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. @@ -1499,6 +1612,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({ @@ -1556,9 +1699,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") @@ -1573,8 +1715,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): @@ -1827,16 +1967,31 @@ 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"] + 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 [])) @@ -1845,14 +2000,14 @@ 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), @@ -1918,9 +2073,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"), @@ -1990,6 +2145,8 @@ 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 {}), }) sys.exit(0) @@ -2186,11 +2343,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), @@ -2205,26 +2360,31 @@ 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 {}), }, 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), @@ -2235,6 +2395,8 @@ 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 {}), }) sys.exit(0) diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index 2cf4dd1c..11af0273 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -212,3 +212,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_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_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 |
