summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/tests
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-11-05 14:28:20 -0800
committerGitHub <noreply@github.com>2026-11-05 14:28:20 -0800
commiteba976de6eed86f916e2c3ccd6f176faf19c3bc7 (patch)
tree86843a325f1cae49ae38b2d0cf43b5e1e3d01f34 /plugins/security-guidance/tests
parent0672a295389aa640fb0544ef03a768ac37b30daa (diff)
parent69c35c1f37db93d13dee0513587064fafc40be26 (diff)
Merge pull request #6965 from anthropics/mhegazy/sg-agentic-stop-on-auth
security-guidance: stop the commit reviewer on refused credentials, end hung reviews in time
Diffstat (limited to 'plugins/security-guidance/tests')
-rw-r--r--plugins/security-guidance/tests/test_agentic_auth_stop.py148
-rw-r--r--plugins/security-guidance/tests/test_inflight_reviews.py116
-rw-r--r--plugins/security-guidance/tests/test_review_outcomes.py20
3 files changed, 284 insertions, 0 deletions
diff --git a/plugins/security-guidance/tests/test_agentic_auth_stop.py b/plugins/security-guidance/tests/test_agentic_auth_stop.py
new file mode 100644
index 00000000..a2108cfc
--- /dev/null
+++ b/plugins/security-guidance/tests/test_agentic_auth_stop.py
@@ -0,0 +1,148 @@
+"""The agentic reviewer stops as soon as its credentials are refused, instead
+of waiting for the inner CLI to give up, and leaves every other run alone."""
+import os
+import subprocess
+import sys
+import types
+
+import pytest
+
+import llm
+from conftest import write_cli
+
+
+class _Assistant:
+ def __init__(self, error=None):
+ self.content, self.error = [], error
+
+
+class _System:
+ subtype = "api_retry"
+
+ def __init__(self, status):
+ self.data = {"error_status": status}
+
+
+@pytest.fixture
+def sdk(monkeypatch, tmp_path):
+ """Replays `script.messages`, then a clean result, and counts what the
+ review read of them."""
+ script = types.SimpleNamespace(messages=[], read=0)
+
+ class ClaudeAgentOptions:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+
+ class ResultMessage:
+ subtype, usage, total_cost_usd = "success", {}, 0.0
+ structured_output = {"findings": []}
+
+ async def query(prompt, options):
+ for m in script.messages:
+ script.read += 1
+ yield m
+ yield ResultMessage()
+
+ mod = types.ModuleType("claude_agent_sdk")
+ mod.ClaudeAgentOptions, mod.ResultMessage, mod.query = ClaudeAgentOptions, ResultMessage, query
+ mod.AssistantMessage = _Assistant
+ monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "")
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state"))
+ monkeypatch.delenv("CLAUDE_CODE_REMOTE", raising=False)
+ return script
+
+
+def _review(repo):
+ return llm.agentic_review(str(repo), [("a.py", "+x = 1\n")], ["a.py"])[2]
+
+
+class TestStopsOnRefusedCredentials:
+ def test_first_auth_failure_ends_the_review(self, sdk, tmp_path):
+ sdk.messages = [_Assistant(error="authentication_failed") for _ in range(50)]
+ m = _review(tmp_path)
+ assert sdk.read == 1
+ assert m["agentic_fallback"] == "investigate:_ReviewerAuthFailed"
+
+ def test_repeated_401_retries_end_the_review(self, sdk, tmp_path):
+ sdk.messages = [_System(401) for _ in range(10)]
+ m = _review(tmp_path)
+ assert sdk.read == llm._AGENTIC_MAX_401_RETRIES
+ assert m["agentic_fallback"] == "investigate:_ReviewerAuthFailed"
+
+
+class TestLeavesOtherRunsAlone:
+ def test_a_remote_session_rides_out_401_retries(self, sdk, tmp_path, monkeypatch):
+ monkeypatch.setenv("CLAUDE_CODE_REMOTE", "true")
+ sdk.messages = [_System(401) for _ in range(10)]
+ assert "agentic_fallback" not in _review(tmp_path)
+
+ def test_a_login_renewed_after_one_401_goes_on(self, sdk, tmp_path):
+ sdk.messages = [_System(401), _Assistant()]
+ assert "agentic_fallback" not in _review(tmp_path)
+
+ def test_401s_that_are_not_in_a_row_do_not_add_up(self, sdk, tmp_path):
+ sdk.messages = [_System(401), _System(401), _Assistant()] * 3
+ assert "agentic_fallback" not in _review(tmp_path)
+
+ def test_other_retries_do_not_count(self, sdk, tmp_path):
+ sdk.messages = [_System(s) for s in (529, 429, None, 500, 529, 529)]
+ assert "agentic_fallback" not in _review(tmp_path)
+
+ def test_other_assistant_errors_do_not_stop_it(self, sdk, tmp_path):
+ sdk.messages = [_Assistant(error="rate_limit"), _Assistant(error="server_error")]
+ assert "agentic_fallback" not in _review(tmp_path)
+
+ def test_a_message_without_the_field_is_read_as_before(self, sdk, tmp_path):
+ class Old:
+ content = []
+ sys.modules["claude_agent_sdk"].AssistantMessage = Old
+ sdk.messages = [Old()]
+ assert "agentic_fallback" not in _review(tmp_path)
+
+
+_REFUSED_CLI = """
+import json, os, sys, time
+open(os.environ["SG_TEST_PID_FILE"], "w").write(str(os.getpid()))
+def send(m):
+ sys.stdout.write(json.dumps(m) + chr(10)); sys.stdout.flush()
+for line in sys.stdin:
+ m = json.loads(line)
+ if m.get("type") == "control_request":
+ send({"type": "control_response", "response": {"subtype": "success",
+ "request_id": m["request_id"], "response": {}}})
+ elif m.get("type") == "user":
+ for _ in range(500):
+ send({"type": "assistant", "error": "authentication_failed", "message": {
+ "role": "assistant", "model": "m", "content": [{"type": "text", "text": "401"}]}})
+ time.sleep(0.02)
+ time.sleep(60)
+"""
+
+_DRIVER = """
+import json, llm, os, sys, time
+start = time.time()
+metrics = llm.agentic_review(sys.argv[1], [("a.py", "+x = 1")], ["a.py"])[2]
+pid = int(open(os.environ["SG_TEST_PID_FILE"]).read())
+try:
+ os.kill(pid, 0); alive = True
+except OSError:
+ alive = False
+print(json.dumps({"fallback": metrics.get("agentic_fallback"), "alive": alive}), flush=True)
+os._exit(0)
+"""
+
+
+def test_real_sdk_closes_the_cli_quietly(tmp_path):
+ """Stops the real SDK's child, and prints no traceback for the hook's
+ stderr, which reaches the session."""
+ pytest.importorskip("claude_agent_sdk")
+ env = {**os.environ, "SG_TEST_PID_FILE": str(tmp_path / "pid"),
+ "SG_AGENTIC_CLI_PATH": str(write_cli(tmp_path, "claude", _REFUSED_CLI)),
+ "SECURITY_WARNINGS_STATE_DIR": str(tmp_path / "state"),
+ "PYTHONPATH": str(os.path.dirname(llm.__file__))}
+ r = subprocess.run([sys.executable, "-c", _DRIVER, str(tmp_path)], env=env,
+ capture_output=True, text=True, timeout=60)
+ assert "Traceback" not in r.stderr, r.stderr
+ assert '"fallback": "investigate:_ReviewerAuthFailed"' in r.stdout, (r.stdout, r.stderr)
+ assert '"alive": false' in r.stdout, r.stdout
diff --git a/plugins/security-guidance/tests/test_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py
index 4c339a5f..fa998501 100644
--- a/plugins/security-guidance/tests/test_inflight_reviews.py
+++ b/plugins/security-guidance/tests/test_inflight_reviews.py
@@ -4,6 +4,7 @@ import json
import os
import subprocess
import sys
+import threading
import time
import pytest
@@ -152,6 +153,63 @@ def test_push_stops_waiting_after_the_limit(tmp_path, hook_env, stub_api):
assert len(_reviews(stub_api)) == 1
+def test_a_push_that_waited_ends_within_the_hook_limit(tmp_path, monkeypatch):
+ """The wait for a commit review and the race share one limit; a race that
+ restarts it runs the hook past Claude Code's timeout, with no notice."""
+ import security_reminder_hook as hook
+
+ repo, remote = _repo_with_remote(tmp_path)
+ _, sha, _, _ = _commit_and_push(repo, remote)
+ monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 1.0)
+ monkeypatch.setattr(hook, "_RACE_END_S", 1.5)
+ monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
+ monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0")
+ release = threading.Event()
+ monkeypatch.setattr(hook, "agentic_review", lambda *a, **k: release.wait(20))
+ monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: release.wait(20))
+
+ started = time.monotonic()
+ try:
+ with _held_by_another_review(repo, sha):
+ _, waited = diffstate._reviewed_after_inflight(str(repo), [sha], 1.0, poll_s=0.05)
+ _, _, m = hook._agentic_review_with_race(
+ str(repo), [], [], [], spent_s=waited)
+ finally:
+ release.set()
+ assert 1.0 <= waited < 1.5
+ assert 1.5 <= time.monotonic() - started < 2.4
+ assert m["review_failed"] is True and m["api_error"] == hook._RACE_TIMED_OUT
+
+
+def test_the_push_handler_counts_its_wait(tmp_path, agentic_env, stub_api):
+ repo, remote = _repo_with_remote(tmp_path)
+ _, sha, _, push_out = _commit_and_push(repo, remote)
+ log = tmp_path / "race.log"
+ env = {**agentic_env, "SG_INFLIGHT_WAIT_S": "2", "SG_AGENTIC_RACE_DELAY_S": "60",
+ "SECURITY_GUIDANCE_DEBUG_LOG": str(log)}
+ with _held_by_another_review(repo, sha):
+ _, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), env)
+ assert metrics_of(so)["inflight_wait_s"] >= 2
+ assert "already spent, fallback starts after 5" in log.read_text()
+
+
+def test_the_fallback_starts_sooner_after_a_wait(tmp_path, monkeypatch):
+ import security_reminder_hook as hook
+
+ monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
+ monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "180")
+ release = threading.Event()
+ monkeypatch.setattr(hook, "agentic_review", lambda *a, **k: release.wait(20))
+ monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: ("guidance", []))
+ monkeypatch.setattr(hook.llm, "last_review_failed", lambda: False)
+ try:
+ g, _, m = hook._agentic_review_with_race(str(tmp_path), [], [], [], spent_s=240.0)
+ finally:
+ release.set()
+ assert g == "guidance"
+ assert (m["race_winner"], m["race_delay_s"], m["race_started"]) == (2, 0, 1)
+
+
def test_push_does_not_wait_when_an_earlier_commit_needs_review_anyway(tmp_path, hook_env, stub_api):
repo, remote = _repo_with_remote(tmp_path)
base = git(repo, "rev-parse", "HEAD").strip()
@@ -376,3 +434,61 @@ def test_windows_lock_is_off_where_the_call_is_missing(monkeypatch):
monkeypatch.setattr(diffstate, "_win_lock_file_ex", None)
with pytest.raises(OSError):
diffstate._win_lock_nb(7, exclusive=True)
+
+
+_SHORT_LIMIT = (
+ "import sys\n"
+ "sys.path.insert(0, sys.argv[1])\n"
+ "import security_reminder_hook as hook\n"
+ "hook._RACE_END_S = float(sys.argv[2])\n"
+ "hook.main()\n"
+)
+
+
+def _run_with_limit(payload, env, limit_s):
+ started = time.monotonic()
+ r = subprocess.run(
+ [sys.executable, "-c", _SHORT_LIMIT, _HOOKS_DIR, str(limit_s)],
+ input=json.dumps(payload), capture_output=True, text=True, env=env, timeout=30)
+ return time.monotonic() - started, r
+
+
+def test_single_shot_after_a_fast_agentic_failure_ends_in_time(
+ tmp_path, hook_env, failing_inner_cli, stub_api):
+ """The agentic run fails before the fallback starts, and the single-shot
+ review that follows hangs: the session still hears before the hook limit."""
+ pytest.importorskip("claude_agent_sdk")
+ repo, _ = _repo_with_remote(tmp_path)
+ _, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n")
+ stub_api.delay = 6
+ env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli,
+ "SG_AGENTIC_RACE_DELAY_S": "60"}
+ took, r = _run_with_limit(bash_payload(repo, "git commit -m change", commit_out), env, 4)
+ assert 4 <= took < 10, r.stderr
+ assert r.returncode == 2 and "did not finish in time" in r.stderr
+ assert metrics_of(r.stdout)["agentic_fallback"] == 2
+
+
+def test_single_shot_after_a_push_wait_ends_in_time(
+ tmp_path, hook_env, failing_inner_cli, stub_api):
+ pytest.importorskip("claude_agent_sdk")
+ repo, remote = _repo_with_remote(tmp_path)
+ _, sha, _, push_out = _commit_and_push(repo, remote)
+ stub_api.delay = 10
+ env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli,
+ "SG_INFLIGHT_WAIT_S": "4", "SG_AGENTIC_RACE_DELAY_S": "60"}
+ with _held_by_another_review(repo, sha):
+ took, r = _run_with_limit(bash_payload(repo, "git push origin main", push_out), env, 8)
+ assert 8 <= took < 11.5, r.stderr # 12 s if the wait did not count
+ assert r.returncode == 2 and "did not finish in time" in r.stderr
+ assert metrics_of(r.stdout)["inflight_wait_s"] >= 4
+
+
+def test_single_shot_with_the_agentic_review_off_ends_in_time(tmp_path, hook_env, stub_api):
+ repo, _ = _repo_with_remote(tmp_path)
+ _, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n")
+ stub_api.delay = 6
+ env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "0"}
+ took, r = _run_with_limit(bash_payload(repo, "git commit -m change", commit_out), env, 4)
+ assert 4 <= took < 10, r.stderr
+ assert r.returncode == 2 and "did not finish in time" in r.stderr
diff --git a/plugins/security-guidance/tests/test_review_outcomes.py b/plugins/security-guidance/tests/test_review_outcomes.py
index 887ff9c0..806e9bdd 100644
--- a/plugins/security-guidance/tests/test_review_outcomes.py
+++ b/plugins/security-guidance/tests/test_review_outcomes.py
@@ -1,5 +1,6 @@
"""A review that got no verdict is never reported as clean."""
import json
+import threading
import time
import pytest
@@ -188,6 +189,25 @@ class TestFailedReviewIsNotClean:
run.calls = calls
return run
+ def test_review_ends_when_neither_side_returns(self, race, monkeypatch):
+ """A request that never answers holds both sides; the deadline holds anyway."""
+ monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 0.1)
+ monkeypatch.setattr(hook, "_RACE_END_S", 0.2)
+ release = threading.Event()
+ monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: release.wait(5))
+
+ def stuck_agentic(*a, **k):
+ release.wait(5)
+ started = time.monotonic()
+ try:
+ guidance, vulns, m = race(stuck_agentic)
+ finally:
+ release.set()
+ assert time.monotonic() - started < 2
+ assert (guidance, vulns) == (None, [])
+ assert m["review_failed"] is True
+ assert m["api_error"] == hook._RACE_TIMED_OUT
+
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."""