summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/tests
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-15 22:19:13 +0000
committerClaude <noreply@anthropic.com>2026-10-15 22:20:59 +0000
commit9e4906b18c07462941ff499d47576bf04c40534a (patch)
treee8c791647db7a47c623ed01f4dc4f5e7dd02e1e5 /plugins/security-guidance/tests
parenteb638fbf680ae279a9e6699d2243344ccddc9624 (diff)
parent83e004a98e1fc268a94cc6a74b1b054630542696 (diff)
Merge remote-tracking branch 'origin/main' into mhegazy/sg-diff-prefix-configmhegazy/sg-diff-prefix-config
Diffstat (limited to 'plugins/security-guidance/tests')
-rw-r--r--plugins/security-guidance/tests/conftest.py78
-rw-r--r--plugins/security-guidance/tests/test_custom_headers.py95
-rw-r--r--plugins/security-guidance/tests/test_diff_parsing.py99
-rw-r--r--plugins/security-guidance/tests/test_findings_delivery.py88
-rw-r--r--plugins/security-guidance/tests/test_review_outcomes.py298
-rw-r--r--plugins/security-guidance/tests/test_secret_shaped_paths.py95
-rw-r--r--plugins/security-guidance/tests/test_untracked_cap.py85
7 files changed, 838 insertions, 0 deletions
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
diff --git a/plugins/security-guidance/tests/test_secret_shaped_paths.py b/plugins/security-guidance/tests/test_secret_shaped_paths.py
new file mode 100644
index 00000000..bfd5180d
--- /dev/null
+++ b/plugins/security-guidance/tests/test_secret_shaped_paths.py
@@ -0,0 +1,95 @@
+import os
+import subprocess
+
+import pytest
+
+from conftest import (
+ GIT_ENV, git, make_repo, metrics_of, run_hook, stop_payload, ups_payload,
+)
+
+import gitutil
+
+
+@pytest.mark.parametrize("path", [
+ "dot_config/private_example/encrypted_private_token",
+ "encrypted_private_dot_netrc",
+ "home/encrypted_config.yaml",
+ "id_ed25519",
+ ".ssh/id_rsa",
+ "private_dot_ssh/private_id_ecdsa",
+ "deploy_rsa",
+ "keys/github_ed25519",
+ ".env.production.json",
+ ".env.local.yaml",
+ "config/dot_env.toml",
+ "private_dot_netrc",
+ "dot_aws/credentials",
+ "Deploy_RSA",
+])
+def test_secret_shaped_names_are_not_reviewable(path):
+ assert gitutil._is_secret_shaped(path)
+ assert not gitutil._is_reviewable_source(path)
+
+
+@pytest.mark.parametrize("path", [
+ "src/private_api.py",
+ "src/id_generator.py",
+ "lib/encrypted_store.py",
+ "crypto/rsa.py",
+ "auth/sign_rsa.go",
+ "app/credentials.py",
+ "scripts/run_migrations.sh",
+ "dot_product.py",
+ "config/environment.json",
+ "bin/deploy",
+ "Dockerfile.dev",
+ "executable_backup.sh",
+])
+def test_ordinary_source_stays_reviewable(path):
+ assert not gitutil._is_secret_shaped(path)
+ assert gitutil._is_reviewable_source(path)
+
+
+def _staged_diff(repo):
+ r = subprocess.run(
+ [*gitutil.GIT_CMD, "diff", "--cached", "--no-color", "-M"], cwd=repo,
+ capture_output=True, env={**os.environ, **GIT_ENV},
+ )
+ assert r.returncode == 0, r.stderr
+ return r.stdout.decode("utf-8", errors="replace")
+
+
+def test_secret_content_is_left_out_of_the_parsed_diff(tmp_path):
+ repo = make_repo(tmp_path / "repo")
+ (repo / "encrypted_private_token").write_text("CIPHERTEXT_BODY\n")
+ (repo / "id_ed25519").write_text("PRIVATE_KEY_BODY\n")
+ (repo / ".env.production.json").write_text('{"API_KEY": "ENV_SECRET_BODY"}\n')
+ (repo / "app.py").write_text("import os\nos.system(input())\n")
+ git(repo, "add", "-A")
+ diff = _staged_diff(repo)
+ parsed = gitutil.parse_diff_into_files(diff)
+ assert [p for p, _ in parsed] == ["app.py"]
+ assert "_BODY" not in "".join(c for _, c in parsed)
+ assert gitutil.extract_file_paths_from_diff(diff) == ["app.py"]
+
+
+def test_rename_away_from_a_secret_name_is_left_out(tmp_path):
+ body = "".join(f"KEY_{i}=SECRET_VALUE_{i}\n" for i in range(30))
+ repo = make_repo(tmp_path / "repo", {"deploy_rsa": body})
+ git(repo, "mv", "deploy_rsa", "notes.sh")
+ (repo / "notes.sh").write_text(body + "KEY_NEW=SECRET_VALUE_NEW\n")
+ git(repo, "add", "-A")
+ diff = _staged_diff(repo)
+ assert "rename from deploy_rsa" in diff
+ assert gitutil.parse_diff_into_files(diff) == []
+ assert gitutil.extract_file_paths_from_diff(diff) == []
+
+
+def test_stop_hook_reports_how_many_files_it_left_out(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo")
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "id_ed25519").write_text("-----BEGIN OPENSSH PRIVATE KEY-----\n")
+ (repo / ".env.local").write_text("TOKEN=abc\n")
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ assert metrics_of(stdout).get("secret_shaped_skipped") == 2
+ assert stub_api.calls == []
diff --git a/plugins/security-guidance/tests/test_untracked_cap.py b/plugins/security-guidance/tests/test_untracked_cap.py
new file mode 100644
index 00000000..00fd4015
--- /dev/null
+++ b/plugins/security-guidance/tests/test_untracked_cap.py
@@ -0,0 +1,85 @@
+import os
+import time
+
+from conftest import make_repo, metrics_of, run_hook, stop_payload, ups_payload
+
+import diffstate
+
+SRC = "import os\nos.system(input())\n"
+
+
+def _review(repo, snapshot):
+ paths, _base, root, _untracked, metrics = diffstate.compute_v2_review_set(
+ str(repo), None, None, snapshot)
+ return sorted(os.path.relpath(p, root) for p in paths), metrics
+
+
+class TestCappedSnapshot:
+ def _repo(self, tmp_path, monkeypatch, n=30, cap=10):
+ monkeypatch.setattr(diffstate, "UNTRACKED_BASELINE_CAP", cap)
+ monkeypatch.setattr(diffstate, "_CAPPED_BASELINE_SLACK_NS", 20_000_000)
+ repo = make_repo(tmp_path / "repo")
+ for i in range(n):
+ (repo / f"old_{i:03d}.py").write_text(SRC)
+ time.sleep(0.1)
+ return repo
+
+ def test_snapshot_records_when_it_was_capped(self, tmp_path, monkeypatch):
+ repo = self._repo(tmp_path, monkeypatch)
+ before = time.time_ns()
+ snap = diffstate._list_untracked(str(repo))
+ assert before <= snap[diffstate.UNTRACKED_CAPPED_AT_KEY] <= time.time_ns()
+ assert len(snap) == 10 + 1
+
+ def test_uncapped_snapshot_has_no_marker(self, tmp_path, monkeypatch):
+ repo = self._repo(tmp_path, monkeypatch, n=5)
+ assert diffstate.UNTRACKED_CAPPED_AT_KEY not in diffstate._list_untracked(str(repo))
+
+ def test_files_past_the_cap_are_not_reviewed_when_untouched(self, tmp_path, monkeypatch):
+ repo = self._repo(tmp_path, monkeypatch)
+ snap = diffstate._list_untracked(str(repo))
+ review, metrics = _review(repo, snap)
+ assert review == []
+ assert metrics["preexisting_untracked_excluded"] == 30
+
+ def test_new_and_edited_files_past_the_cap_are_reviewed(self, tmp_path, monkeypatch):
+ repo = self._repo(tmp_path, monkeypatch)
+ snap = diffstate._list_untracked(str(repo))
+ time.sleep(0.1)
+ (repo / "zz_new.py").write_text(SRC)
+ (repo / "old_025.py").write_text(SRC + "eval(input())\n")
+ (repo / "old_003.py").write_text(SRC + "eval(input())\n") # inside the cap
+ review, _ = _review(repo, snap)
+ assert review == ["old_003.py", "old_025.py", "zz_new.py"]
+
+ def test_file_moved_in_with_an_old_mtime_is_reviewed(self, tmp_path, monkeypatch):
+ repo = self._repo(tmp_path, monkeypatch)
+ snap = diffstate._list_untracked(str(repo))
+ time.sleep(0.1)
+ new = repo / "zz_extracted.py"
+ new.write_text(SRC)
+ os.utime(new, (1_600_000_000, 1_600_000_000)) # as tar or cp -p would leave it
+ review, _ = _review(repo, snap)
+ assert review == ["zz_extracted.py"]
+
+
+def test_stop_hook_does_not_re_review_files_past_the_cap(tmp_path, hook_env, stub_api):
+ """More untracked files than the snapshot holds: the same old files must
+ not be sent for review turn after turn (#6407)."""
+ repo = make_repo(tmp_path / "repo")
+ n_files = diffstate.UNTRACKED_BASELINE_CAP + 60
+ for i in range(n_files):
+ (repo / f"old_{i:05d}.py").write_text(SRC)
+ time.sleep(2.2) # older than the snapshot by more than the timestamp slack
+
+ for _turn in range(2):
+ run_hook(ups_payload(repo), hook_env)
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ # Telemetry: a count above the cap is how this path shows up.
+ assert metrics_of(stdout)["preexisting_untracked_excluded"] == n_files
+ assert stub_api.calls == []
+
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "zz_new.py").write_text(SRC)
+ run_hook(stop_payload(repo), hook_env)
+ assert len([c for c in stub_api.calls if "messages" in c]) == 1