| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import inspect |
| 4 |
import functools |
| 5 |
from typing import Dict, Callable, Optional, Protocol |
| 6 |
from dataclasses import field, dataclass |
| 7 |
from typing_extensions import TypeIs, override, runtime_checkable |
| 8 |
|
| 9 |
|
| 10 |
def _empty_headers() -> Dict[str, str]: |
| 11 |
return {} |
| 12 |
|
| 13 |
|
| 14 |
__all__ = [ |
| 15 |
"AccessToken", |
| 16 |
"AccessTokenProvider", |
| 17 |
"AsyncAccessTokenProvider", |
| 18 |
"BaseURLBoundProvider", |
| 19 |
"IdentityTokenProvider", |
| 20 |
"CredentialResult", |
| 21 |
] |
| 22 |
|
| 23 |
|
| 24 |
@dataclass(frozen=True) |
| 25 |
class AccessToken: |
| 26 |
"""An Anthropic API access token with optional expiry. |
| 27 |
|
| 28 |
`expires_at` is unix seconds; `None` means no expiry information |
| 29 |
(the token will be treated as never-expires by `TokenCache`). |
| 30 |
Exactly `0` means the provider does its own caching, so the client asks it |
| 31 |
again before every request, concurrently if requests are concurrent. Any |
| 32 |
other past value is an expired token and is refreshed one call at a time. |
| 33 |
|
| 34 |
`repr()` masks the token (at most its last four characters) so a frame |
| 35 |
or log line holding an `AccessToken` never exposes the raw value — |
| 36 |
crash reporters that capture traceback locals render their `repr`. |
| 37 |
""" |
| 38 |
|
| 39 |
token: str |
| 40 |
expires_at: Optional[int] = None |
| 41 |
|
| 42 |
@override |
| 43 |
def __repr__(self) -> str: |
| 44 |
# str() first: a malformed token endpoint can hand us a non-str token |
| 45 |
# and a repr must never raise (crash reporters call it blindly). |
| 46 |
token = str(self.token) |
| 47 |
masked = f"...{token[-4:]}" if len(token) >= 12 else "**********" |
| 48 |
return f"AccessToken(token='{masked}', expires_at={self.expires_at!r})" |
| 49 |
|
| 50 |
|
| 51 |
class AccessTokenProvider(Protocol): |
| 52 |
"""Callable that mints or returns a cached access token. |
| 53 |
|
| 54 |
Re-invoking the provider IS the refresh mechanism — providers have no |
| 55 |
separate `refresh()` method. Providers may be stateful (hold config / |
| 56 |
paths) but the *cache* lives in `TokenCache`, not here. |
| 57 |
|
| 58 |
The optional `force_refresh` flag is set by |
| 59 |
`TokenCache.invalidate` after a 401: providers with on-disk caches |
| 60 |
(user_oauth, oidc_federation) must bypass their freshness short-circuit |
| 61 |
and always fetch fresh when it is True. Providers without a cache can |
| 62 |
accept and ignore the flag. |
| 63 |
""" |
| 64 |
|
| 65 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: ... |
| 66 |
|
| 67 |
|
| 68 |
class AsyncAccessTokenProvider(Protocol): |
| 69 |
"""Async twin of `AccessTokenProvider`, with the same `force_refresh` contract. |
| 70 |
|
| 71 |
It must be an `async def` function, or an object whose `__call__` is one; |
| 72 |
`AsyncAnthropic` awaits it on the event loop and caches the result like a |
| 73 |
sync provider's. |
| 74 |
""" |
| 75 |
|
| 76 |
async def __call__(self, *, force_refresh: bool = False) -> AccessToken: ... |
| 77 |
|
| 78 |
|
| 79 |
def unwrap_partial(obj: object) -> object: |
| 80 |
while isinstance(obj, functools.partial): |
| 81 |
obj = obj.func |
| 82 |
return obj |
| 83 |
|
| 84 |
|
| 85 |
def is_async_token_provider(provider: object) -> TypeIs[AsyncAccessTokenProvider]: |
| 86 |
"""True for an `async def` function, an object whose `__call__` is one, or a `functools.partial` of either.""" |
| 87 |
# iscoroutinefunction looks through a partial of a function but not of a callable object. |
| 88 |
provider = unwrap_partial(provider) |
| 89 |
return inspect.iscoroutinefunction(provider) or inspect.iscoroutinefunction(getattr(provider, "__call__", None)) # noqa: B004 |
| 90 |
|
| 91 |
|
| 92 |
@runtime_checkable |
| 93 |
class BaseURLBoundProvider(AccessTokenProvider, Protocol): |
| 94 |
"""A provider whose token exchange targets a specific deployment. |
| 95 |
|
| 96 |
The client calls `for_base_url` with its own `base_url` at |
| 97 |
construction. Providers that don't implement this resolve their own |
| 98 |
exchange endpoint and are used as-is. |
| 99 |
""" |
| 100 |
|
| 101 |
def for_base_url(self, base_url: str) -> AccessTokenProvider: |
| 102 |
"""Return the provider a client with `base_url` should exchange through. |
| 103 |
|
| 104 |
Either `self`, bound to `base_url`, or — if another client already |
| 105 |
bound `self` to a different deployment — a separate provider bound to |
| 106 |
`base_url`, so that client's binding is left alone. |
| 107 |
""" |
| 108 |
... |
| 109 |
|
| 110 |
|
| 111 |
# Innermost layer: returns the raw external JWT string (used as the |
| 112 |
# `identity_token_provider` argument to `WorkloadIdentityCredentials`). |
| 113 |
IdentityTokenProvider = Callable[[], str] |
| 114 |
|
| 115 |
|
| 116 |
@dataclass(frozen=True) |
| 117 |
class CredentialResult: |
| 118 |
"""Bundles an `AccessTokenProvider` with config-level metadata. |
| 119 |
|
| 120 |
Returned by `default_credentials`. The `extra_headers` dict |
| 121 |
carries headers that should be set on every API request (e.g. |
| 122 |
`anthropic-workspace-id`). The client merges these into its default |
| 123 |
headers at construction time. |
| 124 |
|
| 125 |
`base_url` is the API host the resolved profile is configured for |
| 126 |
(e.g. a staging endpoint). The client adopts it as its request |
| 127 |
`base_url` *only* when the user did not supply one explicitly via |
| 128 |
the `base_url=` kwarg or `ANTHROPIC_BASE_URL` — see the |
| 129 |
constructor in `_client.py`. `None` means the profile did not |
| 130 |
specify a host and the client keeps its own default. |
| 131 |
""" |
| 132 |
|
| 133 |
provider: AccessTokenProvider |
| 134 |
extra_headers: Dict[str, str] = field(default_factory=_empty_headers) |
| 135 |
base_url: Optional[str] = None |