summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-08 01:00:45 +0000
committerClaude <noreply@anthropic.com>2026-10-09 16:04:08 +0000
commit860b93cb3898d30683ef9b1b70755d4fb0c2ff57 (patch)
tree73b675981e0f318bbfd9b8a408ad253cda1f514b /plugins
parentac996c0dde7fb2a9f805cd5277ffc95ecd44a321 (diff)
security-guidance: send ANTHROPIC_CUSTOM_HEADERS on the plugin's own API callsmhegazy/sg-gateway-headers
The plugin's own API calls (the /v1/models lookup and the review itself) never sent ANTHROPIC_CUSTOM_HEADERS, so a gateway that takes its key in a custom header answered 401 and reviews never ran (anthropics/claude-code#99857). The headers are now parsed the way Claude Code parses them (one `Name: Value` per line, split at the first colon) and sent on every call. A custom line replaces a header of the same name. anthropic-beta lines are not forwarded: the review needs none of the user's betas.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/README.md2
-rw-r--r--plugins/security-guidance/hooks/llm.py44
-rw-r--r--plugins/security-guidance/tests/conftest.py78
-rw-r--r--plugins/security-guidance/tests/test_custom_headers.py70
4 files changed, 193 insertions, 1 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index 58736a85..3da33525 100644
--- a/plugins/security-guidance/README.md
+++ b/plugins/security-guidance/README.md
@@ -95,7 +95,7 @@ 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. The gateway operator's terms apply.
+- **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.
- **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 and finding categories — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded.
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 3c1eb5e3..1f06cee7 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -267,6 +267,38 @@ def _cap_files_for_prompt(files):
_auth_prefer_token = False
+# A valid HTTP header name (an RFC 9110 token).
+_HEADER_NAME = re.compile(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+")
+_custom_header_lines_skipped = set()
+
+
+def _custom_headers() -> List[Tuple[str, str]]:
+ """ANTHROPIC_CUSTOM_HEADERS as (name, value) pairs, parsed the way Claude
+ Code parses it: one `Name: Value` per line, split at the first colon,
+ trimmed, lines with no name dropped. Lines http.client cannot send (an
+ invalid name, a carriage return or non-Latin-1 text in the value) are
+ skipped. Values are never logged: they are often credentials."""
+ pairs = []
+ raw = os.environ.get("ANTHROPIC_CUSTOM_HEADERS", "")
+ for number, line in enumerate(re.split(r"\r?\n", raw), 1):
+ name, sep, value = line.partition(":")
+ name, value = name.strip(), value.strip()
+ if not sep or not name:
+ continue
+ try:
+ value.encode("latin-1")
+ sendable = bool(_HEADER_NAME.fullmatch(name)) and "\r" not in value
+ except UnicodeEncodeError:
+ sendable = False
+ if not sendable:
+ if number not in _custom_header_lines_skipped:
+ _custom_header_lines_skipped.add(number)
+ debug_log(f"ANTHROPIC_CUSTOM_HEADERS: skipped line {number}, not a valid HTTP header")
+ continue
+ pairs.append((name, value))
+ return pairs
+
+
def _build_auth_headers(use_token, betas=("structured-outputs-2025-11-13",)):
betas = list(betas)
headers = {
@@ -278,6 +310,18 @@ def _build_auth_headers(use_token, betas=("structured-outputs-2025-11-13",)):
betas.append("oauth-2025-04-20")
else:
headers["x-api-key"] = ANTHROPIC_API_KEY
+ for name, value in _custom_headers():
+ lowered = name.lower()
+ if lowered == "anthropic-beta":
+ # Not sent: the review needs none of the user's betas, and Claude
+ # Code drops anthropic-beta lines when the organization's
+ # compliance policy disables experimental betas.
+ continue
+ # As in Claude Code, a custom line wins over a header of the same
+ # name that the plugin set, including the credential header.
+ for existing in [k for k in headers if k.lower() == lowered]:
+ del headers[existing]
+ headers[name] = value
if betas:
headers["anthropic-beta"] = ",".join(betas)
return headers
diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py
index 2cf4dd1c..11af0273 100644
--- a/plugins/security-guidance/tests/conftest.py
+++ b/plugins/security-guidance/tests/conftest.py
@@ -212,3 +212,81 @@ def ups_payload(cwd, session_id="s1"):
"prompt": "hi",
"cwd": str(cwd),
}
+
+
+# ── a local Anthropic-compatible endpoint the hook can be pointed at ──────
+
+class _Gateway(http.server.BaseHTTPRequestHandler):
+ """An Anthropic-compatible endpoint. With `required` set it answers 401
+ unless that header arrives, like a LiteLLM proxy keyed on a custom header."""
+
+ def _handle(self):
+ n = int(self.headers.get("Content-Length") or 0)
+ if n:
+ self.rfile.read(n)
+ srv = self.server
+ srv.requests.append((self.command, self.path, {k.lower(): v for k, v in self.headers.items()}))
+ name, value = srv.required or (None, None)
+ if name and self.headers.get(name) != value:
+ return self._send(401, {"type": "error", "error": {
+ "type": "authentication_error", "message": "Invalid proxy server token"}})
+ if srv.status != 200:
+ return self._send(srv.status, {"type": "error", "error": {"type": "api_error"}})
+ if self.command == "GET":
+ return self._send(200, {"data": [{"id": "claude-opus-5-5"}], "has_more": False})
+ text = (srv.reply if srv.reply is not None else json.dumps(
+ {"hasVulnerabilities": bool(srv.vulns), "vulnerabilities": srv.vulns}))
+ self._send(200, {
+ "id": "msg_stub", "type": "message", "role": "assistant",
+ "model": "stub", "stop_reason": "end_turn",
+ "content": [{"type": "text", "text": text}],
+ "usage": {"input_tokens": 1, "output_tokens": 1},
+ })
+
+ do_GET = do_POST = do_HEAD = _handle
+
+ def _send(self, status, payload):
+ body = json.dumps(payload).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *a):
+ pass
+
+
+@pytest.fixture
+def gateway():
+ srv = http.server.HTTPServer(("127.0.0.1", 0), _Gateway)
+ srv.requests, srv.required, srv.status, srv.reply, srv.vulns = [], None, 200, None, []
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ try:
+ yield srv
+ finally:
+ srv.shutdown()
+
+
+@pytest.fixture
+def env(hook_env, gateway):
+ e = dict(hook_env)
+ e["ANTHROPIC_BASE_URL"] = f"http://127.0.0.1:{gateway.server_port}"
+ e.pop("SECURITY_REVIEW_MODEL", None)
+ return e
+
+
+@pytest.fixture
+def failing_inner_cli(tmp_path):
+ """An inner CLI that prints a warning on stderr and exits 1; the review
+ then falls back to a single-shot call."""
+ cli = tmp_path / "claude"
+ cli.write_text("#!/bin/sh\necho 'claude.ai connectors are disabled' >&2\nexit 1\n")
+ cli.chmod(0o755)
+ return str(cli)
+
+
+@pytest.fixture
+def agentic_env(env, failing_inner_cli):
+ pytest.importorskip("claude_agent_sdk")
+ return {**env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli}
diff --git a/plugins/security-guidance/tests/test_custom_headers.py b/plugins/security-guidance/tests/test_custom_headers.py
new file mode 100644
index 00000000..2d9fa3ef
--- /dev/null
+++ b/plugins/security-guidance/tests/test_custom_headers.py
@@ -0,0 +1,70 @@
+"""ANTHROPIC_CUSTOM_HEADERS reach every call the plugin makes."""
+from conftest import (
+ STUB_VULN, VULN_PY, edit_payload, run_hook, stop_payload, ups_payload,
+)
+
+import llm
+
+GATEWAY_KEY = ("x-litellm-api-key", "Bearer sk-gateway")
+
+
+class TestCustomHeaders:
+ def test_parsed_like_claude_code(self, monkeypatch):
+ monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS",
+ "x-litellm-api-key: Bearer sk-1\r\n"
+ "X-Tenant: acme:eu \n"
+ "no colon here\n"
+ ": no name\n"
+ "\n"
+ "X-Empty:")
+ assert llm._custom_headers() == [
+ ("x-litellm-api-key", "Bearer sk-1"), ("X-Tenant", "acme:eu"), ("X-Empty", ""),
+ ]
+
+ def test_unsendable_lines_are_skipped(self, monkeypatch):
+ monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS",
+ "bad name: x\nX-Ok: 1\nX-Uni: caf\u00e9\u2603\nX-Cr: a\rb")
+ assert llm._custom_headers() == [("X-Ok", "1")]
+
+ def test_sent_with_the_plugin_credentials(self, monkeypatch):
+ monkeypatch.setattr(llm, "ANTHROPIC_AUTH_TOKEN", "oauth")
+ monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "x-litellm-api-key: k")
+ h = llm._build_auth_headers(use_token=True)
+ assert h["x-litellm-api-key"] == "k"
+ assert h["Authorization"] == "Bearer oauth"
+
+ def test_custom_line_wins_over_the_same_header(self, monkeypatch):
+ monkeypatch.setattr(llm, "ANTHROPIC_AUTH_TOKEN", "oauth")
+ monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "authorization: Bearer gw")
+ h = llm._build_auth_headers(use_token=True)
+ assert [v for k, v in h.items() if k.lower() == "authorization"] == ["Bearer gw"]
+
+ def test_custom_beta_lines_are_not_sent(self, monkeypatch):
+ monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "anthropic-beta: extra-1\nX-Ok: 1")
+ h = llm._build_auth_headers(use_token=False)
+ assert h["anthropic-beta"] == "structured-outputs-2025-11-13"
+ assert h["X-Ok"] == "1"
+
+ def test_without_custom_headers_only_the_plugin_headers_are_sent(self, monkeypatch):
+ monkeypatch.delenv("ANTHROPIC_CUSTOM_HEADERS", raising=False)
+ assert set(llm._build_auth_headers(use_token=False)) == {
+ "Content-Type", "anthropic-version", "x-api-key", "anthropic-beta"}
+
+ def test_stop_review_reaches_a_header_keyed_gateway(self, env, gateway, workspace):
+ """Every plugin call (model lookup and review) carries the gateway
+ key, and the review finds the vuln."""
+ _, repo = workspace
+ gateway.required = GATEWAY_KEY
+ gateway.vulns = [STUB_VULN]
+ e = {**env, "ANTHROPIC_CUSTOM_HEADERS": f"{GATEWAY_KEY[0]}: {GATEWAY_KEY[1]}"}
+ run_hook(ups_payload(repo), e)
+ (repo / "app.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, repo / "app.py", VULN_PY), e)
+ rc, so, se = run_hook(stop_payload(repo), e)
+ assert rc == 2, (so, se)
+ assert "command_injection" in se
+ calls = [(m, p.split("?")[0]) for m, p, _ in gateway.requests]
+ assert ("GET", "/v1/models") in calls and ("POST", "/v1/messages") in calls
+ for method, path, headers in gateway.requests:
+ if path.startswith("/v1/"):
+ assert headers.get(GATEWAY_KEY[0]) == GATEWAY_KEY[1], (method, path)