diff options
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/README.md | 4 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 30 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_reviewer_oauth_token.py | 54 |
3 files changed, 83 insertions, 5 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index e0c4a888..ee8d1217 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -53,8 +53,8 @@ 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 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. +- **`ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in the environment** — used as is, against `ANTHROPIC_BASE_URL` if you set one. With no base URL, the commit/push reviewer treats a claude.ai token (`sk-ant-oat`) the way it treats a sign-in, below. +- **Signed in to Claude Code (`/login`)** — Claude Code passes your sign-in to the plugin's hooks, and reviews use that account. The commit/push reviewer's Claude Code runs on that token alone and does not renew the login you have stored. - **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, 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. diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index ee9ad2be..6a5eebf2 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -1971,6 +1971,19 @@ def _api_retry_status(msg: Any) -> Optional[int]: return status if isinstance(status, int) else None +_OAUTH_TOKEN_PREFIX = "sk-ant-oat" + + +def _oauth_variable_is_safe() -> bool: + """Whether a claude.ai token may move out of ANTHROPIC_AUTH_TOKEN. With a + base URL set it can be a gateway's bearer, bare mode ignores the OAuth + variable, and a cloud session has no stored login to protect and rotates + its own token.""" + bare = os.environ.get("CLAUDE_CODE_SIMPLE", "").strip().lower() + return not (os.environ.get("ANTHROPIC_BASE_URL", "").strip() + or bare in ("1", "true", "yes", "on") or _is_remote_session()) + + def _agentic_spawn_env() -> Dict[str, str]: """opts.env for the SDK-spawned inner `claude` CLI. @@ -1986,7 +1999,8 @@ def _agentic_spawn_env() -> Dict[str, str]: blanking the inherited OAuth token there strands the grandchild with zero credentials → ProcessError → agentic silently falls back to single-shot on every commit. So forward the OAuth token whenever it - is the only credential. + is the only credential, as CLAUDE_CODE_OAUTH_TOKEN when it is a + claude.ai token. """ env = { # Policy settings can enable this plugin inside the reviewing CLI too; @@ -2018,7 +2032,16 @@ def _agentic_spawn_env() -> Dict[str, str]: # No API key — forward the OAuth token from the parent process so the # SDK grandchild has credentials. Empty string is fine (the SDK will # use whatever auth path is left). - env["ANTHROPIC_AUTH_TOKEN"] = os.environ.get("ANTHROPIC_AUTH_TOKEN") or "" + token = os.environ.get("ANTHROPIC_AUTH_TOKEN") or "" + if token.startswith(_OAUTH_TOKEN_PREFIX) and _oauth_variable_is_safe(): + # Given as ANTHROPIC_AUTH_TOKEN, the inner CLI still renews a stored + # claude.ai login it does not run on, which can sign the user out. + # Given as its OAuth token, it leaves the stored login alone. That + # route also turns on 1-hour cache writes, which cost more. + env["CLAUDE_CODE_OAUTH_TOKEN"] = token + env["FORCE_PROMPT_CACHING_5M"] = "1" + token = "" + env["ANTHROPIC_AUTH_TOKEN"] = token return env @@ -2217,7 +2240,8 @@ def _agentic_review( # env as {**os.environ, **opts.env}, so the inner claude inherits # it and prefers it over ANTHROPIC_API_KEY — but some model # endpoints reject OAuth bearers (401 → exit 1 → silent - # fallback). Override with empty so API-key auth wins. + # fallback). Override with empty so API-key auth wins. With no + # API key, a claude.ai token moves to CLAUDE_CODE_OAUTH_TOKEN. # # On CCR (entrypoint=remote*) the daemon passes auth on file # descriptors to the top-level claude process; the SDK-spawned diff --git a/plugins/security-guidance/tests/test_reviewer_oauth_token.py b/plugins/security-guidance/tests/test_reviewer_oauth_token.py new file mode 100644 index 00000000..878608db --- /dev/null +++ b/plugins/security-guidance/tests/test_reviewer_oauth_token.py @@ -0,0 +1,54 @@ +"""The inner CLI runs on a handed claude.ai token, not a stored login.""" +import llm +import pytest + +OAUTH_TOKEN = "sk-ant-oat01-token" + + +def _spawn_env(monkeypatch, **credentials): + for name in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", + "ANTHROPIC_BASE_URL", "CLAUDE_CODE_SIMPLE", "CLAUDE_CODE_REMOTE"): + monkeypatch.delenv(name, raising=False) + for name, value in credentials.items(): + monkeypatch.setenv(name, value) + return llm._agentic_spawn_env() + + +class TestReviewerOauthToken: + def test_claude_ai_token_goes_to_the_oauth_variable(self, monkeypatch): + env = _spawn_env(monkeypatch, ANTHROPIC_AUTH_TOKEN=OAUTH_TOKEN) + assert env["CLAUDE_CODE_OAUTH_TOKEN"] == OAUTH_TOKEN + assert env["ANTHROPIC_AUTH_TOKEN"] == "" + + def test_cache_writes_stay_at_five_minutes(self, monkeypatch): + env = _spawn_env(monkeypatch, ANTHROPIC_AUTH_TOKEN=OAUTH_TOKEN) + assert env["FORCE_PROMPT_CACHING_5M"] == "1" + + def test_other_bearer_stays_where_it_was(self, monkeypatch): + env = _spawn_env(monkeypatch, ANTHROPIC_AUTH_TOKEN="gateway-bearer") + assert env["ANTHROPIC_AUTH_TOKEN"] == "gateway-bearer" + assert "CLAUDE_CODE_OAUTH_TOKEN" not in env + assert "FORCE_PROMPT_CACHING_5M" not in env + + @pytest.mark.parametrize("name", ["ANTHROPIC_BASE_URL", "CLAUDE_CODE_SIMPLE", "CLAUDE_CODE_REMOTE"]) + def test_token_stays_put_where_the_oauth_variable_is_unsafe(self, monkeypatch, name): + env = _spawn_env(monkeypatch, ANTHROPIC_AUTH_TOKEN=OAUTH_TOKEN, **{name: "1"}) + assert env["ANTHROPIC_AUTH_TOKEN"] == OAUTH_TOKEN + assert "CLAUDE_CODE_OAUTH_TOKEN" not in env + + @pytest.mark.parametrize("name, value", [ + ("ANTHROPIC_BASE_URL", ""), ("ANTHROPIC_BASE_URL", " "), + ("CLAUDE_CODE_SIMPLE", "0"), ("CLAUDE_CODE_REMOTE", "0"), ("CLAUDE_CODE_REMOTE", "false")]) + def test_blank_or_off_counts_as_not_set(self, monkeypatch, name, value): + env = _spawn_env(monkeypatch, ANTHROPIC_AUTH_TOKEN=OAUTH_TOKEN, **{name: value}) + assert env["CLAUDE_CODE_OAUTH_TOKEN"] == OAUTH_TOKEN + + def test_api_key_wins_over_a_claude_ai_token(self, monkeypatch): + env = _spawn_env(monkeypatch, ANTHROPIC_API_KEY="key", ANTHROPIC_AUTH_TOKEN=OAUTH_TOKEN) + assert env["ANTHROPIC_AUTH_TOKEN"] == "" + assert "CLAUDE_CODE_OAUTH_TOKEN" not in env + + def test_no_credential_adds_nothing(self, monkeypatch): + env = _spawn_env(monkeypatch) + assert env["ANTHROPIC_AUTH_TOKEN"] == "" + assert "CLAUDE_CODE_OAUTH_TOKEN" not in env |
