diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-19 15:37:53 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-19 17:05:01 +0000 |
| commit | e0d9e154cc7c8d545f5d78c2f51fb9c0dc655b08 (patch) | |
| tree | f938e81764e2d9d63d771e9deac6e904f6b393e1 /plugins/security-guidance/hooks | |
| parent | 303ad63c6a45cee47be5590655e67fe1a1b6611d (diff) | |
security-guidance: review through Claude Code in a Claude apps gateway sign-in
In a Claude Code session signed in to a Claude apps gateway with /login,
Claude Code gives plugin hooks no credential, so the Stop, commit, push
and agentic commit reviews were all skipped.
When the plugin has no credential of its own, it now asks the user's
installed claude (`claude auth status --json`) whether the session is
signed in to a gateway. A yes or no is kept for the session; when the CLI
gives no usable answer, the next hook asks again. If apiProvider is
"gateway" and loggedIn is true, the reviews run through that same CLI,
which restores the stored sign-in by itself, so no credential enters the
plugin. A review the CLI cannot complete counts as a failed review, never
a clean one. The reviews run even with
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC set, as they do on Bedrock and
Vertex: the gateway docs suggest setting it, and the review goes through
the gateway like the session's own requests.
The CLI is found the way the agentic reviewer already finds it:
SG_AGENTIC_CLI_PATH, CLAUDE_CODE_EXECPATH, then fixed install paths, with
no PATH search, and it must be a full path. The reviews use Claude Code's
opus and sonnet aliases, which resolve to the ids Claude Code itself uses
on a gateway, and get the 120 s a direct review gets. Review rows set bit
4 of gateway_cfg, so this route's failure rate can be read apart from
first-party reviews.
Every Claude Code the plugin starts for a review, on any provider, now
runs with SECURITY_GUIDANCE_DISABLE=1. If policy settings enable the
plugin inside that CLI, its hooks there don't start reviews of their own.
The weekly notice that the reviews are not running is no longer shown in
a session signed in to a gateway, since the reviews do run there. The
edit that would show it asks claude first, and the notice marker is
written either way, so that edit waits for claude at most once a week.
Sessions the gateway route cannot review still get the notice, unless,
in the past week, an edit's check found a session signed in to a
gateway. Their skipped reviews still report no_creds.
Diffstat (limited to 'plugins/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 255 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 45 |
2 files changed, 219 insertions, 81 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index aaf785fb..a58bd54f 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -23,6 +23,7 @@ import json import logging import os import re +import subprocess import sys import tempfile import threading @@ -35,7 +36,7 @@ from typing import Optional, Tuple, Dict, Any, List, Callable import extensibility import review_api from _base import debug_log, _record_usage, _record_http_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir # noqa: F401 -from session_state import with_locked_state +from session_state import load_state, with_locked_state from gitutil import git_config_env, SAFE_GIT_CONFIG @@ -322,10 +323,12 @@ def _custom_headers() -> List[Tuple[str, str]]: def gateway_cfg() -> int: - """How the plugin's own API calls are routed, for telemetry: bit 1 when + """How the plugin's reviews are routed, for telemetry: bit 1 when ANTHROPIC_BASE_URL names a host other than api.anthropic.com, bit 2 when - at least one ANTHROPIC_CUSTOM_HEADERS line is sent. 0 when neither. A - number only: no host, header name or value.""" + at least one ANTHROPIC_CUSTOM_HEADERS line is sent, bit 4 when reviews + run through the user's claude on a Claude apps gateway sign-in (see + gateway_review_cli). 0 when none. A number only: no host, header name + or value.""" cfg = 0 base = _anthropic_base_url() try: @@ -336,6 +339,8 @@ def gateway_cfg() -> int: cfg |= 1 if any(name.lower() != "anthropic-beta" for name, _ in _custom_headers()): cfg |= 2 + if _gateway_cli: + cfg |= 4 return cfg @@ -558,16 +563,17 @@ def _write_review_model_cache(path, endpoint_key, model, now): def default_review_model() -> str: """Model for a review the user hasn't pinned with SECURITY_REVIEW_MODEL. - 3P providers go through the Agent SDK, so the CLI alias does the work. - 1P and gateways get the newest Opus the endpoint lists, looked up at most - once per _REVIEW_MODEL_TTL_SECONDS; _PINNED_REVIEW_MODEL when the lookup - can't answer. Never raises. + 3P providers and Claude apps gateway sign-ins go through the Agent SDK, + so the CLI alias does the work. 1P and LLM gateways set with + ANTHROPIC_BASE_URL get the newest Opus the endpoint lists, looked up at + most once per _REVIEW_MODEL_TTL_SECONDS; _PINNED_REVIEW_MODEL when the + lookup can't answer. Never raises. """ global _review_model_memo explicit = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() if explicit: return explicit - if _is_3p_provider(): + if _is_3p_provider() or _gateway_cli: return _CLI_OPUS_ALIAS if not HAS_API_CREDENTIALS: return _PINNED_REVIEW_MODEL @@ -591,16 +597,157 @@ def default_review_model() -> str: return _review_model_memo -def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None): +# A session signed in to a Claude apps gateway with /login gives hooks no +# credential, but a child `claude` restores that sign-in by itself, so reviews +# can run through the user's CLI without a credential entering this process. + +# `claude auth status` may wait for a settings helper script an administrator +# configured, which Claude Code gives 10 s by default. +_GATEWAY_CHECK_TIMEOUT_S = 15 +_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 + + +def _user_cli_path() -> Optional[str]: + """The user's own `claude`: SG_AGENTIC_CLI_PATH if set ("" selects the + SDK's bundled CLI), else the first of the absolute paths below that + exists, else None.""" + cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") + if cli_path is not None: + return cli_path + # CLAUDE_CODE_EXECPATH is the absolute path to the running CC binary + # itself (e.g. ~/.local/share/claude/versions/2.1.x — that's the binary, + # not a directory). Claude Code sets it for the Bash tool's shells, not for + # hooks, so hooks usually find the CLI at a fixed path below. We do NOT + # fall back to shutil.which("claude") because the hook's cwd is the + # user's (potentially attacker-supplied) repo, and Windows shutil.which + # searches cwd first — a checked-in ./claude.exe would get spawned. + # Absolute-path probes only. + for p in ( + os.environ.get("CLAUDE_CODE_EXECPATH"), + os.path.expanduser("~/.local/bin/claude"), + "/root/.local/bin/claude", + # Claude Code Remote container install path. + "/opt/claude-code/bin/claude", + ): + if p and os.path.isfile(p): + return p + return None + + +def _tolerate_unknown_sdk_messages() -> None: + """Make the SDK's message parser pass unknown message types through + instead of raising: a CLI newer than the SDK emits types the SDK does not + know (e.g. rate_limit_event).""" + try: + from claude_agent_sdk._internal import message_parser as _mp + import claude_agent_sdk._internal.client as _sdk_client + from claude_agent_sdk import SystemMessage as _SysMsg + + _orig_parse = _mp.parse_message + if getattr(_orig_parse, "_sg_tolerant", False): + return + + def _tolerant(data): + try: + return _orig_parse(data) + except Exception: + return _SysMsg(subtype=data.get("type", "unknown"), data=data) + + _tolerant._sg_tolerant = True + _mp.parse_message = _tolerant + _sdk_client.parse_message = _tolerant + except Exception: + pass + + +def _gateway_signed_in(cli: str) -> Optional[bool]: + """Whether `cli auth status --json` reports a session signed in to a + Claude apps gateway. None when the CLI gave no usable answer (an error, a + timeout, or output that is not a JSON object).""" + try: + # A process the CLI starts can keep stdout open after the CLI exits; + # reading a pipe would then wait out the timeout and lose the answer. + with tempfile.TemporaryFile() as out: + subprocess.run( + [cli, "auth", "status", "--json"], stdin=subprocess.DEVNULL, + stdout=out, stderr=subprocess.DEVNULL, + env={**os.environ, **_agentic_spawn_env()}, + cwd=os.path.expanduser("~"), + timeout=_GATEWAY_CHECK_TIMEOUT_S, check=False, + ) + out.seek(0) + status = json.loads(out.read(64 * 1024)) + except Exception as e: + debug_log(f"gateway check: no usable answer from {cli} ({type(e).__name__})") + return None + if not isinstance(status, dict): + debug_log("gateway check: answer was not a JSON object") + return None + provider, logged_in = status.get("apiProvider"), status.get("loggedIn") + debug_log(f"gateway check: apiProvider={str(provider)[:40]!r} loggedIn={repr(logged_in)[:10]}") + # A managed machine that names a gateway but was never signed in also + # reports "gateway". + return provider == "gateway" and logged_in is True + + +def gateway_review_cli(session_id) -> Optional[str]: + """The CLI to review through when the plugin has no credential but the + session is signed in to a Claude apps gateway; None otherwise. A yes or + 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 + if _gateway_cli is not None: + return _gateway_cli or None + cli = _user_cli_path() or "" + ok = None + # No skip for CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, as on Bedrock and Vertex: + # the gateway docs suggest setting it, and the review goes through the + # gateway like the session's own requests. + if not os.path.isabs(cli): + debug_log("gateway check: skipped, SG_AGENTIC_CLI_PATH is not a full path" + if "SG_AGENTIC_CLI_PATH" in os.environ + else "gateway check: skipped, no claude at ~/.local/bin/claude or the other " + "usual full paths (SG_AGENTIC_CLI_PATH can name one)") + else: + cached = load_state(session_id).get(_GATEWAY_STATE_KEY) + if (isinstance(cached, dict) and cached.get("cli") == cli + and isinstance(cached.get("ok"), bool)): + ok = cached["ok"] + debug_log(f"gateway check: using this session's saved answer (signed in: {ok})") + else: + ok = _gateway_signed_in(cli) + if ok is not None: + def _save(state): + state[_GATEWAY_STATE_KEY] = {"cli": cli, "ok": ok} + with_locked_state(session_id, _save) + _gateway_cli = cli if ok else "" + return _gateway_cli or None + + +def can_review(session_id) -> bool: + """True when the plugin has a credential, or has none but the session is + signed in to a Claude apps gateway. Call it before reviewing: the review + takes the gateway route only after it has said yes in this process.""" + return HAS_API_CREDENTIALS or gateway_review_cli(session_id) is not None + + +def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, + cli_path=None): """Single-turn SDK call as a substitute for the HTTP _call_claude path on - 3P providers. Uses the same `output_format` JSON-schema contract so the - return value shape is identical (parsed dict or None). + 3P providers, and, with `cli_path` set, for a session signed in to a + Claude apps gateway. Uses the same `output_format` JSON-schema contract so + the return value shape is identical (parsed dict or 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 _last_call_claude_http_error = None + route = "gateway" if cli_path else "3P" try: import asyncio as _asyncio @@ -625,13 +772,16 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) query, ) except Exception as e: - debug_log(f"3P sdk-single-turn: SDK unavailable ({e})") + debug_log(f"{route} sdk-single-turn: SDK unavailable ({e})") _last_call_claude_http_error = -1 _record_http_error(-1) return None _send_sdk_logs_to_debug_log() - cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None + if cli_path: + _tolerate_unknown_sdk_messages() + else: + cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None default_model = default_review_model() chosen_model = model or default_model @@ -677,25 +827,26 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) # in 5-15s; >60s means the child claude is hung (e.g. user has the 3P env # var set but no provider creds → child waits for an auth that never # comes). Bound the wait so a misconfigured 3P session doesn't stall the - # whole hook. + # 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=60)), + lambda: _asyncio.run(_asyncio.wait_for(_arun(), timeout=timeout_s)), _captured_stderr) if _captured_stderr: - debug_log(f"3P sdk-single-turn child stderr ({len(_captured_stderr)} lines):") + debug_log(f"{route} sdk-single-turn child stderr ({len(_captured_stderr)} lines):") for _l in _captured_stderr[:20]: debug_log(f" | {_l.rstrip()}") return result except _asyncio.TimeoutError: - debug_log("3P sdk-single-turn: timeout after 60s") + debug_log(f"{route} sdk-single-turn: timeout after {timeout_s}s") _last_call_claude_http_error = -1 _record_http_error(-1) return None except Exception as e: - debug_log(f"3P sdk-single-turn: query failed ({e})") + debug_log(f"{route} sdk-single-turn: query failed ({e})") if _captured_stderr: - debug_log(f"3P sdk-single-turn child stderr ({len(_captured_stderr)} lines):") + debug_log(f"{route} sdk-single-turn child stderr ({len(_captured_stderr)} lines):") for _l in _captured_stderr[:20]: debug_log(f" | {_l.rstrip()}") _last_call_claude_http_error = -1 @@ -736,6 +887,13 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, max_tokens=max_tokens, model=model) if not HAS_API_CREDENTIALS: + if _gateway_cli: + # Signed in to a Claude apps gateway: the user's CLI reviews with + # its own stored sign-in (see gateway_review_cli). + if cacheable_prefix: + prompt = cacheable_prefix + "\n\n" + prompt + return _call_claude_via_sdk(prompt, output_schema, max_tokens=max_tokens, + model=model, cli_path=_gateway_cli) return None global _auth_prefer_token @@ -893,6 +1051,9 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, explicit = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() primary = default_review_model() + # Through the user's CLI, the alias gives the Sonnet id the user's own + # sessions use on the gateway, including any ANTHROPIC_DEFAULT_SONNET_MODEL. + fallback = "sonnet" if _gateway_cli else "claude-sonnet-4-6" if not _dual_or_enabled(): # Single-call path. Reuse the same sonnet-fallback retry as a dual_or @@ -903,7 +1064,7 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, if r is None and not explicit: 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="claude-sonnet-4-6", + max_tokens=max_tokens, model=fallback, retry_5xx=True, cacheable_prefix=cacheable_prefix) return r @@ -914,7 +1075,7 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, if r is None and not explicit: 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="claude-sonnet-4-6", + max_tokens=max_tokens, model=fallback, retry_5xx=True, cacheable_prefix=cacheable_prefix) return r @@ -1204,7 +1365,7 @@ def analyze_code_security(files: List[Tuple[str, str]], is_diff: bool = False, p """ _review_status.failed = False _review_status.status = None - if not HAS_API_CREDENTIALS or not files: + if not (HAS_API_CREDENTIALS or _gateway_cli) or not files: return None, [] # Build language context from file extensions @@ -1477,6 +1638,9 @@ def _agentic_spawn_env() -> Dict[str, str]: is the only credential. """ env = { + # Policy settings can enable this plugin inside the reviewing CLI too; + # its hooks there must not start reviews of their own. + "SECURITY_GUIDANCE_DISABLE": "1", "FALLBACK_FOR_ALL_PRIMARY_MODELS": "1", "CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR": "", "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR": "", @@ -1630,50 +1794,9 @@ def _agentic_review( # `[Request interrupted by user]` and gives up). The CLI that launched # this hook is by definition >= the plugin's tested floor, so it's # always at least as capable. - # - # CLAUDE_CODE_EXECPATH is the absolute path to the running CC binary - # itself (e.g. ~/.local/share/claude/versions/2.1.x — that's the binary, - # not a directory). It is the exact CLI that loaded this hook. We do NOT - # fall back to shutil.which("claude") because the hook's cwd is the - # user's (potentially attacker-supplied) repo, and Windows shutil.which - # searches cwd first — a checked-in ./claude.exe would get spawned. - # Absolute-path probes only. - # - # Also monkeypatch the SDK's message parser to tolerate unknown message - # types (newer CLI emits rate_limit_event which older SDK raises on). - cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") - if cli_path is None: - for p in ( - os.environ.get("CLAUDE_CODE_EXECPATH"), - os.path.expanduser("~/.local/bin/claude"), - "/root/.local/bin/claude", - # Claude Code Remote container install path. CLAUDE_CODE_EXECPATH - # is not exported to hook subprocesses there, so without this - # candidate cli_path resolves to None and the SDK uses its - # bundled CLI — which lags the running CC by builds. - "/opt/claude-code/bin/claude", - ): - if p and os.path.isfile(p): - cli_path = p - break + cli_path = _gateway_cli or _user_cli_path() if cli_path: - try: - from claude_agent_sdk._internal import message_parser as _mp - import claude_agent_sdk._internal.client as _sdk_client - from claude_agent_sdk import SystemMessage as _SysMsg - - _orig_parse = _mp.parse_message - - def _tolerant(data): - try: - return _orig_parse(data) - except Exception: - return _SysMsg(subtype=data.get("type", "unknown"), data=data) - - _mp.parse_message = _tolerant - _sdk_client.parse_message = _tolerant - except Exception: - pass + _tolerate_unknown_sdk_messages() # Without a callback the inner CLI writes to this hook's stderr, which # Claude Code shows Claude as the review notice. Log it instead. diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 6401a370..b13741ea 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -321,12 +321,13 @@ def emit_metrics( _write_hook_output(out) -def _llm_review_off(): +def _llm_review_off(session_id): """Why no LLM review can run: (log text, extra metrics), or None.""" if not ENABLE_CODE_SECURITY_REVIEW: return "LLM review disabled", {} - if not HAS_API_CREDENTIALS: - return "no API credentials", {"no_creds": True} + if not llm.can_review(session_id): + return ("no API credentials and no Claude apps gateway sign-in", + {"no_creds": True}) return None @@ -344,16 +345,18 @@ def _credential_withholding_env_vars(): return names -def _no_credentials_notice(file_path): +def _no_credentials_notice(file_path, session_id): """Text telling the user the LLM reviews are not running, or None. - Without credentials every Stop, commit and push review is skipped, and - nothing else tells the user. Returned for an edit inside a git repo (the - reviews only look at those), at most once a week per install: the marker - file in the state dir holds the time of the last notice. A marker that - can't be written means no notice rather than one on every edit. The - caller is the Edit/Write hook because the review hooks run in the - background, where Claude Code does not show a systemMessage. + With no credential and no Claude apps gateway sign-in, every Stop, + commit and push review is skipped, and nothing else tells the user. + Returned for an edit inside a git repo (the reviews only look at those), + at most once a week per install: the marker file in the state dir holds + the time of the last notice, or of the last check that found the reviews + running through a Claude apps gateway sign-in. A marker that can't be + written means no notice rather than one on every edit. The caller is the + Edit/Write hook because the review hooks run in the background, where + Claude Code does not show a systemMessage. """ import time as _time try: @@ -369,6 +372,12 @@ def _no_credentials_notice(file_path): os.makedirs(os.path.dirname(marker), exist_ok=True) with open(marker, "w"): pass + # In a session signed in to a Claude apps gateway the reviews do run, + # through the user's claude (llm.gateway_review_cli). `claude auth + # status` runs only after the marker is written, so an edit waits for + # it at most once a week. + if llm.can_review(session_id): + return None except OSError: return None withheld_by = _credential_withholding_env_vars() @@ -1210,6 +1219,12 @@ def _review_failure_reason(status): if llm._is_3p_provider(): return ("provider", "the review through the cloud provider got no answer", "The plugin's log has the provider's error.") + if llm._gateway_cli: + pinned = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() + return ("gateway", "the review through Claude Code on the Claude apps gateway returned no result", + "The plugin's log has the reason. If it says the sign-in has expired, run /login again." + + (f" SECURITY_REVIEW_MODEL ({pinned}) may also name a model the gateway does " + "not serve." if pinned else "")) if status == 401: return ("auth", "the API rejected the plugin's credentials (HTTP 401)", f"The sign-in may have expired or been revoked{gateway}.") @@ -1402,7 +1417,7 @@ def handle_commit_review_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 32, **_base}) sys.exit(0) - off = _llm_review_off() + off = _llm_review_off(session_id) if off: debug_log(f"Commit review: {off[0]}") emit_metrics({"skipped": True, "skip_reason": 22, **off[1], **_base}) @@ -1871,7 +1886,7 @@ def handle_push_sweep_posttooluse(input_data): if interrupted: emit_metrics({"skipped": True, "skip_reason": 21, **_base}) sys.exit(0) - off = _llm_review_off() + off = _llm_review_off(session_id) if off: emit_metrics({"skipped": True, "skip_reason": 22, **off[1], **_base}) sys.exit(0) @@ -2294,7 +2309,7 @@ def handle_stop_hook(input_data): debug_log(f"Stop hook: already fired {fire_count} times (max {MAX_STOP_HOOK_FIRINGS}), skipping") _skip(2) - off = _llm_review_off() + off = _llm_review_off(session_id) if off: debug_log(f"Stop hook: {off[0]}") _skip(3, **off[1]) @@ -2756,7 +2771,7 @@ def main(): if (ENABLE_CODE_SECURITY_REVIEW and not HAS_API_CREDENTIALS and (ENABLE_STOP_REVIEW or COMMIT_REVIEW_ENABLED or PUSH_SWEEP_ENABLED)): - notice = _no_credentials_notice(file_path) + notice = _no_credentials_notice(file_path, session_id) if notice: output["systemMessage"] = notice if output: |
