diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-31 17:01:36 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-31 17:01:47 +0000 |
| commit | 9d796f8636954cece459f45ff7386eaee912de5c (patch) | |
| tree | 9d5bb389fd47a62b5431d95520fe5769a63501e6 /plugins | |
| parent | a7ba5b93db0c7c8d17f3f1d25853adca79598a1a (diff) | |
security-guidance: stop the commit reviewer on refused credentials, end hung reviews in time
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 104 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 14 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_agentic_auth_stop.py | 148 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_review_outcomes.py | 20 |
4 files changed, 247 insertions, 39 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 468d9e6d..f1f88427 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -17,6 +17,7 @@ Two reassignable globals here are read by handlers in ``_last_review_truncated_bytes``. Handlers reference them as ``llm.X`` (not via ``from``-import) so they observe reassignment. """ +import contextlib import hashlib import json import logging @@ -1023,9 +1024,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, _record_usage(getattr(msg, "usage", None) or {}, chosen_model, cost_usd=getattr(msg, "total_cost_usd", None)) elif getattr(msg, "subtype", None) == "api_retry": - data = getattr(msg, "data", None) - status = data.get("error_status") if isinstance(data, dict) else None - _retried_after.add(str(status) if isinstance(status, int) else "no response") + status = _api_retry_status(msg) + _retried_after.add(str(status) if status is not None else "no response") return structured # 60s ceiling: a single review request on a healthy 3P endpoint completes @@ -1838,6 +1838,23 @@ def _run_inner_cli(start: Callable[[], Any], stderr_lines: List[str]) -> Any: return start() +class _ReviewerAuthFailed(Exception): + """The agentic reviewer's credentials were refused; retrying cannot help.""" + + +# Retry notices in a row, each after a 401, at which the review stops. One is +# normal: the CLI renews a stored login after a 401 and tries again. Not used +# in a remote session, where the CLI waits out a short sign-in outage on purpose. +_AGENTIC_MAX_401_RETRIES = 3 + + +def _api_retry_status(msg: Any) -> Optional[int]: + """The HTTP status of the CLI's api_retry notice, if it gives one.""" + data = getattr(msg, "data", None) + status = data.get("error_status") if isinstance(data, dict) else None + return status if isinstance(status, int) else None + + def _agentic_spawn_env() -> Dict[str, str]: """opts.env for the SDK-spawned inner `claude` CLI. @@ -2116,39 +2133,54 @@ def _agentic_review( # Blocks are matched by shape so older SDK builds need no extra import. file_tool_ids = set() - async for msg in query(prompt=_once(), options=opts): - if isinstance(msg, AssistantMessage): - n += 1 - for b in getattr(msg, "content", None) or []: - if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS - and getattr(b, "id", None)): - file_tool_ids.add(b.id) - ctx["rv_tool_calls"] += 1 - elif isinstance(msg, ResultMessage): - subtype = msg.subtype - if msg.structured_output is not None: - structured = msg.structured_output - # SDK ResultMessage carries aggregate usage + cache-aware - # cost across the whole multi-turn run; prefer its cost over - # the price-table estimate. getattr guards older SDK builds. - _record_usage(getattr(msg, "usage", None) or {}, model, - cost_usd=getattr(msg, "total_cost_usd", None)) - for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")): - value = getattr(msg, attr, None) - # Counting must never fail the review: anything that - # is not a positive finite number adds nothing. - if (isinstance(value, (int, float)) and not isinstance(value, bool) - and 0 < value < float("inf")): - ctx[key] += int(value) - else: - # Tool results come back as user messages. - content = getattr(msg, "content", None) - if isinstance(content, list): - ctx["rv_tool_err"] += sum( - 1 for b in content - if getattr(b, "is_error", None) is True - and getattr(b, "tool_use_id", None) in file_tool_ids - ) + auth_retries = 0 + # Closed on the way out, also on a raise, so the CLI stops with the review. + async with contextlib.aclosing(query(prompt=_once(), options=opts)) as messages: + async for msg in messages: + if isinstance(msg, AssistantMessage): + # Old CLIs answer each refused request by asking the model + # again, hundreds of times; the message is the same on all. + if getattr(msg, "error", None) == "authentication_failed": + raise _ReviewerAuthFailed("authentication_failed") + auth_retries = 0 + n += 1 + for b in getattr(msg, "content", None) or []: + if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS + and getattr(b, "id", None)): + file_tool_ids.add(b.id) + ctx["rv_tool_calls"] += 1 + elif isinstance(msg, ResultMessage): + subtype = msg.subtype + if msg.structured_output is not None: + structured = msg.structured_output + # SDK ResultMessage carries aggregate usage + cache-aware + # cost across the whole multi-turn run; prefer its cost over + # the price-table estimate. getattr guards older SDK builds. + _record_usage(getattr(msg, "usage", None) or {}, model, + cost_usd=getattr(msg, "total_cost_usd", None)) + for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")): + value = getattr(msg, attr, None) + # Counting must never fail the review: anything that + # is not a positive finite number adds nothing. + if (isinstance(value, (int, float)) and not isinstance(value, bool) + and 0 < value < float("inf")): + ctx[key] += int(value) + elif getattr(msg, "subtype", None) == "api_retry": + # A gateway's 401 without the API's x-should-retry: false + # keeps the CLI retrying for about three minutes. + auth_retries = auth_retries + 1 if _api_retry_status(msg) == 401 else 0 + if (auth_retries >= _AGENTIC_MAX_401_RETRIES + and not os.environ.get("CLAUDE_CODE_REMOTE")): + raise _ReviewerAuthFailed(f"{auth_retries} retries after HTTP 401") + else: + # Tool results come back as user messages. + content = getattr(msg, "content", None) + if isinstance(content, list): + ctx["rv_tool_err"] += sum( + 1 for b in content + if getattr(b, "is_error", None) is True + and getattr(b, "tool_use_id", None) in file_tool_ids + ) return structured, n, subtype def _run(system: str, prompt: str, *, schema: Dict[str, Any] diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 3efe344e..6897ea66 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -1270,6 +1270,10 @@ COMMIT_REVIEW_ENABLED = is_commit_review_enabled() # neither side waits for the other any longer; well inside Claude Code's # 10-minute hook timeout. _RACE_MAX_WAIT_S = 480 +# Seconds after which the review ends even if a side is still waiting on a +# request that does not answer, with time left to tell the session before +# Claude Code kills the hook. The inner CLI exits with the hook. +_RACE_END_S = 570 # api_error for a race that hit that deadline with no verdict. _RACE_TIMED_OUT = -2 @@ -1313,6 +1317,7 @@ def _agentic_review_with_race( agentic_done = _th.Event() fallback_result: Dict[str, Any] = {} deadline = _t.monotonic() + _RACE_MAX_WAIT_S + timed_out = (None, [], {"agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT}) def _agentic() -> None: try: @@ -1356,7 +1361,11 @@ def _agentic_review_with_race( _th.Thread(target=_agentic, daemon=True).start() _th.Thread(target=_fallback, daemon=True).start() - winner, (g, v, m) = q.get() + try: + winner, (g, v, m) = q.get(timeout=_RACE_END_S) + except _queue.Empty: + debug_log("review race: nothing returned in time") + winner, (g, v, m) = "fallback", timed_out # What the agentic run saw of its directory, and how much work it did, # is kept when the fallback's result replaces it below. reviewer_context = ( @@ -1369,8 +1378,7 @@ def _agentic_review_with_race( if fallback_done.wait(timeout=max(0.0, deadline - _t.monotonic())): winner, (g, v, m) = "fallback", fallback_result["r"] else: - winner, (g, v, m) = "fallback", (None, [], { - "agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT}) + winner, (g, v, m) = "fallback", timed_out m = {**m, **reviewer_context} # a copy: don't mutate the callee's metrics dict m["race_winner"] = 1 if winner == "agentic" else 2 m["race_delay_s"] = delay_s 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_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.""" |
