summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-11-07 02:01:31 +0000
committerClaude <noreply@anthropic.com>2026-11-07 02:01:31 +0000
commitf98b876f06d8fa0175815dac4af0b5aedc942a16 (patch)
tree5fcdb640aa6fd756747016724493894d14f3b6b5 /plugins
parentc07c748f1c680734a813eefd909bc073f8a9103f (diff)
security-guidance: send a claude.ai token as a bearer, hold back a gateway'smhegazy/sg-credential-routing
A claude.ai token that arrives as ANTHROPIC_API_KEY (from an apiKeyHelper) is refused by the API as a key; send it as a bearer. On hosts other than Claude Code, a bearer that is not a claude.ai token is not sent without a base URL. Other hosts' base URLs and cloud providers are left alone. Fixes #6955 Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/README.md2
-rw-r--r--plugins/security-guidance/hooks/llm.py54
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py5
-rw-r--r--plugins/security-guidance/tests/test_credential_routing.py131
4 files changed, 185 insertions, 7 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index e0c4a888..99c2cda6 100644
--- a/plugins/security-guidance/README.md
+++ b/plugins/security-guidance/README.md
@@ -59,6 +59,8 @@ The pattern warnings need no credentials. The LLM reviews (the diff review on St
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.
+On the default API host, a claude.ai token (`sk-ant-oat`) that arrives as `ANTHROPIC_API_KEY`, for example from an `apiKeyHelper`, is sent as a bearer token. On hosts other than Claude Code, any other `ANTHROPIC_AUTH_TOKEN` is not used without a base URL, because it is meant for a gateway: set `ANTHROPIC_BASE_URL` to that gateway.
+
### Enabling/disabling layers
| Variable | Default | What it does |
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index ee9ad2be..e4143dd2 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -40,7 +40,7 @@ except ImportError: # a Python built without TLS
import extensibility
import review_api
-from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs, make_state_dir # noqa: F401
+from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs, make_state_dir, portable_output # noqa: F401
from session_state import load_state, with_locked_state
from gitutil import git_config_env, SAFE_GIT_CONFIG
@@ -108,11 +108,45 @@ def _bootstrap_pywin32(site_packages_dir):
debug_log(f"pywin32 bootstrap failed (may break SDK import on Windows): {e}")
-# Plan Security Check Configuration
-ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
-# OAuth access token — Claude Code passes this for /login users.
-# The Anthropic API accepts it as `Authorization: Bearer <token>` instead of `x-api-key`.
-ANTHROPIC_AUTH_TOKEN = os.environ.get("ANTHROPIC_AUTH_TOKEN", "")
+_CLAUDE_AI_TOKEN_PREFIX = "sk-ant-oat"
+_API_HOST = "api.anthropic.com"
+
+
+def _route_credentials(env, portable: bool) -> bool:
+ """Put the credentials in `env` where the default API host can use them.
+ Returns whether a token was held back. Does nothing for another API host
+ or a cloud provider: what those take is their own business.
+
+ - Claude Code hands an apiKeyHelper's output over as ANTHROPIC_API_KEY,
+ also when it is a claude.ai token. The API takes that only as a
+ bearer, so as a key every review ends in a 401.
+ - A host other than Claude Code can hand its own gateway's bearer without
+ the gateway's address. It is no credential for the default API host, so
+ it is not sent there. Claude Code passes both, so its sessions are left
+ alone."""
+ base = env.get("ANTHROPIC_BASE_URL", "").strip()
+ try:
+ api_host = (urllib.parse.urlsplit(base).hostname or "").lower() if base else _API_HOST
+ except ValueError:
+ return False
+ if api_host != _API_HOST or _HAS_3P_PROVIDER_AT_LOAD:
+ return False
+ held_back = False
+ token = env.get("ANTHROPIC_AUTH_TOKEN", "")
+ # With a base URL the token was meant for it, whichever shape it has.
+ if portable and not base and token and not token.startswith(_CLAUDE_AI_TOKEN_PREFIX):
+ del env["ANTHROPIC_AUTH_TOKEN"]
+ token, held_back = "", True
+ debug_log("ANTHROPIC_AUTH_TOKEN not used: it is not a claude.ai token and "
+ "ANTHROPIC_BASE_URL is not set")
+ key = env.get("ANTHROPIC_API_KEY", "")
+ if key.startswith(_CLAUDE_AI_TOKEN_PREFIX) and (
+ not token or token.startswith(_CLAUDE_AI_TOKEN_PREFIX)):
+ env["ANTHROPIC_AUTH_TOKEN"] = token or key
+ del env["ANTHROPIC_API_KEY"]
+ return held_back
+
+
# On 3P providers (Bedrock/Vertex/Foundry/Mantle), credentials live in the
# provider env (AWS_PROFILE, GOOGLE_APPLICATION_CREDENTIALS, etc.) — not in
# ANTHROPIC_*. Treat presence of any 3P provider flag as "has credentials"
@@ -130,6 +164,14 @@ _HAS_3P_PROVIDER_AT_LOAD = any(
"CLAUDE_CODE_USE_ANTHROPIC_AWS",
)
)
+# In os.environ itself, so the CLI a review starts gets the same credentials.
+AUTH_TOKEN_HELD_BACK = _route_credentials(os.environ, portable_output())
+
+# Plan Security Check Configuration
+ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
+# OAuth access token — Claude Code passes this for /login users.
+# The Anthropic API accepts it as `Authorization: Bearer <token>` instead of `x-api-key`.
+ANTHROPIC_AUTH_TOKEN = os.environ.get("ANTHROPIC_AUTH_TOKEN", "")
HAS_API_CREDENTIALS = bool(
ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN or _HAS_3P_PROVIDER_AT_LOAD
)
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 47a992aa..a2794616 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -446,7 +446,10 @@ def _no_credentials_notice(file_path, session_id):
except OSError:
return None
withheld_by = _credential_withholding_env_vars()
- if withheld_by:
+ if llm.AUTH_TOKEN_HELD_BACK:
+ why = ("ANTHROPIC_AUTH_TOKEN is not a claude.ai token and "
+ "ANTHROPIC_BASE_URL is not set, so it was not sent anywhere")
+ elif withheld_by:
why = ("Claude Code does not pass your sign-in to plugins while "
+ " or ".join(withheld_by) + " is set")
else:
diff --git a/plugins/security-guidance/tests/test_credential_routing.py b/plugins/security-guidance/tests/test_credential_routing.py
new file mode 100644
index 00000000..106ec470
--- /dev/null
+++ b/plugins/security-guidance/tests/test_credential_routing.py
@@ -0,0 +1,131 @@
+"""Which credential a review sends to the default API host. Made-up values."""
+import os
+import sys
+
+import pytest
+
+import llm
+from conftest import edit_payload, run_hook, stop_payload, ups_payload, VULN_PY
+
+OAT = "sk-ant-oat01-made-up"
+KEY = "sk-ant-api03-made-up"
+BEARER = "vck_made-up"
+K, T, B = "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"
+GATEWAY = "https://gateway.example.com"
+
+
+def _route(env, portable=False):
+ env = dict(env)
+ return llm._route_credentials(env, portable), env
+
+
+@pytest.mark.parametrize("portable", [False, True])
+@pytest.mark.parametrize("before, after", [
+ ({K: OAT}, {T: OAT}),
+ ({K: OAT, B: ""}, {T: OAT, B: ""}),
+ ({K: OAT, B: " "}, {T: OAT, B: " "}),
+ ({K: OAT, T: ""}, {T: OAT}),
+ # The session's own token is kept, the key could not have worked.
+ ({K: OAT, T: OAT + "2"}, {T: OAT + "2"}),
+ ({K: KEY}, {K: KEY}),
+ ({K: KEY, T: OAT}, {K: KEY, T: OAT}),
+ ({K: ""}, {K: ""}),
+ ({T: OAT}, {T: OAT}),
+ ({}, {}),
+ ({K: OAT, B: "https://api.anthropic.com"}, {T: OAT, B: "https://api.anthropic.com"}),
+ # With a base URL the token was meant for it.
+ ({T: BEARER, B: "https://api.anthropic.com"}, {T: BEARER, B: "https://api.anthropic.com"}),
+ ({K: OAT, B: "https://["}, {K: OAT, B: "https://["}),
+ # A gateway decides for itself what it takes.
+ ({K: OAT, B: GATEWAY}, {K: OAT, B: GATEWAY}),
+ ({T: BEARER, B: GATEWAY}, {T: BEARER, B: GATEWAY}),
+])
+def test_claude_ai_token_as_key(before, after, portable):
+ assert _route(before, portable) == (False, after)
+
+
+@pytest.mark.parametrize("before, after", [
+ ({T: BEARER}, {}),
+ ({T: BEARER, B: ""}, {B: ""}),
+ ({K: KEY, T: BEARER}, {K: KEY}),
+ ({K: OAT, T: BEARER}, {T: OAT}),
+])
+def test_other_bearer_without_a_base_url_on_another_host(before, after):
+ assert _route(before, portable=True) == (True, after)
+
+
+@pytest.mark.parametrize("env", [{T: BEARER}, {K: KEY, T: BEARER}, {K: OAT, T: BEARER}])
+def test_other_bearer_in_claude_code_is_left_alone(env):
+ assert _route(env) == (False, env)
+
+
+@pytest.mark.parametrize("env", [{K: OAT}, {T: BEARER}, {K: OAT, T: BEARER}])
+def test_cloud_provider_is_left_alone(env, monkeypatch):
+ monkeypatch.setattr(llm, "_HAS_3P_PROVIDER_AT_LOAD", True)
+ assert _route(env, portable=True) == (False, env)
+
+
+def _load(hook_env, **extra):
+ """What a fresh import of llm makes of the environment."""
+ import subprocess
+ env = {k: v for k, v in hook_env.items() if k not in (K, T, B, "CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT")}
+ env.update(extra)
+ code = ("import sys; sys.path.insert(0, %r); import llm; e = llm._agentic_spawn_env(); "
+ "import os; child = {**os.environ, **e}; "
+ "print(repr([llm.ANTHROPIC_API_KEY, llm.ANTHROPIC_AUTH_TOKEN, llm.HAS_API_CREDENTIALS, "
+ "llm.AUTH_TOKEN_HELD_BACK, child.get('ANTHROPIC_API_KEY') or '', "
+ "child.get('ANTHROPIC_AUTH_TOKEN') or child.get('CLAUDE_CODE_OAUTH_TOKEN') or '']))"
+ % os.path.dirname(llm.__file__))
+ r = subprocess.run([sys.executable, "-c", code], env=env, capture_output=True, text=True)
+ assert r.returncode == 0, r.stderr
+ import ast
+ return ast.literal_eval(r.stdout.strip().splitlines()[-1])
+
+
+def test_the_reviewing_cli_gets_the_token_as_a_token(hook_env):
+ assert _load(hook_env, **{K: OAT}) == ["", OAT, True, False, "", OAT]
+
+
+def test_api_key_is_unchanged(hook_env):
+ assert _load(hook_env, **{K: KEY}) == [KEY, "", True, False, KEY, ""]
+
+
+def test_held_back_token_reaches_nothing(hook_env):
+ assert _load(hook_env, SECURITY_GUIDANCE_PORTABLE_OUTPUT="1", **{T: BEARER}) == [
+ "", "", False, True, "", ""]
+
+
+def test_same_token_in_claude_code_is_sent_as_before(hook_env):
+ assert _load(hook_env, **{T: BEARER}) == ["", BEARER, True, False, "", BEARER]
+
+
+class TestHook:
+ @pytest.fixture
+ def env(self, hook_env):
+ e = {k: v for k, v in hook_env.items() if k not in (K, T, B)}
+ for name in ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_TELEMETRY", "DO_NOT_TRACK"):
+ e.pop(name, None)
+ e["SECURITY_GUIDANCE_PORTABLE_OUTPUT"] = "1"
+ return e
+
+ @pytest.mark.parametrize("other", [{}, {"DISABLE_TELEMETRY": "1"}])
+ def test_held_back_token_is_said_once(self, workspace, env, other):
+ _, repo = workspace
+ env.update(other)
+ env[T] = BEARER
+ (repo / "app.py").write_text(VULN_PY)
+ payload = edit_payload(repo, repo / "app.py", new_string=VULN_PY)
+ _, out, _ = run_hook(payload, env)
+ assert "ANTHROPIC_BASE_URL is not set, so it was not sent anywhere" in out
+ assert BEARER not in out
+ _, out, _ = run_hook(payload, env)
+ assert "not running" not in out
+
+ def test_with_its_base_url_the_review_runs(self, workspace, env, stub_api):
+ _, repo = workspace
+ env[T] = BEARER
+ env[B] = f"http://127.0.0.1:{stub_api.server_port}"
+ run_hook(ups_payload(repo), env)
+ (repo / "app.py").write_text(VULN_PY)
+ run_hook(stop_payload(repo), env)
+ assert stub_api.calls.count("/v1/messages") == 1