diff options
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/README.md | 15 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 42 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 5 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_review_usage_log.py | 116 |
4 files changed, 178 insertions, 0 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index e9d8e370..b8a67ed4 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -108,6 +108,21 @@ Where that data goes depends on your Claude Code configuration: The plugin writes its own debug log to `~/.claude/security/log.txt` (override with `SECURITY_GUIDANCE_DEBUG_LOG`). The log contains diffstate metadata, finding categories, the Agent SDK's own warnings and errors, and up to 20 lines per review that the agentic reviewer's inner Claude Code prints to stderr — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded. +### Review usage and cost + +The LLM reviews use your API path, so they cost tokens (or subscription usage) on top of your own session. The default reviewer is the newest Opus model. On the Anthropic API path the diff review on Stop calls the API directly, so it does not appear in Claude Code's own cost figures or transcripts. After each review the plugin writes one line to its debug log: + +``` +Review usage: review=stop session=<session id> model=claude-opus-5-5 calls=1 in=31994 out=3250 cache_read=0 cache_write=0 est_cost_usd=0.1930 +``` + +- `review` is `stop`, `commit` or `push`; `session` is the Claude Code session that triggered it. +- `calls` counts API requests for the diff review and reviewer runs for the agentic commit/push review, where `model` is the model that was asked for (`opus` by default). +- `est_cost_usd` is an estimate at list prices, not a bill: on a subscription the review counts against your usage limits instead. A trailing `~` means the model had no entry in the plugin's price table and a default rate was used. A review cut short (timeout, session exit) may not be counted. +- The log rotates at 1 MB, so copy these lines out if you need a longer history. + +To spend less, set `SECURITY_REVIEW_MODEL` (diff review) and `SG_AGENTIC_MODEL` (commit/push review) to a cheaper model, or turn reviews off (see [Enabling/disabling layers](#enablingdisabling-layers)). + ## Limitations This is a best-effort assistive tool, not a guarantee. Treat findings as suggestions, not as a substitute for human code review, SAST/DAST, dependency scanning, or pen-testing. The reviewer can miss vulnerabilities, produce false positives, and may behave differently across codebases, languages, and model versions. **No warranty is provided** — use is subject to Anthropic's [Commercial Terms](https://www.anthropic.com/legal/commercial-terms). diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index f05a0094..1daa6642 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -7,6 +7,7 @@ circular import). It must stay free of any other intra-plugin imports. """ import json import os +import re import threading from datetime import datetime @@ -168,6 +169,10 @@ _USAGE = { # reported it manually. "http_err_last": 0, # most recent HTTP error code this invocation "http_err_count": 0, # total HTTP errors (4xx + 5xx + network) + # For the usage log line only: model ids as recorded (the requested alias + # on the Agent SDK path), and whether any call had no price-table entry. + "models": [], + "default_priced": False, } _USAGE_LOCK = threading.Lock() @@ -204,12 +209,15 @@ def _record_usage(usage, model, cost_usd=None): cw = int(u.get("cache_creation_input_tokens") or 0) except (TypeError, ValueError): return + default_priced = False if cost_usd is None: pin, pout = _PRICE_DEFAULT + default_priced = True m = (model or "").lower() for k, v in sorted(_PRICE_PER_MTOK.items(), key=lambda kv: -len(kv[0])): if m.startswith(k): pin, pout = v + default_priced = False break cost_usd = (i * pin + o * pout + cr * pin * 0.1 + cw * pin * 1.25) / 1_000_000 with _USAGE_LOCK: @@ -219,6 +227,10 @@ def _record_usage(usage, model, cost_usd=None): _USAGE["cw"] += cw _USAGE["cost"] += float(cost_usd or 0.0) _USAGE["n"] += 1 + _USAGE["default_priced"] = _USAGE["default_priced"] or default_priced + name = re.sub(r"[^A-Za-z0-9_.:/@-]", "_", str(model or ""))[:80] + if name and name not in _USAGE["models"]: + _USAGE["models"].append(name) def _record_http_error(status): @@ -245,6 +257,36 @@ def _record_http_error(status): _USAGE["http_err_count"] += 1 +# Set by main() and the review handlers: which review this invocation runs +# and for which Claude Code session, so the usage log line can be attributed. +_USAGE_CONTEXT = {"session_id": "", "review": "stop"} + + +def _log_usage(usage): + """Write this invocation's review usage to the debug log. + + `usage` is a `_usage_metrics()` snapshot, the same numbers that go out + with the hook's metrics. The raw-HTTP review leaves no Claude Code + transcript and no OpenTelemetry event; without this line nothing on the + machine records what it used. `est_cost_usd` is that same rollup: list + prices (the inner CLI's own figure on the Agent SDK path), `~` appended + when a model had no price-table entry and the default rate was used. + """ + if not usage.get("api_calls"): + return + with _USAGE_LOCK: + models = ",".join(_USAGE["models"]) or "-" + approx = "~" if _USAGE["default_priced"] else "" + debug_log( + f"Review usage: review={_USAGE_CONTEXT.get('review') or '-'} " + f"session={_USAGE_CONTEXT.get('session_id') or '-'} " + f"model={models} calls={usage['api_calls']} " + f"in={usage['tok_in']} out={usage['tok_out']} " + f"cache_read={usage['tok_cache_r']} cache_write={usage['tok_cache_w']} " + f"est_cost_usd={usage['cost_usd']:.4f}{approx}" + ) + + def _usage_metrics(): """Snapshot the accumulator as metric keys. Returns {} when no API calls AND no HTTP errors were made so skip-path emits don't burn key budget. diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 1da44e48..87cfb86a 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -83,6 +83,7 @@ from _base import ( # noqa: E402,F401 PROVENANCE_TAG, PROVENANCE_BANNER, _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, + _USAGE_CONTEXT, _log_usage, state_dir as _resolve_state_dir, write_hook_output as _write_hook_output, ) @@ -274,6 +275,7 @@ def emit_metrics( add decision/reason as above. Defaults to "PostToolUse" (commit-review and push-sweep are the most common callers); handle_stop_hook passes "Stop". """ + _log_usage(_usage_metrics()) head = {} if _PV and "pv" not in metrics: head["pv"] = _PV @@ -1202,6 +1204,7 @@ def handle_commit_review_posttooluse(input_data): the Stop hook won't re-flag the same (filePath, vulnerableCode) pair. """ session_id = input_data.get("session_id", "default") + _USAGE_CONTEXT["review"] = "commit" tool_input = input_data.get("tool_input", {}) tool_response = input_data.get("tool_response", {}) cwd = input_data.get("cwd", "") @@ -1756,6 +1759,7 @@ def handle_push_sweep_posttooluse(input_data): command = tool_input.get("command", "") or "" cwd = input_data.get("cwd") session_id = input_data.get("session_id", "") + _USAGE_CONTEXT["review"] = "push" bash_output = ( (tool_response.get("stdout", "") or "") + "\n" @@ -2498,6 +2502,7 @@ def main(): sys.exit(0) session_id = input_data.get("session_id", "default") + _USAGE_CONTEXT["session_id"] = re.sub(r"[^A-Za-z0-9_.-]", "_", str(session_id))[:80] tool_name = input_data.get("tool_name", "") tool_input = input_data.get("tool_input", {}) hook_event_name = input_data.get("hook_event_name", "") diff --git a/plugins/security-guidance/tests/test_review_usage_log.py b/plugins/security-guidance/tests/test_review_usage_log.py new file mode 100644 index 00000000..bca87d51 --- /dev/null +++ b/plugins/security-guidance/tests/test_review_usage_log.py @@ -0,0 +1,116 @@ +"""Each LLM review leaves one usage line in the plugin's debug log.""" +import re + +from conftest import ( + VULN_PY, bash_payload, commit_file, edit_payload, git, metrics_of, run_hook, + stop_payload, ups_payload, +) + +USAGE = re.compile( + r"Review usage: review=(\w+) session=(\S+) model=(\S+) calls=(\d+) " + r"in=(\d+) out=(\d+) cache_read=(\d+) cache_write=(\d+) est_cost_usd=(\d+\.\d{4}~?)$" +) + + +def _usage_lines(env): + log = env["SECURITY_GUIDANCE_DEBUG_LOG"] + try: + text = open(log).read() + except FileNotFoundError: + return [] + return [m.groups() for m in map(USAGE.search, text.splitlines()) if m] + + +def _env(hook_env, tmp_path): + return {**hook_env, "SECURITY_GUIDANCE_DEBUG_LOG": str(tmp_path / "log.txt"), + "SECURITY_REVIEW_MODEL": "claude-opus-5-5"} + + +def test_stop_review_logs_its_usage_with_the_session(workspace, hook_env, tmp_path): + _, repo = workspace + env = _env(hook_env, tmp_path) + run_hook(ups_payload(repo, session_id="sess-1"), env) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py", VULN_PY, session_id="sess-1"), env) + assert _usage_lines(env) == [] + rc, so, _ = run_hook(stop_payload(repo, session_id="sess-1"), env) + + m = metrics_of(so) + assert m["api_calls"] == 1 + # "stub" is not in the price table, so the estimate is marked. + assert _usage_lines(env) == [ + ("stop", "sess-1", "stub", "1", "1", "1", "0", "0", f"{m['cost_usd']:.4f}~"), + ] + + +def test_commit_review_logs_review_commit(workspace, hook_env, tmp_path): + _, repo = workspace + env = _env(hook_env, tmp_path) + _, out = commit_file(repo, "app.py", VULN_PY) + run_hook(bash_payload(repo, "git commit -m change", out, session_id="sess 2/x"), env) + + lines = _usage_lines(env) + assert len(lines) == 1 + assert lines[0][:2] == ("commit", "sess_2_x") and lines[0][3] == "1" + + +def test_no_line_when_no_review_ran(workspace, hook_env, tmp_path): + _, repo = workspace + env = _env(hook_env, tmp_path) + run_hook(ups_payload(repo), env) + run_hook(stop_payload(repo), env) + assert _usage_lines(env) == [] + + +def test_failed_request_logs_no_usage(workspace, hook_env, stub_api, tmp_path): + _, repo = workspace + env = _env(hook_env, tmp_path) + stub_api.status = 400 + _, out = commit_file(repo, "app.py", VULN_PY) + run_hook(bash_payload(repo, "git commit -m change", out), env) + assert _usage_lines(env) == [] + + +def test_push_review_logs_review_push(workspace, hook_env, tmp_path): + _, repo = workspace + env = _env(hook_env, tmp_path) + remote = tmp_path / "remote.git" + git(tmp_path, "init", "-q", "--bare", str(remote)) + git(repo, "remote", "add", "origin", str(remote)) + git(repo, "push", "-q", "-u", "origin", "main") + base = git(repo, "rev-parse", "HEAD").strip() + sha, _ = commit_file(repo, "app.py", VULN_PY) + git(repo, "push", "-q", "origin", "main") + out = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n" + run_hook(bash_payload(repo, "git push origin main", out), env) + + lines = _usage_lines(env) + assert len(lines) == 1 and lines[0][0] == "push" + + +def test_line_carries_the_same_numbers_as_the_metrics(tmp_path, monkeypatch): + import _base + logged = [] + monkeypatch.setattr(_base, "debug_log", logged.append) + monkeypatch.setattr(_base, "_USAGE", { + "in": 0, "out": 0, "cr": 0, "cw": 0, "cost": 0.0, "n": 0, + "http_err_last": 0, "http_err_count": 0, "models": [], "default_priced": False, + }) + monkeypatch.setattr(_base, "_USAGE_CONTEXT", {"session_id": "abc", "review": "stop"}) + _base._log_usage(_base._usage_metrics()) + assert logged == [] + + _base._record_usage({"input_tokens": 31994, "output_tokens": 3250, + "cache_read_input_tokens": 7, "cache_creation_input_tokens": 9}, + "claude-opus-5-5") + _base._record_usage({"input_tokens": 1, "output_tokens": 1}, "opus", cost_usd=0.5) + _base._record_usage({"input_tokens": 1, "output_tokens": 1}, + "bad model\nReview usage: forged") + usage = _base._usage_metrics() + _base._log_usage(usage) + assert logged == [ + "Review usage: review=stop session=abc " + "model=claude-opus-5-5,opus,bad_model_Review_usage:_forged calls=3 " + f"in=31996 out=3252 cache_read=7 cache_write=9 est_cost_usd={usage['cost_usd']:.4f}~" + ] + assert usage["cost_usd"] > 0.69 |
