diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-19 17:05:01 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-19 17:05:01 +0000 |
| commit | 5ffcb09d596798a7531fc8651336dff478852061 (patch) | |
| tree | 3a529db7c1b41a54346dc5e9e1eae7d3906f2f36 /plugins | |
| parent | e0d9e154cc7c8d545f5d78c2f51fb9c0dc655b08 (diff) | |
security-guidance: keep a turn's review when the gateway sign-in check gives no answer
When `claude auth status` gives no usable answer, the Stop hook skipped
the review and dropped the turn's changes, so they were never reviewed
even once the check answered. They are now kept for the next Stop
review, as for other transient skips.
A gateway review that runs out of time is no longer tried again on
Sonnet: what makes it do so (a rejected sign-in, an unreachable gateway)
does not depend on the model, and the second attempt doubled the wait.
The timeout's log line now says which API statuses the CLI retried, and
includes the CLI's stderr.
The new tests no longer share one state file across sessions when run
inside a remote session.
Diffstat (limited to 'plugins')
4 files changed, 105 insertions, 17 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index a58bd54f..c2c9cdd1 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -608,6 +608,13 @@ _GATEWAY_STATE_KEY = "gateway_sign_in" # The CLI that reviews for a signed-in gateway session, "" when this process # decided not to use the gateway route, None before it has decided. _gateway_cli: Optional[str] = None +# True when this process asked the CLI about the sign-in and got no usable +# answer: the reviews are skipped, but the session may well be signed in. +_gateway_check_unanswered = False +# True once a review through the gateway route ran out of time. What makes +# it do so (a rejected sign-in, a gateway that cannot be reached) does not +# depend on the model, so the Sonnet attempt is not made after it. +_gateway_review_timed_out = False def _user_cli_path() -> Optional[str]: @@ -699,7 +706,7 @@ def gateway_review_cli(session_id) -> Optional[str]: no from the CLI is kept for the rest of the session, so signing in or out mid-session takes effect in the next one. When the CLI gives no usable answer, nothing is saved, so the next hook asks again.""" - global _gateway_cli + global _gateway_cli, _gateway_check_unanswered if _gateway_cli is not None: return _gateway_cli or None cli = _user_cli_path() or "" @@ -720,6 +727,7 @@ def gateway_review_cli(session_id) -> Optional[str]: debug_log(f"gateway check: using this session's saved answer (signed in: {ok})") else: ok = _gateway_signed_in(cli) + _gateway_check_unanswered = ok is None if ok is not None: def _save(state): state[_GATEWAY_STATE_KEY] = {"cli": cli, "ok": ok} @@ -745,7 +753,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, No tools (see _only_tools_args) — the security review only needs structured output, not Read/Grep/Glob. Single turn keeps cost predictable. """ - global _last_call_claude_http_error + global _last_call_claude_http_error, _gateway_review_timed_out _last_call_claude_http_error = None route = "gateway" if cli_path else "3P" @@ -789,6 +797,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, # error (auth missing, model id wrong, etc.) in the debug log instead # of just "exit code 1". _captured_stderr: List[str] = [] + # HTTP statuses (or "no response") the CLI said it retried an API request after. + _retried_after: set = set() async def _arun(): opts = ClaudeAgentOptions( @@ -821,6 +831,10 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, structured = msg.structured_output _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") return structured # 60s ceiling: a single review request on a healthy 3P endpoint completes @@ -829,26 +843,34 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, # comes). Bound the wait so a misconfigured 3P session doesn't stall the # whole hook. A gateway review gets the 120 s a direct HTTP review gets. timeout_s = 120 if route == "gateway" else 60 - try: - result = _run_inner_cli( - lambda: _asyncio.run(_asyncio.wait_for(_arun(), timeout=timeout_s)), - _captured_stderr) + + def _log_child_stderr(): if _captured_stderr: debug_log(f"{route} sdk-single-turn child stderr ({len(_captured_stderr)} lines):") for _l in _captured_stderr[:20]: debug_log(f" | {_l.rstrip()}") + + try: + result = _run_inner_cli( + lambda: _asyncio.run(_asyncio.wait_for(_arun(), timeout=timeout_s)), + _captured_stderr) + _log_child_stderr() return result except _asyncio.TimeoutError: - debug_log(f"{route} sdk-single-turn: timeout after {timeout_s}s") + # The CLI retries a refused or unreachable API by itself and reports + # each retry in its output, not on stderr. + debug_log(f"{route} sdk-single-turn: timeout after {timeout_s}s" + + (f"; the CLI's API requests were retried after status " + f"{', '.join(sorted(_retried_after))}" if _retried_after else "")) + _log_child_stderr() + if route == "gateway": + _gateway_review_timed_out = True _last_call_claude_http_error = -1 _record_http_error(-1) return None except Exception as e: debug_log(f"{route} sdk-single-turn: query failed ({e})") - if _captured_stderr: - debug_log(f"{route} sdk-single-turn child stderr ({len(_captured_stderr)} lines):") - for _l in _captured_stderr[:20]: - debug_log(f" | {_l.rstrip()}") + _log_child_stderr() _last_call_claude_http_error = -1 _record_http_error(-1) return None @@ -1061,7 +1083,7 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget, max_tokens=max_tokens, model=primary, retry_5xx=False, cacheable_prefix=cacheable_prefix) - if r is None and not explicit: + if r is None and not explicit and not _gateway_review_timed_out: debug_log(f"single: {primary} failed, falling back to sonnet") r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget, max_tokens=max_tokens, model=fallback, @@ -1072,7 +1094,7 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget, max_tokens=max_tokens, model=primary, retry_5xx=False, cacheable_prefix=cacheable_prefix) - if r is None and not explicit: + if r is None and not explicit and not _gateway_review_timed_out: debug_log(f"dual_or: {primary} leg failed, falling back to sonnet") r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget, max_tokens=max_tokens, model=fallback, diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index b13741ea..ca34ed45 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -2312,7 +2312,9 @@ def handle_stop_hook(input_data): off = _llm_review_off(session_id) if off: debug_log(f"Stop hook: {off[0]}") - _skip(3, **off[1]) + # When the sign-in check gave no answer, this turn's changes are kept + # for the next Stop review. + _skip(3, restore=llm._gateway_check_unanswered, **off[1]) # Stop-hook-only kill switch — placed after consume_stop_state so # touched_paths is still cleared each turn (a disabled Stop hook that diff --git a/plugins/security-guidance/tests/test_gateway_sign_in.py b/plugins/security-guidance/tests/test_gateway_sign_in.py index c9e82fdd..e2469fb7 100644 --- a/plugins/security-guidance/tests/test_gateway_sign_in.py +++ b/plugins/security-guidance/tests/test_gateway_sign_in.py @@ -1,7 +1,9 @@ """Reviews in a session signed in to a Claude apps gateway with /login, where Claude Code gives hooks no credential.""" +import asyncio import json import sys +import types import pytest @@ -59,17 +61,21 @@ def model_of(call): @pytest.fixture def no_credential(monkeypatch, tmp_path): - for var in ("SECURITY_REVIEW_MODEL", "CLAUDE_CODE_EXECPATH", *llm._PROVIDER_ENV_VARS): + # CLAUDE_CODE_REMOTE_SESSION_ID makes every session share one state file. + for var in ("SECURITY_REVIEW_MODEL", "CLAUDE_CODE_EXECPATH", "CLAUDE_CODE_REMOTE_SESSION_ID", + *llm._PROVIDER_ENV_VARS): monkeypatch.delenv(var, raising=False) monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(tmp_path / "no-claude")) monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) monkeypatch.setattr(_base, "DEBUG_LOG_FILE", str(tmp_path / "log.txt")) monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", False) - monkeypatch.setattr(llm, "_gateway_cli", None) + new_hook_process(monkeypatch) def new_hook_process(monkeypatch): monkeypatch.setattr(llm, "_gateway_cli", None) + monkeypatch.setattr(llm, "_gateway_check_unanswered", False) + monkeypatch.setattr(llm, "_gateway_review_timed_out", False) class TestGatewaySignInCheck: @@ -223,6 +229,15 @@ class TestGatewayReviewOutcome: assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, []) assert llm.last_review_failed() + def test_failed_review_is_tried_on_sonnet_unless_it_timed_out(self, child, monkeypatch): + child.reply = None + assert llm.can_review("s1") + llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) + assert len(child.prompts) == 2 + monkeypatch.setattr(llm, "_gateway_review_timed_out", True) + llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) + assert len(child.prompts) == 3 and llm.last_review_failed() + def test_not_signed_in_sends_nothing(self, child, monkeypatch, tmp_path): cli, _ = make_cli(tmp_path, NOT_SIGNED_IN, name="signed-out") monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) @@ -232,9 +247,38 @@ class TestGatewayReviewOutcome: assert child.prompts == [] +def test_timed_out_review_logs_what_the_cli_retried(no_credential, monkeypatch, tmp_path): + """The CLI retries a refused sign-in by itself until the plugin's time + limit; the retries are in its output, not on stderr.""" + class Retry: + subtype, data = "api_retry", {"error_status": 401} + + async def query(prompt, options): + yield Retry() + raise asyncio.TimeoutError() + + mod = types.ModuleType("claude_agent_sdk") + mod.query = query + mod.ClaudeAgentOptions = lambda **kwargs: kwargs + mod.AssistantMessage = type("AssistantMessage", (), {}) + mod.ResultMessage = type("ResultMessage", (), {}) + monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) + cli, _ = make_cli(tmp_path, SIGNED_IN) + schema = {"type": "object", "properties": {}} + assert llm._call_claude_via_sdk("review this", schema, cli_path=str(cli)) is None + assert llm._gateway_review_timed_out is True + assert ("gateway sdk-single-turn: timeout after 120s; the CLI's API requests were " + "retried after status 401") in (tmp_path / "log.txt").read_text() + # Not for the cloud-provider route, where the model can be the reason. + monkeypatch.setattr(llm, "_gateway_review_timed_out", False) + assert llm._call_claude_via_sdk("review this", schema) is None + assert llm._gateway_review_timed_out is False + + def without_credential(hook_env): return {k: v for k, v in hook_env.items() - if k not in ("ANTHROPIC_API_KEY", "SECURITY_REVIEW_MODEL", *llm._PROVIDER_ENV_VARS)} + if k not in ("ANTHROPIC_API_KEY", "SECURITY_REVIEW_MODEL", + "CLAUDE_CODE_REMOTE_SESSION_ID", *llm._PROVIDER_ENV_VARS)} class TestHooksInASignedInSession: @@ -332,3 +376,21 @@ class TestHooksInASignedInSession: rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env) assert rc == 0 and metrics_of(so)["skip_reason"] == 22 assert len(calls_of(calls)) == 1 + + def test_unanswered_sign_in_check_keeps_the_turn_for_the_next_stop( + self, hook_env, tmp_path, workspace): + env = without_credential(hook_env) + cli, calls = make_cli(tmp_path, "") + env["SG_AGENTIC_CLI_PATH"] = str(cli) + _, repo = workspace + assert run_hook(ups_payload(repo), env)[0] == 0 + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env) + rc, so, _ = run_hook(stop_payload(repo), env) + assert metrics_of(so)["skip_reason"] == 3 and not review_calls(calls) + # The CLI answers in the next turn: the first turn's edit is reviewed. + make_cli(tmp_path, SIGNED_IN) + assert run_hook(ups_payload(repo), env)[0] == 0 + rc, so, _ = run_hook(stop_payload(repo), env) + assert metrics_of(so)["review_failed"] is True + assert review_calls(calls) diff --git a/plugins/security-guidance/tests/test_no_credentials_notice.py b/plugins/security-guidance/tests/test_no_credentials_notice.py index 99e85c8d..a828e2ed 100644 --- a/plugins/security-guidance/tests/test_no_credentials_notice.py +++ b/plugins/security-guidance/tests/test_no_credentials_notice.py @@ -14,6 +14,8 @@ from test_gateway_sign_in import NOT_SIGNED_IN, SIGNED_IN, calls_of, make_cli # Anything in the developer's shell that changes whether a review would run. _AMBIENT = ( "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", + # Makes every session share one state file. + "CLAUDE_CODE_REMOTE_SESSION_ID", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_TELEMETRY", "DO_NOT_TRACK", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "CLAUDE_CODE_USE_MANTLE", "CLAUDE_CODE_USE_ANTHROPIC_AWS", |
