Skip to content

The agent that grows with you

fix(auth): key_cmd Console keys on api.anthropic.com go out as x-api-key, not Bearer

kshitijk4poor58e0a6e2c3d2
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.py
index afb08b4b774..949079cb361 100644
--- a/agent/anthropic_adapter.py
+++ b/agent/anthropic_adapter.py
@@ -14,7 +14,7 @@ import subprocess
from contextlib import suppress
from typing import Any, Dict, List, Optional
-from utils import normalize_proxy_env_vars
+from utils import base_url_hostname, normalize_proxy_env_vars
from agent.anthropic_credentials import _is_oauth_token
from agent.anthropic_endpoints import (
@@ -409,7 +409,13 @@ def _build_anthropic_client_with_bearer_hook(
normalize_proxy_env_vars()
from agent.azure_identity_adapter import build_bearer_http_client
normalized_base_url, kwargs = _base_client_kwargs(base_url, timeout)
- kwargs["http_client"] = build_bearer_http_client(token_provider, timeout=kwargs["timeout"])
+ # A key_cmd on the native host can print a Console API key, which (as in the static path's
+ # _auth_style) belongs in x-api-key; OAuth tokens and Azure/third-party routes keep Bearer.
+ native_host = not base_url or base_url_hostname(str(base_url)) == "api.anthropic.com"
+ kwargs["http_client"] = build_bearer_http_client(
+ token_provider, timeout=kwargs["timeout"],
+ sends_as_api_key=(lambda token: not _is_oauth_token(token)) if native_host else None,
+ )
kwargs["auth_token"] = "entra-id-bearer-via-http-hook"
betas = _common_betas_for_base_url(normalized_base_url, drop_context_1m_beta=drop_context_1m_beta)
from agent.anthropic_credentials import anthropic_route_is_oauth
diff --git a/agent/azure_identity_adapter.py b/agent/azure_identity_adapter.py
index a75b41e7896..edf095b6233 100644
--- a/agent/azure_identity_adapter.py
+++ b/agent/azure_identity_adapter.py
@@ -309,11 +309,12 @@ def _strip_auth_headers(request: Any) -> None:
request.headers.pop(header_name, None)
-def build_bearer_http_client(token_provider: Callable[[], str], **httpx_kwargs: Any) -> Any:
+def build_bearer_http_client(token_provider: Callable[[], str], *, sends_as_api_key: Callable[[str], bool] | None = None, **httpx_kwargs: Any) -> Any:
"""``httpx.Client`` minting a fresh Entra bearer JWT per outbound request. The Anthropic SDK computes
``Authorization`` once at construction, so per-request refresh needs a ``request`` hook: mint (cheap —
azure-identity caches), strip pre-set auth headers, set ``Authorization: Bearer``. ``httpx_kwargs`` are
- forwarded verbatim (``timeout``, ``transport``...)."""
+ forwarded verbatim (``timeout``, ``transport``...). ``sends_as_api_key(token)`` True puts the minted
+ token in ``x-api-key`` instead (a ``key_cmd`` printing a native Anthropic Console key)."""
if not is_token_provider(token_provider):
raise ValueError("build_bearer_http_client requires a zero-arg callable token provider")
import httpx
@@ -331,7 +332,10 @@ def build_bearer_http_client(token_provider: Callable[[], str], **httpx_kwargs:
_strip_auth_headers(request)
return
_strip_auth_headers(request)
- request.headers["Authorization"] = f"Bearer {token}"
+ if sends_as_api_key is not None and sends_as_api_key(token):
+ request.headers["x-api-key"] = token
+ else:
+ request.headers["Authorization"] = f"Bearer {token}"
return httpx.Client(event_hooks={"request": [_inject_bearer]}, **httpx_kwargs)
diff --git a/tests/agent/test_anthropic_client_auth.py b/tests/agent/test_anthropic_client_auth.py
index b3f4842ac6d..75d5a22440c 100644
--- a/tests/agent/test_anthropic_client_auth.py
+++ b/tests/agent/test_anthropic_client_auth.py
@@ -79,3 +79,22 @@ def test_console_key_families_carry_x_api_key_without_claude_code_identity(monke
assert (headers.get("x-api-key") == key) is (not oauth)
assert ("claude-code-20250219" in headers.get("anthropic-beta", "")) is oauth
assert ("claude-code/" in headers.get("user-agent", "")) is oauth
+
+
[email protected](("base_url", "family", "expect"), [
+ ("https://api.anthropic.com", "usr01", "x-api-key"), ("https://api.anthropic.com", "api03", "x-api-key"),
+ ("https://api.anthropic.com", "oat01", "bearer"), ("https://gateway.invalid/anthropic", "usr01", "bearer"),
+])
+def test_key_cmd_token_lands_in_the_header_its_family_needs(monkeypatch, base_url, family, expect):
+ """A key_cmd (callable) credential takes the per-request hook path: on the native host a Console key it
+ prints must go out as x-api-key like the static path; OAuth tokens and non-native gateways keep Bearer."""
+ pytest.importorskip("anthropic")
+ import httpx
+
+ monkeypatch.setattr("agent.anthropic_adapter._claude_code_version_cache", "0.0.0")
+ key = "sk-" + "ant-" + family + "-" + "X" * 24
+ client = build_anthropic_client(lambda: key, base_url)
+ request = httpx.Request("POST", base_url + "/v1/messages", headers={"Authorization": "Bearer entra-id-bearer-via-http-hook"})
+ client._client.event_hooks["request"][0](request)
+ sent = {"x-api-key": request.headers.get("x-api-key"), "bearer": request.headers.get("authorization")}
+ assert sent == ({"x-api-key": key, "bearer": None} if expect == "x-api-key" else {"x-api-key": None, "bearer": "Bearer " + key})