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 | |
| 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')
| -rw-r--r-- | plugins/security-guidance/README.md | 14 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 255 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 45 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/conftest.py | 3 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_gateway_sign_in.py | 334 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_no_credentials_notice.py | 38 |
6 files changed, 602 insertions, 87 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index f4806fca..caef1866 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -20,7 +20,7 @@ Marketplace ships enabled by default in Claude Code — no setup beyond having t - Claude Code CLI ≥ v2.1.144 - Python 3.8+ on `PATH` (`python3`, `python`, or `py -3` — the plugin picks the first that works) -- Credentials for the LLM reviews: your Claude Code sign-in, an API key, or 3P provider config (see [Credentials](#credentials)) +- Credentials for the LLM reviews: your Claude Code sign-in (a Claude apps gateway sign-in needs Claude Code 2.1.195 or later), an API key, or 3P provider config (see [Credentials](#credentials)) ## Configuration @@ -31,7 +31,7 @@ All configuration is via environment variables. None are required for default be By default both reviews run on the newest Claude Opus, and move to the next one when it is released — there is no model version to bump: - The LLM diff review asks your API endpoint (`GET /v1/models`) which Opus models it serves and uses the newest. The answer is cached for a day in the plugin's state directory. If the endpoint can't answer, the review uses `claude-opus-5-5`. -- The agentic commit reviewer, and every review on Bedrock, Vertex, and Foundry, runs through your installed Claude Code and uses its `opus` alias — the same model `/model opus` selects, including any `ANTHROPIC_DEFAULT_OPUS_MODEL` you have set. +- The agentic commit reviewer, and every review in a session signed in to a Claude apps gateway with `/login`, run through your installed Claude Code. Other reviews on Bedrock, Vertex, and Foundry run through the copy of Claude Code bundled with the Agent SDK, or `SG_AGENTIC_CLI_PATH` if set. All of them use Claude Code's `opus` alias: the model `/model opus` selects, including any `ANTHROPIC_DEFAULT_OPUS_MODEL` you have set. On a gateway that alias may name an older Opus than the newest one. To pin a model, or to use a cheaper one: @@ -52,11 +52,12 @@ SECURITY_REVIEW_MODEL=claude-opus-5-5 The pattern warnings need no credentials. The LLM reviews (the diff review on Stop and the commit/push reviewer) use the first of these that applies: -- **A cloud provider (Bedrock, Vertex, Foundry)** — if Claude Code is configured for one, reviews run through your installed Claude Code with that provider config. +- **A cloud provider (Bedrock, Vertex, Foundry)** — if Claude Code is configured for one, reviews run through Claude Code with that provider config. - **`ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in the environment** — used as is, against `ANTHROPIC_BASE_URL` if you set one. - **Signed in to Claude Code (`/login`)** — Claude Code passes your sign-in to the plugin's hooks, and reviews use that account. +- **Signed in to a Claude apps gateway (`/login`)** — Claude Code passes no sign-in to plugins on a gateway, so reviews run through your installed Claude Code, which uses its own stored sign-in. The plugin never reads it. The plugin looks for Claude Code at `~/.local/bin/claude`, where the native installer puts it on macOS and Linux; on Windows, or for any other install, set `SG_AGENTIC_CLI_PATH` to its full path. -Claude Code does not pass your sign-in to plugins in a session started with `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_TELEMETRY`, or `DO_NOT_TRACK` set. If no credentials reach the plugin, for that or any other reason, the LLM reviews are skipped and only the pattern warnings run. The plugin tells you so when Claude edits a file in a git repo, at most once a week. Set `ENABLE_CODE_SECURITY_REVIEW=0` if that is what you want; it also hides the notice. +Claude Code does not pass your sign-in to plugins in a session started with `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_TELEMETRY`, or `DO_NOT_TRACK` set. If no credentials reach the plugin, for that or any other reason, and the plugin cannot review through a Claude apps gateway sign-in, the LLM reviews are skipped and only the pattern warnings run. The plugin tells you so when Claude edits a file in a git repo, at most once a week. Set `ENABLE_CODE_SECURITY_REVIEW=0` if that is what you want; it also hides the notice. ### Enabling/disabling layers @@ -114,9 +115,10 @@ The plugin sends data to a model endpoint to perform its reviews. Specifically, Where that data goes depends on your Claude Code configuration: - **Default (Anthropic API / subscription):** sent to `api.anthropic.com` and handled under Anthropic's [Commercial Terms](https://www.anthropic.com/legal/commercial-terms) and [Privacy Policy](https://www.anthropic.com/legal/privacy). - **LLM gateway** (`ANTHROPIC_BASE_URL` set): sent to your gateway URL instead, with the headers in `ANTHROPIC_CUSTOM_HEADERS` (except `anthropic-beta`). The gateway operator's terms apply. +- **Claude apps gateway, signed in with `/login`:** your installed Claude Code sends the reviews to the gateway, using its own stored sign-in. The plugin never reads the sign-in. The gateway operator's terms apply. - **3rd-party providers** (Bedrock / Vertex / Foundry / Mantle): sent to your configured provider endpoint. The provider's data-handling terms apply (e.g., AWS / GCP / Azure). -The plugin writes its own debug log to `~/.claude/security/log.txt` (override with `SECURITY_GUIDANCE_DEBUG_LOG`). The log contains diffstate metadata, finding categories, the Agent SDK's own warnings and errors, and up to 20 lines per review that the agentic reviewer's inner Claude Code prints to stderr — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded. +The plugin writes its own debug log to `~/.claude/security/log.txt` (override with `SECURITY_GUIDANCE_DEBUG_LOG`). The log contains diffstate metadata, finding categories, the Agent SDK's own warnings and errors, and up to 20 lines of stderr from each Claude Code run the plugin starts for a review (20 in all for each agentic commit review, which starts several runs) — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded. ### Review usage and cost @@ -141,7 +143,7 @@ This is a best-effort assistive tool, not a guarantee. Treat findings as suggest **Plugin doesn't seem to fire** — check that `~/.claude/claude-security-guidance.md` (or hook activity) shows in debug logs. Run Claude Code with `--debug-file /tmp/claude/debug.txt` and grep for `security_reminder_hook`. The plugin also writes its own log to `~/.claude/security/log.txt`. -**Review never finds anything** — verify your API path works, and that credentials reach the plugin (see [Credentials](#credentials)): `~/.claude/security/log.txt` says `no API credentials` when they don't. When a commit or push review gets no usable answer from the model, Claude is told once per session for each kind of review and failure (for example "Commit security review did not complete: …"), and the reason is logged. If a commit whose review failed is pushed later from Claude Code, the push review checks it. On 3P providers, if you set `SECURITY_REVIEW_MODEL`, check it is a provider-specific id your account can invoke. On LLM gateways, check the gateway's logs for `POST /v1/messages` traffic from the plugin. +**Review never finds anything** — verify your API path works, and that credentials reach the plugin (see [Credentials](#credentials)): `~/.claude/security/log.txt` says `no API credentials` when they don't. When a commit or push review gets no usable answer from the model, Claude is told once per session for each kind of review and failure (for example "Commit security review did not complete: …"), and the reason is logged. If a commit whose review failed is pushed later from Claude Code, the push review checks it. On 3P providers, if you set `SECURITY_REVIEW_MODEL`, check it is a provider-specific id your account can invoke. On LLM gateways, check the gateway's logs for `POST /v1/messages` traffic from the plugin. In a session signed in to a Claude apps gateway with `/login`, reviews run only when `claude auth status` shows the gateway and that you are logged in. They run through the Claude Code at `~/.local/bin/claude`, where the native installer puts it on macOS and Linux. On Windows, or for any other install, set `SG_AGENTIC_CLI_PATH` to its full path. **Too many false positives** — set `SECURITY_REVIEW_MODEL` to a cheaper model (`claude-sonnet-5-5`) and re-evaluate; if precision is the priority, stay on the default. 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: diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index 998401c2..669adc4f 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -137,6 +137,9 @@ def hook_env(tmp_path, stub_api): "ANTHROPIC_BASE_URL": f"http://127.0.0.1:{stub_api.server_port}", "NO_PROXY": "*", "no_proxy": "*", "SG_AGENTIC_COMMIT_REVIEW": "0", + # Points the plugin at a claude that does not exist, so no hook test + # runs this machine's own claude. + "SG_AGENTIC_CLI_PATH": str(tmp_path / "no-claude"), "SECURITY_GUIDANCE_COMMIT_REVIEW": "on", "SG_PUSH_SWEEP": "on", "PYTHONDONTWRITEBYTECODE": "1", diff --git a/plugins/security-guidance/tests/test_gateway_sign_in.py b/plugins/security-guidance/tests/test_gateway_sign_in.py new file mode 100644 index 00000000..c9e82fdd --- /dev/null +++ b/plugins/security-guidance/tests/test_gateway_sign_in.py @@ -0,0 +1,334 @@ +"""Reviews in a session signed in to a Claude apps gateway with /login, where +Claude Code gives hooks no credential.""" +import json +import sys + +import pytest + +from conftest import ( + VULN_PY, bash_payload, commit_file, edit_payload, git, metrics_of, run_hook, + stop_payload, ups_payload, +) + +import _base +import llm + +SIGNED_IN = json.dumps({"loggedIn": True, "authMethod": "third_party", "apiProvider": "gateway"}) +NOT_SIGNED_IN = json.dumps({"loggedIn": False, "authMethod": "none", "apiProvider": "gateway"}) + + +def make_cli(tmp_path, auth_status, *, name="claude", hang=False, linger=False): + """A fake `claude` that logs each call to <name>.calls as its arguments, the + SECURITY_GUIDANCE_DISABLE it got and its working directory, prints + `auth_status` for `auth status --json`, and fails anything else. `hang` + waits 5 s before answering; `linger` leaves a process running that holds + stdout open after the CLI exits.""" + calls = tmp_path / f"{name}.calls" + cli = tmp_path / name + cli.write_text(f"""#!{sys.executable} +import os, subprocess, sys, time +with open({str(calls)!r}, "a") as f: + f.write(" ".join(sys.argv[1:]) + " | SGD=" + os.environ.get("SECURITY_GUIDANCE_DISABLE", "") + + " | CWD=" + os.getcwd() + "\\n") +if sys.argv[1:3] != ["auth", "status"]: + sys.stderr.write("review refused\\n") + sys.exit(1) +if {hang!r}: + time.sleep(5) +sys.stdout.write({auth_status!r}) +sys.stdout.flush() +if {linger!r}: + subprocess.Popen([sys.executable, "-c", "import time; time.sleep(5)"]) +""") + cli.chmod(0o755) + return cli, calls + + +def calls_of(calls): + return calls.read_text().splitlines() if calls.exists() else [] + + +def review_calls(calls): + return [c for c in calls_of(calls) if "--input-format stream-json" in c] + + +def model_of(call): + args = call.split(" | ")[0].split() + return args[args.index("--model") + 1] + + +@pytest.fixture +def no_credential(monkeypatch, tmp_path): + for var in ("SECURITY_REVIEW_MODEL", "CLAUDE_CODE_EXECPATH", *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) + + +def new_hook_process(monkeypatch): + monkeypatch.setattr(llm, "_gateway_cli", None) + + +class TestGatewaySignInCheck: + @pytest.mark.parametrize("auth_status, signed_in", [ + pytest.param(SIGNED_IN, True, id="signed-in"), + pytest.param(NOT_SIGNED_IN, False, id="gateway-named-but-not-signed-in"), + pytest.param(json.dumps({"loggedIn": True, "apiProvider": "firstParty"}), False, + id="first-party"), + pytest.param(json.dumps({"loggedIn": "true", "apiProvider": "gateway"}), False, + id="logged-in-not-a-boolean"), + pytest.param("Logged in via gateway", False, id="not-json"), + pytest.param("[]", False, id="not-an-object"), + pytest.param("[" * 60000, False, id="too-deeply-nested"), + ]) + def test_reviews_only_for_a_signed_in_gateway_session( + self, no_credential, monkeypatch, tmp_path, auth_status, signed_in): + cli, calls = make_cli(tmp_path, auth_status) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert llm.can_review("s1") is signed_in + assert [c.split(" | ")[0] for c in calls_of(calls)] == ["auth status --json"] + + def test_cli_that_cannot_start_means_no_review(self, no_credential): + assert llm.can_review("s1") is False + + def test_no_cli_found_means_no_review(self, no_credential, monkeypatch): + monkeypatch.setattr(llm, "_user_cli_path", lambda: None) + assert llm.can_review("s1") is False + + def test_relative_cli_path_is_not_run(self, no_credential, monkeypatch, tmp_path): + cli, calls = make_cli(tmp_path, SIGNED_IN) + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "./claude") + assert llm.can_review("s1") is False + assert calls_of(calls) == [] + + def test_asked_from_the_home_directory(self, no_credential, monkeypatch, tmp_path): + cli, calls = make_cli(tmp_path, SIGNED_IN) + home, repo = tmp_path / "home", tmp_path / "repo" + home.mkdir() + repo.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.chdir(repo) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert llm.can_review("s1") + assert calls_of(calls)[0].endswith(f"CWD={home}") + + def test_hung_cli_means_no_review(self, no_credential, monkeypatch, tmp_path): + cli, _ = make_cli(tmp_path, SIGNED_IN, hang=True) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + monkeypatch.setattr(llm, "_GATEWAY_CHECK_TIMEOUT_S", 1) + assert llm.can_review("s1") is False + + def test_answer_is_read_while_a_process_it_started_holds_stdout( + self, no_credential, monkeypatch, tmp_path): + cli, _ = make_cli(tmp_path, SIGNED_IN, linger=True) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + monkeypatch.setattr(llm, "_GATEWAY_CHECK_TIMEOUT_S", 3) + assert llm.can_review("s1") is True + + def test_asked_once_per_session(self, no_credential, monkeypatch, tmp_path): + cli, calls = make_cli(tmp_path, SIGNED_IN) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert llm.can_review("s1") + new_hook_process(monkeypatch) + assert llm.can_review("s1") + assert len(calls_of(calls)) == 1 + new_hook_process(monkeypatch) + assert llm.can_review("s2") + assert len(calls_of(calls)) == 2 + + def test_no_answer_is_asked_again(self, no_credential, monkeypatch, tmp_path): + cli, calls = make_cli(tmp_path, "") + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert llm.can_review("s1") is False + make_cli(tmp_path, SIGNED_IN) + new_hook_process(monkeypatch) + assert llm.can_review("s1") is True + assert len(calls_of(calls)) == 2 + + def test_a_different_cli_is_asked_again(self, no_credential, monkeypatch, tmp_path): + first, _ = make_cli(tmp_path, SIGNED_IN, name="first") + second, second_calls = make_cli(tmp_path, NOT_SIGNED_IN, name="second") + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(first)) + assert llm.can_review("s1") + new_hook_process(monkeypatch) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(second)) + assert llm.can_review("s1") is False + assert len(calls_of(second_calls)) == 1 + + def test_credential_in_env_never_asks_the_cli(self, no_credential, monkeypatch, tmp_path): + cli, calls = make_cli(tmp_path, SIGNED_IN) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) + assert llm.can_review("s1") + assert calls_of(calls) == [] + + def test_telemetry_names_the_route(self, no_credential, monkeypatch, tmp_path): + monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False) + monkeypatch.delenv("ANTHROPIC_CUSTOM_HEADERS", raising=False) + cli, _ = make_cli(tmp_path, SIGNED_IN) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert llm.gateway_cfg() == 0 + assert llm.can_review("s1") + assert llm.gateway_cfg() == 4 + + def test_essential_traffic_only_still_reviews(self, no_credential, monkeypatch, tmp_path): + cli, _ = make_cli(tmp_path, SIGNED_IN) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + monkeypatch.setenv("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1") + assert llm.can_review("s1") + + +class FakeChild: + """Stands in for the child CLI's review; `reply` is what each call returns.""" + + def __init__(self): + self.prompts = [] + self.reply = {"hasVulnerabilities": False, "vulnerabilities": []} + + def __call__(self, prompt, schema, *, max_tokens=16000, model=None, cli_path=None): + self.prompts.append(prompt) + if self.reply is None: + llm._last_call_claude_http_error = -1 + return self.reply + + +class TestGatewayReviewOutcome: + @pytest.fixture + def child(self, no_credential, monkeypatch, tmp_path): + cli, _ = make_cli(tmp_path, SIGNED_IN) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + fake = FakeChild() + monkeypatch.setattr(llm, "_call_claude_via_sdk", fake) + return fake + + def test_review_is_sent_to_the_child(self, child): + assert llm.can_review("s1") + assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, []) + assert not llm.last_review_failed() + assert "+x = 1" in child.prompts[0] + assert child.prompts[0].startswith(llm._CODE_REVIEW_RUBRIC) + + @pytest.mark.parametrize("reply", [ + pytest.param(None, id="child-failed"), + pytest.param({"findings": []}, id="no-verdict"), + ]) + def test_child_without_a_verdict_is_a_failed_review(self, child, reply): + child.reply = reply + assert llm.can_review("s1") + assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, []) + assert 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)) + assert not llm.can_review("s1") + assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, []) + assert not llm.last_review_failed() + assert child.prompts == [] + + +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)} + + +class TestHooksInASignedInSession: + """The hooks with the real Agent SDK and a fake CLI that signs in but + refuses every review.""" + + @pytest.fixture + def session(self, hook_env, tmp_path): + pytest.importorskip("claude_agent_sdk") + env = without_credential(hook_env) + cli, calls = make_cli(tmp_path, SIGNED_IN) + env["SG_AGENTIC_CLI_PATH"] = str(cli) + return env, calls + + def test_commit_review_goes_through_the_cli_and_fails_loudly(self, session, workspace): + env, calls = session + _, repo = workspace + sha, out = commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env) + assert rc == 2 + assert metrics_of(so)["review_failed"] is True + assert ("did not complete: the review through Claude Code on the Claude apps " + "gateway returned no result.") in se + reviewed = repo / ".git" / "sg-reviewed-shas" + assert not reviewed.exists() or sha not in reviewed.read_text() + made = calls_of(calls) + assert made[0].startswith("auth status --json") + reviews = review_calls(calls) + assert [model_of(r) for r in reviews] == ["opus", "sonnet"] + # Every claude process the plugin starts (the sign-in check and the + # reviews) has this plugin switched off. The Agent SDK's own + # `claude -v` version check starts no session, so it is not checked. + assert " | SGD=1 | " in made[0] + assert all(" | SGD=1 | " in r for r in reviews) + # The single-shot review gets no tools, as on Bedrock and Vertex. + assert all(" --tools --strict-mcp-config" in r for r in reviews) + assert metrics_of(so)["gateway_cfg"] & 4 + + def test_pinned_model_is_sent_as_given(self, session, workspace): + env, calls = session + env["SECURITY_REVIEW_MODEL"] = "claude-sonnet-5-5" + _, repo = workspace + _, out = commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env) + assert rc == 2 + assert [model_of(r) for r in review_calls(calls)] == ["claude-sonnet-5-5"] + assert "SECURITY_REVIEW_MODEL (claude-sonnet-5-5) may also name a model" in se + + def test_agentic_commit_review_runs(self, session, workspace): + env, calls = session + env["SG_AGENTIC_COMMIT_REVIEW"] = "1" + env["SG_AGENTIC_MAX_TURNS"] = "7" + _, repo = workspace + _, out = commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env) + assert rc == 2 and metrics_of(so)["review_failed"] is True + reviews = review_calls(calls) + assert any("--max-turns 7" in r for r in reviews) + # The agentic reviewer gets the file-reading tools and nothing else. + assert any(" --tools Read,Grep,Glob --strict-mcp-config" in r for r in reviews) + + def test_stop_review_goes_through_the_cli(self, session, workspace): + env, calls = session + ws, 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, se = run_hook(stop_payload(repo), env) + assert metrics_of(so)["review_failed"] is True + assert review_calls(calls) + + def test_push_review_goes_through_the_cli(self, session, workspace, tmp_path): + env, calls = session + 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() + sha, _ = commit_file(repo, "app.py", VULN_PY) + 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 rc == 2 and m["push_sweep"] is True and m["review_failed"] is True, m + assert review_calls(calls) + + def test_not_signed_in_skips_and_asks_once(self, hook_env, tmp_path, workspace): + env = without_credential(hook_env) + cli, calls = make_cli(tmp_path, NOT_SIGNED_IN) + env["SG_AGENTIC_CLI_PATH"] = str(cli) + _, repo = workspace + for n in range(2): + _, out = commit_file(repo, "app.py", VULN_PY + f"# {n}\n") + 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 diff --git a/plugins/security-guidance/tests/test_no_credentials_notice.py b/plugins/security-guidance/tests/test_no_credentials_notice.py index 1995397e..99e85c8d 100644 --- a/plugins/security-guidance/tests/test_no_credentials_notice.py +++ b/plugins/security-guidance/tests/test_no_credentials_notice.py @@ -9,6 +9,7 @@ from conftest import ( bash_payload, commit_file, edit_payload, git, metrics_of, run_hook, stop_payload, ups_payload, VULN_PY, ) +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 = ( @@ -173,3 +174,40 @@ def test_skipped_reviews_report_the_missing_credentials(workspace, hook_env, stu bash_payload(repo, "git push origin main", session_id="s3")): rc, out, _ = run_hook(payload, off) assert "no_creds" not in metrics_of(out) + + +def test_no_notice_in_a_signed_in_gateway_session(workspace, hook_env, tmp_path): + # Claude Code passes no credential there, but the reviews run through + # the user's claude, so they are running. + _, repo = workspace + cli, calls = make_cli(tmp_path, SIGNED_IN) + env = _env(hook_env, SG_AGENTIC_CLI_PATH=str(cli)) + assert _notice(repo, env) is None + # The check counts as this week's: a new session's edit does not ask. + assert _notice(repo, env, session_id="s2") is None + assert os.path.exists(_marker(env)) + assert [c.split(" | ")[0] for c in calls_of(calls)] == ["auth status --json"] + # A week later the edit asks again. + eight_days = time.time() - 8 * 86400 + os.utime(_marker(env), (eight_days, eight_days)) + assert _notice(repo, env, session_id="s3") is None + assert len(calls_of(calls)) == 2 + + +def test_edit_outside_a_git_repo_does_not_ask_claude(workspace, hook_env, tmp_path): + cli, calls = make_cli(tmp_path, SIGNED_IN) + plain = tmp_path / "plain" + plain.mkdir() + env = _env(hook_env, SG_AGENTIC_CLI_PATH=str(cli)) + assert _notice(plain, env, name="notes.py") is None + assert calls_of(calls) == [] + + +def test_notice_when_the_gateway_session_is_not_signed_in(workspace, hook_env, tmp_path): + _, repo = workspace + cli, calls = make_cli(tmp_path, NOT_SIGNED_IN) + env = _env(hook_env, SG_AGENTIC_CLI_PATH=str(cli)) + assert "is not running" in _notice(repo, env) + # Within the week no notice is due, so claude is not asked again. + assert _notice(repo, env, session_id="s2") is None + assert len(calls_of(calls)) == 1 |
