summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-13 13:44:50 -0700
committerGitHub <noreply@github.com>2026-10-13 13:44:50 -0700
commit99951e9e4678548f90531dfc80be2e95e4618ff0 (patch)
treeaa4fc2b331506098fbb755f48f695ee80d0169a4 /plugins
parentd44ca8eb76581bfc5be38cc4c9b7e75be3c22046 (diff)
parent860b93cb3898d30683ef9b1b70755d4fb0c2ff57 (diff)
Merge pull request #6378 from anthropics/mhegazy/sg-gateway-headers
security-guidance: send ANTHROPIC_CUSTOM_HEADERS on the plugin's own API calls
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/test_custom_headers.py70
3 files changed, 115 insertions, 1 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index 228fef11..3e68cf74 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 925ba547..25adfe00 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -286,6 +286,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 = {
@@ -297,6 +329,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/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)