| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import copy |
| 4 |
import time |
| 5 |
import logging |
| 6 |
from types import TracebackType |
| 7 |
from typing import Any, Dict, Type, Union, NoReturn, Optional |
| 8 |
from typing_extensions import override |
| 9 |
|
| 10 |
import httpx2 |
| 11 |
|
| 12 |
from ._types import AccessToken, IdentityTokenProvider |
| 13 |
from ._secrets import ( |
| 14 |
SecretStr, |
| 15 |
_unwrap_secret, |
| 16 |
_strip_traceback, |
| 17 |
_json_dumps_secrets, |
| 18 |
_wrap_secret_fields, |
| 19 |
_NonObjectPayloadError, |
| 20 |
) |
| 21 |
from ._constants import ( |
| 22 |
TOKEN_ENDPOINT, |
| 23 |
DEFAULT_BASE_URL, |
| 24 |
GRANT_TYPE_JWT_BEARER, |
| 25 |
OAUTH_API_BETA_HEADER, |
| 26 |
FEDERATION_BETA_HEADER, |
| 27 |
TOKEN_EXCHANGE_TIMEOUT, |
| 28 |
_user_agent, |
| 29 |
_require_https, |
| 30 |
) |
| 31 |
from ..._exceptions import AnthropicError |
| 32 |
|
| 33 |
# jwt-bearer POSTs require BOTH beta headers — oauth-2025-04-20 unlocks the |
| 34 |
# token endpoint family, and oidc-federation-2026-04-01 routes the POST to the |
| 35 |
# Go userauth handler rather than the Python oauth_server. |
| 36 |
_JWT_BEARER_BETA_HEADER = f"{OAUTH_API_BETA_HEADER},{FEDERATION_BETA_HEADER}" |
| 37 |
|
| 38 |
# Max characters of response body kept on WorkloadIdentityError.body and in |
| 39 |
# exception messages. Token endpoints sometimes echo back the assertion JWT or |
| 40 |
# other sensitive material on error; truncating limits the blast radius if the |
| 41 |
# exception ends up in user logs or crash reports. |
| 42 |
_MAX_ERROR_BODY_CHARS = 256 |
| 43 |
|
| 44 |
# Hard limits on the wire size of the assertion JWT we send and the response |
| 45 |
# body we accept from the token endpoint. JWTs from real IdPs are <4 KiB; a |
| 46 |
# 16 KiB ceiling catches misconfiguration (e.g. a PEM cert path passed as the |
| 47 |
# token) before we POST it. The 1 MiB response cap bounds memory if a misrouted |
| 48 |
# endpoint streams back something pathological. |
| 49 |
_MAX_ASSERTION_BYTES = 16 * 1024 |
| 50 |
_MAX_TOKEN_RESPONSE_BYTES = 1 << 20 |
| 51 |
|
| 52 |
|
| 53 |
def _request_id(resp: httpx2.Response) -> Optional[str]: |
| 54 |
rid: Optional[str] = resp.headers.get("Request-Id") or resp.headers.get("request-id") |
| 55 |
return rid |
| 56 |
|
| 57 |
|
| 58 |
def _redact_body(body: Any) -> Any: |
| 59 |
"""Truncate a token-endpoint error body for safe inclusion in an exception.""" |
| 60 |
if body is None: |
| 61 |
return None |
| 62 |
if isinstance(body, str): |
| 63 |
if len(body) <= _MAX_ERROR_BODY_CHARS: |
| 64 |
return body |
| 65 |
return body[:_MAX_ERROR_BODY_CHARS] + f"... <{len(body) - _MAX_ERROR_BODY_CHARS} more chars>" |
| 66 |
# For dict payloads, only keep OAuth standard error fields (RFC 6749 §5.2). |
| 67 |
if isinstance(body, dict): |
| 68 |
kept: Dict[str, Any] = {} |
| 69 |
for key in ("error", "error_description", "error_uri"): |
| 70 |
if key in body: |
| 71 |
kept[key] = body[key] |
| 72 |
return kept |
| 73 |
return None |
| 74 |
|
| 75 |
|
| 76 |
def _raise_token_endpoint_error(resp: httpx2.Response, *, message_prefix: str, hint: Optional[str] = None) -> NoReturn: |
| 77 |
"""Raise a redacted `WorkloadIdentityError` from a non-200 token-endpoint response. |
| 78 |
|
| 79 |
Shared between the jwt-bearer exchange path in this module and the |
| 80 |
refresh_token grant path in `_providers`. |
| 81 |
|
| 82 |
The raw response body (which token endpoints can echo credential material |
| 83 |
into) is never bound to a local in this frame — only the redaction is — |
| 84 |
so this frame is safe under crash reporters that capture traceback locals. |
| 85 |
|
| 86 |
`hint` is an optional caller-supplied diagnostic appended verbatim to the |
| 87 |
error message (after the redacted body). Callers gate it on the response |
| 88 |
status and their own state — this helper does not inspect `resp` for it. |
| 89 |
""" |
| 90 |
try: |
| 91 |
redacted = _redact_body(resp.json()) |
| 92 |
except ValueError: |
| 93 |
redacted = _redact_body(resp.text) |
| 94 |
message = f"{message_prefix} (HTTP {resp.status_code}): {redacted}" |
| 95 |
if hint: |
| 96 |
message = f"{message} {hint}" |
| 97 |
raise WorkloadIdentityError( |
| 98 |
message, |
| 99 |
status_code=resp.status_code, |
| 100 |
body=redacted, |
| 101 |
request_id=_request_id(resp), |
| 102 |
) |
| 103 |
|
| 104 |
|
| 105 |
__all__ = ["WorkloadIdentityCredentials", "WorkloadIdentityError", "exchange_federation_assertion"] |
| 106 |
|
| 107 |
log: logging.Logger = logging.getLogger(__name__) |
| 108 |
|
| 109 |
|
| 110 |
class WorkloadIdentityError(AnthropicError): |
| 111 |
"""Raised when the OIDC token exchange (`POST /v1/oauth/token`) fails.""" |
| 112 |
|
| 113 |
status_code: Optional[int] |
| 114 |
body: Any |
| 115 |
request_id: Optional[str] |
| 116 |
|
| 117 |
def __init__( |
| 118 |
self, |
| 119 |
message: str, |
| 120 |
*, |
| 121 |
status_code: Optional[int] = None, |
| 122 |
body: Any = None, |
| 123 |
request_id: Optional[str] = None, |
| 124 |
) -> None: |
| 125 |
super().__init__(message) |
| 126 |
self.status_code = status_code |
| 127 |
self.body = body |
| 128 |
self.request_id = request_id |
| 129 |
|
| 130 |
@override |
| 131 |
def __str__(self) -> str: |
| 132 |
base = super().__str__() |
| 133 |
if self.request_id: |
| 134 |
return f"{base} [request_id={self.request_id}]" |
| 135 |
return base |
| 136 |
|
| 137 |
|
| 138 |
class WorkloadIdentityCredentials: |
| 139 |
"""Exchanges an external OIDC JWT for an Anthropic access token via the |
| 140 |
RFC 7523 `jwt-bearer` grant. |
| 141 |
|
| 142 |
This is an `AccessTokenProvider`: calling it performs a *fresh* token |
| 143 |
exchange. Wrap in a `TokenCache` (done automatically when passed as |
| 144 |
`credentials=` to `anthropic.Anthropic`) to avoid exchanging on every |
| 145 |
request. |
| 146 |
|
| 147 |
Args: |
| 148 |
organization_id: The organization's raw UUID string (organizations do |
| 149 |
not use tagged IDs). |
| 150 |
workspace_id: Optional `wrkspc_*` tagged ID, or the literal |
| 151 |
`"default"` to scope the token to the organization's default |
| 152 |
workspace. When omitted the server picks the rule's sole enabled |
| 153 |
workspace, else the org default if the rule covers it. Required |
| 154 |
when the rule enables more than one non-default workspace, or to |
| 155 |
target a specific workspace other than the one the server would |
| 156 |
pick. The minted token is workspace-scoped: per-request workspace |
| 157 |
selection (the `anthropic-workspace-id` header) is not supported |
| 158 |
for federation tokens — switching workspaces requires a new token |
| 159 |
exchange with a different `workspace_id`. |
| 160 |
""" |
| 161 |
|
| 162 |
def __init__( |
| 163 |
self, |
| 164 |
*, |
| 165 |
identity_token_provider: IdentityTokenProvider, |
| 166 |
federation_rule_id: str, |
| 167 |
organization_id: str, |
| 168 |
service_account_id: Optional[str] = None, |
| 169 |
workspace_id: Optional[str] = None, |
| 170 |
scope: Optional[str] = None, |
| 171 |
http_client: Optional[httpx2.Client] = None, |
| 172 |
) -> None: |
| 173 |
self._identity_token_provider = identity_token_provider |
| 174 |
self._federation_rule_id = federation_rule_id |
| 175 |
self._organization_id = organization_id |
| 176 |
self._service_account_id = service_account_id |
| 177 |
self._workspace_id = workspace_id |
| 178 |
# Scope is informational only for federation: the server derives the |
| 179 |
# effective scope from the matching federation rule and the gateway |
| 180 |
# transform drops unknown body fields, so it is intentionally NOT sent |
| 181 |
# on the jwt-bearer request. |
| 182 |
self._scope = scope |
| 183 |
# The client passing this object as `credentials=` calls |
| 184 |
# `for_base_url` to set its own endpoint, so the token exchange |
| 185 |
# and the API calls hit the same deployment. There is intentionally no |
| 186 |
# constructor kwarg for this: a token minted by one deployment is only |
| 187 |
# valid against that deployment, so splitting exchange-base from |
| 188 |
# client-base is always a bug. |
| 189 |
self._bound_base_url: Optional[str] = None |
| 190 |
if http_client is None: |
| 191 |
self._http_client = httpx2.Client(timeout=TOKEN_EXCHANGE_TIMEOUT) |
| 192 |
self._owns_http_client = True |
| 193 |
else: |
| 194 |
self._http_client = http_client |
| 195 |
self._owns_http_client = False |
| 196 |
|
| 197 |
@property |
| 198 |
def scope(self) -> Optional[str]: |
| 199 |
return self._scope |
| 200 |
|
| 201 |
@property |
| 202 |
def _base_url(self) -> str: |
| 203 |
return self._bound_base_url or DEFAULT_BASE_URL |
| 204 |
|
| 205 |
def bind_base_url(self, base_url: str) -> None: |
| 206 |
"""Set the API `base_url` the token exchange POSTs to. |
| 207 |
|
| 208 |
For standalone use (no client) or tests. Clients bind through |
| 209 |
`for_base_url`, which never rebinds an instance another client |
| 210 |
is already exchanging through. |
| 211 |
""" |
| 212 |
bound = base_url.rstrip("/") |
| 213 |
_require_https(bound, field="base_url") |
| 214 |
self._bound_base_url = bound |
| 215 |
|
| 216 |
def for_base_url(self, base_url: str) -> "WorkloadIdentityCredentials": |
| 217 |
"""Return the provider a client with `base_url` should exchange through. |
| 218 |
|
| 219 |
Binds in place, unless another client already bound this instance to a |
| 220 |
different host (e.g. the parent of `copy(base_url=...)`). Rebinding |
| 221 |
would move that client's token exchange too, so a copy bound to |
| 222 |
`base_url` is returned instead; it shares the identity token and |
| 223 |
borrows (never closes) this instance's `httpx2.Client`. |
| 224 |
""" |
| 225 |
bound = base_url.rstrip("/") |
| 226 |
provider = self |
| 227 |
if self._bound_base_url is not None and self._bound_base_url != bound: |
| 228 |
provider = copy.copy(self) |
| 229 |
provider._owns_http_client = False |
| 230 |
provider.bind_base_url(bound) |
| 231 |
return provider |
| 232 |
|
| 233 |
def close(self) -> None: |
| 234 |
"""Close the underlying `httpx2.Client` if we created it.""" |
| 235 |
if self._owns_http_client: |
| 236 |
self._http_client.close() |
| 237 |
|
| 238 |
def __enter__(self) -> "WorkloadIdentityCredentials": |
| 239 |
return self |
| 240 |
|
| 241 |
def __exit__( |
| 242 |
self, |
| 243 |
exc_type: Optional[Type[BaseException]], |
| 244 |
exc: Optional[BaseException], |
| 245 |
tb: Optional[TracebackType], |
| 246 |
) -> None: |
| 247 |
self.close() |
| 248 |
|
| 249 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: |
| 250 |
# Re-invoke the identity token provider every time — the underlying |
| 251 |
# file (e.g. a k8s projected SA token) may have rotated. force_refresh |
| 252 |
# is a no-op: this provider has no cache to bypass. |
| 253 |
del force_refresh |
| 254 |
jwt = SecretStr(self._identity_token_provider()) |
| 255 |
|
| 256 |
assertion_bytes = len(jwt.get_secret_value().encode("utf-8")) |
| 257 |
if assertion_bytes > _MAX_ASSERTION_BYTES: |
| 258 |
raise WorkloadIdentityError( |
| 259 |
f"Identity token assertion is {assertion_bytes} bytes, which exceeds the " |
| 260 |
f"{_MAX_ASSERTION_BYTES}-byte limit. This is almost certainly not a JWT — check " |
| 261 |
f"that the identity-token path points at the projected token, not a key or cert." |
| 262 |
) |
| 263 |
|
| 264 |
body: Dict[str, Union[str, SecretStr]] = { |
| 265 |
"grant_type": GRANT_TYPE_JWT_BEARER, |
| 266 |
"assertion": jwt, |
| 267 |
"federation_rule_id": self._federation_rule_id, |
| 268 |
"organization_id": self._organization_id, |
| 269 |
} |
| 270 |
if self._service_account_id is not None: |
| 271 |
body["service_account_id"] = self._service_account_id |
| 272 |
if self._workspace_id is not None: |
| 273 |
body["workspace_id"] = self._workspace_id |
| 274 |
|
| 275 |
url = f"{self._base_url}{TOKEN_ENDPOINT}" |
| 276 |
try: |
| 277 |
resp = self._http_client.post( |
| 278 |
url, |
| 279 |
# Serialized inline so the raw request bytes are never bound |
| 280 |
# to a local here; SecretStr values unwrap at dump time. |
| 281 |
content=_json_dumps_secrets(body), |
| 282 |
headers={ |
| 283 |
"anthropic-beta": _JWT_BEARER_BETA_HEADER, |
| 284 |
"Content-Type": "application/json", |
| 285 |
"User-Agent": _user_agent(), |
| 286 |
}, |
| 287 |
) |
| 288 |
except httpx2.HTTPError as err: |
| 289 |
raise WorkloadIdentityError(f"Failed to reach token endpoint {url}: {err}") from _strip_traceback(err) |
| 290 |
|
| 291 |
request_id = _request_id(resp) |
| 292 |
|
| 293 |
if len(resp.content) > _MAX_TOKEN_RESPONSE_BYTES: |
| 294 |
raise WorkloadIdentityError( |
| 295 |
f"Token endpoint response body exceeds {_MAX_TOKEN_RESPONSE_BYTES} bytes " |
| 296 |
f"(got {len(resp.content)}); refusing to parse.", |
| 297 |
status_code=resp.status_code, |
| 298 |
request_id=request_id, |
| 299 |
) |
| 300 |
|
| 301 |
if resp.status_code >= 400: |
| 302 |
# A 401 is almost always a federation-rule mismatch. Point at the |
| 303 |
# rule and the Console auth-event log; when the caller hasn't pinned |
| 304 |
# a workspace, also surface the multi-workspace fix rather than |
| 305 |
# making them dig through docs. |
| 306 |
hint: Optional[str] = None |
| 307 |
if resp.status_code == 401: |
| 308 |
hint = "Ensure your federation rule matches your identity token. " |
| 309 |
if self._workspace_id is None: |
| 310 |
hint += ( |
| 311 |
"If your federation rule is scoped to multiple workspaces, set the " |
| 312 |
"ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' " |
| 313 |
"config key, or the workspace_id= argument. " |
| 314 |
) |
| 315 |
hint += ( |
| 316 |
"View your authentication events in the Workload identity page of Claude Console for more details." |
| 317 |
) |
| 318 |
_raise_token_endpoint_error(resp, message_prefix="Token exchange failed", hint=hint) |
| 319 |
|
| 320 |
try: |
| 321 |
# Token values are SecretStr-wrapped in place at the parse |
| 322 |
# boundary, so every error path below may hold `data` in its |
| 323 |
# frame without retaining raw credential material. |
| 324 |
data = _wrap_secret_fields(resp.json()) |
| 325 |
except ValueError as err: |
| 326 |
redacted = _redact_body(resp.text) |
| 327 |
raise WorkloadIdentityError( |
| 328 |
f"Token endpoint returned non-JSON response (status {resp.status_code}): {redacted}", |
| 329 |
status_code=resp.status_code, |
| 330 |
body=redacted, |
| 331 |
request_id=request_id, |
| 332 |
) from _strip_traceback(err) |
| 333 |
except _NonObjectPayloadError as err: |
| 334 |
# A non-object payload can be an echo of the request (assertion |
| 335 |
# included), so it is rejected inside the helper — no frame in |
| 336 |
# this traceback holds it — and only its type name is reported. |
| 337 |
raise WorkloadIdentityError( |
| 338 |
f"Token endpoint returned a JSON {err.type_name} (status {resp.status_code}); expected an object.", |
| 339 |
status_code=resp.status_code, |
| 340 |
request_id=request_id, |
| 341 |
) from None |
| 342 |
|
| 343 |
token_type = data.get("token_type") |
| 344 |
if token_type is not None and str(token_type).lower() != "bearer": |
| 345 |
raise WorkloadIdentityError( |
| 346 |
f"Token endpoint returned unsupported token_type {token_type!r} (expected 'Bearer').", |
| 347 |
status_code=resp.status_code, |
| 348 |
body=_redact_body(data), |
| 349 |
request_id=request_id, |
| 350 |
) |
| 351 |
|
| 352 |
try: |
| 353 |
token = data["access_token"] |
| 354 |
# `expires_in` is a JSON number per RFC 6749 §5.1; coerce to int seconds. |
| 355 |
expires_in = int(data["expires_in"]) |
| 356 |
except (KeyError, TypeError, ValueError, OverflowError) as err: |
| 357 |
raise WorkloadIdentityError( |
| 358 |
"Token endpoint response missing required fields (access_token / expires_in).", |
| 359 |
status_code=resp.status_code, |
| 360 |
body=_redact_body(data), |
| 361 |
request_id=request_id, |
| 362 |
) from err |
| 363 |
|
| 364 |
return AccessToken(token=_unwrap_secret(token), expires_at=int(time.time()) + expires_in) |
| 365 |
|
| 366 |
|
| 367 |
def exchange_federation_assertion( |
| 368 |
*, |
| 369 |
assertion: Union[str, SecretStr], |
| 370 |
federation_rule_id: str, |
| 371 |
organization_id: str, |
| 372 |
service_account_id: Optional[str] = None, |
| 373 |
workspace_id: Optional[str] = None, |
| 374 |
base_url: Optional[str] = None, |
| 375 |
http_client: Optional[httpx2.Client] = None, |
| 376 |
) -> AccessToken: |
| 377 |
"""Perform a single RFC 7523 `jwt-bearer` exchange and return the resulting |
| 378 |
`AccessToken`. |
| 379 |
|
| 380 |
This is a one-shot convenience wrapper around `WorkloadIdentityCredentials` |
| 381 |
for callers that already have the assertion JWT in hand and just want the |
| 382 |
Anthropic access token back (no caching, no provider plumbing). |
| 383 |
|
| 384 |
`assertion` may be a `pydantic.SecretStr` to keep it redacted |
| 385 |
end-to-end; a plain `str` is wrapped on entry. |
| 386 |
""" |
| 387 |
if isinstance(assertion, str): |
| 388 |
# Rebind so this frame's local holds the wrapped form — the raw string |
| 389 |
# then lives only in the caller's frame, which no callee can scrub. |
| 390 |
assertion = SecretStr(assertion) |
| 391 |
creds = WorkloadIdentityCredentials( |
| 392 |
identity_token_provider=assertion.get_secret_value, |
| 393 |
federation_rule_id=federation_rule_id, |
| 394 |
organization_id=organization_id, |
| 395 |
service_account_id=service_account_id, |
| 396 |
workspace_id=workspace_id, |
| 397 |
http_client=http_client, |
| 398 |
) |
| 399 |
if base_url is not None: |
| 400 |
creds.bind_base_url(base_url) |
| 401 |
try: |
| 402 |
return creds() |
| 403 |
finally: |
| 404 |
creds.close() |