Debian Codegraph @

src/anthropic/lib/credentials/_auth.py

raw
1 from __future__ import annotations
2
3 import logging
4 import threading
5 from typing import Generator, AsyncGenerator
6 from typing_extensions import override
7
8 import httpx2
9
10 from ._cache import TokenCache
11 from ._constants import OAUTH_API_BETA_HEADER
12
13 __all__ = ["AccessTokenAuth"]
14
15 log: logging.Logger = logging.getLogger(__name__)
16
17 _warn_once_lock = threading.Lock()
18 _warn_once_seen: set[str] = set()
19
20
21 def _warn_once(key: str, message: str, *args: object) -> None:
22 """Emit a log warning at most once per `key` per process."""
23 with _warn_once_lock:
24 if key in _warn_once_seen:
25 return
26 _warn_once_seen.add(key)
27 log.warning(message, *args)
28
29
30 def warn_explicit_static_shadows_credentials(param: str) -> None:
31 """Warn that an explicit `api_key=` / `auth_token=` argument shadows
32 an explicit `credentials=` provider passed to the same constructor or
33 `copy()` call. The static credential wins at the request-header level
34 (`AccessTokenAuth.sync_auth_flow` short-circuits on the pre-set header),
35 which silently disables the credentials provider.
36 """
37 _warn_once(
38 f"explicit-shadow:{param}",
39 "`%s=` was passed alongside `credentials=`; the static credential "
40 "takes precedence and the credentials provider is silently disabled. "
41 "Pass only one.",
42 param,
43 )
44
45
46 def warn_env_static_shadows_auto_discovery(env_var: str) -> None:
47 """Warn that an `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` from the
48 environment is shadowing the SDK's profile / federation auto-discovery.
49
50 Per the credential-precedence spec, a static-credential env var silently
51 disables the auto-discovered federation and profile paths. Surface a
52 one-shot warning so migrating users can see why their `ANTHROPIC_PROFILE`
53 or WIF env vars are being ignored.
54 """
55 _warn_once(
56 f"env-shadow:{env_var}",
57 "%s is set and takes precedence over the SDK's profile / federation "
58 "auto-discovery; unset %s to use the auto-discovered credential.",
59 env_var,
60 env_var,
61 )
62
63
64 class AccessTokenAuth(httpx2.Auth):
65 """Adapts a `TokenCache` to httpx's `httpx2.Auth` protocol.
66
67 Used by `anthropic.Anthropic.custom_auth` to inject `Authorization: Bearer`
68 plus the OAuth beta header on every request, with proactive refresh handled by
69 `TokenCache`.
70
71 Static credentials shadow federation: if the outgoing request already carries
72 an `X-Api-Key` or `Authorization` header (set by the client's api_key /
73 auth_token path), this auth flow is a no-op. That matches the Go SDK's
74 `authMiddleware` and the documented precedence in the WIF user guide —
75 a static `ANTHROPIC_API_KEY` shadows any credentials provider.
76 """
77
78 requires_response_body = False
79
80 def __init__(self, token_cache: TokenCache) -> None:
81 self._token_cache = token_cache
82
83 @staticmethod
84 def _has_static_credential(request: httpx2.Request) -> bool:
85 return bool(request.headers.get("X-Api-Key") or request.headers.get("Authorization"))
86
87 def _apply(self, request: httpx2.Request, token: str) -> None:
88 request.headers["Authorization"] = f"Bearer {token}"
89 existing_beta = request.headers.get("anthropic-beta", "")
90 # Tokenize the comma-separated header so dedupe matches whole flag
91 # names rather than substrings — `oauth-2025-04-20` would otherwise
92 # spuriously match a future `oauth-2025-04-20b`.
93 #
94 # The flag we inject here is the *API* beta (oauth-2025-04-20), which
95 # unlocks `Authorization: Bearer` auth on the API. The *federation*
96 # beta (oidc-federation-2026-04-01) is a separate routing switch used
97 # only on jwt-bearer POSTs to /v1/oauth/token — see _workload.py.
98 existing_flags = [flag.strip() for flag in existing_beta.split(",") if flag.strip()]
99 if OAUTH_API_BETA_HEADER not in existing_flags:
100 existing_flags.append(OAUTH_API_BETA_HEADER)
101 request.headers["anthropic-beta"] = ",".join(existing_flags)
102
103 @override
104 def sync_auth_flow(self, request: httpx2.Request) -> Generator[httpx2.Request, httpx2.Response, None]:
105 if self._has_static_credential(request):
106 yield request
107 return
108 token = self._token_cache.get_token()
109 self._apply(request, token)
110 yield request
111
112 @override
113 async def async_auth_flow(self, request: httpx2.Request) -> AsyncGenerator[httpx2.Request, httpx2.Response]:
114 if self._has_static_credential(request):
115 yield request
116 return
117 token = await self._token_cache.async_get_token()
118 self._apply(request, token)
119 yield request