| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
from typing import Optional |
| 5 |
|
| 6 |
from ._types import CredentialResult, IdentityTokenProvider |
| 7 |
from ._workload import WorkloadIdentityCredentials |
| 8 |
from ._constants import ( |
| 9 |
ENV_SCOPE, |
| 10 |
ENV_API_KEY, |
| 11 |
ENV_PROFILE, |
| 12 |
ENV_AUTH_TOKEN, |
| 13 |
ENV_CONFIG_DIR, |
| 14 |
ENV_WORKSPACE_ID, |
| 15 |
ENV_IDENTITY_TOKEN, |
| 16 |
ENV_ORGANIZATION_ID, |
| 17 |
ENV_FEDERATION_RULE_ID, |
| 18 |
ENV_SERVICE_ACCOUNT_ID, |
| 19 |
_has_active_profile_config, |
| 20 |
_has_explicit_active_config, |
| 21 |
resolve_identity_token_path, |
| 22 |
) |
| 23 |
from ._providers import StaticToken, CredentialsFile, IdentityTokenFile |
| 24 |
from ..._exceptions import AnthropicError, CredentialsError |
| 25 |
|
| 26 |
__all__ = ["default_credentials"] |
| 27 |
|
| 28 |
|
| 29 |
def _build_federation_result(*, base_url: str) -> Optional[CredentialResult]: |
| 30 |
"""Build a `CredentialResult` for the env-var federation path |
| 31 |
(step 4 in the precedence spec). Returns `None` if the required trio |
| 32 |
isn't fully set.""" |
| 33 |
federation_rule_id = os.environ.get(ENV_FEDERATION_RULE_ID) |
| 34 |
organization_id = os.environ.get(ENV_ORGANIZATION_ID) |
| 35 |
has_literal_token = ENV_IDENTITY_TOKEN in os.environ |
| 36 |
identity_token_path = resolve_identity_token_path() |
| 37 |
|
| 38 |
if not federation_rule_id or not organization_id: |
| 39 |
return None |
| 40 |
if not has_literal_token and identity_token_path is None: |
| 41 |
return None |
| 42 |
|
| 43 |
identity_provider: IdentityTokenProvider |
| 44 |
if identity_token_path is not None: |
| 45 |
identity_provider = IdentityTokenFile(identity_token_path) |
| 46 |
else: |
| 47 |
# Read the env var on every call so a rotated value is picked up |
| 48 |
# at the next token exchange (don't capture into a closure). |
| 49 |
def _read_env_token() -> str: |
| 50 |
value = os.environ.get(ENV_IDENTITY_TOKEN) |
| 51 |
if value is None: |
| 52 |
raise CredentialsError( |
| 53 |
f"{ENV_IDENTITY_TOKEN} is not set; the workload-identity chain " |
| 54 |
f"selected this provider at construction time but the env var " |
| 55 |
f"is no longer present." |
| 56 |
) |
| 57 |
return value |
| 58 |
|
| 59 |
identity_provider = _read_env_token |
| 60 |
|
| 61 |
provider = WorkloadIdentityCredentials( |
| 62 |
identity_token_provider=identity_provider, |
| 63 |
federation_rule_id=federation_rule_id, |
| 64 |
organization_id=organization_id, |
| 65 |
service_account_id=os.environ.get(ENV_SERVICE_ACCOUNT_ID), |
| 66 |
# Coerce empty string to None so a defaulted-but-empty CI variable |
| 67 |
# doesn't put `"workspace_id": ""` on the wire — matches the falsy |
| 68 |
# skip in `._providers._fill_missing_from_env`. |
| 69 |
workspace_id=os.environ.get(ENV_WORKSPACE_ID) or None, |
| 70 |
scope=os.environ.get(ENV_SCOPE), |
| 71 |
) |
| 72 |
provider.bind_base_url(base_url) |
| 73 |
return CredentialResult(provider=provider) |
| 74 |
|
| 75 |
|
| 76 |
def default_credentials(*, base_url: str = "https://api.anthropic.com") -> Optional[CredentialResult]: |
| 77 |
"""Resolve a `CredentialResult` from the environment per the |
| 78 |
credential-resolution spec. First match wins. |
| 79 |
|
| 80 |
Implements steps 2-5 of the spec precedence chain (step 1 is handled at |
| 81 |
the client constructor level, above this function): |
| 82 |
|
| 83 |
Step 2a: `ANTHROPIC_API_KEY` → return `None` so the client uses its |
| 84 |
existing `X-Api-Key` header path. (API keys are not Bearer |
| 85 |
tokens, so they can't flow through this chain.) |
| 86 |
Step 2b: `ANTHROPIC_AUTH_TOKEN` → `StaticToken` (Bearer). |
| 87 |
Step 3: `ANTHROPIC_PROFILE` / `ANTHROPIC_CONFIG_DIR` set, or the |
| 88 |
`active_config` pointer file exists → load that profile. |
| 89 |
This is *explicit profile selection*; failures propagate. |
| 90 |
Step 4: `ANTHROPIC_FEDERATION_RULE_ID` + `ANTHROPIC_ORGANIZATION_ID` |
| 91 |
+ `ANTHROPIC_IDENTITY_TOKEN[_FILE]` → direct jwt-bearer |
| 92 |
exchange via `WorkloadIdentityCredentials`. Critically, |
| 93 |
step 4 sits **between** explicit profile (step 3) and |
| 94 |
fallback profile (step 5): a machine with WIF env vars wired |
| 95 |
up must use WIF even if a leftover `default` profile exists |
| 96 |
on disk, but a user who explicitly `ANTHROPIC_PROFILE=dev` |
| 97 |
still gets their profile. |
| 98 |
Step 5: Fallback active profile from disk (`configs/default.json` |
| 99 |
or whatever `active_config` points at). Errors at this step |
| 100 |
are swallowed and the chain falls through — a corrupt |
| 101 |
unselected profile shouldn't break an otherwise-explicit |
| 102 |
api_key= path. |
| 103 |
|
| 104 |
Returns `None` when nothing matches — the client will fall back to |
| 105 |
its normal "no auth configured" error. |
| 106 |
""" |
| 107 |
# Step 2a — env api_key: return None so the base client handles X-Api-Key. |
| 108 |
if os.environ.get(ENV_API_KEY): |
| 109 |
return None |
| 110 |
|
| 111 |
# Step 2b — env auth_token: static bearer. |
| 112 |
auth_token = os.environ.get(ENV_AUTH_TOKEN) |
| 113 |
if auth_token: |
| 114 |
return CredentialResult(provider=StaticToken(auth_token)) |
| 115 |
|
| 116 |
# Step 3 — explicit profile selection (ANTHROPIC_PROFILE / ANTHROPIC_CONFIG_DIR |
| 117 |
# / active_config pointer). Failures propagate — a user who explicitly |
| 118 |
# names a profile expects a broken config to surface, not to fall through. |
| 119 |
env_explicit = bool(os.environ.get(ENV_PROFILE) or os.environ.get(ENV_CONFIG_DIR)) |
| 120 |
pointer_explicit = _has_explicit_active_config() |
| 121 |
if env_explicit or pointer_explicit: |
| 122 |
creds_file = CredentialsFile() |
| 123 |
creds_file.bind_base_url(base_url) |
| 124 |
extra_headers = creds_file.extra_headers() |
| 125 |
return CredentialResult( |
| 126 |
provider=creds_file, |
| 127 |
extra_headers=extra_headers, |
| 128 |
base_url=creds_file.resolved_base_url, |
| 129 |
) |
| 130 |
|
| 131 |
# Step 4 — env-var workload identity federation. Sits above the |
| 132 |
# fallback on-disk profile so a machine with WIF env vars uses WIF |
| 133 |
# even if a leftover `default` profile exists on disk. |
| 134 |
federation_result = _build_federation_result(base_url=base_url) |
| 135 |
if federation_result is not None: |
| 136 |
return federation_result |
| 137 |
|
| 138 |
# Step 5 — fallback active profile from disk. Errors are swallowed and |
| 139 |
# the chain falls through because the user didn't explicitly select |
| 140 |
# this profile; a corrupt auto-discovered config shouldn't break |
| 141 |
# construction. |
| 142 |
if _has_active_profile_config(): |
| 143 |
creds_file = CredentialsFile() |
| 144 |
creds_file.bind_base_url(base_url) |
| 145 |
try: |
| 146 |
extra_headers = creds_file.extra_headers() |
| 147 |
except AnthropicError: |
| 148 |
return None |
| 149 |
return CredentialResult( |
| 150 |
provider=creds_file, |
| 151 |
extra_headers=extra_headers, |
| 152 |
base_url=creds_file.resolved_base_url, |
| 153 |
) |
| 154 |
|
| 155 |
return None |