diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-10-02 14:26:10 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-02 14:26:10 -0700 |
| commit | d182ca456ca09d31d139f7d3818d1d333b103cce (patch) | |
| tree | 9ce47f83ebee05e7d7b800ab86b99b5ebfc9e357 /plugins | |
| parent | 2f189354595613190f575ab1f7510f3a94150022 (diff) | |
| parent | 01f8be9b220b6e993a3c2cb219f28d7cc6fd3d6f (diff) | |
Merge pull request #6350 from anthropics/mhegazy/sg-track-latest-opus
security-guidance: follow the newest Opus instead of a pinned release
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/.claude-plugin/plugin.json | 2 | ||||
| -rw-r--r-- | plugins/security-guidance/README.md | 23 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 3 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 203 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 2 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_review_model.py | 404 |
6 files changed, 609 insertions, 28 deletions
diff --git a/plugins/security-guidance/.claude-plugin/plugin.json b/plugins/security-guidance/.claude-plugin/plugin.json index af05be0a..375e65a0 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.8", + "version": "2.0.9", "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 485f22fb..58736a85 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -3,7 +3,7 @@ Security review for Claude-generated code. Three layers: 1. **Pattern warnings** — instant regex-based reminders on `Edit`/`Write` for ~25 known-dangerous patterns (`yaml.load`, `torch.load(weights_only=False)`, `pickle.load` on untrusted data, raw `innerHTML`, hardcoded secrets, etc.). -2. **LLM diff review** — when Claude finishes a turn, the plugin sends the diff to a fast LLM call (Opus 4.7 by default) and feeds high-severity findings back to Claude so it can fix them before you see the response. +2. **LLM diff review** — when Claude finishes a turn, the plugin sends the diff to a fast LLM call (the newest Opus by default) and feeds high-severity findings back to Claude so it can fix them before you see the response. 3. **Agentic commit review** — on `git commit`, an SDK-driven reviewer reads related files (`Read`/`Grep`/`Glob`) to trace data flow across the codebase, catching multi-file vulnerabilities pattern matching misses (IDOR, auth bypass, cross-file SSRF). Findings cover common web-vulnerability classes — injection, XSS, SSRF, hardcoded secrets, IDOR, auth bypass, unsafe deserialization, and path traversal among others. @@ -28,18 +28,25 @@ All configuration is via environment variables. None are required for default be ### Selecting a model +By default both reviews run on the newest Claude Opus, and move to the next one when it is released — there is no model version to bump: + +- The LLM diff review asks your API endpoint (`GET /v1/models`) which Opus models it serves and uses the newest. The answer is cached for a day in the plugin's state directory. If the endpoint can't answer, the review uses `claude-opus-5-5`. +- The agentic commit reviewer, and every review on Bedrock, Vertex, and Foundry, runs through your installed Claude Code and uses its `opus` alias — the same model `/model opus` selects, including any `ANTHROPIC_DEFAULT_OPUS_MODEL` you have set. + +To pin a model, or to use a cheaper one: + ```bash # 1P / gateway: a canonical model id -SECURITY_REVIEW_MODEL=claude-opus-4-7 # default +SECURITY_REVIEW_MODEL=claude-opus-5-5 # Bedrock: use the inference-profile id -SECURITY_REVIEW_MODEL=us.anthropic.claude-opus-4-7 +SECURITY_REVIEW_MODEL=us.anthropic.claude-opus-5-5 -# Vertex: use the Vertex date-tag form -SECURITY_REVIEW_MODEL=claude-opus-4-7@20260218 +# Vertex / Foundry: the provider's model id +SECURITY_REVIEW_MODEL=claude-opus-5-5 ``` -`SECURITY_REVIEW_MODEL` controls the LLM diff review. `SG_AGENTIC_MODEL` (same syntax) controls the agentic commit reviewer; defaults to the same model. +`SECURITY_REVIEW_MODEL` controls the LLM diff review. `SG_AGENTIC_MODEL` (same syntax) controls the agentic commit reviewer. ### Enabling/disabling layers @@ -101,9 +108,9 @@ 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, check `SECURITY_REVIEW_MODEL` is set to a provider-specific id (not a bare `claude-opus-4-7`). 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. 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** — drop `SECURITY_REVIEW_MODEL` to a cheaper model (`claude-sonnet-4-6`) and re-evaluate; if precision is the priority, stay on Opus 4.7. +**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. **Want to silence a specific finding** — add a comment to the line explaining why it's safe; the LLM reviewer treats inline justifications as exclusions. For systemic exclusions, document them in your `claude-security-guidance.md`. diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index ce051753..44b205f0 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -140,6 +140,9 @@ _PRICE_PER_MTOK = { "claude-sonnet-4-6": (3.0, 15.0), "claude-opus-4-6": (15.0, 75.0), "claude-opus-4-7": (5.0, 25.0), + "claude-opus-4-8": (5.0, 25.0), + "claude-opus-5": (5.0, 25.0), + "claude-opus-5-5": (4.0, 20.0), } _PRICE_DEFAULT = (3.0, 15.0) diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 1430dd4e..ae6038cc 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -18,10 +18,13 @@ Two reassignable globals here are read by handlers in ``from``-import) so they observe reassignment. """ import glob +import hashlib import json import os import re import sys +import tempfile +import time import urllib.request from typing import Optional, Tuple, Dict, Any, List @@ -125,11 +128,19 @@ HAS_API_CREDENTIALS = bool( ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN or _HAS_3P_PROVIDER_AT_LOAD ) -# Model for security review. Default chosen for its precision profile on +# Model for security review. Opus is the default for its precision profile on # interruptive review surfaces — false positives are the dominant uninstall # driver, so the default favors precision over recall and over latency. # Override via the SECURITY_REVIEW_MODEL env var (see README). -SECURITY_REVIEW_MODEL = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() or "claude-opus-4-7" +# +# Without an override the review follows the newest Opus rather than a +# release named here: default_review_model() resolves it per call path. +# _PINNED_REVIEW_MODEL is only what a review uses when that lookup fails. +_PINNED_REVIEW_MODEL = "claude-opus-5-5" +# Claude Code's own alias. The CLI the Agent SDK spawns resolves it to the +# newest Opus it knows how to drive, in the provider's id form on 3P. +_CLI_OPUS_ALIAS = "opus" +SECURITY_REVIEW_MODEL = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() or _PINNED_REVIEW_MODEL # OAuth subscriber tokens (ANTHROPIC_AUTH_TOKEN) require this exact system prompt # for api.anthropic.com/v1/messages — the API checks for one of the known Claude @@ -256,8 +267,8 @@ def _cap_files_for_prompt(files): _auth_prefer_token = False -def _build_auth_headers(use_token): - betas = ["structured-outputs-2025-11-13"] +def _build_auth_headers(use_token, betas=("structured-outputs-2025-11-13",)): + betas = list(betas) headers = { "Content-Type": "application/json", "anthropic-version": "2023-06-01", @@ -267,7 +278,8 @@ def _build_auth_headers(use_token): betas.append("oauth-2025-04-20") else: headers["x-api-key"] = ANTHROPIC_API_KEY - headers["anthropic-beta"] = ",".join(betas) + if betas: + headers["anthropic-beta"] = ",".join(betas) return headers @@ -278,7 +290,10 @@ def _build_auth_headers(use_token): _ADAPTIVE_THINKING_MODELS = ( "claude-opus-4-6", "claude-opus-4-7", + "claude-opus-4-8", + "claude-opus-5", "claude-sonnet-4-6", + "claude-sonnet-5", ) _LEGACY_THINKING_MODELS = ( "claude-3-", @@ -339,6 +354,159 @@ def _is_3p_provider() -> bool: return False +# ── Default review model ───────────────────────────────────────────────── +# The API has no alias for "newest Opus", so the raw-HTTP path asks the +# endpoint it is about to call (GET /v1/models) and keeps the answer in the +# state dir. Asking that endpoint, not api.anthropic.com, means a gateway +# that serves an older Opus gets a model it can actually route. + +_REVIEW_MODEL_CACHE_FILE = "review_model.json" +_REVIEW_MODEL_TTL_SECONDS = 24 * 3600 +# A failed lookup is remembered too, for less long: otherwise an endpoint +# without /v1/models costs every hook fire the lookup timeout. +_REVIEW_MODEL_RETRY_SECONDS = 3600 +_REVIEW_MODEL_LOOKUP_TIMEOUT = 5 +_REVIEW_MODEL_LISTING_MAX_BYTES = 4 * 1024 * 1024 + +# claude-opus-<major>[-<minor>][-<yyyymmdd>]. Anything else a listing or the +# cache file holds (other families, gateway-prefixed names, free text) is +# never sent as a model id. +_OPUS_ID = re.compile(r"claude-opus-(\d{1,2})(?:-(\d{1,2}))?(?:-(\d{8}))?") + +_review_model_memo: Optional[str] = None + + +def _newest_opus(model_ids) -> Optional[str]: + """The highest-versioned Opus id in `model_ids`, or None.""" + best = None + for model_id in model_ids: + m = _OPUS_ID.fullmatch(model_id) if isinstance(model_id, str) else None + if not m: + continue + version = (int(m.group(1)), int(m.group(2) or 0), m.group(3) or "") + if best is None or version > best[0]: + best = (version, model_id) + return best[1] if best else None + + +def _fetch_newest_opus() -> Optional[str]: + """Newest Opus the configured endpoint lists; None if it can't say.""" + # Newest first, so one modest page is enough; an org with many models + # otherwise returns a megabyte-sized listing. + url = _anthropic_base_url() + "/v1/models?limit=100" + use_token = _auth_prefer_token or not ANTHROPIC_API_KEY + for _ in range(2): + request = urllib.request.Request( + url, headers=_build_auth_headers(use_token, betas=()), method="GET", + ) + try: + with urllib.request.urlopen( + request, timeout=_REVIEW_MODEL_LOOKUP_TIMEOUT, + ) as response: + listing = json.loads( + response.read(_REVIEW_MODEL_LISTING_MAX_BYTES).decode("utf-8") + ) + entries = listing.get("data") if isinstance(listing, dict) else None + if not isinstance(entries, list): + debug_log("review model lookup: no model list in response") + return None + ids = [e.get("id") for e in entries if isinstance(e, dict)] + if listing.get("has_more"): + # A truncated page may hold no current Opus at all (an org's + # own models can fill it); never let it pick an older one. + ids.append(_PINNED_REVIEW_MODEL) + return _newest_opus(ids) + except urllib.error.HTTPError as e: + if e.code == 401 and not use_token and ANTHROPIC_AUTH_TOKEN: + use_token = True + continue + debug_log(f"review model lookup: HTTP {e.code}") + return None + except Exception as e: + debug_log(f"review model lookup failed: {type(e).__name__}") + return None + return None + + +def _read_review_model_cache(path, endpoint_key, now): + """(hit, model) from the cache file. `model` is None for a remembered + failed lookup. The file is user-writable state: every field is checked + and a model id is accepted only if it has the shape of an Opus id.""" + try: + with open(path, "r", encoding="utf-8") as f: + entry = json.loads(f.read(4096)) + except (OSError, ValueError): + return False, None + if not isinstance(entry, dict) or entry.get("endpoint") != endpoint_key: + return False, None + at = entry.get("at") + if isinstance(at, bool) or not isinstance(at, (int, float)): + return False, None + model = entry.get("model") + if model is None: + ttl = _REVIEW_MODEL_RETRY_SECONDS + elif isinstance(model, str) and _OPUS_ID.fullmatch(model): + ttl = _REVIEW_MODEL_TTL_SECONDS + else: + return False, None + if not 0 <= now - at < ttl: + return False, None + return True, model + + +def _write_review_model_cache(path, endpoint_key, model, now): + tmp = None + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".review_model.") + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump({"endpoint": endpoint_key, "model": model, "at": now}, f) + os.replace(tmp, path) + except OSError as e: + debug_log(f"review model cache not written: {type(e).__name__}") + if tmp: + try: + os.unlink(tmp) + except OSError: + pass + + +def default_review_model() -> str: + """Model for a review the user hasn't pinned with SECURITY_REVIEW_MODEL. + + 3P providers go through the Agent SDK, so the CLI alias does the work. + 1P and gateways get the newest Opus the endpoint lists, looked up at most + once per _REVIEW_MODEL_TTL_SECONDS; _PINNED_REVIEW_MODEL when the lookup + can't answer. Never raises. + """ + global _review_model_memo + explicit = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() + if explicit: + return explicit + if _is_3p_provider(): + return _CLI_OPUS_ALIAS + if not HAS_API_CREDENTIALS: + return _PINNED_REVIEW_MODEL + if _review_model_memo: + return _review_model_memo + try: + path = os.path.join(_resolve_state_dir(), _REVIEW_MODEL_CACHE_FILE) + # Hashed: a gateway URL can carry credentials. + endpoint_key = hashlib.sha256( + _anthropic_base_url().encode("utf-8") + ).hexdigest()[:16] + now = time.time() + hit, model = _read_review_model_cache(path, endpoint_key, now) + if not hit: + model = _fetch_newest_opus() + _write_review_model_cache(path, endpoint_key, model, now) + except Exception as e: + debug_log(f"review model resolution failed: {type(e).__name__}") + model = None + _review_model_memo = model or _PINNED_REVIEW_MODEL + return _review_model_memo + + def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None): """Single-turn SDK call as a substitute for the HTTP _call_claude path on 3P providers. Uses the same `output_format` JSON-schema contract so the @@ -379,7 +547,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) return None cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None - chosen_model = model or SECURITY_REVIEW_MODEL + default_model = default_review_model() + chosen_model = model or default_model # Capture child claude stderr so a failing 3P call surfaces the real # error (auth missing, model id wrong, etc.) in the debug log instead @@ -396,10 +565,10 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) model=chosen_model, output_format={"type": "json_schema", "schema": output_schema}, # Identical --model/--fallback-model is rejected by the CLI at - # startup; chosen_model defaults to SECURITY_REVIEW_MODEL, so - # only pass a fallback when it actually differs. + # startup; chosen_model defaults to default_model, so only pass + # a fallback when it actually differs. fallback_model=( - SECURITY_REVIEW_MODEL if chosen_model != SECURITY_REVIEW_MODEL else None + default_model if chosen_model != default_model else None ), env=_agentic_spawn_env(), stderr=lambda l: _captured_stderr.append(l), @@ -450,7 +619,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, retry_5xx=True): """ Call the configured LLM model with extended thinking and structured outputs. - Model defaults to Sonnet 4.6 but can be overridden via SECURITY_REVIEW_MODEL env var. + Model defaults to default_review_model(); SECURITY_REVIEW_MODEL overrides it. Returns parsed JSON response or None on failure. On failure, sets module-level _last_call_claude_http_error to the HTTP status (or -1 for network/timeout) so callers can distinguish API failure from an @@ -485,7 +654,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, headers = _build_auth_headers(use_token) payload = { - "model": model or SECURITY_REVIEW_MODEL, + "model": model or default_review_model(), "max_tokens": max_tokens, "system": CLAUDE_CODE_SYSTEM_PROMPT, "messages": [{"role": "user", "content": prompt}], @@ -622,7 +791,7 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, from concurrent.futures import ThreadPoolExecutor explicit = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() - primary = explicit or SECURITY_REVIEW_MODEL + primary = default_review_model() if not _dual_or_enabled(): # Single-call path. Reuse the same sonnet-fallback retry as a dual_or @@ -1187,10 +1356,8 @@ def agentic_review( debug_log(f"agentic_review: SDK unavailable ({e}); falling back") return None, [], {"agentic_fallback": f"import:{type(e).__name__}"} - # Default to the documented public model. Overridable via SG_AGENTIC_MODEL. - # The bundled SDK CLI only knows public model names. - _DEFAULT_PUBLIC_MODEL = "claude-opus-4-7" - model = os.environ.get("SG_AGENTIC_MODEL") or _DEFAULT_PUBLIC_MODEL + # 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")) # In production repo_dir is the user's working tree (full repo). Under the # eval harness it's a temp dir with ONLY touched_paths — the agent can't @@ -1302,11 +1469,11 @@ def agentic_review( # Identical --model/--fallback-model is rejected by the inner CLI # at startup ("Fallback model cannot be the same as the main # model", exit 1 → ProcessError). The default model here IS - # _DEFAULT_PUBLIC_MODEL, so an unconditional fallback_model would + # _CLI_OPUS_ALIAS, so an unconditional fallback_model would # kill every spawn before the first API call. Omit the fallback # when it would equal the primary. fallback_model=( - _DEFAULT_PUBLIC_MODEL if model != _DEFAULT_PUBLIC_MODEL else None + _CLI_OPUS_ALIAS if model != _CLI_OPUS_ALIAS else None ), # Plugin-hook subprocesses get ANTHROPIC_AUTH_TOKEN (the user's # OAuth token) injected by Claude Code. The SDK builds the child diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 48a7eb49..00f9d5d6 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -46,7 +46,7 @@ Per-feature toggles (all default enabled; set to "0" to disable): - ENABLE_COMMIT_REVIEW: PostToolUse[Bash] commit security review Other: -- SECURITY_REVIEW_MODEL: Model for LLM review (default: claude-opus-4-7) +- SECURITY_REVIEW_MODEL: Model for LLM review (default: the newest Opus) - ANTHROPIC_API_KEY: Required for LLM-based reviews - ANTHROPIC_AUTH_TOKEN: Alternative to API key — OAuth access token sent as Bearer auth. Claude Code passes this automatically for OAuth-authenticated users. diff --git a/plugins/security-guidance/tests/test_review_model.py b/plugins/security-guidance/tests/test_review_model.py new file mode 100644 index 00000000..e290f35e --- /dev/null +++ b/plugins/security-guidance/tests/test_review_model.py @@ -0,0 +1,404 @@ +"""The default review model follows the newest Opus instead of a pinned release.""" +import http.server +import json +import sys +import threading +import time +import types + +import pytest + +from conftest import ( + VULN_PY, edit_payload, metrics_of, run_hook, stop_payload, ups_payload, +) + +import llm + +SCHEMA = {"type": "object", "properties": {"hasVulnerabilities": {"type": "boolean"}}} +PINNED = "claude-opus-5-5" + + +class _Api(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.server.gets.append((self.path, dict(self.headers))) + if self.server.models_status != 200: + return self._send(self.server.models_status, {"type": "error"}) + self._send(200, self.server.models_body) + + def do_POST(self): + n = int(self.headers.get("Content-Length") or 0) + body = json.loads(self.rfile.read(n)) + self.server.posts.append(body) + self._send(200, { + "id": "msg_stub", "type": "message", "role": "assistant", + "model": body["model"], "stop_reason": "end_turn", + "content": [{"type": "text", "text": json.dumps( + {"hasVulnerabilities": False, "vulnerabilities": []})}], + "usage": {"input_tokens": 1, "output_tokens": 1}, + }) + + 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 + + +def _models(*ids): + return {"data": [{"type": "model", "id": i} for i in ids], "has_more": False} + + +@pytest.fixture +def api(tmp_path, monkeypatch): + srv = http.server.HTTPServer(("127.0.0.1", 0), _Api) + srv.gets, srv.posts = [], [] + srv.models_status = 200 + srv.models_body = _models( + "claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5-5", "claude-opus-5", + "claude-opus-4-8", "claude-opus-4-7", "claude-opus-4-5-20251101", + ) + threading.Thread(target=srv.serve_forever, daemon=True).start() + for var in ("SECURITY_REVIEW_MODEL", "SG_AGENTIC_MODEL", "SG_DUAL_OR", + "CLAUDE_CODE_EXECPATH", "SG_AGENTIC_CLI_PATH", *llm._PROVIDER_ENV_VARS): + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("ANTHROPIC_BASE_URL", f"http://127.0.0.1:{srv.server_port}") + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + monkeypatch.setenv("NO_PROXY", "*") + monkeypatch.setenv("no_proxy", "*") + monkeypatch.setattr(llm, "ANTHROPIC_API_KEY", "test-key") + monkeypatch.setattr(llm, "ANTHROPIC_AUTH_TOKEN", "") + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) + monkeypatch.setattr(llm, "_auth_prefer_token", False) + monkeypatch.setattr(llm, "_review_model_memo", None, raising=False) + try: + yield srv + finally: + srv.shutdown() + + +def _new_process(monkeypatch): + """Each hook fire is a fresh process: only the on-disk cache carries over.""" + monkeypatch.setattr(llm, "_review_model_memo", None, raising=False) + + +def _review(): + return llm._call_claude_dual_or( + "review this", SCHEMA, + bool_key="hasVulnerabilities", list_key="vulnerabilities", + ) + + +class TestNewestOpus: + def test_highest_version_wins_whatever_the_order(self): + ids = ["claude-opus-4-7", "claude-opus-5-5", "claude-opus-5", "claude-opus-4-8"] + assert llm._newest_opus(ids) == "claude-opus-5-5" + assert llm._newest_opus(reversed(ids)) == "claude-opus-5-5" + + def test_minor_version_compares_as_a_number(self): + assert llm._newest_opus(["claude-opus-5-9", "claude-opus-5-10"]) == "claude-opus-5-10" + + def test_snapshot_date_is_not_a_version(self): + ids = ["claude-opus-4-20250514", "claude-opus-4-1-20250805", "claude-opus-4-5-20251101"] + assert llm._newest_opus(ids) == "claude-opus-4-5-20251101" + + def test_other_families_and_malformed_ids_are_ignored(self): + ids = [ + "claude-fable-5-1", "claude-sonnet-5-5", "claude-haiku-4-5", + "claude-opus-9-preview", "bedrock/claude-opus-9", "claude-opus-9 --flag", + "us.anthropic.claude-opus-9", None, 7, "claude-opus-4-7", + ] + assert llm._newest_opus(ids) == "claude-opus-4-7" + + def test_no_opus_listed(self): + assert llm._newest_opus(["claude-sonnet-5-5", "gpt-x"]) is None + + +class TestReviewRequestModel: + def test_review_uses_the_newest_opus_the_endpoint_lists(self, api): + assert _review() == {"hasVulnerabilities": False, "vulnerabilities": []} + assert [p["model"] for p in api.posts] == ["claude-opus-5-5"] + + def test_a_release_newer_than_the_pinned_default_is_picked_up(self, api): + api.models_body = _models("claude-opus-6", "claude-opus-5-5") + _review() + assert [p["model"] for p in api.posts] == ["claude-opus-6"] + + def test_gateway_listing_only_an_older_opus_gets_that_one(self, api): + api.models_body = _models("claude-opus-4-8", "claude-sonnet-5") + _review() + assert [p["model"] for p in api.posts] == ["claude-opus-4-8"] + + def test_truncated_listing_does_not_pick_an_older_opus(self, api): + api.models_body = {**_models("org-model-2", "org-model-1", "claude-opus-4-7"), + "has_more": True} + _review() + assert [p["model"] for p in api.posts] == [PINNED] + + def test_truncated_listing_still_picks_a_newer_opus(self, api): + api.models_body = {**_models("claude-opus-6", "org-model-1"), "has_more": True} + _review() + assert [p["model"] for p in api.posts] == ["claude-opus-6"] + + def test_lookup_asks_for_one_modest_page(self, api): + _review() + assert api.gets[0][0] == "/v1/models?limit=100" + + def test_lookup_authenticates_like_the_review_call(self, api): + _review() + path, headers = api.gets[0] + assert path.startswith("/v1/models") + lowered = {k.lower(): v for k, v in headers.items()} + assert lowered["x-api-key"] == "test-key" + assert lowered["anthropic-version"] == "2023-06-01" + + def test_oauth_only_session_sends_the_bearer_token(self, api, monkeypatch): + monkeypatch.setattr(llm, "ANTHROPIC_API_KEY", "") + monkeypatch.setattr(llm, "ANTHROPIC_AUTH_TOKEN", "oauth-token") + _review() + lowered = {k.lower(): v for k, v in api.gets[0][1].items()} + assert lowered["authorization"] == "Bearer oauth-token" + assert "oauth-2025-04-20" in lowered["anthropic-beta"] + assert "x-api-key" not in lowered + + def test_explicit_model_is_used_as_is_without_a_lookup(self, api, monkeypatch): + monkeypatch.setenv("SECURITY_REVIEW_MODEL", "claude-sonnet-5") + _review() + assert [p["model"] for p in api.posts] == ["claude-sonnet-5"] + assert api.gets == [] + + +class TestLookupFailure: + @pytest.mark.parametrize("status", [401, 403, 404, 500]) + def test_falls_back_to_the_pinned_default(self, api, status): + api.models_status = status + _review() + assert [p["model"] for p in api.posts] == [PINNED] + + @pytest.mark.parametrize("body", [ + {"data": []}, {"data": "nope"}, {"object": "list"}, [], "text", + {"data": [{"id": "gpt-x"}, {"name": "claude-opus-9"}, "claude-opus-9"]}, + ]) + def test_unusable_listing_falls_back_to_the_pinned_default(self, api, body): + api.models_body = body + assert llm.default_review_model() == PINNED + + def test_unreachable_endpoint_falls_back_to_the_pinned_default(self, api, monkeypatch): + monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://127.0.0.1:1") + assert llm.default_review_model() == PINNED + + def test_no_credentials_means_no_lookup(self, api, monkeypatch): + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", False) + assert llm.default_review_model() == PINNED + assert api.gets == [] + + def test_failure_is_not_retried_on_every_hook_fire(self, api, monkeypatch): + api.models_status = 500 + assert llm.default_review_model() == PINNED + _new_process(monkeypatch) + assert llm.default_review_model() == PINNED + assert len(api.gets) == 1 + + def test_failure_is_retried_after_the_retry_window(self, api, monkeypatch): + api.models_status = 500 + assert llm.default_review_model() == PINNED + api.models_status = 200 + later = time.time() + llm._REVIEW_MODEL_RETRY_SECONDS + 1 + monkeypatch.setattr(llm.time, "time", lambda: later) + _new_process(monkeypatch) + assert llm.default_review_model() == "claude-opus-5-5" + + +class TestCache: + def test_one_lookup_serves_later_hook_fires(self, api, monkeypatch): + assert llm.default_review_model() == "claude-opus-5-5" + _new_process(monkeypatch) + api.models_body = _models("claude-opus-6") + assert llm.default_review_model() == "claude-opus-5-5" + assert len(api.gets) == 1 + + def test_one_lookup_per_process(self, api): + llm.default_review_model() + llm.default_review_model() + assert len(api.gets) == 1 + + def test_new_release_is_seen_once_the_cache_expires(self, api, monkeypatch): + assert llm.default_review_model() == "claude-opus-5-5" + api.models_body = _models("claude-opus-6", "claude-opus-5-5") + later = time.time() + llm._REVIEW_MODEL_TTL_SECONDS + 1 + monkeypatch.setattr(llm.time, "time", lambda: later) + _new_process(monkeypatch) + assert llm.default_review_model() == "claude-opus-6" + + def test_cache_from_another_endpoint_is_not_reused(self, api, monkeypatch): + assert llm.default_review_model() == "claude-opus-5-5" + other = http.server.HTTPServer(("127.0.0.1", 0), _Api) + other.gets, other.posts = [], [] + other.models_status = 200 + other.models_body = _models("claude-opus-4-8") + threading.Thread(target=other.serve_forever, daemon=True).start() + try: + monkeypatch.setenv("ANTHROPIC_BASE_URL", f"http://127.0.0.1:{other.server_port}") + _new_process(monkeypatch) + assert llm.default_review_model() == "claude-opus-4-8" + finally: + other.shutdown() + + @pytest.mark.parametrize("model", [ + "claude-opus-9 --dangerously-skip-permissions", "../../etc/passwd", + "claude-fable-5-1", 7, ["claude-opus-9"], + ]) + def test_tampered_cache_entry_is_ignored(self, api, monkeypatch, tmp_path, model): + assert llm.default_review_model() == "claude-opus-5-5" + cache = tmp_path / "state" / llm._REVIEW_MODEL_CACHE_FILE + entry = json.loads(cache.read_text()) + entry["model"] = model + cache.write_text(json.dumps(entry)) + _new_process(monkeypatch) + assert llm.default_review_model() == "claude-opus-5-5" + assert len(api.gets) == 2 + + @pytest.mark.parametrize("content", ["", "not json", "[]", '{"at": "soon"}', '{"at": 1e999}']) + def test_corrupt_cache_file_is_ignored(self, api, monkeypatch, tmp_path, content): + (tmp_path / "state").mkdir() + (tmp_path / "state" / llm._REVIEW_MODEL_CACHE_FILE).write_text(content) + assert llm.default_review_model() == "claude-opus-5-5" + + def test_future_dated_cache_entry_is_ignored(self, api, monkeypatch, tmp_path): + assert llm.default_review_model() == "claude-opus-5-5" + cache = tmp_path / "state" / llm._REVIEW_MODEL_CACHE_FILE + entry = json.loads(cache.read_text()) + entry["at"] = time.time() + 10 * 365 * 24 * 3600 + cache.write_text(json.dumps(entry)) + api.models_body = _models("claude-opus-6") + _new_process(monkeypatch) + assert llm.default_review_model() == "claude-opus-6" + + def test_unwritable_state_dir_still_resolves(self, api, monkeypatch, tmp_path): + blocker = tmp_path / "file" + blocker.write_text("x") + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(blocker / "state")) + assert llm.default_review_model() == "claude-opus-5-5" + + def test_endpoint_url_is_not_written_to_disk(self, api, monkeypatch, tmp_path): + llm.default_review_model() + cache = (tmp_path / "state" / llm._REVIEW_MODEL_CACHE_FILE).read_text() + assert "127.0.0.1" not in cache + + +@pytest.fixture +def fake_sdk(monkeypatch): + """Stand-in for claude_agent_sdk that records the options of each spawn.""" + spawned = [] + + class ClaudeAgentOptions: + def __init__(self, **kwargs): + self.kwargs = kwargs + spawned.append(kwargs) + + class AssistantMessage: + pass + + class ResultMessage: + subtype = "success" + usage = {} + total_cost_usd = 0.0 + structured_output = {"findings": [], "hasVulnerabilities": False, + "vulnerabilities": []} + + async def query(prompt, options): + yield ResultMessage() + + sdk = types.ModuleType("claude_agent_sdk") + sdk.ClaudeAgentOptions = ClaudeAgentOptions + sdk.AssistantMessage = AssistantMessage + sdk.ResultMessage = ResultMessage + sdk.query = query + monkeypatch.setitem(sys.modules, "claude_agent_sdk", sdk) + return spawned + + +class TestSdkPaths: + """Reviews that run through the Agent SDK name the CLI's own `opus` alias, + so the CLI that drives the model is the one that picks it.""" + + def test_agentic_review_defaults_to_the_cli_alias(self, api, fake_sdk, tmp_path): + llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + assert fake_sdk[0]["model"] == "opus" + assert fake_sdk[0]["fallback_model"] is None + assert api.gets == [] + + def test_agentic_review_override_falls_back_to_the_alias(self, api, fake_sdk, + tmp_path, monkeypatch): + monkeypatch.setenv("SG_AGENTIC_MODEL", "claude-sonnet-5") + llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + assert fake_sdk[0]["model"] == "claude-sonnet-5" + assert fake_sdk[0]["fallback_model"] == "opus" + + @pytest.mark.parametrize("provider_var", [ + "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", + ]) + def test_3p_review_defaults_to_the_cli_alias(self, api, fake_sdk, monkeypatch, + provider_var): + monkeypatch.setenv(provider_var, "1") + _review() + assert fake_sdk[0]["model"] == "opus" + assert fake_sdk[0]["fallback_model"] is None + assert api.gets == [] and api.posts == [] + + def test_3p_review_keeps_an_explicit_provider_id(self, api, fake_sdk, monkeypatch): + monkeypatch.setenv("CLAUDE_CODE_USE_BEDROCK", "1") + monkeypatch.setenv("SECURITY_REVIEW_MODEL", "us.anthropic.claude-opus-4-7") + _review() + assert fake_sdk[0]["model"] == "us.anthropic.claude-opus-4-7" + + +class TestStopHookProcess: + """The hook as Claude Code runs it: one process per fire, config from env.""" + + def _env(self, api, hook_env): + env = dict(hook_env) + env["ANTHROPIC_BASE_URL"] = f"http://127.0.0.1:{api.server_port}" + env.pop("SECURITY_REVIEW_MODEL", None) + return env + + def _edit_then_stop(self, repo, env, session_id): + run_hook(ups_payload(repo, session_id=session_id), env) + (repo / "app.py").write_text(VULN_PY + f"# {session_id}\n") + run_hook(edit_payload(repo, repo / "app.py", VULN_PY, session_id=session_id), env) + rc, so, se = run_hook(stop_payload(repo, session_id=session_id), env) + m = metrics_of(so) + assert m.get("skip_reason") is None and m["files_reviewed"] == 1, (m, se) + + def test_stop_review_runs_on_the_newest_opus(self, api, hook_env, workspace): + _, repo = workspace + env = self._env(api, hook_env) + self._edit_then_stop(repo, env, "s1") + assert [p["model"] for p in api.posts] == ["claude-opus-5-5"] + self._edit_then_stop(repo, env, "s2") + assert [p["model"] for p in api.posts] == ["claude-opus-5-5"] * 2 + assert len(api.gets) == 1 + + def test_stop_review_honors_the_override(self, api, hook_env, workspace): + _, repo = workspace + env = self._env(api, hook_env) + env["SECURITY_REVIEW_MODEL"] = "claude-sonnet-5" + self._edit_then_stop(repo, env, "s1") + assert [p["model"] for p in api.posts] == ["claude-sonnet-5"] + assert api.gets == [] + + +class TestPricing: + def test_current_opus_is_not_priced_as_the_unknown_model_default(self): + import _base + with _base._USAGE_LOCK: + before = _base._USAGE["cost"] + _base._record_usage({"input_tokens": 1_000_000, "output_tokens": 1_000_000}, + "claude-opus-5-5") + with _base._USAGE_LOCK: + after = _base._USAGE["cost"] + assert after - before == pytest.approx(24.0) |
