summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-10 02:52:11 +0000
committerClaude <noreply@anthropic.com>2026-11-10 02:52:11 +0000
commit21a7082f3f6c3782aba8e7efc8fad6de41e822de (patch)
treec74f6b46bba303cd1f72ee61c8a55d1bdf0e5a95 /plugins
parentdceb15d50832e6adf380bedc26dde03d251324b9 (diff)
security-guidance: hold back a host's token by the host, not the output settingmhegazy/sg-credential-host-detection
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/_base.py23
-rw-r--r--plugins/security-guidance/hooks/llm.py8
-rw-r--r--plugins/security-guidance/tests/test_credential_routing.py27
3 files changed, 50 insertions, 8 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 99607e4a..75fcbdce 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -175,19 +175,33 @@ _CLAUDE_CODE_OUTPUT_FIELDS = ("metrics", "rewakeSummary")
def _detect_portable_output():
+ forced = _forced_portable_output()
+ if forced is not None:
+ return forced
+ return _detect_other_host()
+
+
+def _forced_portable_output():
forced = os.environ.get("SECURITY_GUIDANCE_PORTABLE_OUTPUT", "").strip().lower()
if forced in ("1", "true", "yes", "on"):
return True
if forced in ("0", "false", "no", "off"):
return False
+ return None
+
+
+def _detect_other_host():
+ """The host does not identify itself as Claude Code, and passes PLUGIN_ROOT
+ or was told to use portable output, which a host we cannot detect needs."""
if os.environ.get("CLAUDECODE") or os.environ.get("CLAUDE_CODE_ENTRYPOINT"):
return False
- return bool(os.environ.get("PLUGIN_ROOT"))
+ return bool(os.environ.get("PLUGIN_ROOT")) or _forced_portable_output() is True
# Decided once, from the environment the host started the hook with: code the
# hook runs in-process later can set these variables itself.
_PORTABLE_OUTPUT = _detect_portable_output()
+_OTHER_HOST = _detect_other_host()
def portable_output():
@@ -199,6 +213,13 @@ def portable_output():
return _PORTABLE_OUTPUT
+def other_host():
+ """True when a host other than Claude Code started this hook. Unlike
+ portable_output(), a Claude Code session stays one whatever
+ SECURITY_GUIDANCE_PORTABLE_OUTPUT says."""
+ return _OTHER_HOST
+
+
def write_hook_output(out):
"""Print one hook output line. In portable mode the Claude Code only
fields are left out; what remains (possibly `{}`) is still valid output."""
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 6f8c68e2..0789969c 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, portable_output # 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, other_host # noqa: F401
from session_state import load_state, with_locked_state
from gitutil import git_config_env, SAFE_GIT_CONFIG
@@ -112,7 +112,7 @@ _CLAUDE_AI_TOKEN_PREFIX = "sk-ant-oat"
_API_HOST = "api.anthropic.com"
-def _route_credentials(env, portable: bool) -> bool:
+def _route_credentials(env, on_other_host: 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.
@@ -134,7 +134,7 @@ def _route_credentials(env, portable: bool) -> bool:
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):
+ if on_other_host 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 "
@@ -165,7 +165,7 @@ _HAS_3P_PROVIDER_AT_LOAD = any(
)
)
# In os.environ itself, so the CLI a review starts gets the same credentials.
-AUTH_TOKEN_HELD_BACK = _route_credentials(os.environ, portable_output())
+AUTH_TOKEN_HELD_BACK = _route_credentials(os.environ, other_host())
# Plan Security Check Configuration
ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
diff --git a/plugins/security-guidance/tests/test_credential_routing.py b/plugins/security-guidance/tests/test_credential_routing.py
index 106ec470..27afa12a 100644
--- a/plugins/security-guidance/tests/test_credential_routing.py
+++ b/plugins/security-guidance/tests/test_credential_routing.py
@@ -1,5 +1,6 @@
"""Which credential a review sends to the default API host. Made-up values."""
import os
+import subprocess
import sys
import pytest
@@ -91,7 +92,7 @@ def test_api_key_is_unchanged(hook_env):
def test_held_back_token_reaches_nothing(hook_env):
- assert _load(hook_env, SECURITY_GUIDANCE_PORTABLE_OUTPUT="1", **{T: BEARER}) == [
+ assert _load(hook_env, PLUGIN_ROOT="/plugin", **{T: BEARER}) == [
"", "", False, True, "", ""]
@@ -103,9 +104,9 @@ 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"):
+ for name in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_TELEMETRY", "DO_NOT_TRACK"):
e.pop(name, None)
- e["SECURITY_GUIDANCE_PORTABLE_OUTPUT"] = "1"
+ e["PLUGIN_ROOT"] = "/plugin"
return e
@pytest.mark.parametrize("other", [{}, {"DISABLE_TELEMETRY": "1"}])
@@ -129,3 +130,23 @@ class TestHook:
(repo / "app.py").write_text(VULN_PY)
run_hook(stop_payload(repo), env)
assert stub_api.calls.count("/v1/messages") == 1
+
+
+@pytest.mark.parametrize("extra,held_back", [
+ ({"CLAUDECODE": "1", "SECURITY_GUIDANCE_PORTABLE_OUTPUT": "1"}, False),
+ ({"CLAUDECODE": "1", "PLUGIN_ROOT": "/p", "SECURITY_GUIDANCE_PORTABLE_OUTPUT": "1"}, False),
+ ({"PLUGIN_ROOT": "/p", "SECURITY_GUIDANCE_PORTABLE_OUTPUT": "0"}, True),
+ ({"PLUGIN_ROOT": "/p"}, True),
+ ({"SECURITY_GUIDANCE_PORTABLE_OUTPUT": "1"}, True),
+ ({}, False),
+])
+def test_the_output_setting_does_not_decide_the_host(extra, held_back):
+ hooks = os.path.dirname(os.path.abspath(llm.__file__))
+ env = {k: v for k, v in os.environ.items()
+ if k not in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "PLUGIN_ROOT", B,
+ "SECURITY_GUIDANCE_PORTABLE_OUTPUT")}
+ out = subprocess.run(
+ [sys.executable, "-c", "import llm; print(llm.AUTH_TOKEN_HELD_BACK)"],
+ cwd=hooks, env={**env, T: BEARER, **extra, "PYTHONDONTWRITEBYTECODE": "1"},
+ capture_output=True, text=True, timeout=60)
+ assert out.stdout.strip().splitlines()[-1] == str(held_back), out.stderr