| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import sys |
| 5 |
import pathlib |
| 6 |
from typing import Optional |
| 7 |
|
| 8 |
from ..._exceptions import AnthropicError, CredentialsError |
| 9 |
|
| 10 |
GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer" |
| 11 |
GRANT_TYPE_REFRESH_TOKEN = "refresh_token" |
| 12 |
TOKEN_ENDPOINT = "/v1/oauth/token" |
| 13 |
|
| 14 |
# Seconds to wait on the /v1/oauth/token POST before giving up. Tokens are cheap |
| 15 |
# to mint and the handler is fast; a long timeout mostly means a sick backend. |
| 16 |
TOKEN_EXCHANGE_TIMEOUT = 30.0 |
| 17 |
|
| 18 |
# Beta header required on any authenticated API request that uses a Bearer |
| 19 |
# token obtained via OAuth/federation (unlocks `Authorization: Bearer` auth |
| 20 |
# at all), and on refresh_token grants against /v1/oauth/token. |
| 21 |
OAUTH_API_BETA_HEADER = "oauth-2025-04-20" |
| 22 |
|
| 23 |
# Beta header routing switch for /v1/oauth/token jwt-bearer grants. Presence |
| 24 |
# routes the POST to the api-go userauth handler (jwt-bearer only); absence |
| 25 |
# routes it to the Python oauth_server (authorization_code / refresh_token). |
| 26 |
# MUST only be sent on jwt-bearer exchanges — sending it on refresh_token would |
| 27 |
# misroute the request to userauth and fail with "unsupported grant_type". |
| 28 |
FEDERATION_BETA_HEADER = "oidc-federation-2026-04-01" |
| 29 |
|
| 30 |
# Proactive refresh thresholds (seconds before expiry). Tuned for ≤10min token TTL. |
| 31 |
ADVISORY_REFRESH_SECONDS = 120 |
| 32 |
MANDATORY_REFRESH_SECONDS = 30 |
| 33 |
|
| 34 |
DEFAULT_PROFILE = "default" |
| 35 |
DEFAULT_BASE_URL = "https://api.anthropic.com" |
| 36 |
|
| 37 |
# Env vars — explicit auth (tier 0) |
| 38 |
ENV_API_KEY = "ANTHROPIC_API_KEY" |
| 39 |
ENV_AUTH_TOKEN = "ANTHROPIC_AUTH_TOKEN" |
| 40 |
|
| 41 |
# Env vars — config dir + profile selection (tier 1) |
| 42 |
ENV_CONFIG_DIR = "ANTHROPIC_CONFIG_DIR" |
| 43 |
ENV_PROFILE = "ANTHROPIC_PROFILE" |
| 44 |
|
| 45 |
# Env vars — direct workload identity, bypassing config files (tier 2) |
| 46 |
ENV_IDENTITY_TOKEN = "ANTHROPIC_IDENTITY_TOKEN" |
| 47 |
ENV_IDENTITY_TOKEN_FILE = "ANTHROPIC_IDENTITY_TOKEN_FILE" |
| 48 |
ENV_FEDERATION_RULE_ID = "ANTHROPIC_FEDERATION_RULE_ID" |
| 49 |
ENV_ORGANIZATION_ID = "ANTHROPIC_ORGANIZATION_ID" |
| 50 |
ENV_SERVICE_ACCOUNT_ID = "ANTHROPIC_SERVICE_ACCOUNT_ID" |
| 51 |
ENV_WORKSPACE_ID = "ANTHROPIC_WORKSPACE_ID" |
| 52 |
ENV_SCOPE = "ANTHROPIC_SCOPE" |
| 53 |
ENV_BASE_URL = "ANTHROPIC_BASE_URL" |
| 54 |
|
| 55 |
|
| 56 |
def _user_agent() -> str: # pyright: ignore[reportUnusedFunction] — used by _workload/_providers |
| 57 |
"""`User-Agent` value sent on token-endpoint POSTs. |
| 58 |
|
| 59 |
Computed lazily so this module doesn't need to import `_version` at |
| 60 |
module load time (the credentials package is otherwise import-light). |
| 61 |
""" |
| 62 |
from ..._version import __version__ |
| 63 |
|
| 64 |
return f"anthropic-python/{__version__}" |
| 65 |
|
| 66 |
|
| 67 |
def _config_dir() -> pathlib.Path: |
| 68 |
"""Resolve the config directory. |
| 69 |
|
| 70 |
`ANTHROPIC_CONFIG_DIR` env var → platform default. |
| 71 |
|
| 72 |
Platform defaults: |
| 73 |
* Linux & macOS: `~/.config/anthropic/` — XDG-style on both platforms |
| 74 |
for consistency across SDKs (macOS does **not** use |
| 75 |
`~/Library/Application Support/`). |
| 76 |
* Windows: `%APPDATA%\\Anthropic\\` |
| 77 |
""" |
| 78 |
env = os.environ.get(ENV_CONFIG_DIR) |
| 79 |
if env: |
| 80 |
return pathlib.Path(env) |
| 81 |
if sys.platform == "win32": |
| 82 |
appdata = os.environ.get("APPDATA") |
| 83 |
base = pathlib.Path(appdata) if appdata else pathlib.Path.home() / "AppData" / "Roaming" |
| 84 |
return base / "Anthropic" |
| 85 |
return pathlib.Path.home() / ".config" / "anthropic" |
| 86 |
|
| 87 |
|
| 88 |
def _read_active_config_pointer() -> Optional[str]: |
| 89 |
"""Return the stripped contents of `<config_dir>/active_config`, or `None` |
| 90 |
if the pointer file is missing or empty.""" |
| 91 |
try: |
| 92 |
name = (_config_dir() / "active_config").read_text(encoding="utf-8").strip() |
| 93 |
except OSError: |
| 94 |
return None |
| 95 |
return name or None |
| 96 |
|
| 97 |
|
| 98 |
def _active_profile() -> str: # pyright: ignore[reportUnusedFunction] — used by _providers |
| 99 |
"""Resolve the active profile name. |
| 100 |
|
| 101 |
`ANTHROPIC_PROFILE` env var → `<config_dir>/active_config` pointer file |
| 102 |
→ `"default"` literal. The resolved name is validated against path- |
| 103 |
traversal patterns before being returned. |
| 104 |
""" |
| 105 |
env = os.environ.get(ENV_PROFILE) |
| 106 |
if env: |
| 107 |
_validate_profile_name(env, source=ENV_PROFILE) |
| 108 |
return env |
| 109 |
name = _read_active_config_pointer() |
| 110 |
if name is None: |
| 111 |
return DEFAULT_PROFILE |
| 112 |
_validate_profile_name(name, source="active_config pointer file") |
| 113 |
return name |
| 114 |
|
| 115 |
|
| 116 |
def _require_https(url: str, *, field: str) -> None: # pyright: ignore[reportUnusedFunction] — used by _workload/_providers |
| 117 |
"""Reject non-`https://` token-endpoint URLs. |
| 118 |
|
| 119 |
Localhost is allowed for testing so `base_url="http://localhost:8080"` |
| 120 |
works against a local `oauth_server` instance; everything else must be |
| 121 |
TLS-encrypted because the body of these POSTs carries the assertion JWT |
| 122 |
or a long-lived refresh token. |
| 123 |
""" |
| 124 |
lowered = url.lower().rstrip("/") |
| 125 |
if lowered.startswith("https://"): |
| 126 |
return |
| 127 |
if lowered.startswith(("http://localhost", "http://127.0.0.1", "http://[::1]")): |
| 128 |
return |
| 129 |
raise CredentialsError( |
| 130 |
f"{field} must use https (got {url!r}); the token-exchange endpoint " |
| 131 |
f"carries secret material and cannot be used over cleartext HTTP." |
| 132 |
) |
| 133 |
|
| 134 |
|
| 135 |
def _validate_profile_name(profile: str, *, source: str = "profile name") -> None: |
| 136 |
"""Reject profile names that could escape the config directory. |
| 137 |
|
| 138 |
Profile names come from user-controlled sources (`ANTHROPIC_PROFILE`, |
| 139 |
the `active_config` pointer file, `CredentialsFile(profile=...)`) and |
| 140 |
are interpolated into filesystem paths. A value like `"../../etc/shadow"` |
| 141 |
would otherwise let a read of `configs/<profile>.json` escape the config |
| 142 |
root entirely. Pass `source=` so the error message names where the bad |
| 143 |
value came from. |
| 144 |
""" |
| 145 |
if not profile: |
| 146 |
raise CredentialsError(f"{source} must not be empty.") |
| 147 |
if profile != profile.strip(): |
| 148 |
raise CredentialsError(f"{source} {profile!r} has leading or trailing whitespace.") |
| 149 |
if profile.startswith("."): |
| 150 |
raise CredentialsError(f"{source} {profile!r} must not start with a dot.") |
| 151 |
for sep in ("/", "\\", os.sep): |
| 152 |
if sep and sep in profile: |
| 153 |
raise CredentialsError( |
| 154 |
f"{source} {profile!r} must not contain path separators — " |
| 155 |
f"profiles are filenames under the config directory. Pick a name without {sep!r}." |
| 156 |
) |
| 157 |
if "\x00" in profile: |
| 158 |
raise CredentialsError(f"{source} {profile!r} must not contain null bytes.") |
| 159 |
|
| 160 |
|
| 161 |
def _resolve_under(base: pathlib.Path, candidate: pathlib.Path) -> pathlib.Path: |
| 162 |
"""Assert `candidate` resolves to a descendant of `base`, return it verbatim. |
| 163 |
|
| 164 |
The containment check uses `resolve(strict=False)` on both sides so |
| 165 |
symlinks and `..` segments are normalized for the purposes of escape |
| 166 |
detection. The returned path is the *original* (unresolved) candidate — |
| 167 |
callers that care about symlink following must handle it themselves |
| 168 |
(e.g. `os.stat(follow_symlinks=False)`). |
| 169 |
""" |
| 170 |
base_resolved = base.resolve(strict=False) |
| 171 |
candidate_resolved = candidate.resolve(strict=False) |
| 172 |
try: |
| 173 |
candidate_resolved.relative_to(base_resolved) |
| 174 |
except ValueError as err: |
| 175 |
raise CredentialsError(f"Resolved path {candidate_resolved} escapes config directory {base_resolved}.") from err |
| 176 |
return candidate |
| 177 |
|
| 178 |
|
| 179 |
def _config_file_path(profile: str) -> pathlib.Path: # pyright: ignore[reportUnusedFunction] — used by _providers |
| 180 |
"""Path to `<config_dir>/configs/<profile>.json` (non-secret, 0644).""" |
| 181 |
_validate_profile_name(profile) |
| 182 |
base = _config_dir() |
| 183 |
return _resolve_under(base, base / "configs" / f"{profile}.json") |
| 184 |
|
| 185 |
|
| 186 |
def _credentials_file_path(profile: str) -> pathlib.Path: # pyright: ignore[reportUnusedFunction] — used by _providers |
| 187 |
"""Path to `<config_dir>/credentials/<profile>.json` (secret, 0600).""" |
| 188 |
_validate_profile_name(profile) |
| 189 |
base = _config_dir() |
| 190 |
return _resolve_under(base, base / "credentials" / f"{profile}.json") |
| 191 |
|
| 192 |
|
| 193 |
def _has_active_profile_config() -> bool: # pyright: ignore[reportUnusedFunction] — used by _chain |
| 194 |
"""Tighter auto-discover check for the tier-1 credential chain. |
| 195 |
|
| 196 |
Returns `True` only if the *active* profile's config file exists. The |
| 197 |
previous version returned `True` for any `.json` under `configs/`, |
| 198 |
which meant a stray `configs/work.json` on disk was enough to steer |
| 199 |
`default_credentials()` into reading `configs/default.json` and |
| 200 |
failing because `default.json` wasn't there. |
| 201 |
""" |
| 202 |
try: |
| 203 |
return _config_file_path(_active_profile()).is_file() |
| 204 |
except (OSError, AnthropicError): |
| 205 |
return False |
| 206 |
|
| 207 |
|
| 208 |
def _has_explicit_active_config() -> bool: # pyright: ignore[reportUnusedFunction] — used by _chain |
| 209 |
"""True if the user wrote a non-empty `active_config` pointer file. |
| 210 |
|
| 211 |
This is an explicit opt-in signal equivalent to setting `ANTHROPIC_PROFILE`: |
| 212 |
the user has told us which profile to load. If the target config file is |
| 213 |
missing or malformed, the chain should surface that error rather than |
| 214 |
silently falling through — matching how `ANTHROPIC_PROFILE=missing` |
| 215 |
behaves today. |
| 216 |
""" |
| 217 |
return _read_active_config_pointer() is not None |
| 218 |
|
| 219 |
|
| 220 |
def resolve_identity_token_path(path: str | os.PathLike[str] | None = None) -> pathlib.Path | None: |
| 221 |
"""ctor arg → `ANTHROPIC_IDENTITY_TOKEN_FILE` → `None`.""" |
| 222 |
if path is not None: |
| 223 |
return pathlib.Path(path) |
| 224 |
env = os.environ.get(ENV_IDENTITY_TOKEN_FILE) |
| 225 |
if env: |
| 226 |
return pathlib.Path(env) |
| 227 |
return None |
| 228 |
|
| 229 |
|
| 230 |
def _has_auto_discoverable_credentials() -> bool: # pyright: ignore[reportUnusedFunction] — used by _client |
| 231 |
"""True if the environment / filesystem contains signals that would |
| 232 |
normally drive the tier-1 (profile) or tier-2 (env federation) paths of |
| 233 |
`default_credentials`. |
| 234 |
|
| 235 |
Used by the shadow-warning detection in the client constructor: if a |
| 236 |
static `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` is set alongside |
| 237 |
any of these signals, the auto-discovery would have yielded a credential |
| 238 |
but got silently shadowed — and the user should know. |
| 239 |
""" |
| 240 |
if os.environ.get(ENV_PROFILE) or os.environ.get(ENV_CONFIG_DIR): |
| 241 |
return True |
| 242 |
if _has_explicit_active_config(): |
| 243 |
return True |
| 244 |
if os.environ.get(ENV_FEDERATION_RULE_ID) and os.environ.get(ENV_ORGANIZATION_ID): |
| 245 |
if os.environ.get(ENV_IDENTITY_TOKEN_FILE) or os.environ.get(ENV_IDENTITY_TOKEN): |
| 246 |
return True |
| 247 |
return False |