| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import copy |
| 5 |
import json |
| 6 |
import stat |
| 7 |
import time |
| 8 |
import logging |
| 9 |
import pathlib |
| 10 |
import tempfile |
| 11 |
from typing import TYPE_CHECKING, Any, Dict, Union, Optional, cast |
| 12 |
from typing_extensions import override |
| 13 |
|
| 14 |
import httpx2 |
| 15 |
|
| 16 |
from ._types import AccessToken, IdentityTokenProvider |
| 17 |
from ._secrets import ( |
| 18 |
SecretStr, |
| 19 |
_unwrap_secret, |
| 20 |
_strip_traceback, |
| 21 |
_json_dumps_secrets, |
| 22 |
_wrap_secret_fields, |
| 23 |
_NonObjectPayloadError, |
| 24 |
) |
| 25 |
from ._constants import ( |
| 26 |
ENV_SCOPE, |
| 27 |
ENV_PROFILE, |
| 28 |
ENV_BASE_URL, |
| 29 |
ENV_AUTH_TOKEN, |
| 30 |
ENV_CONFIG_DIR, |
| 31 |
TOKEN_ENDPOINT, |
| 32 |
DEFAULT_BASE_URL, |
| 33 |
ENV_WORKSPACE_ID, |
| 34 |
ENV_ORGANIZATION_ID, |
| 35 |
OAUTH_API_BETA_HEADER, |
| 36 |
ENV_FEDERATION_RULE_ID, |
| 37 |
ENV_SERVICE_ACCOUNT_ID, |
| 38 |
TOKEN_EXCHANGE_TIMEOUT, |
| 39 |
ENV_IDENTITY_TOKEN_FILE, |
| 40 |
GRANT_TYPE_REFRESH_TOKEN, |
| 41 |
MANDATORY_REFRESH_SECONDS, |
| 42 |
_user_agent, |
| 43 |
_require_https, |
| 44 |
_active_profile, |
| 45 |
_config_file_path, |
| 46 |
_credentials_file_path, |
| 47 |
resolve_identity_token_path, |
| 48 |
) |
| 49 |
from ..._exceptions import AnthropicError, CredentialsError, IdentityTokenFileError |
| 50 |
|
| 51 |
log: logging.Logger = logging.getLogger(__name__) |
| 52 |
|
| 53 |
if TYPE_CHECKING: |
| 54 |
from ._workload import WorkloadIdentityCredentials |
| 55 |
|
| 56 |
__all__ = ["StaticToken", "EnvToken", "CredentialsFile", "InMemoryConfig", "IdentityTokenFile"] |
| 57 |
|
| 58 |
|
| 59 |
def _coerce_expires_at(value: Any, source: Optional[pathlib.Path]) -> Optional[int]: |
| 60 |
"""Parse a credentials-file `expires_at` field into Unix seconds.""" |
| 61 |
if value is None: |
| 62 |
return None |
| 63 |
try: |
| 64 |
return int(value) |
| 65 |
except (TypeError, ValueError) as err: |
| 66 |
where = f"credentials file at {source}" if source is not None else "credentials" |
| 67 |
raise CredentialsError( |
| 68 |
f"{where} has invalid 'expires_at' {value!r}; expected an integer " |
| 69 |
f"Unix timestamp in seconds. The SDK does not parse ISO8601 — convert " |
| 70 |
f"with int(datetime.timestamp()) before writing the file." |
| 71 |
) from err |
| 72 |
|
| 73 |
|
| 74 |
# Discriminator written to credentials/<profile>.json. Only one value in v1; |
| 75 |
# future credential shapes (e.g. private key material) get their own. |
| 76 |
CREDENTIALS_FILE_TYPE = "oauth_token" |
| 77 |
|
| 78 |
# On-disk file-format versions. Absent on read = 1 (current shape). |
| 79 |
CONFIG_FILE_VERSION = "1.0" |
| 80 |
CREDENTIALS_FILE_VERSION = "1.0" |
| 81 |
|
| 82 |
# Discriminator values for the config file's `authentication.type` field. |
| 83 |
AUTH_TYPE_OIDC_FEDERATION = "oidc_federation" |
| 84 |
AUTH_TYPE_USER_OAUTH = "user_oauth" |
| 85 |
|
| 86 |
|
| 87 |
def _fill_missing_from_env(config: Dict[str, Any], auth: Dict[str, Any]) -> None: |
| 88 |
"""Fill empty profile fields from corresponding ANTHROPIC_* env vars. |
| 89 |
|
| 90 |
The profile file is authoritative — this only fills fields the file left |
| 91 |
unset. Empty-string env values are treated as unset. |
| 92 |
""" |
| 93 |
|
| 94 |
def fill(target: Dict[str, Any], key: str, env_var: str) -> None: |
| 95 |
# Absent-key and empty-string profile values are both treated as unset. |
| 96 |
if not target.get(key): |
| 97 |
v = os.environ.get(env_var) |
| 98 |
if v: |
| 99 |
target[key] = v |
| 100 |
|
| 101 |
fill(config, "base_url", ENV_BASE_URL) |
| 102 |
fill(config, "organization_id", ENV_ORGANIZATION_ID) |
| 103 |
fill(config, "workspace_id", ENV_WORKSPACE_ID) |
| 104 |
|
| 105 |
auth_type = auth.get("type") |
| 106 |
if auth_type == AUTH_TYPE_OIDC_FEDERATION: |
| 107 |
fill(auth, "federation_rule_id", ENV_FEDERATION_RULE_ID) |
| 108 |
fill(auth, "service_account_id", ENV_SERVICE_ACCOUNT_ID) |
| 109 |
fill(auth, "scope", ENV_SCOPE) |
| 110 |
if not auth.get("identity_token"): |
| 111 |
v = os.environ.get(ENV_IDENTITY_TOKEN_FILE) |
| 112 |
if v: |
| 113 |
auth["identity_token"] = {"source": "file", "path": v} |
| 114 |
elif auth_type == AUTH_TYPE_USER_OAUTH: |
| 115 |
fill(auth, "scope", ENV_SCOPE) |
| 116 |
|
| 117 |
|
| 118 |
class StaticToken: |
| 119 |
"""An `AccessTokenProvider` that always returns a fixed token with no expiry.""" |
| 120 |
|
| 121 |
def __init__(self, token: str) -> None: |
| 122 |
self._token = token |
| 123 |
|
| 124 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: |
| 125 |
del force_refresh # no provider-side cache to bypass |
| 126 |
return AccessToken(token=self._token, expires_at=None) |
| 127 |
|
| 128 |
|
| 129 |
class EnvToken: |
| 130 |
"""An `AccessTokenProvider` that reads `ANTHROPIC_AUTH_TOKEN` at call time.""" |
| 131 |
|
| 132 |
def __init__(self, env_var: str = ENV_AUTH_TOKEN) -> None: |
| 133 |
self._env_var = env_var |
| 134 |
|
| 135 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: |
| 136 |
del force_refresh |
| 137 |
value = os.environ.get(self._env_var) |
| 138 |
if value is None: |
| 139 |
raise CredentialsError( |
| 140 |
f"Environment variable {self._env_var} is not set. " |
| 141 |
f"Set it or pass an explicit `credentials=` provider to the client." |
| 142 |
) |
| 143 |
return AccessToken(token=value, expires_at=None) |
| 144 |
|
| 145 |
|
| 146 |
class CredentialsFile: |
| 147 |
"""An `AccessTokenProvider` backed by a named profile. |
| 148 |
|
| 149 |
A profile is a pair of files under the config directory |
| 150 |
(`~/.config/anthropic/` by default; override with `ANTHROPIC_CONFIG_DIR`): |
| 151 |
|
| 152 |
* `configs/<profile>.json` — non-secret. Holds the nested |
| 153 |
`"authentication"` object (discriminated by its `"type"` field), plus |
| 154 |
top-level `organization_id`, `workspace_id`, and `base_url`. |
| 155 |
The `authentication` object may contain a `credentials_path` field |
| 156 |
overriding the credentials file location. |
| 157 |
* `credentials/<profile>.json` — secret (0600). Holds `access_token`, |
| 158 |
`expires_at`, and (for `user_oauth` with a `client_id`) |
| 159 |
`refresh_token`. |
| 160 |
|
| 161 |
The split keeps secret material out of files that may need to be readable |
| 162 |
by config-only consumers, and lets the SDK enforce 0600 on the credentials |
| 163 |
file without locking out config readers. |
| 164 |
|
| 165 |
Dispatches on the `authentication.type` discriminator: |
| 166 |
|
| 167 |
`"oidc_federation"` |
| 168 |
OIDC workload identity federation. Lazily constructs a |
| 169 |
`WorkloadIdentityCredentials` delegate from the nested auth |
| 170 |
fields plus the top-level `organization_id` and calls it to perform |
| 171 |
the jwt-bearer exchange. |
| 172 |
|
| 173 |
`"user_oauth"` |
| 174 |
Output of an interactive PKCE login. If the auth block has a |
| 175 |
`client_id`, performs `refresh_token` grants on expiry and |
| 176 |
writes the new tokens back to the credentials file (atomic replace, |
| 177 |
refresh-token rotation supported). Without a `client_id`, the |
| 178 |
credentials file is treated as externally rotated — the SDK re-reads |
| 179 |
it on every invocation and returns whatever `access_token` is |
| 180 |
there, no refresh grant attempted. This is the pattern for a |
| 181 |
sidecar/daemon that mints the access token out-of-band. |
| 182 |
|
| 183 |
Args: |
| 184 |
profile: Profile name. `None` resolves via `ANTHROPIC_PROFILE` env |
| 185 |
→ `<config_dir>/active_config` pointer file → `"default"`. |
| 186 |
""" |
| 187 |
|
| 188 |
def __init__( |
| 189 |
self, |
| 190 |
profile: Optional[str] = None, |
| 191 |
*, |
| 192 |
http_client: Optional[httpx2.Client] = None, |
| 193 |
) -> None: |
| 194 |
self._profile = profile if profile is not None else _active_profile() |
| 195 |
self._config_path = _config_file_path(self._profile) |
| 196 |
self._bound_base_url: Optional[str] = None |
| 197 |
self._http_client = http_client |
| 198 |
self._owned_http_client: Optional[httpx2.Client] = None |
| 199 |
|
| 200 |
# Populated on first __call__ — keeps construction cheap and exception-free |
| 201 |
# so the chain can construct us optimistically after an existence check. |
| 202 |
self._config: Optional[Dict[str, Any]] = None |
| 203 |
self._credentials_path: Optional[pathlib.Path] = None |
| 204 |
self._base_url: str = DEFAULT_BASE_URL |
| 205 |
self._workload_delegate: Optional[WorkloadIdentityCredentials] = None |
| 206 |
|
| 207 |
@property |
| 208 |
def profile(self) -> str: |
| 209 |
return self._profile |
| 210 |
|
| 211 |
@property |
| 212 |
def config_path(self) -> pathlib.Path: |
| 213 |
return self._config_path |
| 214 |
|
| 215 |
@property |
| 216 |
def resolved_base_url(self) -> Optional[str]: |
| 217 |
"""The `base_url` declared in the profile config file, if any. |
| 218 |
|
| 219 |
Returns `None` when the config has no top-level `base_url` key — |
| 220 |
callers should fall back to their own default rather than the |
| 221 |
provider's bound/default value, so a profile that *doesn't* pin a |
| 222 |
host never overrides an explicit client setting. Loads the config |
| 223 |
on first access. |
| 224 |
""" |
| 225 |
config = self._load_config() |
| 226 |
raw = config.get("base_url") |
| 227 |
return str(raw).rstrip("/") if raw else None |
| 228 |
|
| 229 |
def bind_base_url(self, base_url: str) -> None: |
| 230 |
"""Adopt the owning client's `base_url` as a fallback for the token |
| 231 |
exchange. Slots between the config file's own `base_url` field and |
| 232 |
the hard-coded default; a `base_url` in the config file still wins. |
| 233 |
|
| 234 |
Rebinding affects every client holding this instance; clients bind |
| 235 |
through `for_base_url` instead. |
| 236 |
""" |
| 237 |
bound = base_url.rstrip("/") |
| 238 |
# Validate eagerly so an invalid bind fails at bind time, not at the |
| 239 |
# subsequent _load_config() — matches WorkloadIdentityCredentials. |
| 240 |
_require_https(bound, field=f"{self._config_path}: base_url") |
| 241 |
self._bound_base_url = bound |
| 242 |
if self._config is not None: |
| 243 |
self._base_url = self._resolve_base_url(self._config) |
| 244 |
_require_https(self._base_url, field=f"{self._config_path}: base_url") |
| 245 |
|
| 246 |
def for_base_url(self, base_url: str) -> "CredentialsFile": |
| 247 |
"""Return the provider a client with `base_url` should exchange through. |
| 248 |
|
| 249 |
Binds in place, unless another client already bound this instance to a |
| 250 |
different host (e.g. the parent of `copy(base_url=...)`). That binding |
| 251 |
is left alone, and what happens depends on the profile: |
| 252 |
|
| 253 |
* pins its own `base_url`: the bind is irrelevant, return `self`. |
| 254 |
* `oidc_federation`: return a copy bound to `base_url`. It shares the |
| 255 |
identity token and http client, but not the on-disk token cache, whose |
| 256 |
tokens belong to the original deployment. |
| 257 |
* `user_oauth`: return `self`. The refresh token is tied to the |
| 258 |
deployment that issued it, so there is nothing per-host to copy. |
| 259 |
""" |
| 260 |
bound = base_url.rstrip("/") |
| 261 |
if self._bound_base_url is None or self._bound_base_url == bound: |
| 262 |
self.bind_base_url(bound) |
| 263 |
return self |
| 264 |
config = self._load_config() |
| 265 |
if config.get("base_url") or self._auth_block().get("type") != AUTH_TYPE_OIDC_FEDERATION: |
| 266 |
return self |
| 267 |
provider = copy.copy(self) |
| 268 |
provider._http_client = self._get_http_client() |
| 269 |
provider._owned_http_client = None |
| 270 |
provider._workload_delegate = None |
| 271 |
provider._credentials_path = None |
| 272 |
provider.bind_base_url(bound) |
| 273 |
return provider |
| 274 |
|
| 275 |
def _resolve_base_url(self, config: Dict[str, Any]) -> str: |
| 276 |
"""base_url precedence: top-level config field → bound (the owning |
| 277 |
client's base_url, via `bind_base_url`) → default. Validated |
| 278 |
against the scheme/TLS rules so a malicious config with |
| 279 |
`base_url="http://evil/"` can't exfiltrate the assertion or refresh |
| 280 |
token.""" |
| 281 |
if config.get("base_url"): |
| 282 |
return str(config["base_url"]).rstrip("/") |
| 283 |
if self._bound_base_url is not None: |
| 284 |
return self._bound_base_url |
| 285 |
return DEFAULT_BASE_URL |
| 286 |
|
| 287 |
def extra_headers(self) -> Dict[str, str]: |
| 288 |
"""Return headers derived from the config file (e.g. `workspace_id`). |
| 289 |
|
| 290 |
Eagerly reads the config if not yet loaded. The returned dict is |
| 291 |
suitable for merging into the client's default headers. |
| 292 |
""" |
| 293 |
config = self._load_config() |
| 294 |
headers: Dict[str, str] = {} |
| 295 |
# For federation profiles workspace_id is sent in the jwt-bearer |
| 296 |
# exchange body, not as a request header (the minted token is already |
| 297 |
# workspace-scoped, so the header would be ignored). |
| 298 |
if self._auth_block().get("type") != AUTH_TYPE_OIDC_FEDERATION: |
| 299 |
workspace_id = config.get("workspace_id") |
| 300 |
if workspace_id: |
| 301 |
headers["anthropic-workspace-id"] = str(workspace_id) |
| 302 |
return headers |
| 303 |
|
| 304 |
def _load_config(self) -> Dict[str, Any]: |
| 305 |
"""Read and cache the config file, resolving `base_url` and `credentials_path`.""" |
| 306 |
if self._config is not None: |
| 307 |
return self._config |
| 308 |
|
| 309 |
try: |
| 310 |
raw = self._config_path.read_text(encoding="utf-8") |
| 311 |
except FileNotFoundError as err: |
| 312 |
raise CredentialsError( |
| 313 |
f"Config file not found at {self._config_path} (profile {self._profile!r}). " |
| 314 |
f"Set {ENV_PROFILE} to select a different profile, or set {ENV_CONFIG_DIR} " |
| 315 |
f"to relocate the config directory." |
| 316 |
) from err |
| 317 |
except (OSError, UnicodeDecodeError) as err: |
| 318 |
raise CredentialsError(f"Config file at {self._config_path} could not be read: {err}") from err |
| 319 |
try: |
| 320 |
raw_config: Any = json.loads(raw) |
| 321 |
except json.JSONDecodeError as err: |
| 322 |
raise CredentialsError(f"Config file at {self._config_path} is not valid JSON: {err}") from err |
| 323 |
|
| 324 |
if not isinstance(raw_config, dict): |
| 325 |
raise CredentialsError( |
| 326 |
f"Config file at {self._config_path} must contain a JSON object, not {type(raw_config).__name__}." |
| 327 |
) |
| 328 |
config = cast("Dict[str, Any]", raw_config) |
| 329 |
|
| 330 |
raw_auth = config.get("authentication") |
| 331 |
if not isinstance(raw_auth, dict): |
| 332 |
raise CredentialsError( |
| 333 |
f"Config file at {self._config_path} is missing the 'authentication' object. " |
| 334 |
f'Expected shape: {{"authentication": {{"type": ' |
| 335 |
f'"{AUTH_TYPE_OIDC_FEDERATION}"|"{AUTH_TYPE_USER_OAUTH}", ...}}, ...}}' |
| 336 |
) |
| 337 |
auth = cast("Dict[str, Any]", raw_auth) |
| 338 |
|
| 339 |
# Env-vars fill only what the file left empty; runs before derived |
| 340 |
# state (base_url, identity_token path) is resolved. |
| 341 |
_fill_missing_from_env(config, auth) |
| 342 |
|
| 343 |
self._base_url = self._resolve_base_url(config) |
| 344 |
_require_https(self._base_url, field=f"{self._config_path}: base_url") |
| 345 |
|
| 346 |
override = auth.get("credentials_path") |
| 347 |
if override: |
| 348 |
self._credentials_path = pathlib.Path(str(override)).expanduser() |
| 349 |
else: |
| 350 |
self._credentials_path = _credentials_file_path(self._profile) |
| 351 |
|
| 352 |
self._config = config |
| 353 |
return config |
| 354 |
|
| 355 |
def _read_credentials(self) -> Dict[str, Any]: |
| 356 |
"""Read the credentials file. Re-reads on every call — daemons rotate it. |
| 357 |
|
| 358 |
Secret values in the returned dict (every string field not in |
| 359 |
`_secrets._PLAIN_KEYS`) are `SecretStr`-wrapped — unwrap |
| 360 |
with `_unwrap_secret` at the point of use. Writing the dict back |
| 361 |
through `_atomic_write_credentials` unwraps automatically. |
| 362 |
|
| 363 |
On Unix, refuses symlinks and any file readable or writable by group |
| 364 |
or others (`mode & 0o077`). The check is skipped on Windows where |
| 365 |
POSIX mode bits don't carry the same meaning. |
| 366 |
""" |
| 367 |
assert self._credentials_path is not None # set by _load_config |
| 368 |
path = self._credentials_path |
| 369 |
if os.name == "posix": |
| 370 |
try: |
| 371 |
file_stat = os.stat(path, follow_symlinks=False) |
| 372 |
except FileNotFoundError as err: |
| 373 |
raise CredentialsError(f"Credentials file not found at {path} (profile {self._profile!r}).") from err |
| 374 |
except OSError as err: |
| 375 |
raise CredentialsError(f"Credentials file at {path} could not be accessed: {err}") from err |
| 376 |
if stat.S_ISLNK(file_stat.st_mode): |
| 377 |
raise CredentialsError( |
| 378 |
f"Credentials file at {path} is a symlink; refusing to follow " |
| 379 |
f"(move the real file into place to keep secret material on the expected filesystem)." |
| 380 |
) |
| 381 |
mode = stat.S_IMODE(file_stat.st_mode) |
| 382 |
if mode & 0o077: |
| 383 |
raise CredentialsError( |
| 384 |
f"Credentials file at {path} is accessible by group or others (mode {mode:#o}); " |
| 385 |
f"run `chmod 600 {path}` before retrying." |
| 386 |
) |
| 387 |
try: |
| 388 |
# Read → parse → wrap in one expression: neither the raw file text |
| 389 |
# nor an unwrapped token dict is ever bound to a local in this |
| 390 |
# frame, so traceback frame locals stay free of credential |
| 391 |
# material on every error path in and below this method. |
| 392 |
creds: Dict[str, Any] = _wrap_secret_fields(json.loads(path.read_text(encoding="utf-8"))) |
| 393 |
except FileNotFoundError as err: |
| 394 |
raise CredentialsError(f"Credentials file not found at {path} (profile {self._profile!r}).") from err |
| 395 |
except json.JSONDecodeError as err: |
| 396 |
# The JSONDecodeError message carries only position info. |
| 397 |
raise CredentialsError(f"Credentials file at {path} is not valid JSON: {err}") from _strip_traceback(err) |
| 398 |
except _NonObjectPayloadError as err: |
| 399 |
# Rejected inside the helper with the payload unbound — a scalar |
| 400 |
# credentials file is still secret material (e.g. a bare token). |
| 401 |
raise CredentialsError( |
| 402 |
f"Credentials file at {path} must contain a JSON object, not {err.type_name}." |
| 403 |
) from None |
| 404 |
except (OSError, UnicodeDecodeError) as err: |
| 405 |
raise CredentialsError(f"Credentials file at {path} could not be read: {err}") from err |
| 406 |
|
| 407 |
# Validate discriminator if present; lenient if absent so hand-written |
| 408 |
# or older files keep working. Catches config/credentials drift early. |
| 409 |
actual = creds.get("type") |
| 410 |
if actual is not None and actual != CREDENTIALS_FILE_TYPE: |
| 411 |
assert self._config is not None # _load_config always precedes _read_credentials |
| 412 |
auth_type = self._config["authentication"].get("type") |
| 413 |
raise CredentialsError( |
| 414 |
f"credentials file has type {actual!r}; expected {CREDENTIALS_FILE_TYPE!r} " |
| 415 |
f"for authentication.type {auth_type!r}" |
| 416 |
) |
| 417 |
return creds |
| 418 |
|
| 419 |
def _get_http_client(self) -> httpx2.Client: |
| 420 |
"""Return an `httpx2.Client`, lazily creating (and tracking) one we own.""" |
| 421 |
if self._http_client is not None: |
| 422 |
return self._http_client |
| 423 |
if self._owned_http_client is None: |
| 424 |
self._owned_http_client = httpx2.Client(timeout=TOKEN_EXCHANGE_TIMEOUT) |
| 425 |
return self._owned_http_client |
| 426 |
|
| 427 |
def close(self) -> None: |
| 428 |
"""Close the owned `httpx2.Client` if we created one.""" |
| 429 |
if self._owned_http_client is not None: |
| 430 |
self._owned_http_client.close() |
| 431 |
self._owned_http_client = None |
| 432 |
if self._workload_delegate is not None: |
| 433 |
self._workload_delegate.close() |
| 434 |
|
| 435 |
def reload(self) -> None: |
| 436 |
"""Drop the cached config so the next call re-reads it from disk. |
| 437 |
|
| 438 |
`CredentialsFile` caches the parsed config across calls to keep the |
| 439 |
hot path cheap; a daemon that rotates a profile in place (e.g. flips |
| 440 |
`"type": "user_oauth"` to `"type": "oidc_federation"`) will not be |
| 441 |
picked up automatically. Callers that need to react to such changes |
| 442 |
can call `reload()` to force a fresh read on the next `__call__`. |
| 443 |
""" |
| 444 |
self._config = None |
| 445 |
self._workload_delegate = None |
| 446 |
|
| 447 |
def _atomic_write_credentials(self, data: Dict[str, Any]) -> None: |
| 448 |
"""Atomic write to the credentials file (NOT the config file). |
| 449 |
|
| 450 |
`data` may hold `SecretStr` token values (see |
| 451 |
`_read_credentials`); they are unwrapped at dump time, so the |
| 452 |
on-disk format is unchanged and this frame's locals stay redacted if |
| 453 |
the write fails (e.g. ENOSPC) with a crash reporter capturing them. |
| 454 |
""" |
| 455 |
assert self._credentials_path is not None |
| 456 |
parent = self._credentials_path.parent |
| 457 |
parent.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 458 |
# mkstemp gives a unique temp name so concurrent writers (e.g. |
| 459 |
# gunicorn workers cold-starting together) don't race on a fixed |
| 460 |
# `.tmp` path; whichever os.replace lands last wins, which is fine |
| 461 |
# for a best-effort cache. |
| 462 |
fd, tmp = tempfile.mkstemp(dir=parent, prefix=f".{self._credentials_path.name}.", suffix=".tmp") |
| 463 |
try: |
| 464 |
try: |
| 465 |
os.fchmod(fd, 0o600) |
| 466 |
os.write(fd, _json_dumps_secrets(data, indent=2)) |
| 467 |
os.fsync(fd) |
| 468 |
finally: |
| 469 |
os.close(fd) |
| 470 |
os.replace(tmp, self._credentials_path) |
| 471 |
except BaseException: |
| 472 |
try: |
| 473 |
os.unlink(tmp) |
| 474 |
except OSError: |
| 475 |
pass |
| 476 |
raise |
| 477 |
# fsync the parent directory so the rename itself survives a crash on |
| 478 |
# filesystems that defer directory-entry writes. Best-effort: Windows |
| 479 |
# and some POSIX flavours don't support directory fds. |
| 480 |
try: |
| 481 |
dir_fd = os.open(parent, os.O_RDONLY) |
| 482 |
try: |
| 483 |
os.fsync(dir_fd) |
| 484 |
finally: |
| 485 |
os.close(dir_fd) |
| 486 |
except OSError: |
| 487 |
pass |
| 488 |
|
| 489 |
def _auth_block(self) -> Dict[str, Any]: |
| 490 |
"""Return the cached `authentication` sub-object from the config file.""" |
| 491 |
config = self._load_config() |
| 492 |
return cast("Dict[str, Any]", config["authentication"]) |
| 493 |
|
| 494 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: |
| 495 |
auth = self._auth_block() |
| 496 |
auth_type = auth.get("type") |
| 497 |
|
| 498 |
if auth_type == AUTH_TYPE_OIDC_FEDERATION: |
| 499 |
return self._call_oidc_federation(auth, force_refresh=force_refresh) |
| 500 |
|
| 501 |
if auth_type == AUTH_TYPE_USER_OAUTH: |
| 502 |
return self._call_user_oauth(auth, force_refresh=force_refresh) |
| 503 |
|
| 504 |
raise CredentialsError( |
| 505 |
f"Unknown authentication.type {auth_type!r} at {self._config_path}. " |
| 506 |
f"Expected {AUTH_TYPE_OIDC_FEDERATION!r} or {AUTH_TYPE_USER_OAUTH!r}." |
| 507 |
) |
| 508 |
|
| 509 |
def _call_user_oauth(self, auth: Dict[str, Any], *, force_refresh: bool = False) -> AccessToken: |
| 510 |
"""Interactive-login profile. With a `client_id` in the auth block, |
| 511 |
we run the refresh_token grant on expiry; without one, we treat the |
| 512 |
credentials file as externally rotated and just read it fresh. |
| 513 |
""" |
| 514 |
from ._workload import WorkloadIdentityError, _request_id, _raise_token_endpoint_error |
| 515 |
|
| 516 |
creds = self._read_credentials() |
| 517 |
access_token = creds.get("access_token") |
| 518 |
if not access_token: |
| 519 |
raise CredentialsError(f"Credentials file at {self._credentials_path} is missing 'access_token'.") |
| 520 |
|
| 521 |
client_id = auth.get("client_id") |
| 522 |
if not client_id: |
| 523 |
# No client_id → externally rotated. Return whatever the file has; |
| 524 |
# a sidecar/daemon is responsible for keeping it fresh. |
| 525 |
expires_at = _coerce_expires_at(creds.get("expires_at"), self._credentials_path) |
| 526 |
return AccessToken(token=_unwrap_secret(access_token), expires_at=expires_at) |
| 527 |
|
| 528 |
refresh_token = creds.get("refresh_token") |
| 529 |
if not refresh_token: |
| 530 |
raise WorkloadIdentityError( |
| 531 |
f"credentials file for profile {self._profile!r} (authentication.type " |
| 532 |
f"{AUTH_TYPE_USER_OAUTH!r} with client_id) must include 'refresh_token': " |
| 533 |
f"{self._credentials_path}" |
| 534 |
) |
| 535 |
|
| 536 |
# Strict expiry only — TokenCache owns the advisory/mandatory refresh |
| 537 |
# policy. A second threshold here could trigger a refresh grant while |
| 538 |
# the outer cache is still serving fine. |
| 539 |
# force_refresh (set by TokenCache.invalidate after a 401) bypasses |
| 540 |
# the disk-freshness short-circuit so a revoked token isn't re-served. |
| 541 |
expires_at = _coerce_expires_at(creds.get("expires_at"), self._credentials_path) |
| 542 |
if not force_refresh and expires_at is not None and time.time() < expires_at: |
| 543 |
return AccessToken(token=_unwrap_secret(access_token), expires_at=expires_at) |
| 544 |
|
| 545 |
body: Dict[str, Union[str, SecretStr]] = { |
| 546 |
"grant_type": GRANT_TYPE_REFRESH_TOKEN, |
| 547 |
"refresh_token": refresh_token, |
| 548 |
"client_id": client_id, |
| 549 |
} |
| 550 |
|
| 551 |
try: |
| 552 |
resp = self._get_http_client().post( |
| 553 |
f"{self._base_url}{TOKEN_ENDPOINT}", |
| 554 |
# Serialized inline so the raw request bytes are never bound |
| 555 |
# to a local here; SecretStr values unwrap at dump time. |
| 556 |
content=_json_dumps_secrets(body), |
| 557 |
headers={ |
| 558 |
"Content-Type": "application/json", |
| 559 |
# oauth-2025-04-20 unlocks the token endpoint family. Do |
| 560 |
# NOT send oidc-federation-2026-04-01 — that's a routing |
| 561 |
# switch that misroutes refresh_token grants to the Go |
| 562 |
# userauth handler, which only accepts jwt-bearer. |
| 563 |
"anthropic-beta": OAUTH_API_BETA_HEADER, |
| 564 |
"User-Agent": _user_agent(), |
| 565 |
}, |
| 566 |
) |
| 567 |
except httpx2.HTTPError as err: |
| 568 |
raise WorkloadIdentityError( |
| 569 |
f"user_oauth refresh failed to reach token endpoint: {err}" |
| 570 |
) from _strip_traceback(err) |
| 571 |
|
| 572 |
if resp.status_code != 200: |
| 573 |
_raise_token_endpoint_error(resp, message_prefix="user_oauth refresh failed") |
| 574 |
|
| 575 |
try: |
| 576 |
payload: Dict[str, Any] = _wrap_secret_fields(resp.json()) |
| 577 |
except ValueError as err: |
| 578 |
# A raw JSONDecodeError must not escape as the raised error — its |
| 579 |
# message names the decoder, not this grant. Matches the |
| 580 |
# jwt-bearer path's non-JSON handling. |
| 581 |
raise WorkloadIdentityError( |
| 582 |
f"user_oauth refresh returned a non-JSON response (status {resp.status_code}).", |
| 583 |
status_code=resp.status_code, |
| 584 |
request_id=_request_id(resp), |
| 585 |
) from _strip_traceback(err) |
| 586 |
except _NonObjectPayloadError as err: |
| 587 |
# Rejected inside the helper with the payload unbound — a |
| 588 |
# non-object body can echo the request's refresh token. |
| 589 |
raise WorkloadIdentityError( |
| 590 |
f"user_oauth refresh returned a JSON {err.type_name} (status {resp.status_code}); expected an object.", |
| 591 |
status_code=resp.status_code, |
| 592 |
request_id=_request_id(resp), |
| 593 |
) from None |
| 594 |
new_access = payload.get("access_token") |
| 595 |
if not new_access: |
| 596 |
raise WorkloadIdentityError("user_oauth refresh response missing 'access_token'") |
| 597 |
raw_expires_in = payload.get("expires_in", 3600) |
| 598 |
try: |
| 599 |
expires_in = int(raw_expires_in) |
| 600 |
except (TypeError, ValueError, OverflowError) as err: |
| 601 |
raise WorkloadIdentityError( |
| 602 |
f"user_oauth refresh response has invalid 'expires_in' {raw_expires_in!r}; " |
| 603 |
f"expected an integer number of seconds." |
| 604 |
) from err |
| 605 |
new_expires_at = int(time.time()) + expires_in |
| 606 |
new_refresh = payload.get("refresh_token") or refresh_token |
| 607 |
|
| 608 |
creds["version"] = CREDENTIALS_FILE_VERSION |
| 609 |
creds["type"] = CREDENTIALS_FILE_TYPE |
| 610 |
creds["access_token"] = new_access |
| 611 |
creds["expires_at"] = new_expires_at |
| 612 |
creds["refresh_token"] = new_refresh |
| 613 |
# A failed persist propagates: the refresh token may have rotated |
| 614 |
# server-side, so silently continuing would lose it. |
| 615 |
self._atomic_write_credentials(creds) |
| 616 |
|
| 617 |
return AccessToken(token=_unwrap_secret(new_access), expires_at=new_expires_at) |
| 618 |
|
| 619 |
def _read_credentials_if_exists(self) -> Optional[Dict[str, Any]]: |
| 620 |
"""`_read_credentials` variant that returns `None` on absence |
| 621 |
instead of raising — used by the federation disk-cache path where a |
| 622 |
missing credentials file just means "exchange now". |
| 623 |
""" |
| 624 |
assert self._credentials_path is not None |
| 625 |
if not self._credentials_path.exists(): |
| 626 |
return None |
| 627 |
try: |
| 628 |
return self._read_credentials() |
| 629 |
except AnthropicError as err: |
| 630 |
if isinstance(err.__cause__, FileNotFoundError): |
| 631 |
return None |
| 632 |
raise |
| 633 |
|
| 634 |
def _call_oidc_federation(self, auth: Dict[str, Any], *, force_refresh: bool = False) -> AccessToken: |
| 635 |
if self._workload_delegate is None: |
| 636 |
self._workload_delegate = self._build_workload_delegate(auth) |
| 637 |
|
| 638 |
# Disk cache: if a prior exchange wrote credentials/<profile>.json and |
| 639 |
# the token there is unexpired, return it instead of re-exchanging. |
| 640 |
# The in-memory TokenCache layer applies the proactive 120s/30s policy |
| 641 |
# on top of this; the disk cache only matters across process restarts. |
| 642 |
# `_credentials_path` is always set for `CredentialsFile` proper |
| 643 |
# (`_load_config` defaults it); subclasses (`InMemoryConfig`) |
| 644 |
# leave it `None` to opt out of the disk cache entirely. |
| 645 |
if self._credentials_path is None: |
| 646 |
return self._workload_delegate() |
| 647 |
|
| 648 |
# force_refresh (set by TokenCache.invalidate after a 401) bypasses |
| 649 |
# the disk-cache short-circuit so a revoked token isn't re-served. |
| 650 |
cached = self._read_credentials_if_exists() |
| 651 |
if not force_refresh and cached is not None: |
| 652 |
access_token = cached.get("access_token") |
| 653 |
expires_at = cached.get("expires_at") |
| 654 |
try: |
| 655 |
if ( |
| 656 |
access_token |
| 657 |
and expires_at is not None |
| 658 |
and time.time() < float(expires_at) - MANDATORY_REFRESH_SECONDS |
| 659 |
): |
| 660 |
return AccessToken(token=str(_unwrap_secret(access_token)), expires_at=int(expires_at)) |
| 661 |
except (TypeError, ValueError): |
| 662 |
# corrupted expires_at — fall through to re-exchange and overwrite |
| 663 |
pass |
| 664 |
|
| 665 |
token = self._workload_delegate() |
| 666 |
try: |
| 667 |
self._atomic_write_credentials( |
| 668 |
{ |
| 669 |
**(cached or {}), |
| 670 |
"version": CREDENTIALS_FILE_VERSION, |
| 671 |
"type": CREDENTIALS_FILE_TYPE, |
| 672 |
# Wrapped so a failing write never holds the raw token in |
| 673 |
# frame locals; unwrapped again at dump time. |
| 674 |
"access_token": SecretStr(token.token), |
| 675 |
"expires_at": token.expires_at, |
| 676 |
} |
| 677 |
) |
| 678 |
except OSError as err: |
| 679 |
log.debug("federation token disk-cache write-back failed (best-effort): %s", err) |
| 680 |
return token |
| 681 |
|
| 682 |
def _build_workload_delegate(self, auth: Dict[str, Any]) -> WorkloadIdentityCredentials: |
| 683 |
# Import here to avoid a circular import (_workload imports nothing from |
| 684 |
# _providers so the dependency is one-way at runtime). |
| 685 |
from ._workload import WorkloadIdentityError, WorkloadIdentityCredentials |
| 686 |
|
| 687 |
federation_rule_id = auth.get("federation_rule_id") |
| 688 |
assert self._config is not None # _load_config precedes dispatch |
| 689 |
organization_id = self._config.get("organization_id") |
| 690 |
if not federation_rule_id or not organization_id: |
| 691 |
raise WorkloadIdentityError( |
| 692 |
f"config file with authentication.type {AUTH_TYPE_OIDC_FEDERATION!r} must include " |
| 693 |
f"'authentication.federation_rule_id' and top-level 'organization_id': " |
| 694 |
f"{self._config_path}" |
| 695 |
) |
| 696 |
|
| 697 |
# identity_token is a discriminated object so future variants (url, |
| 698 |
# executable, aws_sigv4) slot in without renaming. v1 implements |
| 699 |
# source:"file" only. Absent → fall back to ANTHROPIC_IDENTITY_TOKEN_FILE. |
| 700 |
identity_token_cfg = auth.get("identity_token") |
| 701 |
if identity_token_cfg is not None: |
| 702 |
source = identity_token_cfg.get("source") |
| 703 |
if source != "file": |
| 704 |
raise CredentialsError(f"identity_token source {source!r} is not supported; only 'file' is implemented") |
| 705 |
identity_token_path = identity_token_cfg.get("path") |
| 706 |
if not identity_token_path: |
| 707 |
# Empty/missing path is a config bug, not an env-var fallback |
| 708 |
# signal — the source explicitly says "file", which has no |
| 709 |
# meaning without a path. Without this check we'd silently |
| 710 |
# fall through to ANTHROPIC_IDENTITY_TOKEN_FILE and override |
| 711 |
# user intent. |
| 712 |
raise CredentialsError( |
| 713 |
f"identity_token source 'file' requires a non-empty path; " |
| 714 |
f"profile {self._profile!r} at {self._config_path} has identity_token={identity_token_cfg!r}." |
| 715 |
) |
| 716 |
else: |
| 717 |
identity_token_path = None |
| 718 |
provider = IdentityTokenFile(identity_token_path) if identity_token_path else IdentityTokenFile() |
| 719 |
|
| 720 |
# The delegate borrows our owned httpx2.Client: passing http_client= |
| 721 |
# sets _owns_http_client=False on the delegate so its close() is a |
| 722 |
# no-op. CredentialsFile.close() remains the single closer. |
| 723 |
delegate = WorkloadIdentityCredentials( |
| 724 |
identity_token_provider=provider, |
| 725 |
federation_rule_id=federation_rule_id, |
| 726 |
organization_id=organization_id, |
| 727 |
service_account_id=auth.get("service_account_id"), |
| 728 |
workspace_id=self._config.get("workspace_id"), |
| 729 |
scope=auth.get("scope"), |
| 730 |
http_client=self._get_http_client(), |
| 731 |
) |
| 732 |
delegate.bind_base_url(self._base_url) |
| 733 |
return delegate |
| 734 |
|
| 735 |
|
| 736 |
class IdentityTokenFile: |
| 737 |
"""An `IdentityTokenProvider` that reads a JWT from a file on every call. |
| 738 |
|
| 739 |
Kubernetes projected service-account tokens (and similar) are rotated in place, |
| 740 |
so the file MUST be re-read on every invocation rather than cached. |
| 741 |
""" |
| 742 |
|
| 743 |
def __init__(self, path: Union[str, "os.PathLike[str]", None] = None) -> None: |
| 744 |
resolved = resolve_identity_token_path(path) |
| 745 |
if resolved is None: |
| 746 |
raise CredentialsError( |
| 747 |
f"No identity token file path given. Pass `path=` or set the {ENV_IDENTITY_TOKEN_FILE} " |
| 748 |
f"environment variable." |
| 749 |
) |
| 750 |
self._path = resolved |
| 751 |
|
| 752 |
@property |
| 753 |
def path(self) -> pathlib.Path: |
| 754 |
return self._path |
| 755 |
|
| 756 |
def __call__(self) -> str: |
| 757 |
try: |
| 758 |
content = self._path.read_text(encoding="utf-8").strip() |
| 759 |
except FileNotFoundError as err: |
| 760 |
raise IdentityTokenFileError(f"Identity token file not found at {self._path}.", path=self._path) from err |
| 761 |
except PermissionError as err: |
| 762 |
raise IdentityTokenFileError( |
| 763 |
f"Identity token file at {self._path} is not readable by this process: {err}. " |
| 764 |
f"Check the file mode and the effective uid of the process.", |
| 765 |
path=self._path, |
| 766 |
) from err |
| 767 |
except IsADirectoryError as err: |
| 768 |
raise IdentityTokenFileError( |
| 769 |
f"Identity token path {self._path} is a directory, not a file. " |
| 770 |
f"Point at the projected token file itself.", |
| 771 |
path=self._path, |
| 772 |
) from err |
| 773 |
except (OSError, UnicodeDecodeError) as err: |
| 774 |
raise IdentityTokenFileError( |
| 775 |
f"Identity token file at {self._path} could not be read: {err}", path=self._path |
| 776 |
) from err |
| 777 |
if not content: |
| 778 |
raise IdentityTokenFileError( |
| 779 |
f"Identity token file at {self._path} is empty. " |
| 780 |
f"If this is a Kubernetes projected service-account token, check the " |
| 781 |
f"volume mount and the serviceAccountToken projection audience.", |
| 782 |
path=self._path, |
| 783 |
) |
| 784 |
return content |
| 785 |
|
| 786 |
|
| 787 |
class InMemoryConfig(CredentialsFile): |
| 788 |
"""An `AccessTokenProvider` driven by an in-memory config dict |
| 789 |
(same shape as `configs/<profile>.json`) rather than files on disk. |
| 790 |
|
| 791 |
Intended for callers that want to construct an `anthropic.Anthropic` |
| 792 |
client with a fully programmatic credentials setup — equivalent to the Go |
| 793 |
SDK's `option.WithConfig` / TypeScript SDK's `ClientOptions.config`. |
| 794 |
|
| 795 |
Both `authentication.type` discriminator values are supported: |
| 796 |
|
| 797 |
`"oidc_federation"` |
| 798 |
`authentication.credentials_path` is **optional**. If set, exchanged |
| 799 |
tokens are cached to / read from that file (same atomic 0600 write as |
| 800 |
`CredentialsFile`). If omitted, every call performs a fresh |
| 801 |
jwt-bearer exchange with no on-disk cache. |
| 802 |
|
| 803 |
`"user_oauth"` |
| 804 |
`authentication.credentials_path` is **required** — it is where the |
| 805 |
access/refresh tokens live. Behaviour is identical to a file-backed |
| 806 |
`CredentialsFile` profile of the same shape. |
| 807 |
|
| 808 |
The implementation subclasses `CredentialsFile` so the dispatch, |
| 809 |
refresh-grant, disk-cache and atomic-write logic are shared verbatim; |
| 810 |
only config loading and identity-token resolution are overridden. |
| 811 |
""" |
| 812 |
|
| 813 |
_IN_MEMORY_PATH = pathlib.Path("<in-memory config>") |
| 814 |
|
| 815 |
def __init__( |
| 816 |
self, |
| 817 |
config: Dict[str, Any], |
| 818 |
*, |
| 819 |
identity_token_provider: Optional[IdentityTokenProvider] = None, |
| 820 |
http_client: Optional[httpx2.Client] = None, |
| 821 |
) -> None: |
| 822 |
raw_auth = config.get("authentication") |
| 823 |
if not isinstance(raw_auth, dict): |
| 824 |
raise CredentialsError( |
| 825 |
"config dict is missing the 'authentication' object. " |
| 826 |
f'Expected shape: {{"authentication": {{"type": "{AUTH_TYPE_OIDC_FEDERATION}"' |
| 827 |
f'|"{AUTH_TYPE_USER_OAUTH}", ...}}, ...}}' |
| 828 |
) |
| 829 |
auth = cast("Dict[str, Any]", raw_auth) |
| 830 |
auth_type = auth.get("type") |
| 831 |
if auth_type not in (AUTH_TYPE_OIDC_FEDERATION, AUTH_TYPE_USER_OAUTH): |
| 832 |
raise CredentialsError( |
| 833 |
f"Unknown authentication.type {auth_type!r}. " |
| 834 |
f"Expected {AUTH_TYPE_OIDC_FEDERATION!r} or {AUTH_TYPE_USER_OAUTH!r}." |
| 835 |
) |
| 836 |
|
| 837 |
credentials_path = auth.get("credentials_path") |
| 838 |
if auth_type == AUTH_TYPE_USER_OAUTH and not credentials_path: |
| 839 |
raise CredentialsError( |
| 840 |
f"authentication.type {AUTH_TYPE_USER_OAUTH!r} requires " |
| 841 |
f"'authentication.credentials_path' (where the access/refresh tokens live). " |
| 842 |
f"For profile-based resolution, use CredentialsFile instead." |
| 843 |
) |
| 844 |
|
| 845 |
# CredentialsFile state — set directly rather than calling super().__init__() |
| 846 |
# because the parent constructor reads env/disk for profile resolution. |
| 847 |
self._profile = "<in-memory>" |
| 848 |
self._config_path = self._IN_MEMORY_PATH |
| 849 |
self._bound_base_url: Optional[str] = None |
| 850 |
self._http_client = http_client |
| 851 |
self._owned_http_client: Optional[httpx2.Client] = None |
| 852 |
self._workload_delegate: Optional[WorkloadIdentityCredentials] = None |
| 853 |
self._identity_token_provider_override = identity_token_provider |
| 854 |
|
| 855 |
self._config = config |
| 856 |
self._credentials_path = pathlib.Path(str(credentials_path)).expanduser() if credentials_path else None |
| 857 |
self._base_url = self._resolve_base_url(config) |
| 858 |
_require_https(self._base_url, field="config: base_url") |
| 859 |
|
| 860 |
@override |
| 861 |
def _load_config(self) -> Dict[str, Any]: |
| 862 |
assert self._config is not None |
| 863 |
return self._config |
| 864 |
|
| 865 |
@override |
| 866 |
def reload(self) -> None: |
| 867 |
# Config is fixed at construction; only drop the workload delegate so |
| 868 |
# a re-exchange picks up rotated identity-token state. |
| 869 |
self._workload_delegate = None |
| 870 |
|
| 871 |
@override |
| 872 |
def _build_workload_delegate(self, auth: Dict[str, Any]) -> WorkloadIdentityCredentials: |
| 873 |
if self._identity_token_provider_override is None: |
| 874 |
return super()._build_workload_delegate(auth) |
| 875 |
|
| 876 |
from ._workload import WorkloadIdentityError, WorkloadIdentityCredentials |
| 877 |
|
| 878 |
federation_rule_id = auth.get("federation_rule_id") |
| 879 |
assert self._config is not None |
| 880 |
organization_id = self._config.get("organization_id") |
| 881 |
if not federation_rule_id or not organization_id: |
| 882 |
raise WorkloadIdentityError( |
| 883 |
f"config dict with authentication.type {AUTH_TYPE_OIDC_FEDERATION!r} must include " |
| 884 |
f"'authentication.federation_rule_id' and top-level 'organization_id'" |
| 885 |
) |
| 886 |
delegate = WorkloadIdentityCredentials( |
| 887 |
identity_token_provider=self._identity_token_provider_override, |
| 888 |
federation_rule_id=federation_rule_id, |
| 889 |
organization_id=organization_id, |
| 890 |
service_account_id=auth.get("service_account_id"), |
| 891 |
workspace_id=self._config.get("workspace_id"), |
| 892 |
scope=auth.get("scope"), |
| 893 |
http_client=self._get_http_client(), |
| 894 |
) |
| 895 |
delegate.bind_base_url(self._base_url) |
| 896 |
return delegate |