The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(auth): one native-Anthropic-host predicate for the hook and OAuth identity
kshitijk4poor4e745c539893
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.pyindex 949079cb361..73e1d191060 100644--- a/agent/anthropic_adapter.py+++ b/agent/anthropic_adapter.py@@ -14,9 +14,9 @@ import subprocessfrom contextlib import suppressfrom typing import Any, Dict, List, Optional-from utils import base_url_hostname, normalize_proxy_env_vars+from utils import normalize_proxy_env_vars-from agent.anthropic_credentials import _is_oauth_token+from agent.anthropic_credentials import _is_oauth_token, anthropic_route_is_oauth, is_native_anthropic_hostfrom agent.anthropic_endpoints import (_base_url_needs_context_1m_beta, _is_azure_anthropic_endpoint, _is_kimi_coding_endpoint,_is_minimax_anthropic_endpoint, _is_nous_portal_endpoint, _is_opencode_endpoint,@@ -410,15 +410,15 @@ def _build_anthropic_client_with_bearer_hook(from agent.azure_identity_adapter import build_bearer_http_clientnormalized_base_url, kwargs = _base_client_kwargs(base_url, 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"+ # _auth_style) belongs in x-api-key; OAuth tokens and Azure/third-party routes keep Bearer. The+ # auth header follows each mint, the OAuth identity below the first one: a key_cmd switching+ # between OAuth and a Console key mid-session needs a client rebuild.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,+ sends_as_api_key=(lambda token: not _is_oauth_token(token)) if is_native_anthropic_host(base_url) 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_oauthif anthropic_route_is_oauth(base_url, token_provider):# key_cmd-sourced Claude Code OAuth on the native host: a bare bearer without the Claude Code# identity is answered with 429 rate_limit_error "Error" (#114967) — same headers as thediff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.pyindex 8e25bba24b5..be1df48e298 100644--- a/agent/anthropic_credentials.py+++ b/agent/anthropic_credentials.py@@ -25,10 +25,9 @@ import timefrom collections import OrderedDictfrom pathlib import Pathfrom typing import Any, Dict, Optional-from urllib.parse import urlparsefrom hermes_constants import get_hermes_home-from utils import atomic_json_write+from utils import atomic_json_write, base_url_hostnamefrom agent.secret_scope import get_secret as _get_secretlogger = logging.getLogger(__name__)@@ -70,6 +69,12 @@ def _is_oauth_token(key: str) -> bool:return key.startswith(("sk-ant-", "eyJ", "cc-"))+def is_native_anthropic_host(base_url: Any) -> bool:+ """True when *base_url* is exactly ``api.anthropic.com`` (an empty base_url is the native default)."""+ text = str(base_url or "").strip()+ return not text or base_url_hostname(text) == "api.anthropic.com"++def anthropic_route_is_oauth(base_url: Any, credential: Any, *, provider: Optional[str] = None) -> bool:"""Claude Code OAuth identity for one Anthropic Messages route (#114967).@@ -81,9 +86,7 @@ def anthropic_route_is_oauth(base_url: Any, credential: Any, *, provider: Optionmaterialized once for the shape test (``CommandTokenSource`` caches, so this never double-mints)and a mint failure classifies as non-OAuth — the wire client surfaces the real error."""- text = str(base_url or "").strip()- native_host = not text or (urlparse(text).hostname or "").lower().rstrip(".") == "api.anthropic.com"- if not (native_host or (provider or "").strip().lower() == "anthropic"):+ if not (is_native_anthropic_host(base_url) or (provider or "").strip().lower() == "anthropic"):return Falseif callable(credential) and not isinstance(credential, str):try:diff --git a/agent/azure_identity_adapter.py b/agent/azure_identity_adapter.pyindex edf095b6233..0200d712dcd 100644--- a/agent/azure_identity_adapter.py+++ b/agent/azure_identity_adapter.py@@ -113,7 +113,7 @@ def _default_chain_credential(config: EntraIdentityConfig) -> Any:# is built explicitly from its own secret scope (client secret first, then workload identity). Under multiplex# the ambient default chain is refused outright when the profile sets no credential of its own: every source it# could mint from (env SP, CLI/azd/PowerShell caches, host managed identity) is the launch context's identity,-# and _inject_bearer would ship it to whatever base_url the served profile configured.+# and _inject_auth would ship it to whatever base_url the served profile configured._credentials_by_home: dict[tuple, Any] = {}_AMBIENT_CHAIN_REFUSAL = (@@ -309,7 +309,9 @@ def _strip_auth_headers(request: Any) -> None:request.headers.pop(header_name, None)-def build_bearer_http_client(token_provider: Callable[[], str], *, sends_as_api_key: Callable[[str], bool] | None = None, **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@@ -319,7 +321,7 @@ def build_bearer_http_client(token_provider: Callable[[], str], *, sends_as_api_raise ValueError("build_bearer_http_client requires a zero-arg callable token provider")import httpx- def _inject_bearer(request: httpx.Request) -> None:+ def _inject_auth(request: httpx.Request) -> None:try:token = materialize_bearer_for_http(token_provider)except ValueError as exc:@@ -337,7 +339,7 @@ def build_bearer_http_client(token_provider: Callable[[], str], *, sends_as_api_else:request.headers["Authorization"] = f"Bearer {token}"- return httpx.Client(event_hooks={"request": [_inject_bearer]}, **httpx_kwargs)+ return httpx.Client(event_hooks={"request": [_inject_auth]}, **httpx_kwargs)__all__ = [diff --git a/tests/agent/test_anthropic_client_auth.py b/tests/agent/test_anthropic_client_auth.pyindex 75d5a22440c..37bb8e2a0f2 100644--- a/tests/agent/test_anthropic_client_auth.py+++ b/tests/agent/test_anthropic_client_auth.py@@ -84,6 +84,7 @@ def test_console_key_families_carry_x_api_key_without_claude_code_identity(monke@pytest.mark.parametrize(("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"),+ (None, "svc01", "x-api-key"), # an empty base_url is the native default])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@@ -94,7 +95,7 @@ def test_key_cmd_token_lands_in_the_header_its_family_needs(monkeypatch, base_urmonkeypatch.setattr("agent.anthropic_adapter._claude_code_version_cache", "0.0.0")key = "sk-" + "ant-" + family + "-" + "X" * 24client = build_anthropic_client(lambda: key, base_url)- request = httpx.Request("POST", base_url + "/v1/messages", headers={"Authorization": "Bearer entra-id-bearer-via-http-hook"})+ request = httpx.Request("POST", (base_url or "https://api.anthropic.com") + "/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})