| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import sys |
| 5 |
import copy |
| 6 |
import json |
| 7 |
import time |
| 8 |
import asyncio |
| 9 |
import logging |
| 10 |
import pathlib |
| 11 |
import functools |
| 12 |
import itertools |
| 13 |
import threading |
| 14 |
from typing import Any, Dict, List, Callable, Optional, NamedTuple, cast |
| 15 |
from unittest.mock import MagicMock |
| 16 |
from typing_extensions import Protocol |
| 17 |
|
| 18 |
import httpx2 |
| 19 |
import pytest |
| 20 |
from respx import MockRouter |
| 21 |
|
| 22 |
import anthropic |
| 23 |
from anthropic import ( |
| 24 |
EnvToken, |
| 25 |
Anthropic, |
| 26 |
TokenCache, |
| 27 |
AccessToken, |
| 28 |
StaticToken, |
| 29 |
AnthropicError, |
| 30 |
AsyncAnthropic, |
| 31 |
InMemoryConfig, |
| 32 |
CredentialsFile, |
| 33 |
CredentialsError, |
| 34 |
IdentityTokenFile, |
| 35 |
WorkloadIdentityError, |
| 36 |
IdentityTokenFileError, |
| 37 |
WorkloadIdentityCredentials, |
| 38 |
default_credentials, |
| 39 |
exchange_federation_assertion, |
| 40 |
) |
| 41 |
from anthropic._version import __version__ |
| 42 |
from anthropic._base_client import FinalRequestOptions |
| 43 |
from anthropic.lib.credentials import BaseURLBoundProvider |
| 44 |
from anthropic.lib.credentials._types import is_async_token_provider |
| 45 |
from anthropic.lib.credentials._constants import ( |
| 46 |
TOKEN_ENDPOINT, |
| 47 |
GRANT_TYPE_JWT_BEARER, |
| 48 |
OAUTH_API_BETA_HEADER, |
| 49 |
FEDERATION_BETA_HEADER, |
| 50 |
) |
| 51 |
|
| 52 |
BASE_URL = "https://api.anthropic.com" |
| 53 |
TOKEN_URL = f"{BASE_URL}{TOKEN_ENDPOINT}" |
| 54 |
# A second deployment, for tests that build clients against two hosts at once. |
| 55 |
OTHER_BASE_URL = "https://api.other.example" |
| 56 |
OTHER_TOKEN_URL = f"{OTHER_BASE_URL}{TOKEN_ENDPOINT}" |
| 57 |
|
| 58 |
_ALL_ENV = [ |
| 59 |
"ANTHROPIC_API_KEY", |
| 60 |
"ANTHROPIC_AUTH_TOKEN", |
| 61 |
"ANTHROPIC_CONFIG_DIR", |
| 62 |
"ANTHROPIC_PROFILE", |
| 63 |
"ANTHROPIC_IDENTITY_TOKEN", |
| 64 |
"ANTHROPIC_IDENTITY_TOKEN_FILE", |
| 65 |
"ANTHROPIC_FEDERATION_RULE_ID", |
| 66 |
"ANTHROPIC_ORGANIZATION_ID", |
| 67 |
"ANTHROPIC_SERVICE_ACCOUNT_ID", |
| 68 |
"ANTHROPIC_WORKSPACE_ID", |
| 69 |
"ANTHROPIC_SCOPE", |
| 70 |
] |
| 71 |
|
| 72 |
|
| 73 |
class MockRequestCall(Protocol): |
| 74 |
request: httpx2.Request |
| 75 |
|
| 76 |
|
| 77 |
@pytest.fixture |
| 78 |
def clean_env(monkeypatch: pytest.MonkeyPatch) -> pytest.MonkeyPatch: |
| 79 |
for var in _ALL_ENV: |
| 80 |
monkeypatch.delenv(var, raising=False) |
| 81 |
return monkeypatch |
| 82 |
|
| 83 |
|
| 84 |
@pytest.fixture |
| 85 |
def no_default_creds_file(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 86 |
"""Point the config directory at an empty location so a real |
| 87 |
~/.config/anthropic/ on the dev machine doesn't leak into tests. |
| 88 |
|
| 89 |
Patches `_config_dir` directly rather than setting `ANTHROPIC_CONFIG_DIR` |
| 90 |
so that `clean_env` (which deletes that env var) can't clobber the isolation. |
| 91 |
""" |
| 92 |
empty = tmp_path / "empty-config-dir" |
| 93 |
empty.mkdir() |
| 94 |
monkeypatch.setattr("anthropic.lib.credentials._constants._config_dir", lambda: empty) |
| 95 |
|
| 96 |
|
| 97 |
# Field names that live at the top level of the new nested config shape |
| 98 |
# (outside the `authentication` object). |
| 99 |
_TOP_LEVEL_CONFIG_KEYS = {"base_url", "organization_id", "workspace_id"} |
| 100 |
|
| 101 |
|
| 102 |
def _migrate_legacy_config(flat: Dict[str, Any]) -> Dict[str, Any]: |
| 103 |
"""Adapter: convert a flat legacy config dict into the new nested shape. |
| 104 |
|
| 105 |
Many tests in this file predate the schema migration and pass legacy |
| 106 |
flat configs like `{"type": "workload_identity", "federation_rule_id": ...}`. |
| 107 |
Rather than churn every caller, this helper translates at the test-helper |
| 108 |
layer — tests that want to assert against the new shape directly can |
| 109 |
pass a config dict that already contains an `"authentication"` key. |
| 110 |
""" |
| 111 |
result: Dict[str, Any] = {} |
| 112 |
auth: Dict[str, Any] = {} |
| 113 |
for key, value in flat.items(): |
| 114 |
if key == "type": |
| 115 |
continue |
| 116 |
if key in _TOP_LEVEL_CONFIG_KEYS: |
| 117 |
result[key] = value |
| 118 |
else: |
| 119 |
auth[key] = value |
| 120 |
|
| 121 |
# "external" used to mean "token already in credentials file, no |
| 122 |
# refresh" — the new schema expresses this as user_oauth without a |
| 123 |
# client_id (the key "external → user_oauth" both preserves the daemon |
| 124 |
# semantics and keeps auth-only fields like credentials_path intact). |
| 125 |
# "workload_identity" / "authorized_user" were renamed. |
| 126 |
auth["type"] = { |
| 127 |
"external": "user_oauth", |
| 128 |
"workload_identity": "oidc_federation", |
| 129 |
"authorized_user": "user_oauth", |
| 130 |
}.get(flat["type"], flat["type"]) |
| 131 |
|
| 132 |
result["authentication"] = auth |
| 133 |
return result |
| 134 |
|
| 135 |
|
| 136 |
def _write_profile( |
| 137 |
config_dir: pathlib.Path, |
| 138 |
profile: str, |
| 139 |
config: Dict[str, Any], |
| 140 |
credentials: Optional[Dict[str, Any]] = None, |
| 141 |
) -> None: |
| 142 |
"""Test helper: lay out `configs/<profile>.json` and optionally |
| 143 |
`credentials/<profile>.json` under `config_dir`. |
| 144 |
|
| 145 |
Accepts either the new nested `{"authentication": {...}}` shape or a |
| 146 |
legacy flat shape (`{"type": "workload_identity", ...}`) for backwards |
| 147 |
compatibility with the tests that predate the schema migration. Legacy |
| 148 |
inputs are translated via `_migrate_legacy_config` before being |
| 149 |
written to disk. |
| 150 |
|
| 151 |
Prepends `"type": "oauth_token"` to the credentials dict unless the |
| 152 |
caller already supplied a `type` key (so negative tests can override). |
| 153 |
""" |
| 154 |
if "type" in config and "authentication" not in config: |
| 155 |
config = _migrate_legacy_config(config) |
| 156 |
(config_dir / "configs").mkdir(parents=True, exist_ok=True) |
| 157 |
(config_dir / "configs" / f"{profile}.json").write_text(json.dumps(config)) |
| 158 |
if credentials is not None: |
| 159 |
if "type" not in credentials: |
| 160 |
credentials = {"type": "oauth_token", **credentials} |
| 161 |
(config_dir / "credentials").mkdir(parents=True, exist_ok=True) |
| 162 |
creds_path = config_dir / "credentials" / f"{profile}.json" |
| 163 |
creds_path.write_text(json.dumps(credentials)) |
| 164 |
# Match the 0o600 invariant the real credentials reader now enforces. |
| 165 |
creds_path.chmod(0o600) |
| 166 |
|
| 167 |
|
| 168 |
# --------------------------------------------------------------------------- # |
| 169 |
# Basic providers |
| 170 |
# --------------------------------------------------------------------------- # |
| 171 |
|
| 172 |
|
| 173 |
class TestAccessToken: |
| 174 |
def test_defaults(self) -> None: |
| 175 |
tok = AccessToken("abc") |
| 176 |
assert tok.token == "abc" |
| 177 |
assert tok.expires_at is None |
| 178 |
|
| 179 |
def test_with_expiry(self) -> None: |
| 180 |
tok = AccessToken("abc", expires_at=123) |
| 181 |
assert tok.expires_at == 123 |
| 182 |
|
| 183 |
|
| 184 |
class TestBaseURLBoundProvider: |
| 185 |
def test_deployment_bound_providers_implement_it(self) -> None: |
| 186 |
assert isinstance(_workload_credentials(), BaseURLBoundProvider) |
| 187 |
assert isinstance(CredentialsFile("default"), BaseURLBoundProvider) |
| 188 |
assert issubclass(InMemoryConfig, CredentialsFile) |
| 189 |
|
| 190 |
def test_other_providers_do_not(self) -> None: |
| 191 |
assert not isinstance(StaticToken("tok"), BaseURLBoundProvider) |
| 192 |
assert not isinstance(EnvToken(), BaseURLBoundProvider) |
| 193 |
|
| 194 |
|
| 195 |
class TestStaticToken: |
| 196 |
def test_returns_token(self) -> None: |
| 197 |
p = StaticToken("sk-ant-oat01-static") |
| 198 |
assert p() == AccessToken("sk-ant-oat01-static", None) |
| 199 |
assert p().expires_at is None |
| 200 |
|
| 201 |
|
| 202 |
class TestEnvToken: |
| 203 |
def test_reads_env(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 204 |
monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "env-token") |
| 205 |
assert EnvToken()().token == "env-token" |
| 206 |
|
| 207 |
def test_raises_when_missing(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 208 |
monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False) |
| 209 |
with pytest.raises(AnthropicError, match="ANTHROPIC_AUTH_TOKEN"): |
| 210 |
EnvToken()() |
| 211 |
|
| 212 |
|
| 213 |
class TestIdentityTokenFile: |
| 214 |
def test_rereads_on_each_call(self, tmp_path: pathlib.Path) -> None: |
| 215 |
f = tmp_path / "token" |
| 216 |
f.write_text("jwt-one\n") |
| 217 |
provider = IdentityTokenFile(f) |
| 218 |
assert provider() == "jwt-one" |
| 219 |
|
| 220 |
f.write_text("jwt-two\n") |
| 221 |
assert provider() == "jwt-two" |
| 222 |
|
| 223 |
def test_reads_env_var_path(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 224 |
f = tmp_path / "token" |
| 225 |
f.write_text("from-env") |
| 226 |
monkeypatch.setenv("ANTHROPIC_IDENTITY_TOKEN_FILE", str(f)) |
| 227 |
assert IdentityTokenFile()() == "from-env" |
| 228 |
|
| 229 |
def test_raises_when_no_path(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 230 |
monkeypatch.delenv("ANTHROPIC_IDENTITY_TOKEN_FILE", raising=False) |
| 231 |
with pytest.raises(AnthropicError, match="ANTHROPIC_IDENTITY_TOKEN_FILE"): |
| 232 |
IdentityTokenFile() |
| 233 |
|
| 234 |
def test_raises_when_file_missing(self, tmp_path: pathlib.Path) -> None: |
| 235 |
path = tmp_path / "nope" |
| 236 |
with pytest.raises(IdentityTokenFileError, match="not found") as exc_info: |
| 237 |
IdentityTokenFile(path)() |
| 238 |
# Subclasses AnthropicError so existing handlers keep matching. |
| 239 |
assert isinstance(exc_info.value, CredentialsError) |
| 240 |
assert isinstance(exc_info.value, AnthropicError) |
| 241 |
assert exc_info.value.path == path |
| 242 |
assert isinstance(exc_info.value.__cause__, OSError) |
| 243 |
assert copy.copy(exc_info.value).path == path |
| 244 |
|
| 245 |
|
| 246 |
class TestCredentialsFile: |
| 247 |
"""All tests use `ANTHROPIC_CONFIG_DIR` to point at a tmp directory laid |
| 248 |
out as `configs/<profile>.json` + `credentials/<profile>.json`.""" |
| 249 |
|
| 250 |
@pytest.fixture(autouse=True) |
| 251 |
def _isolate(self, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 252 |
for var in _ALL_ENV: |
| 253 |
monkeypatch.delenv(var, raising=False) |
| 254 |
monkeypatch.setenv("ANTHROPIC_CONFIG_DIR", str(tmp_path)) |
| 255 |
|
| 256 |
# -- "type": "external" ------------------------------------------------ |
| 257 |
|
| 258 |
def test_external(self, tmp_path: pathlib.Path) -> None: |
| 259 |
_write_profile( |
| 260 |
tmp_path, |
| 261 |
"default", |
| 262 |
config={"type": "external"}, |
| 263 |
credentials={"access_token": "sk-ant-oat01-x", "expires_at": 1775000000}, |
| 264 |
) |
| 265 |
tok = CredentialsFile()() |
| 266 |
assert tok.token == "sk-ant-oat01-x" |
| 267 |
assert tok.expires_at == 1775000000 |
| 268 |
|
| 269 |
def test_external_no_expiry(self, tmp_path: pathlib.Path) -> None: |
| 270 |
_write_profile(tmp_path, "default", {"type": "external"}, {"access_token": "sk-ant-oat01-x"}) |
| 271 |
assert CredentialsFile()().expires_at is None |
| 272 |
|
| 273 |
def test_external_rereads_credentials_on_each_call(self, tmp_path: pathlib.Path) -> None: |
| 274 |
"""An external process rotates the credentials file; config stays fixed.""" |
| 275 |
_write_profile(tmp_path, "default", {"type": "external"}, {"access_token": "first"}) |
| 276 |
provider = CredentialsFile() |
| 277 |
assert provider().token == "first" |
| 278 |
|
| 279 |
# External rotation: rewrite credentials only. |
| 280 |
(tmp_path / "credentials" / "default.json").write_text(json.dumps({"access_token": "second"})) |
| 281 |
assert provider().token == "second" |
| 282 |
|
| 283 |
def test_external_missing_credentials_file(self, tmp_path: pathlib.Path) -> None: |
| 284 |
_write_profile(tmp_path, "default", {"type": "external"}) # no credentials file |
| 285 |
with pytest.raises(CredentialsError, match="Credentials file not found") as exc_info: |
| 286 |
CredentialsFile()() |
| 287 |
assert isinstance(exc_info.value, AnthropicError) |
| 288 |
|
| 289 |
def test_credentials_file_wrong_type_raises(self, tmp_path: pathlib.Path) -> None: |
| 290 |
_write_profile( |
| 291 |
tmp_path, |
| 292 |
"default", |
| 293 |
config={"type": "external"}, |
| 294 |
credentials={"type": "something_else", "access_token": "x"}, |
| 295 |
) |
| 296 |
with pytest.raises( |
| 297 |
AnthropicError, |
| 298 |
match="credentials file has type 'something_else'; expected 'oauth_token' for authentication.type 'user_oauth'", |
| 299 |
): |
| 300 |
CredentialsFile()() |
| 301 |
|
| 302 |
def test_credentials_file_absent_type_is_lenient(self, tmp_path: pathlib.Path) -> None: |
| 303 |
"""Hand-written credentials files without `type` are accepted.""" |
| 304 |
_write_profile(tmp_path, "default", {"type": "external"}) |
| 305 |
# Write credentials directly (bypass helper's type injection). |
| 306 |
(tmp_path / "credentials").mkdir(exist_ok=True) |
| 307 |
creds_path = tmp_path / "credentials" / "default.json" |
| 308 |
creds_path.write_text(json.dumps({"access_token": "no-type-field"})) |
| 309 |
creds_path.chmod(0o600) |
| 310 |
assert CredentialsFile()().token == "no-type-field" |
| 311 |
|
| 312 |
def test_unrecognized_top_level_keys_ignored(self, tmp_path: pathlib.Path) -> None: |
| 313 |
"""Unknown top-level keys in both files are silently ignored (forward compat).""" |
| 314 |
_write_profile( |
| 315 |
tmp_path, |
| 316 |
"default", |
| 317 |
config={ |
| 318 |
"type": "external", |
| 319 |
"_note": "test comment", |
| 320 |
"future_field": 123, |
| 321 |
"nested_future": {"a": [1, 2]}, |
| 322 |
}, |
| 323 |
credentials={ |
| 324 |
"access_token": "tolerant", |
| 325 |
"expires_at": 1775000000, |
| 326 |
"_note": "creds comment", |
| 327 |
"future_field": 123, |
| 328 |
}, |
| 329 |
) |
| 330 |
tok = CredentialsFile()() |
| 331 |
assert tok.token == "tolerant" |
| 332 |
assert tok.expires_at == 1775000000 |
| 333 |
|
| 334 |
# -- "type": "workload_identity" -------------------------------------- |
| 335 |
|
| 336 |
@pytest.mark.respx(base_url=BASE_URL) |
| 337 |
def test_workload_identity_dispatch(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 338 |
jwt_path = tmp_path / "jwt" |
| 339 |
jwt_path.write_text("ext-jwt-from-file") |
| 340 |
|
| 341 |
# workload_identity needs no credentials file — config is sufficient. |
| 342 |
_write_profile( |
| 343 |
tmp_path, |
| 344 |
"default", |
| 345 |
config={ |
| 346 |
"type": "workload_identity", |
| 347 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 348 |
"federation_rule_id": "fdrl_file", |
| 349 |
"organization_id": "org-from-file", |
| 350 |
"service_account_id": "svac_file", |
| 351 |
}, |
| 352 |
) |
| 353 |
|
| 354 |
token_route = respx_mock.post(TOKEN_ENDPOINT).mock( |
| 355 |
return_value=httpx2.Response(200, json={"access_token": "exch_tok", "expires_in": 3600}) |
| 356 |
) |
| 357 |
|
| 358 |
provider = CredentialsFile() |
| 359 |
tok = provider() |
| 360 |
assert tok.token == "exch_tok" |
| 361 |
assert tok.expires_at is not None and tok.expires_at > time.time() |
| 362 |
|
| 363 |
assert token_route.call_count == 1 |
| 364 |
body = json.loads(cast("list[MockRequestCall]", token_route.calls)[0].request.content) |
| 365 |
assert body["grant_type"] == GRANT_TYPE_JWT_BEARER |
| 366 |
assert body["assertion"] == "ext-jwt-from-file" |
| 367 |
assert body["federation_rule_id"] == "fdrl_file" |
| 368 |
assert body["organization_id"] == "org-from-file" |
| 369 |
assert body["service_account_id"] == "svac_file" |
| 370 |
assert "workspace_id" not in body |
| 371 |
assert "scope" not in body |
| 372 |
|
| 373 |
# Disk cache: the exchange wrote credentials/<profile>.json with 0600 |
| 374 |
# perms, so the second call returns the cached token without hitting |
| 375 |
# the network. Delegate is still cached on the provider. |
| 376 |
provider() |
| 377 |
assert token_route.call_count == 1 |
| 378 |
assert provider._workload_delegate is not None # pyright: ignore[reportPrivateUsage] |
| 379 |
cached = json.loads((tmp_path / "credentials" / "default.json").read_text()) |
| 380 |
assert cached["version"] == "1.0" |
| 381 |
assert cached["type"] == "oauth_token" |
| 382 |
assert cached["access_token"] == "exch_tok" |
| 383 |
assert isinstance(cached["expires_at"], int) |
| 384 |
|
| 385 |
@pytest.mark.respx() |
| 386 |
def test_bind_base_url_precedence(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 387 |
"""`bind_base_url` slots between the config file's own `base_url` |
| 388 |
field and the hard-coded default: config → bound → default.""" |
| 389 |
jwt_path = tmp_path / "jwt" |
| 390 |
jwt_path.write_text("j") |
| 391 |
bound = "https://bound.example" |
| 392 |
|
| 393 |
def write(profile: str, *, with_base_url: Optional[str]) -> None: |
| 394 |
cfg: Dict[str, Any] = { |
| 395 |
"type": "workload_identity", |
| 396 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 397 |
"federation_rule_id": "fdrl_x", |
| 398 |
"organization_id": "org", |
| 399 |
} |
| 400 |
if with_base_url is not None: |
| 401 |
cfg["base_url"] = with_base_url |
| 402 |
_write_profile(tmp_path, profile, config=cfg) |
| 403 |
|
| 404 |
# config omits base_url, no bind → DEFAULT_BASE_URL |
| 405 |
write("p0", with_base_url=None) |
| 406 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60})) |
| 407 |
CredentialsFile("p0")() |
| 408 |
assert str(cast("list[MockRequestCall]", respx_mock.calls)[-1].request.url) == TOKEN_URL |
| 409 |
|
| 410 |
# config omits base_url + bound → bound |
| 411 |
write("p1", with_base_url=None) |
| 412 |
respx_mock.post(f"{bound}{TOKEN_ENDPOINT}").mock( |
| 413 |
return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60}) |
| 414 |
) |
| 415 |
creds = CredentialsFile("p1") |
| 416 |
creds.bind_base_url(bound) |
| 417 |
creds() |
| 418 |
assert str(cast("list[MockRequestCall]", respx_mock.calls)[-1].request.url) == f"{bound}{TOKEN_ENDPOINT}" |
| 419 |
|
| 420 |
# config has base_url + bound → config wins |
| 421 |
write("p2", with_base_url="https://from-config.example") |
| 422 |
respx_mock.post(f"https://from-config.example{TOKEN_ENDPOINT}").mock( |
| 423 |
return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60}) |
| 424 |
) |
| 425 |
creds = CredentialsFile("p2") |
| 426 |
creds.bind_base_url(bound) |
| 427 |
creds() |
| 428 |
assert ( |
| 429 |
str(cast("list[MockRequestCall]", respx_mock.calls)[-1].request.url) |
| 430 |
== f"https://from-config.example{TOKEN_ENDPOINT}" |
| 431 |
) |
| 432 |
|
| 433 |
# re-entrancy: bind_base_url called *after* _load_config() re-resolves |
| 434 |
# in place — the last bind wins when the config file doesn't pin a host. |
| 435 |
write("p3", with_base_url=None) |
| 436 |
creds = CredentialsFile("p3") |
| 437 |
creds.extra_headers() # forces _load_config() |
| 438 |
creds.bind_base_url("https://first.example") |
| 439 |
creds.bind_base_url("https://second.example") |
| 440 |
assert creds._base_url == "https://second.example" # type: ignore[attr-defined] |
| 441 |
# eager scheme validation — http:// rejected at bind time, before load |
| 442 |
with pytest.raises(AnthropicError, match="https"): |
| 443 |
CredentialsFile("p3").bind_base_url("http://evil.example") |
| 444 |
|
| 445 |
@pytest.mark.respx() |
| 446 |
def test_for_base_url_federation_profile(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 447 |
"""A second host gets its own provider exchanging there; the original |
| 448 |
keeps exchanging at the first host, and only the original uses the |
| 449 |
profile's on-disk cache.""" |
| 450 |
jwt_path = tmp_path / "jwt" |
| 451 |
jwt_path.write_text("ext-jwt") |
| 452 |
_write_profile( |
| 453 |
tmp_path, |
| 454 |
"fed", |
| 455 |
{ |
| 456 |
"type": "workload_identity", |
| 457 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 458 |
"federation_rule_id": "fdrl_01abc", |
| 459 |
"organization_id": "org-uuid", |
| 460 |
}, |
| 461 |
) |
| 462 |
_mock_token_exchange(respx_mock, BASE_URL, "tok-primary") |
| 463 |
_mock_token_exchange(respx_mock, OTHER_BASE_URL, "tok-other") |
| 464 |
creds = CredentialsFile("fed") |
| 465 |
assert creds.for_base_url(BASE_URL) is creds |
| 466 |
assert creds.for_base_url(f"{BASE_URL}/") is creds |
| 467 |
other = creds.for_base_url(OTHER_BASE_URL) |
| 468 |
assert other is not creds |
| 469 |
|
| 470 |
assert other().token == "tok-other" |
| 471 |
assert not (tmp_path / "credentials" / "fed.json").exists() |
| 472 |
assert creds().token == "tok-primary" |
| 473 |
assert json.loads((tmp_path / "credentials" / "fed.json").read_text())["access_token"] == "tok-primary" |
| 474 |
# The other host's provider never consults the file the original wrote. |
| 475 |
assert other().token == "tok-other" |
| 476 |
assert [str(r.url) for r in _requests_to(respx_mock, OTHER_BASE_URL)] == [OTHER_TOKEN_URL, OTHER_TOKEN_URL] |
| 477 |
assert [str(r.url) for r in _requests_to(respx_mock, BASE_URL)] == [TOKEN_URL] |
| 478 |
|
| 479 |
def test_for_base_url_returns_self_when_bind_is_moot(self, tmp_path: pathlib.Path) -> None: |
| 480 |
"""No per-host provider is made when the bind can't change where the |
| 481 |
tokens come from: the profile pins its own `base_url`, or it is a |
| 482 |
user_oauth profile whose refresh token is tied to the issuing host.""" |
| 483 |
_write_profile( |
| 484 |
tmp_path, |
| 485 |
"pinned", |
| 486 |
{"type": "workload_identity", "federation_rule_id": "fdrl_x", "base_url": "https://pinned.example"}, |
| 487 |
) |
| 488 |
pinned = CredentialsFile("pinned") |
| 489 |
assert pinned.for_base_url(BASE_URL) is pinned |
| 490 |
assert pinned.for_base_url(OTHER_BASE_URL) is pinned |
| 491 |
|
| 492 |
_write_profile(tmp_path, "oauth", {"type": "authorized_user", "client_id": "cid"}) |
| 493 |
oauth = CredentialsFile("oauth") |
| 494 |
assert oauth.for_base_url(BASE_URL) is oauth |
| 495 |
assert oauth.for_base_url(OTHER_BASE_URL) is oauth |
| 496 |
|
| 497 |
@pytest.mark.respx(base_url=BASE_URL) |
| 498 |
def test_workload_identity_disk_cache_stale_reexchange( |
| 499 |
self, respx_mock: MockRouter, tmp_path: pathlib.Path |
| 500 |
) -> None: |
| 501 |
"""A stale on-disk credentials file is ignored — fresh exchange happens |
| 502 |
and the file is rewritten.""" |
| 503 |
jwt_path = tmp_path / "jwt" |
| 504 |
jwt_path.write_text("ext-jwt") |
| 505 |
_write_profile( |
| 506 |
tmp_path, |
| 507 |
"default", |
| 508 |
config={ |
| 509 |
"type": "workload_identity", |
| 510 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 511 |
"federation_rule_id": "fdrl_x", |
| 512 |
"organization_id": "org_x", |
| 513 |
}, |
| 514 |
credentials={"access_token": "stale-tok", "expires_at": int(time.time()) - 1}, |
| 515 |
) |
| 516 |
token_route = respx_mock.post(TOKEN_ENDPOINT).mock( |
| 517 |
return_value=httpx2.Response(200, json={"access_token": "fresh-tok", "expires_in": 600}) |
| 518 |
) |
| 519 |
tok = CredentialsFile()() |
| 520 |
assert tok.token == "fresh-tok" |
| 521 |
assert token_route.call_count == 1 |
| 522 |
rewritten = json.loads((tmp_path / "credentials" / "default.json").read_text()) |
| 523 |
assert rewritten["access_token"] == "fresh-tok" |
| 524 |
|
| 525 |
@pytest.mark.respx(base_url=BASE_URL) |
| 526 |
def test_workload_identity_disk_cache_corrupt_expires_at_reexchange( |
| 527 |
self, respx_mock: MockRouter, tmp_path: pathlib.Path |
| 528 |
) -> None: |
| 529 |
"""A non-numeric expires_at in the on-disk credentials file falls |
| 530 |
through to re-exchange instead of raising.""" |
| 531 |
jwt_path = tmp_path / "jwt" |
| 532 |
jwt_path.write_text("ext-jwt") |
| 533 |
_write_profile( |
| 534 |
tmp_path, |
| 535 |
"default", |
| 536 |
config={ |
| 537 |
"type": "workload_identity", |
| 538 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 539 |
"federation_rule_id": "fdrl_x", |
| 540 |
"organization_id": "org_x", |
| 541 |
}, |
| 542 |
credentials={"access_token": "stale-tok", "expires_at": "not-a-number"}, |
| 543 |
) |
| 544 |
token_route = respx_mock.post(TOKEN_ENDPOINT).mock( |
| 545 |
return_value=httpx2.Response(200, json={"access_token": "fresh-tok", "expires_in": 600}) |
| 546 |
) |
| 547 |
tok = CredentialsFile()() |
| 548 |
assert tok.token == "fresh-tok" |
| 549 |
assert token_route.call_count == 1 |
| 550 |
|
| 551 |
def test_workload_identity_missing_required_fields(self, tmp_path: pathlib.Path) -> None: |
| 552 |
_write_profile(tmp_path, "default", {"type": "workload_identity", "federation_rule_id": "fdrl_x"}) |
| 553 |
with pytest.raises( |
| 554 |
WorkloadIdentityError, match="'authentication.federation_rule_id' and top-level 'organization_id'" |
| 555 |
): |
| 556 |
CredentialsFile()() |
| 557 |
|
| 558 |
@pytest.mark.respx(base_url=BASE_URL) |
| 559 |
def test_workload_delegate_borrows_parent_http_client(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 560 |
"""The workload delegate must borrow CredentialsFile's owned httpx2.Client |
| 561 |
rather than creating its own. CredentialsFile.close() then has a single |
| 562 |
client to release; if a refactor regresses this and the delegate creates |
| 563 |
its own pool, this test catches it before close() starts leaking sockets.""" |
| 564 |
jwt_path = tmp_path / "jwt" |
| 565 |
jwt_path.write_text("ext-jwt") |
| 566 |
_write_profile( |
| 567 |
tmp_path, |
| 568 |
"default", |
| 569 |
config={ |
| 570 |
"type": "workload_identity", |
| 571 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 572 |
"federation_rule_id": "fdrl_x", |
| 573 |
"organization_id": "00000000-0000-0000-0000-000000000000", |
| 574 |
}, |
| 575 |
) |
| 576 |
respx_mock.post(TOKEN_ENDPOINT).mock( |
| 577 |
return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60}) |
| 578 |
) |
| 579 |
provider = CredentialsFile() |
| 580 |
provider() |
| 581 |
delegate = provider._workload_delegate # pyright: ignore[reportPrivateUsage] |
| 582 |
assert delegate is not None |
| 583 |
# The delegate must NOT own its httpx2.Client — that would mean we have |
| 584 |
# two pools to track and close(). |
| 585 |
assert delegate._owns_http_client is False # pyright: ignore[reportPrivateUsage] |
| 586 |
# Both objects share the same client instance. |
| 587 |
assert delegate._http_client is provider._get_http_client() # pyright: ignore[reportPrivateUsage] |
| 588 |
provider.close() |
| 589 |
|
| 590 |
def test_workload_identity_unknown_source_raises(self, tmp_path: pathlib.Path) -> None: |
| 591 |
_write_profile( |
| 592 |
tmp_path, |
| 593 |
"default", |
| 594 |
{ |
| 595 |
"type": "workload_identity", |
| 596 |
"federation_rule_id": "f", |
| 597 |
"organization_id": "o", |
| 598 |
"identity_token": {"source": "url", "url": "https://example.com/token"}, |
| 599 |
}, |
| 600 |
) |
| 601 |
with pytest.raises(AnthropicError, match="identity_token source 'url' is not supported"): |
| 602 |
CredentialsFile()() |
| 603 |
|
| 604 |
def test_workload_identity_token_omitted_uses_env( |
| 605 |
self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch |
| 606 |
) -> None: |
| 607 |
jwt_path = tmp_path / "jwt" |
| 608 |
jwt_path.write_text("via-env-chain") |
| 609 |
monkeypatch.setenv("ANTHROPIC_IDENTITY_TOKEN_FILE", str(jwt_path)) |
| 610 |
|
| 611 |
_write_profile( |
| 612 |
tmp_path, "default", {"type": "workload_identity", "federation_rule_id": "f", "organization_id": "o"} |
| 613 |
) |
| 614 |
|
| 615 |
provider = CredentialsFile() |
| 616 |
# Building the delegate succeeds (provider resolved via env); we don't |
| 617 |
# need to exercise the HTTP call here. |
| 618 |
provider._load_config() # pyright: ignore[reportPrivateUsage] |
| 619 |
delegate = provider._build_workload_delegate( # pyright: ignore[reportPrivateUsage] |
| 620 |
provider._auth_block() # pyright: ignore[reportPrivateUsage] |
| 621 |
) |
| 622 |
assert delegate._identity_token_provider() == "via-env-chain" # pyright: ignore[reportPrivateUsage] |
| 623 |
|
| 624 |
# -- "type": "authorized_user" ---------------------------------------- |
| 625 |
|
| 626 |
@pytest.mark.respx(base_url=BASE_URL) |
| 627 |
def test_authorized_user_refresh_and_writeback(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 628 |
"""Refresh writes back to credentials/ only — configs/ stays untouched.""" |
| 629 |
_write_profile( |
| 630 |
tmp_path, |
| 631 |
"default", |
| 632 |
config={"type": "authorized_user", "client_id": "cid", "scope": "x:y"}, |
| 633 |
credentials={ |
| 634 |
"access_token": "old-tok", |
| 635 |
"expires_at": int(time.time()) - 1, |
| 636 |
"refresh_token": "refresh-old", |
| 637 |
}, |
| 638 |
) |
| 639 |
|
| 640 |
refresh_route = respx_mock.post(TOKEN_ENDPOINT).mock( |
| 641 |
return_value=httpx2.Response( |
| 642 |
200, json={"access_token": "new-tok", "expires_in": 3600, "refresh_token": "refresh-new"} |
| 643 |
) |
| 644 |
) |
| 645 |
|
| 646 |
tok = CredentialsFile()() |
| 647 |
assert tok.token == "new-tok" |
| 648 |
assert tok.expires_at is not None and tok.expires_at > time.time() |
| 649 |
|
| 650 |
assert refresh_route.call_count == 1 |
| 651 |
body = json.loads(cast("list[MockRequestCall]", refresh_route.calls)[0].request.content) |
| 652 |
assert body == {"grant_type": "refresh_token", "refresh_token": "refresh-old", "client_id": "cid"} |
| 653 |
|
| 654 |
# Credentials file was rewritten — expires_at is unix int seconds |
| 655 |
creds_file = tmp_path / "credentials" / "default.json" |
| 656 |
rewritten = json.loads(creds_file.read_text()) |
| 657 |
assert rewritten["version"] == "1.0" |
| 658 |
assert rewritten["type"] == "oauth_token" |
| 659 |
assert rewritten["access_token"] == "new-tok" |
| 660 |
assert rewritten["refresh_token"] == "refresh-new" |
| 661 |
assert isinstance(rewritten["expires_at"], int) |
| 662 |
assert rewritten["expires_at"] > time.time() |
| 663 |
assert not creds_file.with_suffix(".json.tmp").exists() |
| 664 |
|
| 665 |
# Config file was NOT touched |
| 666 |
config_after = json.loads((tmp_path / "configs" / "default.json").read_text()) |
| 667 |
assert config_after == { |
| 668 |
"authentication": { |
| 669 |
"type": "user_oauth", |
| 670 |
"client_id": "cid", |
| 671 |
"scope": "x:y", |
| 672 |
} |
| 673 |
} |
| 674 |
|
| 675 |
def test_authorized_user_fresh_token_no_refresh(self, tmp_path: pathlib.Path) -> None: |
| 676 |
_write_profile( |
| 677 |
tmp_path, |
| 678 |
"default", |
| 679 |
config={"type": "authorized_user"}, |
| 680 |
credentials={ |
| 681 |
"access_token": "still-good", |
| 682 |
"expires_at": int(time.time()) + 3600, |
| 683 |
"refresh_token": "refresh-old", |
| 684 |
}, |
| 685 |
) |
| 686 |
tok = CredentialsFile()() |
| 687 |
assert tok.token == "still-good" |
| 688 |
|
| 689 |
@pytest.mark.respx(base_url=BASE_URL) |
| 690 |
def test_authorized_user_refresh_failure(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 691 |
_write_profile( |
| 692 |
tmp_path, |
| 693 |
"default", |
| 694 |
config={"type": "authorized_user", "client_id": "cid"}, |
| 695 |
credentials={"access_token": "old", "expires_at": int(time.time()) - 1, "refresh_token": "rt"}, |
| 696 |
) |
| 697 |
respx_mock.post(TOKEN_ENDPOINT).mock(return_value=httpx2.Response(400, json={"error": "invalid_grant"})) |
| 698 |
with pytest.raises(WorkloadIdentityError, match="refresh failed"): |
| 699 |
CredentialsFile()() |
| 700 |
|
| 701 |
def test_user_oauth_without_client_id_is_static(self, tmp_path: pathlib.Path) -> None: |
| 702 |
"""user_oauth without a client_id is the `external` pattern: the |
| 703 |
credentials file is externally rotated, the SDK re-reads it on every |
| 704 |
call, no refresh grant is attempted. The spec merged this use case |
| 705 |
into user_oauth — a client_id is the opt-in signal for refresh.""" |
| 706 |
_write_profile( |
| 707 |
tmp_path, |
| 708 |
"default", |
| 709 |
config={"type": "authorized_user"}, # migrates to user_oauth, no client_id |
| 710 |
credentials={ |
| 711 |
"access_token": "daemon-minted", |
| 712 |
"expires_at": int(time.time()) + 3600, |
| 713 |
}, |
| 714 |
) |
| 715 |
tok = CredentialsFile()() |
| 716 |
assert tok.token == "daemon-minted" |
| 717 |
|
| 718 |
@pytest.mark.respx(base_url=BASE_URL) |
| 719 |
def test_authorized_user_refresh_beta_headers(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 720 |
"""refresh_token POST must carry oauth-2025-04-20 (unlocks the token |
| 721 |
endpoint family) but NOT oidc-federation-2026-04-01 (that header is a |
| 722 |
routing switch that would send this POST to the Go userauth handler, |
| 723 |
which only accepts jwt-bearer grants).""" |
| 724 |
_write_profile( |
| 725 |
tmp_path, |
| 726 |
"default", |
| 727 |
config={"type": "authorized_user", "client_id": "cid"}, |
| 728 |
credentials={ |
| 729 |
"access_token": "old", |
| 730 |
"expires_at": int(time.time()) - 1, |
| 731 |
"refresh_token": "refresh-old", |
| 732 |
}, |
| 733 |
) |
| 734 |
refresh_route = respx_mock.post(TOKEN_ENDPOINT).mock( |
| 735 |
return_value=httpx2.Response(200, json={"access_token": "new-tok", "expires_in": 3600}) |
| 736 |
) |
| 737 |
CredentialsFile()() |
| 738 |
req = cast("list[MockRequestCall]", refresh_route.calls)[0].request |
| 739 |
beta_flags = {f.strip() for f in req.headers["anthropic-beta"].split(",")} |
| 740 |
assert OAUTH_API_BETA_HEADER in beta_flags |
| 741 |
assert FEDERATION_BETA_HEADER not in beta_flags |
| 742 |
assert req.headers["User-Agent"] == f"anthropic-python/{__version__}" |
| 743 |
|
| 744 |
def test_user_oauth_with_client_id_missing_refresh_token(self, tmp_path: pathlib.Path) -> None: |
| 745 |
"""A user_oauth profile that has a client_id (refresh mode) but no |
| 746 |
refresh_token in the credentials file can't actually refresh — raise |
| 747 |
a clear error rather than 401-looping.""" |
| 748 |
_write_profile( |
| 749 |
tmp_path, |
| 750 |
"default", |
| 751 |
config={"type": "authorized_user", "client_id": "cid"}, |
| 752 |
credentials={"access_token": "x", "expires_at": int(time.time()) - 1}, |
| 753 |
) |
| 754 |
with pytest.raises(WorkloadIdentityError, match="'refresh_token'"): |
| 755 |
CredentialsFile()() |
| 756 |
|
| 757 |
# -- common error paths ----------------------------------------------- |
| 758 |
|
| 759 |
def test_unknown_type(self, tmp_path: pathlib.Path) -> None: |
| 760 |
_write_profile(tmp_path, "default", {"type": "mystery"}) |
| 761 |
with pytest.raises(AnthropicError, match="Unknown authentication.type"): |
| 762 |
CredentialsFile()() |
| 763 |
|
| 764 |
def test_missing_config_file(self, tmp_path: pathlib.Path) -> None: |
| 765 |
# configs/ dir exists but profile file doesn't |
| 766 |
(tmp_path / "configs").mkdir() |
| 767 |
with pytest.raises(AnthropicError, match="Config file not found"): |
| 768 |
CredentialsFile("nonexistent")() |
| 769 |
|
| 770 |
def test_default_credentials_explicit_env_propagates_error( |
| 771 |
self, tmp_path: pathlib.Path, clean_env: pytest.MonkeyPatch |
| 772 |
) -> None: |
| 773 |
"""When ANTHROPIC_PROFILE or ANTHROPIC_CONFIG_DIR is set explicitly, a |
| 774 |
broken config file surfaces immediately — not swallowed into a 'no auth |
| 775 |
configured' misdirection.""" |
| 776 |
clean_env.setenv("ANTHROPIC_CONFIG_DIR", str(tmp_path)) |
| 777 |
clean_env.setenv("ANTHROPIC_PROFILE", "broken") |
| 778 |
(tmp_path / "configs").mkdir() |
| 779 |
(tmp_path / "configs" / "broken.json").write_text("this is not JSON") |
| 780 |
with pytest.raises(AnthropicError, match="not valid JSON"): |
| 781 |
default_credentials() |
| 782 |
|
| 783 |
# -- security: HTTPS enforcement -------------------------------------- |
| 784 |
|
| 785 |
def test_config_base_url_http_rejected(self, tmp_path: pathlib.Path) -> None: |
| 786 |
"""A config file that specifies base_url=http://evil is rejected so a |
| 787 |
malicious config can't exfiltrate the assertion or refresh token.""" |
| 788 |
_write_profile( |
| 789 |
tmp_path, |
| 790 |
"default", |
| 791 |
{"type": "external", "base_url": "http://evil.example.com"}, |
| 792 |
{"access_token": "x"}, |
| 793 |
) |
| 794 |
with pytest.raises(AnthropicError, match="must use https"): |
| 795 |
CredentialsFile()() |
| 796 |
|
| 797 |
def test_config_base_url_localhost_http_allowed(self, tmp_path: pathlib.Path) -> None: |
| 798 |
"""Localhost HTTP is allowed for local oauth_server testing.""" |
| 799 |
_write_profile( |
| 800 |
tmp_path, |
| 801 |
"default", |
| 802 |
{"type": "external", "base_url": "http://localhost:8080"}, |
| 803 |
{"access_token": "x", "expires_at": int(time.time()) + 3600}, |
| 804 |
) |
| 805 |
assert CredentialsFile()().token == "x" |
| 806 |
|
| 807 |
def test_workload_identity_http_rejected(self) -> None: |
| 808 |
from anthropic.lib.credentials import WorkloadIdentityCredentials |
| 809 |
|
| 810 |
creds = WorkloadIdentityCredentials( |
| 811 |
identity_token_provider=lambda: "j", |
| 812 |
federation_rule_id="fdrl_x", |
| 813 |
organization_id="00000000-0000-0000-0000-000000000000", |
| 814 |
) |
| 815 |
with pytest.raises(AnthropicError, match="must use https"): |
| 816 |
creds.bind_base_url("http://evil.example.com") |
| 817 |
|
| 818 |
# -- security: profile-name validation -------------------------------- |
| 819 |
|
| 820 |
def test_profile_name_path_traversal_rejected(self) -> None: |
| 821 |
with pytest.raises(AnthropicError, match="path separators"): |
| 822 |
CredentialsFile(profile="evil/shadow")() |
| 823 |
|
| 824 |
def test_profile_name_leading_dot_rejected(self) -> None: |
| 825 |
with pytest.raises(AnthropicError, match="must not start with a dot"): |
| 826 |
CredentialsFile(profile=".hidden")() |
| 827 |
|
| 828 |
def test_profile_name_empty_rejected(self) -> None: |
| 829 |
with pytest.raises(AnthropicError, match="must not be empty"): |
| 830 |
CredentialsFile(profile="")() |
| 831 |
|
| 832 |
# -- security: credentials file permissions --------------------------- |
| 833 |
|
| 834 |
@pytest.mark.parametrize("mode", [0o644, 0o640, 0o604, 0o660, 0o620, 0o602]) |
| 835 |
def test_credentials_file_group_or_other_access_rejected(self, tmp_path: pathlib.Path, mode: int) -> None: |
| 836 |
if os.name != "posix": |
| 837 |
pytest.skip("POSIX mode bits only") |
| 838 |
_write_profile(tmp_path, "default", {"type": "external"}, {"access_token": "x"}) |
| 839 |
(tmp_path / "credentials" / "default.json").chmod(mode) |
| 840 |
with pytest.raises(AnthropicError, match=rf"accessible by group or others \(mode {mode:#o}\)"): |
| 841 |
CredentialsFile()() |
| 842 |
|
| 843 |
def test_credentials_file_owner_only_accepted(self, tmp_path: pathlib.Path) -> None: |
| 844 |
if os.name != "posix": |
| 845 |
pytest.skip("POSIX mode bits only") |
| 846 |
_write_profile( |
| 847 |
tmp_path, |
| 848 |
"default", |
| 849 |
{"type": "external"}, |
| 850 |
{"access_token": "x", "expires_at": int(time.time()) + 3600}, |
| 851 |
) |
| 852 |
(tmp_path / "credentials" / "default.json").chmod(0o600) |
| 853 |
assert CredentialsFile()().token == "x" |
| 854 |
|
| 855 |
def test_credentials_file_symlink_rejected(self, tmp_path: pathlib.Path) -> None: |
| 856 |
if os.name != "posix": |
| 857 |
pytest.skip("symlink semantics") |
| 858 |
_write_profile(tmp_path, "default", {"type": "external"}, {"access_token": "x"}) |
| 859 |
real = tmp_path / "credentials" / "default.json" |
| 860 |
target = tmp_path / "real-secret.json" |
| 861 |
target.write_text(real.read_text()) |
| 862 |
target.chmod(0o600) |
| 863 |
real.unlink() |
| 864 |
real.symlink_to(target) |
| 865 |
with pytest.raises(AnthropicError, match="symlink"): |
| 866 |
CredentialsFile()() |
| 867 |
|
| 868 |
# -- security: redacted error bodies ---------------------------------- |
| 869 |
|
| 870 |
def test_workload_identity_error_body_redacted(self) -> None: |
| 871 |
from anthropic.lib.credentials._workload import _redact_body |
| 872 |
|
| 873 |
# Long string truncated. |
| 874 |
long = "sensitive_" * 100 |
| 875 |
result = _redact_body(long) |
| 876 |
assert isinstance(result, str) |
| 877 |
assert len(result) < len(long) |
| 878 |
assert "... <" in result |
| 879 |
|
| 880 |
# Dict keeps only OAuth standard error fields; the assertion is dropped. |
| 881 |
dirty = { |
| 882 |
"error": "invalid_grant", |
| 883 |
"error_description": "token expired", |
| 884 |
"assertion": "eyJleHAmple.jwt.sensitive", |
| 885 |
"refresh_token": "rt_sensitive", |
| 886 |
} |
| 887 |
cleaned = _redact_body(dirty) |
| 888 |
assert cleaned == {"error": "invalid_grant", "error_description": "token expired"} |
| 889 |
|
| 890 |
def test_bad_config_json(self, tmp_path: pathlib.Path) -> None: |
| 891 |
(tmp_path / "configs").mkdir() |
| 892 |
(tmp_path / "configs" / "default.json").write_text("{not json") |
| 893 |
with pytest.raises(AnthropicError, match="not valid JSON"): |
| 894 |
CredentialsFile()() |
| 895 |
|
| 896 |
# -- profiles & paths -------------------------------------------------- |
| 897 |
|
| 898 |
def test_explicit_profile(self, tmp_path: pathlib.Path) -> None: |
| 899 |
_write_profile(tmp_path, "work", {"type": "external"}, {"access_token": "work-tok"}) |
| 900 |
_write_profile(tmp_path, "default", {"type": "external"}, {"access_token": "default-tok"}) |
| 901 |
assert CredentialsFile("work")().token == "work-tok" |
| 902 |
assert CredentialsFile()().token == "default-tok" |
| 903 |
|
| 904 |
def test_profile_from_env(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 905 |
_write_profile(tmp_path, "from-env", {"type": "external"}, {"access_token": "env-tok"}) |
| 906 |
monkeypatch.setenv("ANTHROPIC_PROFILE", "from-env") |
| 907 |
assert CredentialsFile()().token == "env-tok" |
| 908 |
|
| 909 |
def test_profile_from_active_config(self, tmp_path: pathlib.Path) -> None: |
| 910 |
_write_profile(tmp_path, "pointed-at", {"type": "external"}, {"access_token": "active-tok"}) |
| 911 |
(tmp_path / "active_config").write_text("pointed-at\n") |
| 912 |
assert CredentialsFile()().token == "active-tok" |
| 913 |
|
| 914 |
def test_env_overrides_active_config(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 915 |
_write_profile(tmp_path, "from-env", {"type": "external"}, {"access_token": "env-tok"}) |
| 916 |
_write_profile(tmp_path, "from-file", {"type": "external"}, {"access_token": "file-tok"}) |
| 917 |
(tmp_path / "active_config").write_text("from-file") |
| 918 |
monkeypatch.setenv("ANTHROPIC_PROFILE", "from-env") |
| 919 |
assert CredentialsFile()().token == "env-tok" |
| 920 |
|
| 921 |
def test_credentials_path_override(self, tmp_path: pathlib.Path) -> None: |
| 922 |
"""Config's `credentials_path` field redirects to a custom location.""" |
| 923 |
custom = tmp_path / "elsewhere" / "secrets.json" |
| 924 |
custom.parent.mkdir() |
| 925 |
custom.write_text(json.dumps({"access_token": "redirected"})) |
| 926 |
custom.chmod(0o600) |
| 927 |
|
| 928 |
_write_profile(tmp_path, "default", {"type": "external", "credentials_path": str(custom)}) |
| 929 |
assert CredentialsFile()().token == "redirected" |
| 930 |
|
| 931 |
@pytest.mark.respx(base_url="https://from-config.example.com") |
| 932 |
def test_base_url_from_config(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 933 |
"""Config `base_url` is used when no ctor override is given.""" |
| 934 |
jwt_path = tmp_path / "jwt" |
| 935 |
jwt_path.write_text("x") |
| 936 |
_write_profile( |
| 937 |
tmp_path, |
| 938 |
"default", |
| 939 |
{ |
| 940 |
"type": "workload_identity", |
| 941 |
"base_url": "https://from-config.example.com", |
| 942 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 943 |
"federation_rule_id": "f", |
| 944 |
"organization_id": "o", |
| 945 |
}, |
| 946 |
) |
| 947 |
token_route = respx_mock.post("/v1/oauth/token").mock( |
| 948 |
return_value=httpx2.Response(200, json={"access_token": "tok", "expires_in": 3600}) |
| 949 |
) |
| 950 |
CredentialsFile()() # no base_url ctor arg → config wins |
| 951 |
assert str(cast("list[MockRequestCall]", token_route.calls)[0].request.url).startswith( |
| 952 |
"https://from-config.example.com/" |
| 953 |
) |
| 954 |
|
| 955 |
# -- review fixes ----------------------------------------------------- |
| 956 |
|
| 957 |
def test_chain_and_class_agree_on_profile(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 958 |
"""default_credentials() and CredentialsFile() resolve to the same profile.""" |
| 959 |
_write_profile(tmp_path, "agreed", {"type": "external"}, {"access_token": "x"}) |
| 960 |
monkeypatch.setenv("ANTHROPIC_PROFILE", "agreed") |
| 961 |
|
| 962 |
result = default_credentials() |
| 963 |
assert result is not None |
| 964 |
chain = result.provider |
| 965 |
direct = CredentialsFile() |
| 966 |
assert isinstance(chain, CredentialsFile) |
| 967 |
assert chain.profile == direct.profile == "agreed" |
| 968 |
assert chain.config_path == direct.config_path |
| 969 |
|
| 970 |
|
| 971 |
# --------------------------------------------------------------------------- # |
| 972 |
# WorkloadIdentityCredentials |
| 973 |
# --------------------------------------------------------------------------- # |
| 974 |
|
| 975 |
|
| 976 |
class TestWorkloadIdentityCredentials: |
| 977 |
@pytest.mark.respx() |
| 978 |
def test_exchange(self, respx_mock: MockRouter) -> None: |
| 979 |
respx_mock.post(TOKEN_URL).mock( |
| 980 |
return_value=httpx2.Response( |
| 981 |
200, |
| 982 |
json={"access_token": "sk-ant-oat01-test", "token_type": "Bearer", "expires_in": 600}, |
| 983 |
) |
| 984 |
) |
| 985 |
|
| 986 |
creds = WorkloadIdentityCredentials( |
| 987 |
identity_token_provider=lambda: "ext.jwt.value", |
| 988 |
federation_rule_id="fdrl_01abc", |
| 989 |
organization_id="00000000-0000-0000-0000-000000000000", |
| 990 |
) |
| 991 |
|
| 992 |
before = time.time() |
| 993 |
token = creds() |
| 994 |
after = time.time() |
| 995 |
|
| 996 |
assert token.token == "sk-ant-oat01-test" |
| 997 |
assert token.expires_at is not None |
| 998 |
assert before + 600 - 2 <= token.expires_at <= after + 600 + 2 |
| 999 |
|
| 1000 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 1001 |
assert len(calls) == 1 |
| 1002 |
req = calls[0].request |
| 1003 |
# jwt-bearer exchange must carry BOTH: oauth-2025-04-20 unlocks the |
| 1004 |
# token endpoint, oidc-federation-2026-04-01 routes to the federation |
| 1005 |
# handler. |
| 1006 |
beta_flags = {f.strip() for f in req.headers["anthropic-beta"].split(",")} |
| 1007 |
assert OAUTH_API_BETA_HEADER in beta_flags |
| 1008 |
assert FEDERATION_BETA_HEADER in beta_flags |
| 1009 |
assert req.headers["User-Agent"] == f"anthropic-python/{__version__}" |
| 1010 |
body = json.loads(req.content) |
| 1011 |
assert body["grant_type"] == GRANT_TYPE_JWT_BEARER |
| 1012 |
assert body["assertion"] == "ext.jwt.value" |
| 1013 |
assert body["federation_rule_id"] == "fdrl_01abc" |
| 1014 |
assert body["organization_id"] == "00000000-0000-0000-0000-000000000000" |
| 1015 |
assert "service_account_id" not in body |
| 1016 |
assert "workspace_id" not in body |
| 1017 |
assert "scope" not in body |
| 1018 |
|
| 1019 |
@pytest.mark.respx() |
| 1020 |
def test_service_account_included(self, respx_mock: MockRouter) -> None: |
| 1021 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60})) |
| 1022 |
creds = WorkloadIdentityCredentials( |
| 1023 |
identity_token_provider=lambda: "j", |
| 1024 |
federation_rule_id="fdrl_01abc", |
| 1025 |
organization_id="org", |
| 1026 |
service_account_id="svac_01xyz", |
| 1027 |
) |
| 1028 |
creds() |
| 1029 |
body = json.loads(cast("list[MockRequestCall]", respx_mock.calls)[0].request.content) |
| 1030 |
assert body["service_account_id"] == "svac_01xyz" |
| 1031 |
assert "scope" not in body |
| 1032 |
|
| 1033 |
@pytest.mark.respx() |
| 1034 |
def test_workspace_id_included(self, respx_mock: MockRouter) -> None: |
| 1035 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60})) |
| 1036 |
creds = WorkloadIdentityCredentials( |
| 1037 |
identity_token_provider=lambda: "j", |
| 1038 |
federation_rule_id="fdrl_01abc", |
| 1039 |
organization_id="org", |
| 1040 |
workspace_id="wrkspc_01abc", |
| 1041 |
) |
| 1042 |
creds() |
| 1043 |
body = json.loads(cast("list[MockRequestCall]", respx_mock.calls)[0].request.content) |
| 1044 |
assert body["workspace_id"] == "wrkspc_01abc" |
| 1045 |
|
| 1046 |
@pytest.mark.respx() |
| 1047 |
def test_workspace_id_default_sentinel(self, respx_mock: MockRouter) -> None: |
| 1048 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60})) |
| 1049 |
creds = WorkloadIdentityCredentials( |
| 1050 |
identity_token_provider=lambda: "j", |
| 1051 |
federation_rule_id="fdrl_01abc", |
| 1052 |
organization_id="org", |
| 1053 |
workspace_id="default", |
| 1054 |
) |
| 1055 |
creds() |
| 1056 |
body = json.loads(cast("list[MockRequestCall]", respx_mock.calls)[0].request.content) |
| 1057 |
assert body["workspace_id"] == "default" |
| 1058 |
|
| 1059 |
@pytest.mark.respx() |
| 1060 |
def test_scope_is_display_only(self, respx_mock: MockRouter) -> None: |
| 1061 |
"""`scope` is stored on the provider for parity but never sent on the |
| 1062 |
wire — the server derives effective scope from the federation rule.""" |
| 1063 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60})) |
| 1064 |
creds = WorkloadIdentityCredentials( |
| 1065 |
identity_token_provider=lambda: "j", |
| 1066 |
federation_rule_id="fdrl_x", |
| 1067 |
organization_id="org", |
| 1068 |
scope="api:read api:write", |
| 1069 |
) |
| 1070 |
creds() |
| 1071 |
assert creds.scope == "api:read api:write" |
| 1072 |
body = json.loads(cast("list[MockRequestCall]", respx_mock.calls)[0].request.content) |
| 1073 |
assert "scope" not in body |
| 1074 |
|
| 1075 |
@pytest.mark.respx() |
| 1076 |
def test_exchange_federation_assertion_helper(self, respx_mock: MockRouter) -> None: |
| 1077 |
respx_mock.post(TOKEN_URL).mock( |
| 1078 |
return_value=httpx2.Response(200, json={"access_token": "sk-ant-oat01-one", "expires_in": 600}) |
| 1079 |
) |
| 1080 |
token = exchange_federation_assertion( |
| 1081 |
assertion="ext.jwt.value", |
| 1082 |
federation_rule_id="fdrl_x", |
| 1083 |
organization_id="org_x", |
| 1084 |
workspace_id="wrkspc_x", |
| 1085 |
) |
| 1086 |
assert token.token == "sk-ant-oat01-one" |
| 1087 |
req = cast("list[MockRequestCall]", respx_mock.calls)[0].request |
| 1088 |
body = json.loads(req.content) |
| 1089 |
assert body["assertion"] == "ext.jwt.value" |
| 1090 |
assert body["federation_rule_id"] == "fdrl_x" |
| 1091 |
assert body["workspace_id"] == "wrkspc_x" |
| 1092 |
|
| 1093 |
@pytest.mark.respx() |
| 1094 |
def test_bind_base_url(self, respx_mock: MockRouter) -> None: |
| 1095 |
"""`bind_base_url` sets the token-exchange URL; unbound → `DEFAULT_BASE_URL`.""" |
| 1096 |
bound = "https://bound.example" |
| 1097 |
|
| 1098 |
# No bind → DEFAULT_BASE_URL |
| 1099 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60})) |
| 1100 |
WorkloadIdentityCredentials( |
| 1101 |
identity_token_provider=lambda: "j", federation_rule_id="fdrl_x", organization_id="org" |
| 1102 |
)() |
| 1103 |
assert str(cast("list[MockRequestCall]", respx_mock.calls)[-1].request.url) == TOKEN_URL |
| 1104 |
|
| 1105 |
# bound → bound |
| 1106 |
respx_mock.post(f"{bound}{TOKEN_ENDPOINT}").mock( |
| 1107 |
return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60}) |
| 1108 |
) |
| 1109 |
creds = WorkloadIdentityCredentials( |
| 1110 |
identity_token_provider=lambda: "j", federation_rule_id="fdrl_x", organization_id="org" |
| 1111 |
) |
| 1112 |
creds.bind_base_url(bound) |
| 1113 |
creds() |
| 1114 |
assert str(cast("list[MockRequestCall]", respx_mock.calls)[-1].request.url) == f"{bound}{TOKEN_ENDPOINT}" |
| 1115 |
|
| 1116 |
def test_bind_base_url_http_rejected(self) -> None: |
| 1117 |
creds = WorkloadIdentityCredentials( |
| 1118 |
identity_token_provider=lambda: "j", federation_rule_id="fdrl_x", organization_id="org" |
| 1119 |
) |
| 1120 |
with pytest.raises(AnthropicError, match="must use https"): |
| 1121 |
creds.bind_base_url("http://evil.example") |
| 1122 |
|
| 1123 |
@pytest.mark.respx() |
| 1124 |
def test_for_base_url(self, respx_mock: MockRouter) -> None: |
| 1125 |
"""The first bind (and re-binds to the same host) happen in place; a |
| 1126 |
bind to another host yields a separate provider and leaves the |
| 1127 |
original's exchange endpoint alone.""" |
| 1128 |
_mock_token_exchange(respx_mock, BASE_URL, "tok-primary") |
| 1129 |
_mock_token_exchange(respx_mock, OTHER_BASE_URL, "tok-other") |
| 1130 |
creds = _workload_credentials() |
| 1131 |
assert creds.for_base_url(f"{BASE_URL}/") is creds |
| 1132 |
assert creds.for_base_url(BASE_URL) is creds |
| 1133 |
other = creds.for_base_url(OTHER_BASE_URL) |
| 1134 |
assert other is not creds |
| 1135 |
|
| 1136 |
assert other().token == "tok-other" |
| 1137 |
assert creds().token == "tok-primary" |
| 1138 |
# The per-host provider borrows the original's connection pool, so |
| 1139 |
# closing it must not take the original down with it. |
| 1140 |
other.close() |
| 1141 |
assert creds().token == "tok-primary" |
| 1142 |
assert [str(r.url) for r in _requests_to(respx_mock, BASE_URL)] == [TOKEN_URL, TOKEN_URL] |
| 1143 |
|
| 1144 |
def test_for_base_url_http_rejected(self) -> None: |
| 1145 |
creds = _workload_credentials() |
| 1146 |
creds.for_base_url(BASE_URL) |
| 1147 |
with pytest.raises(AnthropicError, match="must use https"): |
| 1148 |
creds.for_base_url("http://evil.example") |
| 1149 |
|
| 1150 |
def test_exchange_federation_assertion_http_rejected(self) -> None: |
| 1151 |
with pytest.raises(AnthropicError, match="must use https"): |
| 1152 |
exchange_federation_assertion( |
| 1153 |
assertion="j", |
| 1154 |
federation_rule_id="fdrl_x", |
| 1155 |
organization_id="org_x", |
| 1156 |
base_url="http://example.com", |
| 1157 |
) |
| 1158 |
|
| 1159 |
@pytest.mark.respx() |
| 1160 |
def test_reinvokes_identity_provider(self, respx_mock: MockRouter) -> None: |
| 1161 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60})) |
| 1162 |
calls: List[int] = [] |
| 1163 |
|
| 1164 |
def jwt_provider() -> str: |
| 1165 |
calls.append(1) |
| 1166 |
return f"jwt-{len(calls)}" |
| 1167 |
|
| 1168 |
creds = WorkloadIdentityCredentials( |
| 1169 |
identity_token_provider=jwt_provider, |
| 1170 |
federation_rule_id="f", |
| 1171 |
organization_id="o", |
| 1172 |
) |
| 1173 |
creds() |
| 1174 |
creds() |
| 1175 |
assert len(calls) == 2 |
| 1176 |
bodies = [json.loads(c.request.content) for c in cast("list[MockRequestCall]", respx_mock.calls)] |
| 1177 |
assert bodies[0]["assertion"] == "jwt-1" |
| 1178 |
assert bodies[1]["assertion"] == "jwt-2" |
| 1179 |
|
| 1180 |
@pytest.mark.respx() |
| 1181 |
def test_403_raises(self, respx_mock: MockRouter) -> None: |
| 1182 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(403, json={"error": "assertion rejected"})) |
| 1183 |
creds = WorkloadIdentityCredentials( |
| 1184 |
identity_token_provider=lambda: "j", |
| 1185 |
federation_rule_id="f", |
| 1186 |
organization_id="o", |
| 1187 |
) |
| 1188 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 1189 |
creds() |
| 1190 |
assert exc_info.value.status_code == 403 |
| 1191 |
assert "assertion rejected" in str(exc_info.value) |
| 1192 |
|
| 1193 |
@pytest.mark.respx() |
| 1194 |
def test_503_raises(self, respx_mock: MockRouter) -> None: |
| 1195 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(503, text="overloaded")) |
| 1196 |
creds = WorkloadIdentityCredentials( |
| 1197 |
identity_token_provider=lambda: "j", |
| 1198 |
federation_rule_id="f", |
| 1199 |
organization_id="o", |
| 1200 |
) |
| 1201 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 1202 |
creds() |
| 1203 |
assert exc_info.value.status_code == 503 |
| 1204 |
|
| 1205 |
@pytest.mark.respx() |
| 1206 |
def test_request_id_surfaced_on_error(self, respx_mock: MockRouter) -> None: |
| 1207 |
respx_mock.post(TOKEN_URL).mock( |
| 1208 |
return_value=httpx2.Response(400, json={"error": "invalid_grant"}, headers={"Request-Id": "req_abc123"}) |
| 1209 |
) |
| 1210 |
creds = WorkloadIdentityCredentials( |
| 1211 |
identity_token_provider=lambda: "j", |
| 1212 |
federation_rule_id="f", |
| 1213 |
organization_id="o", |
| 1214 |
) |
| 1215 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 1216 |
creds() |
| 1217 |
assert exc_info.value.request_id == "req_abc123" |
| 1218 |
assert "[request_id=req_abc123]" in str(exc_info.value) |
| 1219 |
|
| 1220 |
@pytest.mark.respx() |
| 1221 |
def test_401_without_workspace_id_includes_hint(self, respx_mock: MockRouter) -> None: |
| 1222 |
"""A failed exchange with no workspace_id should surface all three hint |
| 1223 |
parts: the federation-rule lead-in, the multi-workspace fix, and the |
| 1224 |
Console auth-events pointer.""" |
| 1225 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(401, json={"error": "unauthorized"})) |
| 1226 |
creds = WorkloadIdentityCredentials( |
| 1227 |
identity_token_provider=lambda: "j", |
| 1228 |
federation_rule_id="f", |
| 1229 |
organization_id="o", |
| 1230 |
) |
| 1231 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 1232 |
creds() |
| 1233 |
message = str(exc_info.value) |
| 1234 |
assert "Ensure your federation rule matches your identity token" in message |
| 1235 |
assert "ANTHROPIC_WORKSPACE_ID" in message |
| 1236 |
assert "scoped to multiple workspaces" in message |
| 1237 |
assert "workspace_id" in message |
| 1238 |
assert "View your authentication events" in message |
| 1239 |
|
| 1240 |
@pytest.mark.respx() |
| 1241 |
def test_401_with_workspace_id_set_omits_workspace_hint(self, respx_mock: MockRouter) -> None: |
| 1242 |
"""When workspace_id is already set the multi-workspace fix is noise, |
| 1243 |
but the federation-rule lead-in and Console pointer still apply.""" |
| 1244 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(401, json={"error": "unauthorized"})) |
| 1245 |
creds = WorkloadIdentityCredentials( |
| 1246 |
identity_token_provider=lambda: "j", |
| 1247 |
federation_rule_id="f", |
| 1248 |
organization_id="o", |
| 1249 |
workspace_id="wrkspc_x", |
| 1250 |
) |
| 1251 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 1252 |
creds() |
| 1253 |
message = str(exc_info.value) |
| 1254 |
assert "Ensure your federation rule matches your identity token" in message |
| 1255 |
assert "View your authentication events" in message |
| 1256 |
assert "ANTHROPIC_WORKSPACE_ID" not in message |
| 1257 |
assert "scoped to multiple workspaces" not in message |
| 1258 |
|
| 1259 |
@pytest.mark.respx() |
| 1260 |
def test_non_401_omits_hint(self, respx_mock: MockRouter) -> None: |
| 1261 |
"""The hint is 401-specific; a 5xx or 400 shouldn't suggest a config change.""" |
| 1262 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(500, json={"error": "server_error"})) |
| 1263 |
creds = WorkloadIdentityCredentials( |
| 1264 |
identity_token_provider=lambda: "j", |
| 1265 |
federation_rule_id="f", |
| 1266 |
organization_id="o", |
| 1267 |
) |
| 1268 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 1269 |
creds() |
| 1270 |
message = str(exc_info.value) |
| 1271 |
assert "Ensure your federation rule" not in message |
| 1272 |
assert "ANTHROPIC_WORKSPACE_ID" not in message |
| 1273 |
assert "View your authentication events" not in message |
| 1274 |
|
| 1275 |
def test_oversized_assertion_rejected(self) -> None: |
| 1276 |
big_jwt = "x" * (16 * 1024 + 1) |
| 1277 |
creds = WorkloadIdentityCredentials( |
| 1278 |
identity_token_provider=lambda: big_jwt, |
| 1279 |
federation_rule_id="f", |
| 1280 |
organization_id="o", |
| 1281 |
) |
| 1282 |
with pytest.raises(WorkloadIdentityError, match="exceeds the 16384-byte limit"): |
| 1283 |
creds() |
| 1284 |
|
| 1285 |
@pytest.mark.respx() |
| 1286 |
def test_non_bearer_token_type_rejected(self, respx_mock: MockRouter) -> None: |
| 1287 |
respx_mock.post(TOKEN_URL).mock( |
| 1288 |
return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60, "token_type": "MAC"}) |
| 1289 |
) |
| 1290 |
creds = WorkloadIdentityCredentials( |
| 1291 |
identity_token_provider=lambda: "j", |
| 1292 |
federation_rule_id="f", |
| 1293 |
organization_id="o", |
| 1294 |
) |
| 1295 |
with pytest.raises(WorkloadIdentityError, match="unsupported token_type 'MAC'"): |
| 1296 |
creds() |
| 1297 |
|
| 1298 |
@pytest.mark.respx() |
| 1299 |
def test_bearer_token_type_case_insensitive(self, respx_mock: MockRouter) -> None: |
| 1300 |
respx_mock.post(TOKEN_URL).mock( |
| 1301 |
return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60, "token_type": "bearer"}) |
| 1302 |
) |
| 1303 |
creds = WorkloadIdentityCredentials( |
| 1304 |
identity_token_provider=lambda: "j", |
| 1305 |
federation_rule_id="f", |
| 1306 |
organization_id="o", |
| 1307 |
) |
| 1308 |
assert creds().token == "t" |
| 1309 |
|
| 1310 |
@pytest.mark.respx() |
| 1311 |
def test_oversized_response_body_rejected(self, respx_mock: MockRouter) -> None: |
| 1312 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(200, content=b"x" * ((1 << 20) + 1))) |
| 1313 |
creds = WorkloadIdentityCredentials( |
| 1314 |
identity_token_provider=lambda: "j", |
| 1315 |
federation_rule_id="f", |
| 1316 |
organization_id="o", |
| 1317 |
) |
| 1318 |
with pytest.raises(WorkloadIdentityError, match="response body exceeds"): |
| 1319 |
creds() |
| 1320 |
|
| 1321 |
|
| 1322 |
# --------------------------------------------------------------------------- # |
| 1323 |
# Profile env-var fill (PY-01) + identity_token validation (PY-06) |
| 1324 |
# --------------------------------------------------------------------------- # |
| 1325 |
|
| 1326 |
|
| 1327 |
class TestProfileEnvFill: |
| 1328 |
"""PY-01: profile fields left empty are filled from ANTHROPIC_* env vars, |
| 1329 |
matching Go's `fillMissingFromEnv` precedence (file wins, env fills gaps).""" |
| 1330 |
|
| 1331 |
@pytest.fixture(autouse=True) |
| 1332 |
def _isolate(self, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 1333 |
for var in _ALL_ENV: |
| 1334 |
monkeypatch.delenv(var, raising=False) |
| 1335 |
monkeypatch.setenv("ANTHROPIC_CONFIG_DIR", str(tmp_path)) |
| 1336 |
|
| 1337 |
def test_env_fills_missing_organization_id(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 1338 |
monkeypatch.setenv("ANTHROPIC_ORGANIZATION_ID", "org_from_env") |
| 1339 |
monkeypatch.setenv("ANTHROPIC_IDENTITY_TOKEN_FILE", str(tmp_path / "tok")) |
| 1340 |
(tmp_path / "tok").write_text("jwt") |
| 1341 |
# Profile omits organization_id; env supplies it. |
| 1342 |
_write_profile( |
| 1343 |
tmp_path, |
| 1344 |
"default", |
| 1345 |
config={ |
| 1346 |
"authentication": { |
| 1347 |
"type": "oidc_federation", |
| 1348 |
"federation_rule_id": "fdrl_01abc", |
| 1349 |
} |
| 1350 |
}, |
| 1351 |
) |
| 1352 |
provider = CredentialsFile() |
| 1353 |
# Trigger _load_config via the workload-build path. |
| 1354 |
delegate = provider._build_workload_delegate(provider._auth_block()) # pyright: ignore[reportPrivateUsage] |
| 1355 |
assert delegate._organization_id == "org_from_env" # pyright: ignore[reportPrivateUsage] |
| 1356 |
|
| 1357 |
def test_profile_value_wins_over_env(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 1358 |
monkeypatch.setenv("ANTHROPIC_ORGANIZATION_ID", "org_from_env") |
| 1359 |
monkeypatch.setenv("ANTHROPIC_WORKSPACE_ID", "wrkspc_env") |
| 1360 |
monkeypatch.setenv("ANTHROPIC_IDENTITY_TOKEN_FILE", str(tmp_path / "tok")) |
| 1361 |
(tmp_path / "tok").write_text("jwt") |
| 1362 |
_write_profile( |
| 1363 |
tmp_path, |
| 1364 |
"default", |
| 1365 |
config={ |
| 1366 |
"organization_id": "org_from_file", |
| 1367 |
"workspace_id": "wrkspc_file", |
| 1368 |
"authentication": { |
| 1369 |
"type": "oidc_federation", |
| 1370 |
"federation_rule_id": "fdrl_01abc", |
| 1371 |
}, |
| 1372 |
}, |
| 1373 |
) |
| 1374 |
provider = CredentialsFile() |
| 1375 |
delegate = provider._build_workload_delegate(provider._auth_block()) # pyright: ignore[reportPrivateUsage] |
| 1376 |
assert delegate._organization_id == "org_from_file" # pyright: ignore[reportPrivateUsage] |
| 1377 |
assert delegate._workspace_id == "wrkspc_file" # pyright: ignore[reportPrivateUsage] |
| 1378 |
|
| 1379 |
def test_env_fills_missing_workspace_id(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 1380 |
monkeypatch.setenv("ANTHROPIC_ORGANIZATION_ID", "org_x") |
| 1381 |
monkeypatch.setenv("ANTHROPIC_WORKSPACE_ID", "wrkspc_from_env") |
| 1382 |
monkeypatch.setenv("ANTHROPIC_IDENTITY_TOKEN_FILE", str(tmp_path / "tok")) |
| 1383 |
(tmp_path / "tok").write_text("jwt") |
| 1384 |
_write_profile( |
| 1385 |
tmp_path, |
| 1386 |
"default", |
| 1387 |
config={ |
| 1388 |
"authentication": { |
| 1389 |
"type": "oidc_federation", |
| 1390 |
"federation_rule_id": "fdrl_01abc", |
| 1391 |
} |
| 1392 |
}, |
| 1393 |
) |
| 1394 |
provider = CredentialsFile() |
| 1395 |
delegate = provider._build_workload_delegate(provider._auth_block()) # pyright: ignore[reportPrivateUsage] |
| 1396 |
assert delegate._workspace_id == "wrkspc_from_env" # pyright: ignore[reportPrivateUsage] |
| 1397 |
|
| 1398 |
def test_env_workspace_id_fills_user_oauth(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 1399 |
"""`ANTHROPIC_WORKSPACE_ID` fills `workspace_id` uniformly across |
| 1400 |
profile types — not just federation. This pins the precedence model: |
| 1401 |
ctor override > env var > profile, regardless of `auth.type`. For |
| 1402 |
`user_oauth` the filled value surfaces as the `anthropic-workspace-id` |
| 1403 |
request header (federation routes it into the exchange body instead).""" |
| 1404 |
monkeypatch.setenv("ANTHROPIC_WORKSPACE_ID", "wrkspc_env") |
| 1405 |
creds_path = tmp_path / "creds.json" |
| 1406 |
creds_path.write_text(json.dumps({"type": "oauth_token", "access_token": "tok", "expires_at": None})) |
| 1407 |
_write_profile( |
| 1408 |
tmp_path, |
| 1409 |
"default", |
| 1410 |
config={ |
| 1411 |
"authentication": { |
| 1412 |
"type": "user_oauth", |
| 1413 |
"client_id": "cid", |
| 1414 |
"credentials_path": str(creds_path), |
| 1415 |
} |
| 1416 |
}, |
| 1417 |
) |
| 1418 |
provider = CredentialsFile() |
| 1419 |
assert provider.extra_headers() == {"anthropic-workspace-id": "wrkspc_env"} |
| 1420 |
|
| 1421 |
|
| 1422 |
class TestIdentityTokenValidation: |
| 1423 |
"""PY-06: identity_token.source 'file' with empty path is a config bug, |
| 1424 |
not an env-var fallback signal.""" |
| 1425 |
|
| 1426 |
@pytest.fixture(autouse=True) |
| 1427 |
def _isolate(self, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 1428 |
for var in _ALL_ENV: |
| 1429 |
monkeypatch.delenv(var, raising=False) |
| 1430 |
monkeypatch.setenv("ANTHROPIC_CONFIG_DIR", str(tmp_path)) |
| 1431 |
|
| 1432 |
def test_empty_path_raises(self, tmp_path: pathlib.Path) -> None: |
| 1433 |
_write_profile( |
| 1434 |
tmp_path, |
| 1435 |
"default", |
| 1436 |
config={ |
| 1437 |
"organization_id": "org", |
| 1438 |
"authentication": { |
| 1439 |
"type": "oidc_federation", |
| 1440 |
"federation_rule_id": "fdrl_01abc", |
| 1441 |
"identity_token": {"source": "file", "path": ""}, |
| 1442 |
}, |
| 1443 |
}, |
| 1444 |
) |
| 1445 |
provider = CredentialsFile() |
| 1446 |
with pytest.raises(AnthropicError, match="non-empty path"): |
| 1447 |
provider._build_workload_delegate(provider._auth_block()) # pyright: ignore[reportPrivateUsage] |
| 1448 |
|
| 1449 |
|
| 1450 |
# --------------------------------------------------------------------------- # |
| 1451 |
# TokenCache |
| 1452 |
# --------------------------------------------------------------------------- # |
| 1453 |
|
| 1454 |
|
| 1455 |
class FakeClock: |
| 1456 |
def __init__(self, now: float = 1000.0) -> None: |
| 1457 |
self.now = now |
| 1458 |
|
| 1459 |
def __call__(self) -> float: |
| 1460 |
return self.now |
| 1461 |
|
| 1462 |
|
| 1463 |
class CountingProvider: |
| 1464 |
def __init__(self, tokens: List[AccessToken]) -> None: |
| 1465 |
self.tokens = tokens |
| 1466 |
self.calls = 0 |
| 1467 |
|
| 1468 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 1469 |
self.calls += 1 |
| 1470 |
return self.tokens[min(self.calls - 1, len(self.tokens) - 1)] |
| 1471 |
|
| 1472 |
|
| 1473 |
class TestTokenCache: |
| 1474 |
def test_first_call_fetches(self) -> None: |
| 1475 |
provider = CountingProvider([AccessToken("a", expires_at=2000)]) |
| 1476 |
cache = TokenCache(provider, time_source=FakeClock(1000)) |
| 1477 |
assert cache.get_token() == "a" |
| 1478 |
assert provider.calls == 1 |
| 1479 |
|
| 1480 |
def test_provider_must_return_an_access_token(self) -> None: |
| 1481 |
calls: List[int] = [] |
| 1482 |
|
| 1483 |
def provider(*, force_refresh: bool = False) -> Any: # noqa: ARG001 |
| 1484 |
calls.append(1) |
| 1485 |
return "sk-a-raw-string" |
| 1486 |
|
| 1487 |
with pytest.raises(AnthropicError, match="returned str instead of an AccessToken"): |
| 1488 |
TokenCache(provider).get_token() |
| 1489 |
assert calls == [1] |
| 1490 |
|
| 1491 |
def test_sync_callable_returning_a_coroutine_is_rejected(self) -> None: |
| 1492 |
"""The coroutine is closed, so nothing warns that it was never awaited.""" |
| 1493 |
coroutines: List[Any] = [] |
| 1494 |
|
| 1495 |
async def fetch() -> AccessToken: |
| 1496 |
return AccessToken("t") |
| 1497 |
|
| 1498 |
def provider(*, force_refresh: bool = False) -> Any: # noqa: ARG001 |
| 1499 |
coroutines.append(fetch()) |
| 1500 |
return coroutines[-1] |
| 1501 |
|
| 1502 |
with pytest.raises(AnthropicError, match="returned a coroutine .* pass the `async def` function itself"): |
| 1503 |
TokenCache(provider).get_token() |
| 1504 |
assert coroutines[0].cr_frame is None, "the coroutine should have been closed" |
| 1505 |
|
| 1506 |
def test_get_token_rejects_async_provider(self) -> None: |
| 1507 |
async def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 1508 |
return AccessToken("t") |
| 1509 |
|
| 1510 |
with pytest.raises(RuntimeError, match="async_get_token"): |
| 1511 |
TokenCache(provider).get_token() |
| 1512 |
|
| 1513 |
def test_no_expiry_never_refreshes(self) -> None: |
| 1514 |
provider = CountingProvider([AccessToken("a", expires_at=None)]) |
| 1515 |
clock = FakeClock(1000) |
| 1516 |
cache = TokenCache(provider, time_source=clock) |
| 1517 |
cache.get_token() |
| 1518 |
clock.now = 999999 |
| 1519 |
cache.get_token() |
| 1520 |
cache.get_token() |
| 1521 |
assert provider.calls == 1 |
| 1522 |
|
| 1523 |
def test_fresh_token_not_refetched(self) -> None: |
| 1524 |
clock = FakeClock(1000) |
| 1525 |
provider = CountingProvider([AccessToken("a", expires_at=1000 + 600)]) |
| 1526 |
cache = TokenCache(provider, time_source=clock) |
| 1527 |
cache.get_token() |
| 1528 |
cache.get_token() |
| 1529 |
cache.get_token() |
| 1530 |
assert provider.calls == 1 |
| 1531 |
|
| 1532 |
def test_advisory_refresh_success(self) -> None: |
| 1533 |
clock = FakeClock(1000) |
| 1534 |
provider = CountingProvider([AccessToken("a", expires_at=1000 + 600), AccessToken("b", expires_at=1000 + 1200)]) |
| 1535 |
cache = TokenCache(provider, time_source=clock) |
| 1536 |
assert cache.get_token() == "a" |
| 1537 |
clock.now = 1000 + 600 - 60 # 60s remaining: advisory window (30 < 60 < 120) |
| 1538 |
assert cache.get_token() == "b" |
| 1539 |
assert provider.calls == 2 |
| 1540 |
|
| 1541 |
def test_advisory_refresh_failure_serves_stale(self, caplog: pytest.LogCaptureFixture) -> None: |
| 1542 |
clock = FakeClock(1000) |
| 1543 |
first = AccessToken("a", expires_at=1000 + 600) |
| 1544 |
|
| 1545 |
class P: |
| 1546 |
calls = 0 |
| 1547 |
|
| 1548 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 1549 |
self.calls += 1 |
| 1550 |
if self.calls == 1: |
| 1551 |
return first |
| 1552 |
raise WorkloadIdentityError("backend down") |
| 1553 |
|
| 1554 |
provider = P() |
| 1555 |
cache = TokenCache(provider, time_source=clock) |
| 1556 |
assert cache.get_token() == "a" |
| 1557 |
clock.now = 1000 + 600 - 60 # advisory window |
| 1558 |
with caplog.at_level(logging.WARNING): |
| 1559 |
assert cache.get_token() == "a" # stale served |
| 1560 |
assert any("Advisory token refresh failed (60s remaining)" in r.getMessage() for r in caplog.records) |
| 1561 |
assert provider.calls == 2 |
| 1562 |
|
| 1563 |
def test_mandatory_refresh_failure_raises(self) -> None: |
| 1564 |
clock = FakeClock(1000) |
| 1565 |
first = AccessToken("a", expires_at=1000 + 600) |
| 1566 |
|
| 1567 |
class P: |
| 1568 |
calls = 0 |
| 1569 |
|
| 1570 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 1571 |
self.calls += 1 |
| 1572 |
if self.calls == 1: |
| 1573 |
return first |
| 1574 |
raise WorkloadIdentityError("backend down") |
| 1575 |
|
| 1576 |
provider = P() |
| 1577 |
cache = TokenCache(provider, time_source=clock) |
| 1578 |
cache.get_token() |
| 1579 |
clock.now = 1000 + 600 - 10 # 10s remaining: mandatory window |
| 1580 |
with pytest.raises(WorkloadIdentityError, match="backend down"): |
| 1581 |
cache.get_token() |
| 1582 |
|
| 1583 |
def test_expired_is_mandatory(self) -> None: |
| 1584 |
clock = FakeClock(1000) |
| 1585 |
provider = CountingProvider([AccessToken("a", expires_at=1000 + 600), AccessToken("b", expires_at=1000 + 1200)]) |
| 1586 |
cache = TokenCache(provider, time_source=clock) |
| 1587 |
cache.get_token() |
| 1588 |
clock.now = 1000 + 700 # already expired |
| 1589 |
assert cache.get_token() == "b" |
| 1590 |
assert provider.calls == 2 |
| 1591 |
|
| 1592 |
def test_invalidate(self) -> None: |
| 1593 |
provider = CountingProvider([AccessToken("a", None), AccessToken("b", None)]) |
| 1594 |
cache = TokenCache(provider) |
| 1595 |
assert cache.get_token() == "a" |
| 1596 |
assert cache.get_token() == "a" |
| 1597 |
assert provider.calls == 1 |
| 1598 |
cache.invalidate() |
| 1599 |
assert cache.get_token() == "b" |
| 1600 |
assert provider.calls == 2 |
| 1601 |
|
| 1602 |
def test_retries_once_on_401_from_token_endpoint(self) -> None: |
| 1603 |
"""If the provider raises a 401 WorkloadIdentityError, the cache retries once.""" |
| 1604 |
|
| 1605 |
class Provider401ThenSuccess: |
| 1606 |
calls = 0 |
| 1607 |
|
| 1608 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 1609 |
self.calls += 1 |
| 1610 |
if self.calls == 1: |
| 1611 |
raise WorkloadIdentityError("token exchange failed", status_code=401, body="unauthorized") |
| 1612 |
return AccessToken("fresh", expires_at=None) |
| 1613 |
|
| 1614 |
provider = Provider401ThenSuccess() |
| 1615 |
cache = TokenCache(provider) |
| 1616 |
assert cache.get_token() == "fresh" |
| 1617 |
assert provider.calls == 2 |
| 1618 |
|
| 1619 |
def test_no_retry_on_non_401_error(self) -> None: |
| 1620 |
"""Non-401 errors from the provider are not retried.""" |
| 1621 |
|
| 1622 |
class Provider400: |
| 1623 |
calls = 0 |
| 1624 |
|
| 1625 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 1626 |
self.calls += 1 |
| 1627 |
raise WorkloadIdentityError("bad request", status_code=400, body="invalid") |
| 1628 |
|
| 1629 |
provider = Provider400() |
| 1630 |
cache = TokenCache(provider) |
| 1631 |
with pytest.raises(WorkloadIdentityError, match="bad request"): |
| 1632 |
cache.get_token() |
| 1633 |
assert provider.calls == 1 |
| 1634 |
|
| 1635 |
def test_retry_on_401_still_fails_raises(self) -> None: |
| 1636 |
"""If both attempts return 401, the second error propagates.""" |
| 1637 |
|
| 1638 |
class AlwaysFails401: |
| 1639 |
calls = 0 |
| 1640 |
|
| 1641 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 1642 |
self.calls += 1 |
| 1643 |
raise WorkloadIdentityError("still unauthorized", status_code=401, body="unauthorized") |
| 1644 |
|
| 1645 |
provider = AlwaysFails401() |
| 1646 |
cache = TokenCache(provider) |
| 1647 |
with pytest.raises(WorkloadIdentityError, match="still unauthorized"): |
| 1648 |
cache.get_token() |
| 1649 |
assert provider.calls == 2 |
| 1650 |
|
| 1651 |
def test_concurrent_mandatory_refresh_single_flight(self) -> None: |
| 1652 |
"""N concurrent callers in the mandatory (expired) window trigger |
| 1653 |
exactly one provider call — waiters block on the leader's event.""" |
| 1654 |
import threading as _threading |
| 1655 |
|
| 1656 |
provider_calls: List[int] = [] |
| 1657 |
barrier = _threading.Barrier(8) |
| 1658 |
|
| 1659 |
def slow_provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 1660 |
provider_calls.append(1) |
| 1661 |
# Hold the refresh long enough for the other threads to queue up. |
| 1662 |
time.sleep(0.1) |
| 1663 |
return AccessToken(token="fresh", expires_at=None) |
| 1664 |
|
| 1665 |
cache = TokenCache(slow_provider) |
| 1666 |
results: List[str] = [] |
| 1667 |
lock = _threading.Lock() |
| 1668 |
|
| 1669 |
def worker() -> None: |
| 1670 |
barrier.wait() |
| 1671 |
tok = cache.get_token() |
| 1672 |
with lock: |
| 1673 |
results.append(tok) |
| 1674 |
|
| 1675 |
threads = [_threading.Thread(target=worker) for _ in range(8)] |
| 1676 |
for t in threads: |
| 1677 |
t.start() |
| 1678 |
for t in threads: |
| 1679 |
t.join() |
| 1680 |
|
| 1681 |
assert len(provider_calls) == 1 |
| 1682 |
assert results == ["fresh"] * 8 |
| 1683 |
|
| 1684 |
@pytest.mark.parametrize("expires_at", [1, 1000 - 5], ids=["epoch-plus-one", "just-expired"]) |
| 1685 |
def test_expired_but_nonzero_expiry_keeps_single_flight(self, expires_at: int) -> None: |
| 1686 |
"""Only exactly `expires_at=0` opts out of single-flight; any other past value is an expired token.""" |
| 1687 |
calls = itertools.count(1) |
| 1688 |
release = threading.Event() |
| 1689 |
|
| 1690 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 1691 |
n = next(calls) |
| 1692 |
if n == 2: |
| 1693 |
assert release.wait(5) |
| 1694 |
return AccessToken(f"tok-{n}", expires_at=expires_at if n < 3 else None) |
| 1695 |
|
| 1696 |
cache = TokenCache(provider, time_source=FakeClock(1000)) |
| 1697 |
assert cache.get_token() == "tok-1" |
| 1698 |
tokens: List[str] = [] |
| 1699 |
threads = [threading.Thread(target=lambda: tokens.append(cache.get_token())) for _ in range(3)] |
| 1700 |
for t in threads: |
| 1701 |
t.start() |
| 1702 |
release.set() |
| 1703 |
for t in threads: |
| 1704 |
t.join(timeout=5) |
| 1705 |
assert not t.is_alive(), "get_token() deadlocked" |
| 1706 |
# One caller at a time: tok-2 is expired too, so the next leader fetches tok-3, which is then cached. |
| 1707 |
assert sorted(tokens) == ["tok-2", "tok-3", "tok-3"] |
| 1708 |
|
| 1709 |
def test_zero_expiry_token_is_not_reused(self) -> None: |
| 1710 |
"""A token with `expires_at=0` is not reused, so the provider is called again until it returns a later expiry.""" |
| 1711 |
clock = FakeClock(1000) |
| 1712 |
provider = CountingProvider( |
| 1713 |
[AccessToken("a", expires_at=0), AccessToken("b", expires_at=0), AccessToken("c", expires_at=1000 + 600)] |
| 1714 |
) |
| 1715 |
cache = TokenCache(provider, time_source=clock) |
| 1716 |
assert [cache.get_token() for _ in range(4)] == ["a", "b", "c", "c"] |
| 1717 |
assert provider.calls == 3 |
| 1718 |
|
| 1719 |
def test_zero_expiry_tokens_are_fetched_concurrently(self) -> None: |
| 1720 |
"""Callers don't queue behind each other for a token that can't be shared.""" |
| 1721 |
import threading as _threading |
| 1722 |
|
| 1723 |
calls = itertools.count(1) |
| 1724 |
all_three_fetching = _threading.Barrier(3, timeout=2) # breaks if the callers queued |
| 1725 |
|
| 1726 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 1727 |
n = next(calls) |
| 1728 |
if n > 1: |
| 1729 |
all_three_fetching.wait() |
| 1730 |
return AccessToken(f"tok-{n}", expires_at=0) |
| 1731 |
|
| 1732 |
cache = TokenCache(provider) |
| 1733 |
assert cache.get_token() == "tok-1" |
| 1734 |
tokens: List[str] = [] |
| 1735 |
threads = [_threading.Thread(target=lambda: tokens.append(cache.get_token())) for _ in range(3)] |
| 1736 |
for t in threads: |
| 1737 |
t.start() |
| 1738 |
for t in threads: |
| 1739 |
t.join(timeout=5) |
| 1740 |
assert not t.is_alive(), "get_token() deadlocked" |
| 1741 |
assert sorted(tokens) == ["tok-2", "tok-3", "tok-4"] |
| 1742 |
|
| 1743 |
def test_advisory_caller_skips_when_refresh_in_flight(self) -> None: |
| 1744 |
"""A caller in the advisory window does NOT start a second refresh and |
| 1745 |
does NOT wait on a running one — it just returns the cached token.""" |
| 1746 |
import threading as _threading |
| 1747 |
|
| 1748 |
clock = FakeClock(1000) |
| 1749 |
tokens = [AccessToken("a", expires_at=1000 + 600), AccessToken("b", expires_at=1000 + 1800)] |
| 1750 |
provider_calls: List[int] = [] |
| 1751 |
refresh_started = _threading.Event() |
| 1752 |
release_refresh = _threading.Event() |
| 1753 |
|
| 1754 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 1755 |
provider_calls.append(1) |
| 1756 |
refresh_started.set() |
| 1757 |
release_refresh.wait(timeout=2) |
| 1758 |
return tokens[len(provider_calls) - 1] |
| 1759 |
|
| 1760 |
cache = TokenCache(provider, time_source=clock) |
| 1761 |
# Prime the cache with token 'a'. |
| 1762 |
assert cache.get_token() == "a" |
| 1763 |
|
| 1764 |
# Move into the advisory window and kick off a refresh on a background |
| 1765 |
# thread. It will block in the provider until we release it. |
| 1766 |
clock.now = 1000 + 600 - 60 |
| 1767 |
leader = _threading.Thread(target=cache.get_token) |
| 1768 |
leader.start() |
| 1769 |
assert refresh_started.wait(timeout=2) |
| 1770 |
|
| 1771 |
# A second caller in the advisory window should see the in-flight |
| 1772 |
# refresh and return the cached token immediately — without waiting. |
| 1773 |
t0 = time.monotonic() |
| 1774 |
observed = cache.get_token() |
| 1775 |
elapsed = time.monotonic() - t0 |
| 1776 |
assert observed == "a" |
| 1777 |
assert elapsed < 0.1, f"advisory caller waited for leader ({elapsed:.3f}s)" |
| 1778 |
|
| 1779 |
release_refresh.set() |
| 1780 |
leader.join() |
| 1781 |
# Two provider calls total: the priming call + the leader's advisory |
| 1782 |
# refresh. The bystander did NOT call the provider. |
| 1783 |
assert len(provider_calls) == 2 |
| 1784 |
|
| 1785 |
def test_invalidate_forces_provider_refresh(self) -> None: |
| 1786 |
"""PY-02: after invalidate(), the next provider call receives |
| 1787 |
force_refresh=True so providers with on-disk caches bypass their |
| 1788 |
freshness short-circuit. Without this, a 401 retry would re-read |
| 1789 |
the same expired token from disk and serve it again.""" |
| 1790 |
force_seen: List[bool] = [] |
| 1791 |
tokens = iter([AccessToken("a", expires_at=None), AccessToken("b", expires_at=None)]) |
| 1792 |
|
| 1793 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 1794 |
force_seen.append(force_refresh) |
| 1795 |
return next(tokens) |
| 1796 |
|
| 1797 |
cache = TokenCache(provider) |
| 1798 |
assert cache.get_token() == "a" |
| 1799 |
cache.invalidate() |
| 1800 |
assert cache.get_token() == "b" |
| 1801 |
assert force_seen == [False, True], "force_refresh must be True on the post-invalidate call" |
| 1802 |
|
| 1803 |
def test_zero_arg_provider_backward_compat(self) -> None: |
| 1804 |
"""Providers from before the force_refresh kwarg was added (the old |
| 1805 |
`Callable[[], AccessToken]` shape) must still work — their signature |
| 1806 |
has no `force_refresh`, so they are called without it.""" |
| 1807 |
calls: List[int] = [] |
| 1808 |
|
| 1809 |
def legacy_provider() -> AccessToken: |
| 1810 |
calls.append(1) |
| 1811 |
return AccessToken("legacy", expires_at=None) |
| 1812 |
|
| 1813 |
cache = TokenCache(legacy_provider) # type: ignore[arg-type] |
| 1814 |
assert cache.get_token() == "legacy" |
| 1815 |
# invalidate() sets _next_force; the provider is still called with no arguments. |
| 1816 |
cache.invalidate() |
| 1817 |
assert cache.get_token() == "legacy" |
| 1818 |
assert len(calls) == 2 |
| 1819 |
|
| 1820 |
@pytest.mark.skipif(sys.version_info < (3, 14), reason="annotations are evaluated lazily from Python 3.14") |
| 1821 |
@pytest.mark.parametrize( |
| 1822 |
("signature", "expected"), |
| 1823 |
[("*, force_refresh: bool = False, context: OnlyForTypeCheckers = None", [False, True]), ("", [None, None])], |
| 1824 |
ids=["force_refresh", "zero-arg"], |
| 1825 |
) |
| 1826 |
def test_provider_annotated_with_an_undefined_name(self, signature: str, expected: List[object]) -> None: |
| 1827 |
"""Reading the signature must not evaluate annotations that only resolve for type checkers.""" |
| 1828 |
force_seen: List[object] = [] |
| 1829 |
namespace: Dict[str, Any] = {"AccessToken": AccessToken, "force_seen": force_seen} |
| 1830 |
source = f""" |
| 1831 |
def provider({signature}) -> OnlyForTypeCheckers: |
| 1832 |
force_seen.append(locals().get("force_refresh")) |
| 1833 |
return AccessToken("t") |
| 1834 |
""" |
| 1835 |
# dont_inherit: this module's `from __future__ import annotations` would turn the annotations into strings. |
| 1836 |
exec(compile(source, "<provider>", "exec", dont_inherit=True), namespace) |
| 1837 |
|
| 1838 |
cache = TokenCache(namespace["provider"]) |
| 1839 |
cache.get_token() |
| 1840 |
cache.invalidate() |
| 1841 |
cache.get_token() |
| 1842 |
assert force_seen == expected |
| 1843 |
|
| 1844 |
def test_var_keyword_provider_receives_force_refresh(self) -> None: |
| 1845 |
force_seen: List[object] = [] |
| 1846 |
|
| 1847 |
def provider(**kwargs: object) -> AccessToken: |
| 1848 |
force_seen.append(kwargs.get("force_refresh")) |
| 1849 |
return AccessToken("t") |
| 1850 |
|
| 1851 |
cache = TokenCache(provider) |
| 1852 |
cache.get_token() |
| 1853 |
cache.invalidate() |
| 1854 |
cache.get_token() |
| 1855 |
assert force_seen == [False, True] |
| 1856 |
|
| 1857 |
def test_next_force_preserved_on_provider_failure(self) -> None: |
| 1858 |
"""If invalidate() set the force flag and the provider then raises, |
| 1859 |
the flag must NOT be consumed — a subsequent retry must still see |
| 1860 |
force_refresh=True. Otherwise the retry serves the stale disk token |
| 1861 |
PY-02 was added to bypass.""" |
| 1862 |
force_seen: List[bool] = [] |
| 1863 |
attempts = iter([RuntimeError("transient"), AccessToken("ok", expires_at=None)]) |
| 1864 |
|
| 1865 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 1866 |
force_seen.append(force_refresh) |
| 1867 |
v = next(attempts) |
| 1868 |
if isinstance(v, BaseException): |
| 1869 |
raise v |
| 1870 |
return v |
| 1871 |
|
| 1872 |
cache = TokenCache(provider) |
| 1873 |
cache.invalidate() |
| 1874 |
with pytest.raises(RuntimeError): |
| 1875 |
cache.get_token() |
| 1876 |
# Retry: force flag must still be set. |
| 1877 |
assert cache.get_token() == "ok" |
| 1878 |
assert force_seen == [True, True], "force flag must survive provider failure" |
| 1879 |
|
| 1880 |
def test_next_force_preserved_when_provider_returns_non_token(self) -> None: |
| 1881 |
"""A rejected provider return does not consume the force flag set by invalidate().""" |
| 1882 |
force_seen: List[bool] = [] |
| 1883 |
results = iter([AccessToken("a", expires_at=None), None, AccessToken("b", expires_at=None)]) |
| 1884 |
|
| 1885 |
def provider(*, force_refresh: bool = False) -> AccessToken: |
| 1886 |
force_seen.append(force_refresh) |
| 1887 |
return cast(AccessToken, next(results)) |
| 1888 |
|
| 1889 |
cache = TokenCache(provider) |
| 1890 |
assert cache.get_token() == "a" |
| 1891 |
cache.invalidate() |
| 1892 |
with pytest.raises(AnthropicError, match="credentials provider returned"): |
| 1893 |
cache.get_token() |
| 1894 |
assert cache.get_token() == "b" |
| 1895 |
assert force_seen == [False, True, True] |
| 1896 |
|
| 1897 |
def test_per_request_mode_still_forces_after_invalidate(self) -> None: |
| 1898 |
"""invalidate() still makes the next call pass `force_refresh=True` when nothing is cached.""" |
| 1899 |
force_seen: List[bool] = [] |
| 1900 |
|
| 1901 |
def provider(*, force_refresh: bool = False) -> AccessToken: |
| 1902 |
force_seen.append(force_refresh) |
| 1903 |
return AccessToken(f"tok-{len(force_seen)}", expires_at=0) |
| 1904 |
|
| 1905 |
cache = TokenCache(provider) |
| 1906 |
cache.get_token() |
| 1907 |
cache.get_token() |
| 1908 |
cache.invalidate() |
| 1909 |
cache.get_token() |
| 1910 |
cache.get_token() |
| 1911 |
assert force_seen == [False, False, True, False] |
| 1912 |
|
| 1913 |
def test_concurrent_invalidate_survives_non_forced_call(self) -> None: |
| 1914 |
"""An invalidate() that lands during a non-forced call still forces the next call.""" |
| 1915 |
force_seen: List[bool] = [] |
| 1916 |
|
| 1917 |
def provider(*, force_refresh: bool = False) -> AccessToken: |
| 1918 |
force_seen.append(force_refresh) |
| 1919 |
if len(force_seen) == 2: |
| 1920 |
cache.invalidate() # simulates another request's 401 arriving now |
| 1921 |
return AccessToken(f"tok-{len(force_seen)}", expires_at=0) |
| 1922 |
|
| 1923 |
cache = TokenCache(provider) |
| 1924 |
cache.get_token() # switch to per-request mode |
| 1925 |
cache.get_token() |
| 1926 |
cache.get_token() |
| 1927 |
assert force_seen == [False, False, True] |
| 1928 |
|
| 1929 |
def test_unforced_result_is_not_cached_after_a_concurrent_invalidate(self) -> None: |
| 1930 |
"""The token may be the one the API just rejected, so it serves this request only.""" |
| 1931 |
force_seen: List[bool] = [] |
| 1932 |
|
| 1933 |
def provider(*, force_refresh: bool = False) -> AccessToken: |
| 1934 |
force_seen.append(force_refresh) |
| 1935 |
if len(force_seen) == 1: |
| 1936 |
cache.invalidate() # simulates another request's 401 arriving now |
| 1937 |
return AccessToken(f"tok-{len(force_seen)}") |
| 1938 |
|
| 1939 |
cache = TokenCache(provider) |
| 1940 |
assert cache.get_token() == "tok-1" |
| 1941 |
assert cache.get_token() == "tok-2" |
| 1942 |
assert cache.get_token() == "tok-2" |
| 1943 |
assert force_seen == [False, True] |
| 1944 |
|
| 1945 |
def test_late_per_request_result_does_not_replace_cached_expiring_token(self) -> None: |
| 1946 |
import threading as _threading |
| 1947 |
|
| 1948 |
clock = FakeClock(1000) |
| 1949 |
force_seen: List[bool] = [] |
| 1950 |
p_in, p_release = _threading.Event(), _threading.Event() |
| 1951 |
|
| 1952 |
def provider(*, force_refresh: bool = False) -> AccessToken: |
| 1953 |
force_seen.append(force_refresh) |
| 1954 |
if _threading.current_thread().name == "P": |
| 1955 |
p_in.set() |
| 1956 |
assert p_release.wait(5) |
| 1957 |
return AccessToken("tok-late", expires_at=0) |
| 1958 |
if force_refresh: |
| 1959 |
return AccessToken("tok-forced", expires_at=1000 + 3600) |
| 1960 |
return AccessToken(f"tok-{len(force_seen)}", expires_at=0) |
| 1961 |
|
| 1962 |
cache = TokenCache(provider, time_source=clock) |
| 1963 |
assert cache.get_token() == "tok-1" # per-request mode |
| 1964 |
late: List[str] = [] |
| 1965 |
p = _threading.Thread(target=lambda: late.append(cache.get_token()), name="P", daemon=True) |
| 1966 |
p.start() |
| 1967 |
assert p_in.wait(5) |
| 1968 |
cache.invalidate() |
| 1969 |
assert cache.get_token() == "tok-forced" # cached with a real expiry |
| 1970 |
p_release.set() |
| 1971 |
p.join(5) |
| 1972 |
assert not p.is_alive(), "the late caller deadlocked" |
| 1973 |
assert late == ["tok-late"] # the late caller still uses its own token for its request |
| 1974 |
assert cache.get_token() == "tok-forced" # served from cache, no provider call |
| 1975 |
assert force_seen == [False, False, True] |
| 1976 |
|
| 1977 |
def test_advisory_refresh_backoff_after_failure(self) -> None: |
| 1978 |
"""PY-07: after an advisory refresh failure, subsequent advisory |
| 1979 |
callers within ADVISORY_REFRESH_BACKOFF_SECONDS reuse the cached |
| 1980 |
token instead of re-attempting the provider — preventing an |
| 1981 |
outage during the advisory window from being hammered at request rate.""" |
| 1982 |
from anthropic.lib.credentials._workload import WorkloadIdentityError as _WIE |
| 1983 |
|
| 1984 |
clock = FakeClock(1000) |
| 1985 |
provider_calls: List[int] = [] |
| 1986 |
|
| 1987 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 1988 |
provider_calls.append(1) |
| 1989 |
if len(provider_calls) == 1: |
| 1990 |
return AccessToken("a", expires_at=1000 + 600) |
| 1991 |
raise _WIE("token endpoint down", status_code=503) |
| 1992 |
|
| 1993 |
cache = TokenCache(provider, time_source=clock) |
| 1994 |
assert cache.get_token() == "a" |
| 1995 |
# Step into the advisory window. |
| 1996 |
clock.now = 1000 + 600 - 60 |
| 1997 |
# First advisory call: fires the provider, fails, serves cached. |
| 1998 |
assert cache.get_token() == "a" |
| 1999 |
assert len(provider_calls) == 2 |
| 2000 |
|
| 2001 |
# Second advisory call within backoff window: must reuse cached |
| 2002 |
# WITHOUT calling the provider. |
| 2003 |
clock.now += 3 |
| 2004 |
assert cache.get_token() == "a" |
| 2005 |
assert len(provider_calls) == 2, "provider must not be retried within backoff window" |
| 2006 |
|
| 2007 |
# After the backoff window, the next advisory call retries. |
| 2008 |
clock.now += 3 # total +6 since failure, > 5s backoff |
| 2009 |
assert cache.get_token() == "a" # still serves cached after retry fails |
| 2010 |
assert len(provider_calls) == 3, "provider must be retried after backoff window" |
| 2011 |
|
| 2012 |
|
| 2013 |
# --------------------------------------------------------------------------- # |
| 2014 |
# default_credentials chain |
| 2015 |
# --------------------------------------------------------------------------- # |
| 2016 |
|
| 2017 |
|
| 2018 |
@pytest.mark.usefixtures("no_default_creds_file") |
| 2019 |
class TestDefaultCredentials: |
| 2020 |
def test_api_key_returns_none(self, clean_env: pytest.MonkeyPatch) -> None: |
| 2021 |
clean_env.setenv("ANTHROPIC_API_KEY", "sk-ant-api-key") |
| 2022 |
assert default_credentials() is None |
| 2023 |
|
| 2024 |
def test_auth_token_returns_static(self, clean_env: pytest.MonkeyPatch) -> None: |
| 2025 |
clean_env.setenv("ANTHROPIC_AUTH_TOKEN", "bearer-tok") |
| 2026 |
result = default_credentials() |
| 2027 |
assert result is not None |
| 2028 |
assert isinstance(result.provider, StaticToken) |
| 2029 |
assert result.provider().token == "bearer-tok" |
| 2030 |
|
| 2031 |
def test_config_dir_env_triggers_tier1(self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 2032 |
"""ANTHROPIC_CONFIG_DIR set → tier 1 fires even if dir is empty (explicit opt-in).""" |
| 2033 |
# Re-point _config_dir at tmp_path (the no_default_creds_file fixture |
| 2034 |
# already patched it to an empty dir; override that here). |
| 2035 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2036 |
clean_env.setenv("ANTHROPIC_CONFIG_DIR", str(tmp_path)) |
| 2037 |
_write_profile(tmp_path, "default", {"type": "external"}, {"access_token": "from-file"}) |
| 2038 |
result = default_credentials() |
| 2039 |
assert result is not None |
| 2040 |
assert isinstance(result.provider, CredentialsFile) |
| 2041 |
assert result.provider().token == "from-file" |
| 2042 |
|
| 2043 |
def test_profile_env_triggers_tier1(self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 2044 |
"""ANTHROPIC_PROFILE set → tier 1 fires.""" |
| 2045 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2046 |
clean_env.setenv("ANTHROPIC_PROFILE", "work") |
| 2047 |
_write_profile(tmp_path, "work", {"type": "external"}, {"access_token": "from-work"}) |
| 2048 |
result = default_credentials() |
| 2049 |
assert result is not None |
| 2050 |
assert isinstance(result.provider, CredentialsFile) |
| 2051 |
assert result.provider().token == "from-work" |
| 2052 |
|
| 2053 |
def test_default_dir_with_configs_triggers_tier1( |
| 2054 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 2055 |
) -> None: |
| 2056 |
"""No env vars but configs/ has files → tier 1 fires via _has_any_config().""" |
| 2057 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2058 |
_write_profile(tmp_path, "default", {"type": "external"}, {"access_token": "from-default"}) |
| 2059 |
result = default_credentials() |
| 2060 |
assert result is not None |
| 2061 |
assert isinstance(result.provider, CredentialsFile) |
| 2062 |
|
| 2063 |
def test_workload_identity_tier(self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 2064 |
f = tmp_path / "jwt" |
| 2065 |
f.write_text("ext-jwt") |
| 2066 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN_FILE", str(f)) |
| 2067 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 2068 |
clean_env.setenv("ANTHROPIC_ORGANIZATION_ID", "org-uuid") |
| 2069 |
result = default_credentials() |
| 2070 |
assert result is not None |
| 2071 |
assert isinstance(result.provider, WorkloadIdentityCredentials) |
| 2072 |
|
| 2073 |
def test_workload_identity_literal_token(self, clean_env: pytest.MonkeyPatch) -> None: |
| 2074 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN", "literal-jwt") |
| 2075 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 2076 |
clean_env.setenv("ANTHROPIC_ORGANIZATION_ID", "org-uuid") |
| 2077 |
result = default_credentials() |
| 2078 |
assert result is not None |
| 2079 |
assert isinstance(result.provider, WorkloadIdentityCredentials) |
| 2080 |
|
| 2081 |
def test_workload_identity_scope_env(self, clean_env: pytest.MonkeyPatch) -> None: |
| 2082 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN", "literal-jwt") |
| 2083 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 2084 |
clean_env.setenv("ANTHROPIC_ORGANIZATION_ID", "org-uuid") |
| 2085 |
clean_env.setenv("ANTHROPIC_SCOPE", "api:read api:write") |
| 2086 |
result = default_credentials() |
| 2087 |
assert result is not None |
| 2088 |
assert isinstance(result.provider, WorkloadIdentityCredentials) |
| 2089 |
assert result.provider.scope == "api:read api:write" |
| 2090 |
|
| 2091 |
def test_workload_identity_workspace_id_env(self, clean_env: pytest.MonkeyPatch) -> None: |
| 2092 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN", "literal-jwt") |
| 2093 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 2094 |
clean_env.setenv("ANTHROPIC_ORGANIZATION_ID", "org-uuid") |
| 2095 |
clean_env.setenv("ANTHROPIC_WORKSPACE_ID", "wrkspc_01abc") |
| 2096 |
result = default_credentials() |
| 2097 |
assert result is not None |
| 2098 |
provider = result.provider |
| 2099 |
assert isinstance(provider, WorkloadIdentityCredentials) |
| 2100 |
assert provider._workspace_id == "wrkspc_01abc" # pyright: ignore[reportPrivateUsage] |
| 2101 |
|
| 2102 |
@pytest.mark.respx() |
| 2103 |
def test_workload_identity_workspace_id_env_empty_treated_unset( |
| 2104 |
self, clean_env: pytest.MonkeyPatch, respx_mock: MockRouter |
| 2105 |
) -> None: |
| 2106 |
"""`ANTHROPIC_WORKSPACE_ID=""` (a defaulted-but-empty CI variable) is |
| 2107 |
treated as unset — never put `"workspace_id": ""` on the wire.""" |
| 2108 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN", "literal-jwt") |
| 2109 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 2110 |
clean_env.setenv("ANTHROPIC_ORGANIZATION_ID", "org-uuid") |
| 2111 |
clean_env.setenv("ANTHROPIC_WORKSPACE_ID", "") |
| 2112 |
respx_mock.post(TOKEN_URL).mock(return_value=httpx2.Response(200, json={"access_token": "t", "expires_in": 60})) |
| 2113 |
result = default_credentials() |
| 2114 |
assert result is not None |
| 2115 |
provider = result.provider |
| 2116 |
assert isinstance(provider, WorkloadIdentityCredentials) |
| 2117 |
assert provider._workspace_id is None # pyright: ignore[reportPrivateUsage] |
| 2118 |
provider() |
| 2119 |
body = json.loads(cast("list[MockRequestCall]", respx_mock.calls)[0].request.content) |
| 2120 |
assert "workspace_id" not in body |
| 2121 |
|
| 2122 |
def test_workload_identity_literal_token_reads_fresh(self, clean_env: pytest.MonkeyPatch) -> None: |
| 2123 |
"""Fix 4: ANTHROPIC_IDENTITY_TOKEN must be re-read on every provider |
| 2124 |
invocation, not captured into a closure at chain-construction time.""" |
| 2125 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN", "jwt-v1") |
| 2126 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 2127 |
clean_env.setenv("ANTHROPIC_ORGANIZATION_ID", "org-uuid") |
| 2128 |
result = default_credentials() |
| 2129 |
assert result is not None |
| 2130 |
provider = result.provider |
| 2131 |
assert isinstance(provider, WorkloadIdentityCredentials) |
| 2132 |
assert provider._identity_token_provider() == "jwt-v1" # pyright: ignore[reportPrivateUsage] |
| 2133 |
|
| 2134 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN", "jwt-v2") |
| 2135 |
assert provider._identity_token_provider() == "jwt-v2" # pyright: ignore[reportPrivateUsage] |
| 2136 |
|
| 2137 |
def test_workload_identity_requires_all_three(self, clean_env: pytest.MonkeyPatch) -> None: |
| 2138 |
# only two of three set |
| 2139 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN", "literal-jwt") |
| 2140 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 2141 |
assert default_credentials() is None |
| 2142 |
|
| 2143 |
def test_env_federation_beats_fallback_on_disk_profile( |
| 2144 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 2145 |
) -> None: |
| 2146 |
"""Step 4 (env federation trio) sits above step 5 (fallback on-disk |
| 2147 |
profile) in the precedence spec: a machine with WIF env vars wired |
| 2148 |
up must use WIF even if a leftover `default` profile exists on |
| 2149 |
disk. A user who wants the on-disk profile must set |
| 2150 |
`ANTHROPIC_PROFILE` explicitly (step 3), which would win. |
| 2151 |
""" |
| 2152 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2153 |
_write_profile(tmp_path, "default", {"type": "external"}, {"access_token": "from-on-disk-profile"}) |
| 2154 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN", "literal-jwt") |
| 2155 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 2156 |
clean_env.setenv("ANTHROPIC_ORGANIZATION_ID", "00000000-0000-0000-0000-000000000000") |
| 2157 |
result = default_credentials() |
| 2158 |
assert result is not None |
| 2159 |
assert isinstance(result.provider, WorkloadIdentityCredentials) |
| 2160 |
|
| 2161 |
def test_explicit_profile_beats_env_federation(self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 2162 |
"""Step 3 (ANTHROPIC_PROFILE) sits above step 4 (env federation). |
| 2163 |
An explicit profile selection wins over a federation-configured |
| 2164 |
environment. |
| 2165 |
""" |
| 2166 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2167 |
_write_profile(tmp_path, "dev", {"type": "external"}, {"access_token": "from-dev-profile"}) |
| 2168 |
clean_env.setenv("ANTHROPIC_PROFILE", "dev") |
| 2169 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN", "literal-jwt") |
| 2170 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 2171 |
clean_env.setenv("ANTHROPIC_ORGANIZATION_ID", "00000000-0000-0000-0000-000000000000") |
| 2172 |
result = default_credentials() |
| 2173 |
assert result is not None |
| 2174 |
assert isinstance(result.provider, CredentialsFile) |
| 2175 |
assert result.provider().token == "from-dev-profile" |
| 2176 |
|
| 2177 |
@pytest.mark.usefixtures("clean_env") |
| 2178 |
def test_nothing_set_returns_none(self) -> None: |
| 2179 |
assert default_credentials() is None |
| 2180 |
|
| 2181 |
|
| 2182 |
# --------------------------------------------------------------------------- # |
| 2183 |
# Anthropic(credentials=...) integration |
| 2184 |
# --------------------------------------------------------------------------- # |
| 2185 |
|
| 2186 |
|
| 2187 |
def _mock_token_endpoint(respx_mock: MockRouter) -> None: |
| 2188 |
respx_mock.post(TOKEN_URL).mock( |
| 2189 |
return_value=httpx2.Response( |
| 2190 |
200, |
| 2191 |
json={"access_token": "sk-ant-oat01-test", "token_type": "Bearer", "expires_in": 600}, |
| 2192 |
) |
| 2193 |
) |
| 2194 |
|
| 2195 |
|
| 2196 |
def _message_response() -> httpx2.Response: |
| 2197 |
return httpx2.Response( |
| 2198 |
200, |
| 2199 |
json={ |
| 2200 |
"id": "msg_01", |
| 2201 |
"type": "message", |
| 2202 |
"role": "assistant", |
| 2203 |
"model": "claude-opus-4-5", |
| 2204 |
"content": [{"type": "text", "text": "hi"}], |
| 2205 |
"stop_reason": "end_turn", |
| 2206 |
"stop_sequence": None, |
| 2207 |
"usage": {"input_tokens": 1, "output_tokens": 1}, |
| 2208 |
}, |
| 2209 |
) |
| 2210 |
|
| 2211 |
|
| 2212 |
def _mock_messages_endpoint(respx_mock: MockRouter) -> None: |
| 2213 |
respx_mock.post(f"{BASE_URL}/v1/messages").mock(return_value=_message_response()) |
| 2214 |
|
| 2215 |
|
| 2216 |
def _mock_token_exchange(respx_mock: MockRouter, base_url: str, token: str) -> None: |
| 2217 |
respx_mock.post(f"{base_url}{TOKEN_ENDPOINT}").mock( |
| 2218 |
return_value=httpx2.Response(200, json={"access_token": token, "token_type": "Bearer", "expires_in": 600}) |
| 2219 |
) |
| 2220 |
|
| 2221 |
|
| 2222 |
def _mock_deployment(respx_mock: MockRouter, base_url: str, token: str) -> None: |
| 2223 |
"""Mock one deployment: its token endpoint mints `token` and its |
| 2224 |
messages endpoint accepts anything. Pair with `_requests_to` to |
| 2225 |
check that a client only ever talks to (and presents tokens from) the |
| 2226 |
deployment it was built for.""" |
| 2227 |
_mock_token_exchange(respx_mock, base_url, token) |
| 2228 |
respx_mock.post(f"{base_url}/v1/messages").mock(return_value=_message_response()) |
| 2229 |
|
| 2230 |
|
| 2231 |
def _requests_to(respx_mock: MockRouter, base_url: str) -> List[httpx2.Request]: |
| 2232 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 2233 |
return [c.request for c in calls if str(c.request.url).startswith(f"{base_url}/")] |
| 2234 |
|
| 2235 |
|
| 2236 |
def _assert_exchanged_and_called_own_deployment(respx_mock: MockRouter, base_url: str, token: str) -> None: |
| 2237 |
"""The traffic seen by `base_url` is exactly one exchange followed by |
| 2238 |
one request bearing the token that exchange minted.""" |
| 2239 |
requests = _requests_to(respx_mock, base_url) |
| 2240 |
assert [str(r.url) for r in requests] == [f"{base_url}{TOKEN_ENDPOINT}", f"{base_url}/v1/messages"] |
| 2241 |
assert json.loads(requests[0].content)["assertion"] == "ext-jwt" |
| 2242 |
assert requests[1].headers["Authorization"] == f"Bearer {token}" |
| 2243 |
|
| 2244 |
|
| 2245 |
def _workload_credentials() -> WorkloadIdentityCredentials: |
| 2246 |
return WorkloadIdentityCredentials( |
| 2247 |
identity_token_provider=lambda: "ext-jwt", |
| 2248 |
federation_rule_id="fdrl_01abc", |
| 2249 |
organization_id="org-uuid", |
| 2250 |
) |
| 2251 |
|
| 2252 |
|
| 2253 |
def _send_message(client: Anthropic) -> None: |
| 2254 |
client.messages.create( |
| 2255 |
max_tokens=1, |
| 2256 |
model="claude-opus-4-5", |
| 2257 |
messages=[{"role": "user", "content": "hi"}], |
| 2258 |
) |
| 2259 |
|
| 2260 |
|
| 2261 |
@pytest.mark.usefixtures("clean_env", "no_default_creds_file") |
| 2262 |
class TestAnthropicCredentials: |
| 2263 |
@pytest.mark.respx() |
| 2264 |
def test_messages_request_has_bearer_and_beta(self, respx_mock: MockRouter) -> None: |
| 2265 |
_mock_token_endpoint(respx_mock) |
| 2266 |
_mock_messages_endpoint(respx_mock) |
| 2267 |
|
| 2268 |
client = Anthropic( |
| 2269 |
credentials=WorkloadIdentityCredentials( |
| 2270 |
identity_token_provider=lambda: "ext-jwt", |
| 2271 |
federation_rule_id="fdrl_01abc", |
| 2272 |
organization_id="org-uuid", |
| 2273 |
), |
| 2274 |
) |
| 2275 |
_send_message(client) |
| 2276 |
|
| 2277 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 2278 |
msg_calls = [c for c in calls if str(c.request.url).endswith("/v1/messages")] |
| 2279 |
assert len(msg_calls) == 1 |
| 2280 |
req = msg_calls[0].request |
| 2281 |
assert req.headers["Authorization"] == "Bearer sk-ant-oat01-test" |
| 2282 |
# Authenticated API requests carry oauth-2025-04-20 (API beta) — |
| 2283 |
# NOT the federation routing switch, which is only for jwt-bearer |
| 2284 |
# exchanges at /v1/oauth/token. |
| 2285 |
msg_flags = {f.strip() for f in req.headers["anthropic-beta"].split(",")} |
| 2286 |
assert OAUTH_API_BETA_HEADER in msg_flags |
| 2287 |
assert FEDERATION_BETA_HEADER not in msg_flags |
| 2288 |
assert "X-Api-Key" not in req.headers |
| 2289 |
|
| 2290 |
@pytest.mark.respx() |
| 2291 |
def test_workload_identity_inherits_client_base_url(self, respx_mock: MockRouter) -> None: |
| 2292 |
"""An explicitly-passed WorkloadIdentityCredentials with no `base_url` |
| 2293 |
adopts the client's `base_url` for the token exchange, so the user |
| 2294 |
doesn't have to pass the same URL twice.""" |
| 2295 |
custom_base = "https://api-staging.example" |
| 2296 |
respx_mock.post(f"{custom_base}{TOKEN_ENDPOINT}").mock( |
| 2297 |
return_value=httpx2.Response(200, json={"access_token": "tok-staging", "expires_in": 600}) |
| 2298 |
) |
| 2299 |
respx_mock.post(f"{custom_base}/v1/messages").mock( |
| 2300 |
return_value=httpx2.Response( |
| 2301 |
200, |
| 2302 |
json={ |
| 2303 |
"id": "msg_01", |
| 2304 |
"type": "message", |
| 2305 |
"role": "assistant", |
| 2306 |
"model": "claude-opus-4-5", |
| 2307 |
"content": [{"type": "text", "text": "hi"}], |
| 2308 |
"stop_reason": "end_turn", |
| 2309 |
"stop_sequence": None, |
| 2310 |
"usage": {"input_tokens": 1, "output_tokens": 1}, |
| 2311 |
}, |
| 2312 |
) |
| 2313 |
) |
| 2314 |
|
| 2315 |
client = Anthropic( |
| 2316 |
credentials=WorkloadIdentityCredentials( |
| 2317 |
identity_token_provider=lambda: "ext-jwt", |
| 2318 |
federation_rule_id="fdrl_01abc", |
| 2319 |
organization_id="org-uuid", |
| 2320 |
), |
| 2321 |
base_url=custom_base, |
| 2322 |
) |
| 2323 |
_send_message(client) |
| 2324 |
|
| 2325 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 2326 |
token_calls = [c for c in calls if TOKEN_ENDPOINT in str(c.request.url)] |
| 2327 |
assert len(token_calls) == 1 |
| 2328 |
assert str(token_calls[0].request.url) == f"{custom_base}{TOKEN_ENDPOINT}" |
| 2329 |
msg_calls = [c for c in calls if str(c.request.url).endswith("/v1/messages")] |
| 2330 |
assert msg_calls[0].request.headers["Authorization"] == "Bearer tok-staging" |
| 2331 |
|
| 2332 |
@pytest.mark.respx() |
| 2333 |
def test_token_endpoint_called_once_across_requests(self, respx_mock: MockRouter) -> None: |
| 2334 |
_mock_token_endpoint(respx_mock) |
| 2335 |
_mock_messages_endpoint(respx_mock) |
| 2336 |
|
| 2337 |
client = Anthropic( |
| 2338 |
credentials=WorkloadIdentityCredentials( |
| 2339 |
identity_token_provider=lambda: "ext-jwt", |
| 2340 |
federation_rule_id="fdrl_01abc", |
| 2341 |
organization_id="org-uuid", |
| 2342 |
), |
| 2343 |
) |
| 2344 |
|
| 2345 |
_send_message(client) |
| 2346 |
_send_message(client) |
| 2347 |
|
| 2348 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 2349 |
token_calls = [c for c in calls if TOKEN_ENDPOINT in str(c.request.url)] |
| 2350 |
msg_calls = [c for c in calls if str(c.request.url).endswith("/v1/messages")] |
| 2351 |
assert len(token_calls) == 1 |
| 2352 |
assert len(msg_calls) == 2 |
| 2353 |
|
| 2354 |
@pytest.mark.respx() |
| 2355 |
def test_static_token_credentials(self, respx_mock: MockRouter) -> None: |
| 2356 |
_mock_messages_endpoint(respx_mock) |
| 2357 |
client = Anthropic(credentials=StaticToken("static-bearer")) |
| 2358 |
_send_message(client) |
| 2359 |
|
| 2360 |
req = cast("list[MockRequestCall]", respx_mock.calls)[0].request |
| 2361 |
assert req.headers["Authorization"] == "Bearer static-bearer" |
| 2362 |
assert OAUTH_API_BETA_HEADER in req.headers["anthropic-beta"] |
| 2363 |
|
| 2364 |
@pytest.mark.respx() |
| 2365 |
def test_beta_header_not_duplicated(self, respx_mock: MockRouter) -> None: |
| 2366 |
_mock_messages_endpoint(respx_mock) |
| 2367 |
client = Anthropic(credentials=StaticToken("static-bearer")) |
| 2368 |
client.messages.create( |
| 2369 |
max_tokens=1, |
| 2370 |
model="claude-opus-4-5", |
| 2371 |
messages=[{"role": "user", "content": "hi"}], |
| 2372 |
extra_headers={"anthropic-beta": OAUTH_API_BETA_HEADER}, |
| 2373 |
) |
| 2374 |
req = cast("list[MockRequestCall]", respx_mock.calls)[0].request |
| 2375 |
assert req.headers["anthropic-beta"] == OAUTH_API_BETA_HEADER |
| 2376 |
|
| 2377 |
@pytest.mark.respx() |
| 2378 |
def test_beta_header_dedupe_is_token_based(self, respx_mock: MockRouter) -> None: |
| 2379 |
"""The dedupe check matches whole comma-separated flags, not substrings. |
| 2380 |
A pre-existing flag containing the OAuth beta as a prefix (e.g. a future |
| 2381 |
suffixed variant) must NOT prevent the SDK from adding its own flag.""" |
| 2382 |
_mock_token_endpoint(respx_mock) |
| 2383 |
_mock_messages_endpoint(respx_mock) |
| 2384 |
client = Anthropic( |
| 2385 |
credentials=WorkloadIdentityCredentials( |
| 2386 |
identity_token_provider=lambda: "ext-jwt", |
| 2387 |
federation_rule_id="fdrl_x", |
| 2388 |
organization_id="org-uuid", |
| 2389 |
), |
| 2390 |
) |
| 2391 |
client.messages.create( |
| 2392 |
max_tokens=1, |
| 2393 |
model="claude-opus-4-5", |
| 2394 |
messages=[{"role": "user", "content": "hi"}], |
| 2395 |
extra_headers={"anthropic-beta": f"{OAUTH_API_BETA_HEADER}-future-variant"}, |
| 2396 |
) |
| 2397 |
msg_calls = [ |
| 2398 |
c for c in cast("list[MockRequestCall]", respx_mock.calls) if str(c.request.url).endswith("/v1/messages") |
| 2399 |
] |
| 2400 |
flags = [f.strip() for f in msg_calls[0].request.headers["anthropic-beta"].split(",")] |
| 2401 |
assert OAUTH_API_BETA_HEADER in flags |
| 2402 |
assert f"{OAUTH_API_BETA_HEADER}-future-variant" in flags |
| 2403 |
assert ( |
| 2404 |
msg_calls[0].request.headers["anthropic-beta"] |
| 2405 |
== f"{OAUTH_API_BETA_HEADER}-future-variant,{OAUTH_API_BETA_HEADER}" |
| 2406 |
) |
| 2407 |
|
| 2408 |
@pytest.mark.respx() |
| 2409 |
def test_zero_config_workload_identity_from_env( |
| 2410 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 2411 |
) -> None: |
| 2412 |
f = tmp_path / "jwt" |
| 2413 |
f.write_text("env-jwt") |
| 2414 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN_FILE", str(f)) |
| 2415 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 2416 |
clean_env.setenv("ANTHROPIC_ORGANIZATION_ID", "org-uuid") |
| 2417 |
|
| 2418 |
_mock_token_endpoint(respx_mock) |
| 2419 |
_mock_messages_endpoint(respx_mock) |
| 2420 |
|
| 2421 |
client = Anthropic() |
| 2422 |
assert isinstance(client.credentials, WorkloadIdentityCredentials) |
| 2423 |
_send_message(client) |
| 2424 |
|
| 2425 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 2426 |
token_calls = [c for c in calls if TOKEN_ENDPOINT in str(c.request.url)] |
| 2427 |
msg_calls = [c for c in calls if str(c.request.url).endswith("/v1/messages")] |
| 2428 |
assert len(token_calls) == 1 |
| 2429 |
assert json.loads(token_calls[0].request.content)["assertion"] == "env-jwt" |
| 2430 |
assert msg_calls[0].request.headers["Authorization"] == "Bearer sk-ant-oat01-test" |
| 2431 |
|
| 2432 |
@pytest.mark.respx() |
| 2433 |
def test_zero_config_credentials_file_from_env( |
| 2434 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 2435 |
) -> None: |
| 2436 |
# no_default_creds_file patched _config_dir → empty dir; re-point at tmp_path |
| 2437 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2438 |
clean_env.setenv("ANTHROPIC_CONFIG_DIR", str(tmp_path)) |
| 2439 |
_write_profile(tmp_path, "default", {"type": "external"}, {"access_token": "sk-ant-oat01-file"}) |
| 2440 |
|
| 2441 |
_mock_messages_endpoint(respx_mock) |
| 2442 |
|
| 2443 |
client = Anthropic() |
| 2444 |
assert isinstance(client.credentials, CredentialsFile) |
| 2445 |
_send_message(client) |
| 2446 |
|
| 2447 |
req = cast("list[MockRequestCall]", respx_mock.calls)[0].request |
| 2448 |
assert req.headers["Authorization"] == "Bearer sk-ant-oat01-file" |
| 2449 |
|
| 2450 |
def test_profile_base_url_adopted_by_client(self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 2451 |
"""Outbound: a zero-arg `Anthropic()` adopts the active profile's |
| 2452 |
`base_url` when the user supplied neither `base_url=` nor |
| 2453 |
`ANTHROPIC_BASE_URL`. Precedence: kwarg > env > profile > default.""" |
| 2454 |
clean_env.delenv("ANTHROPIC_BASE_URL", raising=False) |
| 2455 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2456 |
clean_env.setenv("ANTHROPIC_CONFIG_DIR", str(tmp_path)) |
| 2457 |
_write_profile( |
| 2458 |
tmp_path, |
| 2459 |
"default", |
| 2460 |
{"type": "external", "base_url": "https://staging.example"}, |
| 2461 |
{"access_token": "sk-ant-oat01-x"}, |
| 2462 |
) |
| 2463 |
|
| 2464 |
# profile base_url → client.base_url |
| 2465 |
assert str(Anthropic().base_url).rstrip("/") == "https://staging.example" |
| 2466 |
assert str(AsyncAnthropic().base_url).rstrip("/") == "https://staging.example" |
| 2467 |
|
| 2468 |
# ANTHROPIC_BASE_URL beats profile |
| 2469 |
clean_env.setenv("ANTHROPIC_BASE_URL", "https://env.example") |
| 2470 |
assert str(Anthropic().base_url).rstrip("/") == "https://env.example" |
| 2471 |
clean_env.delenv("ANTHROPIC_BASE_URL", raising=False) |
| 2472 |
|
| 2473 |
# base_url= kwarg beats profile |
| 2474 |
assert str(Anthropic(base_url="https://kwarg.example").base_url).rstrip("/") == "https://kwarg.example" |
| 2475 |
|
| 2476 |
# profile without base_url → hardcoded default |
| 2477 |
_write_profile( |
| 2478 |
tmp_path, |
| 2479 |
"default", |
| 2480 |
{"type": "external"}, |
| 2481 |
{"access_token": "sk-ant-oat01-x"}, |
| 2482 |
) |
| 2483 |
assert str(Anthropic().base_url).rstrip("/") == "https://api.anthropic.com" |
| 2484 |
|
| 2485 |
def test_config_dict_base_url_adopted_by_client( |
| 2486 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 2487 |
) -> None: |
| 2488 |
"""Outbound, `config=` path: `Anthropic(config={"base_url": ...})` |
| 2489 |
adopts the dict's `base_url` for API requests when no kwarg/env is |
| 2490 |
set, mirroring the disk-profile behaviour.""" |
| 2491 |
clean_env.delenv("ANTHROPIC_BASE_URL", raising=False) |
| 2492 |
creds_path = tmp_path / "creds.json" |
| 2493 |
creds_path.write_text(json.dumps({"type": "oauth_token", "access_token": "sk-ant-oat01-x"})) |
| 2494 |
creds_path.chmod(0o600) |
| 2495 |
cfg = { |
| 2496 |
"base_url": "https://staging.example", |
| 2497 |
"authentication": {"type": "user_oauth", "credentials_path": str(creds_path)}, |
| 2498 |
} |
| 2499 |
|
| 2500 |
assert str(Anthropic(config=cfg).base_url).rstrip("/") == "https://staging.example" |
| 2501 |
assert str(AsyncAnthropic(config=cfg).base_url).rstrip("/") == "https://staging.example" |
| 2502 |
|
| 2503 |
# explicit base_url= still wins over config dict |
| 2504 |
assert ( |
| 2505 |
str(Anthropic(config=cfg, base_url="https://kwarg.example").base_url).rstrip("/") == "https://kwarg.example" |
| 2506 |
) |
| 2507 |
|
| 2508 |
@pytest.mark.respx() |
| 2509 |
def test_workspace_id_header_from_config( |
| 2510 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 2511 |
) -> None: |
| 2512 |
"""workspace_id in the config file → anthropic-workspace-id header on API requests.""" |
| 2513 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2514 |
clean_env.setenv("ANTHROPIC_CONFIG_DIR", str(tmp_path)) |
| 2515 |
_write_profile( |
| 2516 |
tmp_path, |
| 2517 |
"default", |
| 2518 |
{"type": "external", "workspace_id": "wrkspc_01abc"}, |
| 2519 |
{"access_token": "sk-ant-oat01-file"}, |
| 2520 |
) |
| 2521 |
|
| 2522 |
_mock_messages_endpoint(respx_mock) |
| 2523 |
|
| 2524 |
client = Anthropic() |
| 2525 |
_send_message(client) |
| 2526 |
client.messages.create( |
| 2527 |
max_tokens=1, |
| 2528 |
model="claude-opus-4-5", |
| 2529 |
messages=[{"role": "user", "content": "hi"}], |
| 2530 |
workspace_id="wrkspc_req", |
| 2531 |
) |
| 2532 |
|
| 2533 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 2534 |
assert calls[0].request.headers["anthropic-workspace-id"] == "wrkspc_01abc" |
| 2535 |
assert calls[1].request.headers["anthropic-workspace-id"] == "wrkspc_req" |
| 2536 |
|
| 2537 |
@pytest.mark.respx() |
| 2538 |
def test_401_invalidates_cache_and_retries_once(self, respx_mock: MockRouter) -> None: |
| 2539 |
"""On 401 we invalidate the cache and retry the current request once |
| 2540 |
with a freshly minted token. A second 401 is not retried (single-shot |
| 2541 |
guard via x-stainless-retry-count).""" |
| 2542 |
provider_calls: List[str] = [] |
| 2543 |
|
| 2544 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 2545 |
provider_calls.append("called") |
| 2546 |
return AccessToken(token=f"tok-{len(provider_calls)}", expires_at=None) |
| 2547 |
|
| 2548 |
# 401 then 200 — the retry should succeed transparently. |
| 2549 |
respx_mock.post(f"{BASE_URL}/v1/messages").mock( |
| 2550 |
side_effect=[ |
| 2551 |
httpx2.Response(401, json={"error": "unauthorized"}), |
| 2552 |
httpx2.Response( |
| 2553 |
200, |
| 2554 |
json={ |
| 2555 |
"id": "msg_01", |
| 2556 |
"type": "message", |
| 2557 |
"role": "assistant", |
| 2558 |
"model": "claude-opus-4-5", |
| 2559 |
"content": [{"type": "text", "text": "hi"}], |
| 2560 |
"stop_reason": "end_turn", |
| 2561 |
"stop_sequence": None, |
| 2562 |
"usage": {"input_tokens": 1, "output_tokens": 1}, |
| 2563 |
}, |
| 2564 |
), |
| 2565 |
], |
| 2566 |
) |
| 2567 |
client = Anthropic(credentials=provider, max_retries=2) |
| 2568 |
_send_message(client) |
| 2569 |
assert len(provider_calls) == 2 |
| 2570 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 2571 |
assert calls[0].request.headers["Authorization"] == "Bearer tok-1" |
| 2572 |
assert calls[1].request.headers["Authorization"] == "Bearer tok-2" |
| 2573 |
|
| 2574 |
@pytest.mark.respx() |
| 2575 |
def test_401_retry_is_single_shot(self, respx_mock: MockRouter) -> None: |
| 2576 |
"""Two consecutive 401s → exactly one retry, then the error surfaces |
| 2577 |
even with max_retries > 1 remaining.""" |
| 2578 |
respx_mock.post(f"{BASE_URL}/v1/messages").mock( |
| 2579 |
return_value=httpx2.Response(401, json={"error": "unauthorized"}), |
| 2580 |
) |
| 2581 |
provider_calls: List[str] = [] |
| 2582 |
|
| 2583 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 2584 |
provider_calls.append("called") |
| 2585 |
return AccessToken(token=f"tok-{len(provider_calls)}", expires_at=None) |
| 2586 |
|
| 2587 |
client = Anthropic(credentials=provider, max_retries=3) |
| 2588 |
with pytest.raises(anthropic.AuthenticationError): |
| 2589 |
_send_message(client) |
| 2590 |
assert len(provider_calls) == 2 # initial + one retry |
| 2591 |
assert len(cast("list[MockRequestCall]", respx_mock.calls)) == 2 |
| 2592 |
|
| 2593 |
def test_401_retry_forces_refresh_while_another_request_is_fetching(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 2594 |
"""A 401 retry gets a new token even when another request's non-forced provider call returns first.""" |
| 2595 |
import threading as _threading |
| 2596 |
|
| 2597 |
revoked: List[str] = [] |
| 2598 |
force_seen: List[bool] = [] |
| 2599 |
bearers: List[str] = [] |
| 2600 |
s_in_provider, release_s, s_fetched, r_done = (_threading.Event() for _ in range(4)) |
| 2601 |
|
| 2602 |
def provider(*, force_refresh: bool = False) -> AccessToken: |
| 2603 |
force_seen.append(force_refresh) |
| 2604 |
if _threading.current_thread().name == "S" and not s_in_provider.is_set(): |
| 2605 |
s_in_provider.set() |
| 2606 |
assert release_s.wait(5) |
| 2607 |
return AccessToken("tok-2" if True in force_seen else "tok-1", expires_at=0) |
| 2608 |
|
| 2609 |
def handler(request: httpx2.Request) -> httpx2.Response: |
| 2610 |
if _threading.current_thread().name == "S": |
| 2611 |
s_fetched.set() |
| 2612 |
assert r_done.wait(5) |
| 2613 |
else: |
| 2614 |
bearers.append(request.headers["Authorization"]) |
| 2615 |
if request.headers["Authorization"] in revoked: |
| 2616 |
return httpx2.Response(401, json={"error": "revoked"}, headers={"retry-after-ms": "1"}) |
| 2617 |
return _message_response() |
| 2618 |
|
| 2619 |
def invalidate_then_let_s_finish(cache: TokenCache) -> None: |
| 2620 |
invalidate(cache) |
| 2621 |
release_s.set() |
| 2622 |
assert s_fetched.wait(5) |
| 2623 |
|
| 2624 |
invalidate = TokenCache.invalidate |
| 2625 |
monkeypatch.setattr(TokenCache, "invalidate", invalidate_then_let_s_finish) |
| 2626 |
transport = httpx2.MockTransport(handler) |
| 2627 |
client = Anthropic(credentials=provider, http_client=httpx2.Client(transport=transport), max_retries=2) |
| 2628 |
_send_message(client) |
| 2629 |
revoked.append("Bearer tok-1") |
| 2630 |
s = _threading.Thread(target=_send_message, args=(client,), name="S", daemon=True) |
| 2631 |
s.start() |
| 2632 |
assert s_in_provider.wait(5) |
| 2633 |
try: |
| 2634 |
_send_message(client) |
| 2635 |
finally: |
| 2636 |
r_done.set() |
| 2637 |
release_s.set() |
| 2638 |
s.join(timeout=5) |
| 2639 |
assert not s.is_alive(), "the concurrent request deadlocked" |
| 2640 |
assert bearers == ["Bearer tok-1", "Bearer tok-1", "Bearer tok-2"] |
| 2641 |
# Sliced because S's own 401 retry may or may not have made a fifth call by now. |
| 2642 |
assert force_seen[:4] == [False, False, False, True] |
| 2643 |
|
| 2644 |
@pytest.mark.respx() |
| 2645 |
def test_api_key_precedence_preserved( |
| 2646 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 2647 |
) -> None: |
| 2648 |
# ANTHROPIC_API_KEY takes precedence over the credential chain — credentials |
| 2649 |
# stays None and X-Api-Key is used (existing behavior preserved). |
| 2650 |
clean_env.setenv("ANTHROPIC_API_KEY", "sk-ant-api-key") |
| 2651 |
# also set chain env vars; they should be ignored |
| 2652 |
clean_env.setenv("ANTHROPIC_CONFIG_DIR", str(tmp_path)) |
| 2653 |
_write_profile(tmp_path, "default", {"type": "external"}, {"access_token": "should-not-be-used"}) |
| 2654 |
|
| 2655 |
_mock_messages_endpoint(respx_mock) |
| 2656 |
|
| 2657 |
client = Anthropic() |
| 2658 |
assert client.credentials is None |
| 2659 |
assert client._token_cache is None |
| 2660 |
_send_message(client) |
| 2661 |
|
| 2662 |
req = cast("list[MockRequestCall]", respx_mock.calls)[0].request |
| 2663 |
assert req.headers["X-Api-Key"] == "sk-ant-api-key" |
| 2664 |
assert "Authorization" not in req.headers |
| 2665 |
|
| 2666 |
def test_copy_propagates_credentials(self) -> None: |
| 2667 |
creds = StaticToken("a") |
| 2668 |
client = Anthropic(credentials=creds) |
| 2669 |
copied = client.copy() |
| 2670 |
assert copied.credentials is creds |
| 2671 |
# The TokenCache instance is shared so a with_options() copy doesn't |
| 2672 |
# trigger an independent token exchange. |
| 2673 |
assert copied._token_cache is client._token_cache |
| 2674 |
|
| 2675 |
other = StaticToken("b") |
| 2676 |
copied2 = client.copy(credentials=other) |
| 2677 |
assert copied2.credentials is other |
| 2678 |
assert copied2._token_cache is not client._token_cache |
| 2679 |
|
| 2680 |
cleared = client.copy(credentials=None, api_key="x") |
| 2681 |
assert cleared.credentials is None |
| 2682 |
assert cleared._token_cache is None |
| 2683 |
|
| 2684 |
def test_with_options_alias(self) -> None: |
| 2685 |
client = Anthropic(credentials=StaticToken("a")) |
| 2686 |
copied = client.with_options(max_retries=7) |
| 2687 |
assert copied.max_retries == 7 |
| 2688 |
assert copied.credentials is client.credentials |
| 2689 |
|
| 2690 |
@pytest.mark.respx() |
| 2691 |
def test_copy_with_different_base_url_exchanges_per_client(self, respx_mock: MockRouter) -> None: |
| 2692 |
"""`copy(base_url=...)` must not move the parent's token exchange: |
| 2693 |
each client exchanges its assertion at its own host and only ever |
| 2694 |
presents the token that host minted.""" |
| 2695 |
_mock_deployment(respx_mock, BASE_URL, "tok-primary") |
| 2696 |
_mock_deployment(respx_mock, OTHER_BASE_URL, "tok-other") |
| 2697 |
parent = Anthropic(credentials=_workload_credentials()) |
| 2698 |
child = parent.copy(base_url=OTHER_BASE_URL) |
| 2699 |
|
| 2700 |
# Child first: a parent whose provider had been rebound by the copy |
| 2701 |
# would now exchange at (and send the other host's token to) the |
| 2702 |
# wrong deployment. |
| 2703 |
_send_message(child) |
| 2704 |
_send_message(parent) |
| 2705 |
|
| 2706 |
_assert_exchanged_and_called_own_deployment(respx_mock, OTHER_BASE_URL, "tok-other") |
| 2707 |
_assert_exchanged_and_called_own_deployment(respx_mock, BASE_URL, "tok-primary") |
| 2708 |
|
| 2709 |
@pytest.mark.respx() |
| 2710 |
def test_shared_provider_binds_per_client(self, respx_mock: MockRouter) -> None: |
| 2711 |
"""The same isolation holds when one provider instance is passed to |
| 2712 |
two clients directly: the first client keeps its binding.""" |
| 2713 |
_mock_deployment(respx_mock, BASE_URL, "tok-primary") |
| 2714 |
_mock_deployment(respx_mock, OTHER_BASE_URL, "tok-other") |
| 2715 |
creds = _workload_credentials() |
| 2716 |
primary = Anthropic(credentials=creds) |
| 2717 |
other = Anthropic(credentials=creds, base_url=OTHER_BASE_URL) |
| 2718 |
assert primary.credentials is creds |
| 2719 |
|
| 2720 |
_send_message(other) |
| 2721 |
_send_message(primary) |
| 2722 |
|
| 2723 |
_assert_exchanged_and_called_own_deployment(respx_mock, OTHER_BASE_URL, "tok-other") |
| 2724 |
_assert_exchanged_and_called_own_deployment(respx_mock, BASE_URL, "tok-primary") |
| 2725 |
|
| 2726 |
@pytest.mark.respx() |
| 2727 |
def test_copy_with_same_base_url_shares_token_exchange(self, respx_mock: MockRouter) -> None: |
| 2728 |
"""A copy targeting the same deployment (here spelled without the |
| 2729 |
trailing slash the client normalises to) keeps sharing the parent's |
| 2730 |
provider and cache: one exchange serves both.""" |
| 2731 |
_mock_deployment(respx_mock, BASE_URL, "tok-primary") |
| 2732 |
parent = Anthropic(credentials=_workload_credentials()) |
| 2733 |
child = parent.copy(base_url=BASE_URL) |
| 2734 |
assert child.credentials is parent.credentials |
| 2735 |
|
| 2736 |
_send_message(child) |
| 2737 |
_send_message(parent) |
| 2738 |
|
| 2739 |
requests = _requests_to(respx_mock, BASE_URL) |
| 2740 |
assert [str(r.url) for r in requests] == [TOKEN_URL, f"{BASE_URL}/v1/messages", f"{BASE_URL}/v1/messages"] |
| 2741 |
assert all(r.headers["Authorization"] == "Bearer tok-primary" for r in requests[1:]) |
| 2742 |
|
| 2743 |
@pytest.mark.respx() |
| 2744 |
def test_copy_of_federation_profile_client_exchanges_per_client( |
| 2745 |
self, respx_mock: MockRouter, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch |
| 2746 |
) -> None: |
| 2747 |
"""Profile-backed federation: the copy exchanges at its own host and |
| 2748 |
stays out of the profile's on-disk token cache, which belongs to the |
| 2749 |
parent's deployment.""" |
| 2750 |
monkeypatch.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2751 |
jwt_path = tmp_path / "jwt" |
| 2752 |
jwt_path.write_text("ext-jwt") |
| 2753 |
_write_profile( |
| 2754 |
tmp_path, |
| 2755 |
"fed", |
| 2756 |
{ |
| 2757 |
"type": "workload_identity", |
| 2758 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 2759 |
"federation_rule_id": "fdrl_01abc", |
| 2760 |
"organization_id": "org-uuid", |
| 2761 |
}, |
| 2762 |
) |
| 2763 |
_mock_deployment(respx_mock, BASE_URL, "tok-primary") |
| 2764 |
_mock_deployment(respx_mock, OTHER_BASE_URL, "tok-other") |
| 2765 |
parent = Anthropic(profile="fed") |
| 2766 |
child = parent.copy(base_url=OTHER_BASE_URL) |
| 2767 |
|
| 2768 |
_send_message(child) |
| 2769 |
_send_message(parent) |
| 2770 |
|
| 2771 |
_assert_exchanged_and_called_own_deployment(respx_mock, OTHER_BASE_URL, "tok-other") |
| 2772 |
_assert_exchanged_and_called_own_deployment(respx_mock, BASE_URL, "tok-primary") |
| 2773 |
on_disk = json.loads((tmp_path / "credentials" / "fed.json").read_text()) |
| 2774 |
assert on_disk["access_token"] == "tok-primary" |
| 2775 |
|
| 2776 |
@pytest.mark.respx() |
| 2777 |
def test_copy_of_user_oauth_profile_client_keeps_refresh_endpoint( |
| 2778 |
self, respx_mock: MockRouter, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch |
| 2779 |
) -> None: |
| 2780 |
"""A user_oauth profile's refresh token belongs to the deployment that |
| 2781 |
issued it: a copy pointed at another host still refreshes at the |
| 2782 |
parent's host rather than posting the refresh token elsewhere.""" |
| 2783 |
monkeypatch.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2784 |
_write_profile( |
| 2785 |
tmp_path, |
| 2786 |
"oauth", |
| 2787 |
{"type": "authorized_user", "client_id": "cid"}, |
| 2788 |
{"access_token": "stale", "expires_at": int(time.time()) - 1, "refresh_token": "rt"}, |
| 2789 |
) |
| 2790 |
_mock_token_exchange(respx_mock, BASE_URL, "tok-refreshed") |
| 2791 |
respx_mock.post(f"{OTHER_BASE_URL}/v1/messages").mock(return_value=_message_response()) |
| 2792 |
parent = Anthropic(profile="oauth") |
| 2793 |
child = parent.copy(base_url=OTHER_BASE_URL) |
| 2794 |
assert child.credentials is parent.credentials |
| 2795 |
|
| 2796 |
_send_message(child) |
| 2797 |
|
| 2798 |
assert [str(r.url) for r in _requests_to(respx_mock, BASE_URL)] == [TOKEN_URL] |
| 2799 |
other_requests = _requests_to(respx_mock, OTHER_BASE_URL) |
| 2800 |
assert [str(r.url) for r in other_requests] == [f"{OTHER_BASE_URL}/v1/messages"] |
| 2801 |
assert other_requests[0].headers["Authorization"] == "Bearer tok-refreshed" |
| 2802 |
|
| 2803 |
@pytest.mark.respx() |
| 2804 |
def test_config_param_builds_in_memory_federation(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 2805 |
"""`Anthropic(config={...})` accepts a config-file-shaped dict and |
| 2806 |
wires it through to a federation provider, including `workspace_id` |
| 2807 |
as a default header.""" |
| 2808 |
jwt_path = tmp_path / "jwt" |
| 2809 |
jwt_path.write_text("ext-jwt-value") |
| 2810 |
_mock_token_endpoint(respx_mock) |
| 2811 |
_mock_messages_endpoint(respx_mock) |
| 2812 |
|
| 2813 |
client = Anthropic( |
| 2814 |
config={ |
| 2815 |
"organization_id": "org_x", |
| 2816 |
"workspace_id": "wrkspc_x", |
| 2817 |
"authentication": { |
| 2818 |
"type": "oidc_federation", |
| 2819 |
"federation_rule_id": "fdrl_x", |
| 2820 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 2821 |
}, |
| 2822 |
} |
| 2823 |
) |
| 2824 |
assert isinstance(client.credentials, InMemoryConfig) |
| 2825 |
_send_message(client) |
| 2826 |
msg_req = cast("list[MockRequestCall]", respx_mock.calls)[-1].request |
| 2827 |
assert msg_req.headers["Authorization"] == "Bearer sk-ant-oat01-test" |
| 2828 |
# Federation profiles send workspace_id in the exchange body, not as a header. |
| 2829 |
assert "anthropic-workspace-id" not in msg_req.headers |
| 2830 |
token_req = cast("list[MockRequestCall]", respx_mock.calls)[0].request |
| 2831 |
assert json.loads(token_req.content)["workspace_id"] == "wrkspc_x" |
| 2832 |
|
| 2833 |
def test_config_and_credentials_mutually_exclusive(self) -> None: |
| 2834 |
with pytest.raises(TypeError, match="at most one of"): |
| 2835 |
Anthropic( |
| 2836 |
credentials=StaticToken("a"), |
| 2837 |
config={"authentication": {"type": "oidc_federation"}}, |
| 2838 |
) |
| 2839 |
|
| 2840 |
def test_explicit_api_key_shadows_explicit_config(self, tmp_path: pathlib.Path) -> None: |
| 2841 |
"""Explicit `api_key=` + explicit `config=` is an explicit-explicit |
| 2842 |
shadow case: the static api_key wins at the header level and the |
| 2843 |
config-derived credentials provider is silently disabled. |
| 2844 |
""" |
| 2845 |
jwt_path = tmp_path / "jwt" |
| 2846 |
jwt_path.write_text("ext-jwt.ext-jwt.ext-jwt") |
| 2847 |
cfg = { |
| 2848 |
"organization_id": "org_x", |
| 2849 |
"authentication": { |
| 2850 |
"type": "oidc_federation", |
| 2851 |
"federation_rule_id": "fdrl_x", |
| 2852 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 2853 |
}, |
| 2854 |
} |
| 2855 |
explicit = Anthropic(api_key="sk-explicit", config=cfg) |
| 2856 |
assert explicit.api_key == "sk-explicit" |
| 2857 |
assert isinstance(explicit.credentials, InMemoryConfig) |
| 2858 |
|
| 2859 |
def test_explicit_config_beats_env_api_key(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 2860 |
"""Explicit `config=` is step 1 and beats env `ANTHROPIC_API_KEY` |
| 2861 |
(step 2). The env api_key is ignored entirely and the config-derived |
| 2862 |
credentials provider wins. |
| 2863 |
""" |
| 2864 |
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-from-env") |
| 2865 |
jwt_path = tmp_path / "jwt" |
| 2866 |
jwt_path.write_text("ext-jwt.ext-jwt.ext-jwt") |
| 2867 |
client = Anthropic( |
| 2868 |
config={ |
| 2869 |
"organization_id": "org_x", |
| 2870 |
"authentication": { |
| 2871 |
"type": "oidc_federation", |
| 2872 |
"federation_rule_id": "fdrl_x", |
| 2873 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 2874 |
}, |
| 2875 |
} |
| 2876 |
) |
| 2877 |
assert client.api_key is None |
| 2878 |
assert isinstance(client.credentials, InMemoryConfig) |
| 2879 |
|
| 2880 |
def test_profile_param_loads_named_profile(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 2881 |
"""`Anthropic(profile="staging")` loads `configs/staging.json` from |
| 2882 |
the config directory, equivalent to setting `ANTHROPIC_PROFILE`.""" |
| 2883 |
monkeypatch.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2884 |
_write_profile( |
| 2885 |
tmp_path, |
| 2886 |
"staging", |
| 2887 |
config={"type": "external", "base_url": "https://staging.example"}, |
| 2888 |
credentials={"access_token": "sk-ant-oat01-staging"}, |
| 2889 |
) |
| 2890 |
client = Anthropic(profile="staging") |
| 2891 |
assert isinstance(client.credentials, CredentialsFile) |
| 2892 |
assert client.credentials.profile == "staging" |
| 2893 |
assert str(client.base_url).rstrip("/") == "https://staging.example" |
| 2894 |
|
| 2895 |
def test_profile_and_config_mutually_exclusive(self) -> None: |
| 2896 |
with pytest.raises(TypeError, match="at most one of"): |
| 2897 |
Anthropic(profile="x", config={"authentication": {"type": "oidc_federation"}}) |
| 2898 |
|
| 2899 |
def test_profile_and_credentials_mutually_exclusive(self) -> None: |
| 2900 |
with pytest.raises(TypeError, match="at most one of"): |
| 2901 |
Anthropic(profile="x", credentials=StaticToken("a")) |
| 2902 |
|
| 2903 |
def test_explicit_profile_beats_env_api_key(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 2904 |
"""Explicit `profile=` is a constructor argument and beats env |
| 2905 |
`ANTHROPIC_API_KEY` — the env var is not consulted.""" |
| 2906 |
monkeypatch.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 2907 |
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-from-env") |
| 2908 |
_write_profile(tmp_path, "dev", config={"type": "external"}, credentials={"access_token": "sk-ant-oat01-dev"}) |
| 2909 |
client = Anthropic(profile="dev") |
| 2910 |
assert client.api_key is None |
| 2911 |
assert isinstance(client.credentials, CredentialsFile) |
| 2912 |
assert client.credentials.profile == "dev" |
| 2913 |
|
| 2914 |
def test_workload_identity_error_propagates_through_request_flow(self) -> None: |
| 2915 |
"""A WorkloadIdentityError raised from the credential provider must |
| 2916 |
bubble out of messages.create() as-is, not wrapped in |
| 2917 |
APIConnectionError, and must not trigger retries.""" |
| 2918 |
provider_calls: List[str] = [] |
| 2919 |
|
| 2920 |
def failing_provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 2921 |
provider_calls.append("called") |
| 2922 |
raise WorkloadIdentityError( |
| 2923 |
"simulated 403", |
| 2924 |
status_code=403, |
| 2925 |
body={"error": {"type": "permission_error", "message": "Permission denied"}}, |
| 2926 |
) |
| 2927 |
|
| 2928 |
client = Anthropic(credentials=failing_provider, max_retries=3) |
| 2929 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 2930 |
_send_message(client) |
| 2931 |
assert exc_info.value.status_code == 403 |
| 2932 |
body = cast("Dict[str, Any]", exc_info.value.body) |
| 2933 |
assert body["error"]["type"] == "permission_error" |
| 2934 |
assert len(provider_calls) == 1 |
| 2935 |
|
| 2936 |
def test_duck_typed_token_is_rejected(self) -> None: |
| 2937 |
class TokenTuple(NamedTuple): |
| 2938 |
token: str |
| 2939 |
expires_at: Optional[int] = None |
| 2940 |
|
| 2941 |
def provider(*, force_refresh: bool = False) -> Any: # noqa: ARG001 |
| 2942 |
return TokenTuple("tok-duck") |
| 2943 |
|
| 2944 |
def handler(request: httpx2.Request) -> httpx2.Response: # noqa: ARG001 |
| 2945 |
return _message_response() |
| 2946 |
|
| 2947 |
client = Anthropic(credentials=provider, http_client=httpx2.Client(transport=httpx2.MockTransport(handler))) |
| 2948 |
with pytest.raises(AnthropicError, match="returned TokenTuple instead of an AccessToken") as exc_info: |
| 2949 |
_send_message(client) |
| 2950 |
assert type(exc_info.value) is AnthropicError # not wrapped as APIConnectionError |
| 2951 |
|
| 2952 |
|
| 2953 |
class TestInMemoryConfig: |
| 2954 |
@pytest.mark.respx() |
| 2955 |
def test_oidc_federation(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 2956 |
jwt_path = tmp_path / "jwt" |
| 2957 |
jwt_path.write_text("ext-jwt") |
| 2958 |
respx_mock.post(TOKEN_URL).mock( |
| 2959 |
return_value=httpx2.Response(200, json={"access_token": "tok", "expires_in": 600}) |
| 2960 |
) |
| 2961 |
provider = InMemoryConfig( |
| 2962 |
{ |
| 2963 |
"organization_id": "org_x", |
| 2964 |
"workspace_id": "wrkspc_x", |
| 2965 |
"authentication": { |
| 2966 |
"type": "oidc_federation", |
| 2967 |
"federation_rule_id": "fdrl_x", |
| 2968 |
"service_account_id": "svac_x", |
| 2969 |
"identity_token": {"source": "file", "path": str(jwt_path)}, |
| 2970 |
}, |
| 2971 |
} |
| 2972 |
) |
| 2973 |
token = provider() |
| 2974 |
assert token.token == "tok" |
| 2975 |
# Federation profiles send workspace_id in the exchange body, not as a header. |
| 2976 |
assert provider.extra_headers() == {} |
| 2977 |
body = json.loads(cast("list[MockRequestCall]", respx_mock.calls)[0].request.content) |
| 2978 |
assert body["federation_rule_id"] == "fdrl_x" |
| 2979 |
assert body["organization_id"] == "org_x" |
| 2980 |
assert body["service_account_id"] == "svac_x" |
| 2981 |
assert body["workspace_id"] == "wrkspc_x" |
| 2982 |
|
| 2983 |
def test_identity_token_provider_override(self, respx_mock: MockRouter) -> None: |
| 2984 |
respx_mock.post(TOKEN_URL).mock( |
| 2985 |
return_value=httpx2.Response(200, json={"access_token": "tok", "expires_in": 600}) |
| 2986 |
) |
| 2987 |
provider = InMemoryConfig( |
| 2988 |
{ |
| 2989 |
"organization_id": "org_x", |
| 2990 |
"workspace_id": "wrkspc_x", |
| 2991 |
"authentication": {"type": "oidc_federation", "federation_rule_id": "fdrl_x"}, |
| 2992 |
}, |
| 2993 |
identity_token_provider=lambda: "programmatic-jwt", |
| 2994 |
) |
| 2995 |
provider() |
| 2996 |
body = json.loads(cast("list[MockRequestCall]", respx_mock.calls)[0].request.content) |
| 2997 |
assert body["assertion"] == "programmatic-jwt" |
| 2998 |
# workspace_id flows through InMemoryConfig._build_workload_delegate |
| 2999 |
# even when identity_token_provider is overridden — that branch builds |
| 3000 |
# the delegate independently of the file-backed CredentialsFile path. |
| 3001 |
assert body["workspace_id"] == "wrkspc_x" |
| 3002 |
|
| 3003 |
@pytest.mark.respx() |
| 3004 |
def test_oidc_federation_no_credentials_path_no_disk_cache( |
| 3005 |
self, respx_mock: MockRouter, tmp_path: pathlib.Path |
| 3006 |
) -> None: |
| 3007 |
"""Without `authentication.credentials_path`, every call exchanges |
| 3008 |
fresh — nothing is written to disk.""" |
| 3009 |
token_route = respx_mock.post(TOKEN_URL).mock( |
| 3010 |
return_value=httpx2.Response(200, json={"access_token": "tok", "expires_in": 600}) |
| 3011 |
) |
| 3012 |
provider = InMemoryConfig( |
| 3013 |
{ |
| 3014 |
"organization_id": "org_x", |
| 3015 |
"authentication": {"type": "oidc_federation", "federation_rule_id": "fdrl_x"}, |
| 3016 |
}, |
| 3017 |
identity_token_provider=lambda: "jwt", |
| 3018 |
) |
| 3019 |
provider() |
| 3020 |
provider() |
| 3021 |
assert token_route.call_count == 2 |
| 3022 |
assert not list(tmp_path.glob("**/*.json")) |
| 3023 |
|
| 3024 |
@pytest.mark.respx() |
| 3025 |
def test_oidc_federation_with_credentials_path_disk_cache( |
| 3026 |
self, respx_mock: MockRouter, tmp_path: pathlib.Path |
| 3027 |
) -> None: |
| 3028 |
"""With `authentication.credentials_path` set, the exchanged token is |
| 3029 |
written to that path and a second call returns it without re-exchanging.""" |
| 3030 |
creds_path = tmp_path / "cache.json" |
| 3031 |
token_route = respx_mock.post(TOKEN_URL).mock( |
| 3032 |
return_value=httpx2.Response(200, json={"access_token": "cached-tok", "expires_in": 600}) |
| 3033 |
) |
| 3034 |
provider = InMemoryConfig( |
| 3035 |
{ |
| 3036 |
"organization_id": "org_x", |
| 3037 |
"authentication": { |
| 3038 |
"type": "oidc_federation", |
| 3039 |
"federation_rule_id": "fdrl_x", |
| 3040 |
"credentials_path": str(creds_path), |
| 3041 |
}, |
| 3042 |
}, |
| 3043 |
identity_token_provider=lambda: "jwt", |
| 3044 |
) |
| 3045 |
assert provider().token == "cached-tok" |
| 3046 |
assert token_route.call_count == 1 |
| 3047 |
on_disk = json.loads(creds_path.read_text()) |
| 3048 |
assert on_disk["access_token"] == "cached-tok" |
| 3049 |
assert on_disk["type"] == "oauth_token" |
| 3050 |
if os.name == "posix": |
| 3051 |
assert (creds_path.stat().st_mode & 0o777) == 0o600 |
| 3052 |
# Second call hits disk cache, not network. |
| 3053 |
assert provider().token == "cached-tok" |
| 3054 |
assert token_route.call_count == 1 |
| 3055 |
|
| 3056 |
def test_user_oauth_requires_credentials_path(self) -> None: |
| 3057 |
with pytest.raises(AnthropicError, match="requires 'authentication.credentials_path'"): |
| 3058 |
InMemoryConfig({"authentication": {"type": "user_oauth", "client_id": "cid"}}) |
| 3059 |
|
| 3060 |
@pytest.mark.respx() |
| 3061 |
def test_user_oauth_refresh_and_writeback(self, respx_mock: MockRouter, tmp_path: pathlib.Path) -> None: |
| 3062 |
"""user_oauth with `credentials_path` runs the refresh-token grant on |
| 3063 |
expiry and writes the new tokens back, exactly like a file-backed |
| 3064 |
`CredentialsFile` profile.""" |
| 3065 |
creds_path = tmp_path / "creds.json" |
| 3066 |
creds_path.write_text( |
| 3067 |
json.dumps( |
| 3068 |
{ |
| 3069 |
"type": "oauth_token", |
| 3070 |
"access_token": "old-tok", |
| 3071 |
"expires_at": int(time.time()) - 1, |
| 3072 |
"refresh_token": "refresh-old", |
| 3073 |
} |
| 3074 |
) |
| 3075 |
) |
| 3076 |
creds_path.chmod(0o600) |
| 3077 |
refresh_route = respx_mock.post(TOKEN_URL).mock( |
| 3078 |
return_value=httpx2.Response( |
| 3079 |
200, json={"access_token": "new-tok", "expires_in": 3600, "refresh_token": "refresh-new"} |
| 3080 |
) |
| 3081 |
) |
| 3082 |
provider = InMemoryConfig( |
| 3083 |
{ |
| 3084 |
"workspace_id": "wrkspc_x", |
| 3085 |
"authentication": { |
| 3086 |
"type": "user_oauth", |
| 3087 |
"client_id": "cid", |
| 3088 |
"credentials_path": str(creds_path), |
| 3089 |
}, |
| 3090 |
} |
| 3091 |
) |
| 3092 |
tok = provider() |
| 3093 |
assert tok.token == "new-tok" |
| 3094 |
assert refresh_route.call_count == 1 |
| 3095 |
rewritten = json.loads(creds_path.read_text()) |
| 3096 |
assert rewritten["access_token"] == "new-tok" |
| 3097 |
assert rewritten["refresh_token"] == "refresh-new" |
| 3098 |
# workspace-id header IS set for user_oauth (federation suppresses it). |
| 3099 |
assert provider.extra_headers() == {"anthropic-workspace-id": "wrkspc_x"} |
| 3100 |
|
| 3101 |
def test_unknown_type_rejected(self) -> None: |
| 3102 |
with pytest.raises(AnthropicError, match="Unknown authentication.type"): |
| 3103 |
InMemoryConfig({"authentication": {"type": "something_else"}}) |
| 3104 |
|
| 3105 |
def test_missing_authentication(self) -> None: |
| 3106 |
with pytest.raises(AnthropicError, match="missing the 'authentication' object"): |
| 3107 |
InMemoryConfig({"organization_id": "org_x"}) |
| 3108 |
|
| 3109 |
def test_missing_required_fields(self) -> None: |
| 3110 |
provider = InMemoryConfig( |
| 3111 |
{"authentication": {"type": "oidc_federation"}}, |
| 3112 |
identity_token_provider=lambda: "j", |
| 3113 |
) |
| 3114 |
with pytest.raises(WorkloadIdentityError, match="federation_rule_id"): |
| 3115 |
provider() |
| 3116 |
|
| 3117 |
def test_http_base_url_rejected(self) -> None: |
| 3118 |
with pytest.raises(AnthropicError, match="must use https"): |
| 3119 |
InMemoryConfig( |
| 3120 |
{ |
| 3121 |
"organization_id": "org_x", |
| 3122 |
"base_url": "http://example.com", |
| 3123 |
"authentication": {"type": "oidc_federation", "federation_rule_id": "fdrl_x"}, |
| 3124 |
}, |
| 3125 |
identity_token_provider=lambda: "j", |
| 3126 |
) |
| 3127 |
|
| 3128 |
|
| 3129 |
async def _send_message_async(client: AsyncAnthropic) -> None: |
| 3130 |
await client.messages.create( |
| 3131 |
max_tokens=1, |
| 3132 |
model="claude-opus-4-5", |
| 3133 |
messages=[{"role": "user", "content": "hi"}], |
| 3134 |
) |
| 3135 |
|
| 3136 |
|
| 3137 |
@pytest.mark.usefixtures("clean_env", "no_default_creds_file") |
| 3138 |
class TestAsyncAnthropicCredentials: |
| 3139 |
@pytest.mark.respx() |
| 3140 |
async def test_workspace_id_header_from_config( |
| 3141 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 3142 |
) -> None: |
| 3143 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 3144 |
clean_env.setenv("ANTHROPIC_CONFIG_DIR", str(tmp_path)) |
| 3145 |
_write_profile( |
| 3146 |
tmp_path, |
| 3147 |
"default", |
| 3148 |
{"type": "external", "workspace_id": "wrkspc_01abc"}, |
| 3149 |
{"access_token": "sk-ant-oat01-file"}, |
| 3150 |
) |
| 3151 |
|
| 3152 |
_mock_messages_endpoint(respx_mock) |
| 3153 |
|
| 3154 |
client = AsyncAnthropic() |
| 3155 |
await _send_message_async(client) |
| 3156 |
await client.messages.create( |
| 3157 |
max_tokens=1, |
| 3158 |
model="claude-opus-4-5", |
| 3159 |
messages=[{"role": "user", "content": "hi"}], |
| 3160 |
workspace_id="wrkspc_req", |
| 3161 |
) |
| 3162 |
|
| 3163 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 3164 |
assert calls[0].request.headers["anthropic-workspace-id"] == "wrkspc_01abc" |
| 3165 |
assert calls[1].request.headers["anthropic-workspace-id"] == "wrkspc_req" |
| 3166 |
|
| 3167 |
@pytest.mark.respx() |
| 3168 |
async def test_async_static_token(self, respx_mock: MockRouter) -> None: |
| 3169 |
_mock_messages_endpoint(respx_mock) |
| 3170 |
client = AsyncAnthropic(credentials=StaticToken("async-bearer")) |
| 3171 |
await _send_message_async(client) |
| 3172 |
req = cast("list[MockRequestCall]", respx_mock.calls)[0].request |
| 3173 |
assert req.headers["Authorization"] == "Bearer async-bearer" |
| 3174 |
assert OAUTH_API_BETA_HEADER in req.headers["anthropic-beta"] |
| 3175 |
|
| 3176 |
@pytest.mark.respx() |
| 3177 |
async def test_async_workload_identity_exchange(self, respx_mock: MockRouter) -> None: |
| 3178 |
"""Async client exchanges the OIDC JWT via the token endpoint and |
| 3179 |
attaches the resulting Bearer token to the request.""" |
| 3180 |
_mock_token_endpoint(respx_mock) |
| 3181 |
_mock_messages_endpoint(respx_mock) |
| 3182 |
client = AsyncAnthropic( |
| 3183 |
credentials=WorkloadIdentityCredentials( |
| 3184 |
identity_token_provider=lambda: "ext-jwt", |
| 3185 |
federation_rule_id="fdrl_01abc", |
| 3186 |
organization_id="org-uuid", |
| 3187 |
), |
| 3188 |
) |
| 3189 |
await _send_message_async(client) |
| 3190 |
msg_calls = [ |
| 3191 |
c for c in cast("list[MockRequestCall]", respx_mock.calls) if str(c.request.url).endswith("/v1/messages") |
| 3192 |
] |
| 3193 |
assert len(msg_calls) == 1 |
| 3194 |
assert msg_calls[0].request.headers["Authorization"] == "Bearer sk-ant-oat01-test" |
| 3195 |
|
| 3196 |
@pytest.mark.respx() |
| 3197 |
async def test_async_copy_with_different_base_url_exchanges_per_client(self, respx_mock: MockRouter) -> None: |
| 3198 |
"""Async mirror of the sync test: `copy(base_url=...)` leaves the |
| 3199 |
parent exchanging at, and presenting tokens from, its own host.""" |
| 3200 |
_mock_deployment(respx_mock, BASE_URL, "tok-primary") |
| 3201 |
_mock_deployment(respx_mock, OTHER_BASE_URL, "tok-other") |
| 3202 |
parent = AsyncAnthropic(credentials=_workload_credentials()) |
| 3203 |
child = parent.copy(base_url=OTHER_BASE_URL) |
| 3204 |
|
| 3205 |
await _send_message_async(child) |
| 3206 |
await _send_message_async(parent) |
| 3207 |
|
| 3208 |
_assert_exchanged_and_called_own_deployment(respx_mock, OTHER_BASE_URL, "tok-other") |
| 3209 |
_assert_exchanged_and_called_own_deployment(respx_mock, BASE_URL, "tok-primary") |
| 3210 |
|
| 3211 |
@pytest.mark.respx() |
| 3212 |
async def test_async_copy_with_same_base_url_shares_token_exchange(self, respx_mock: MockRouter) -> None: |
| 3213 |
_mock_deployment(respx_mock, BASE_URL, "tok-primary") |
| 3214 |
parent = AsyncAnthropic(credentials=_workload_credentials()) |
| 3215 |
child = parent.copy(base_url=BASE_URL) |
| 3216 |
assert child.credentials is parent.credentials |
| 3217 |
|
| 3218 |
await _send_message_async(child) |
| 3219 |
await _send_message_async(parent) |
| 3220 |
|
| 3221 |
requests = _requests_to(respx_mock, BASE_URL) |
| 3222 |
assert [str(r.url) for r in requests] == [TOKEN_URL, f"{BASE_URL}/v1/messages", f"{BASE_URL}/v1/messages"] |
| 3223 |
assert all(r.headers["Authorization"] == "Bearer tok-primary" for r in requests[1:]) |
| 3224 |
|
| 3225 |
@pytest.mark.respx() |
| 3226 |
async def test_async_authorized_user_refresh_flow( |
| 3227 |
self, |
| 3228 |
respx_mock: MockRouter, |
| 3229 |
tmp_path: pathlib.Path, |
| 3230 |
monkeypatch: pytest.MonkeyPatch, |
| 3231 |
) -> None: |
| 3232 |
"""Async client calling a CredentialsFile(authorized_user) provider: the |
| 3233 |
blocking refresh_token POST runs on the worker thread via asyncify.""" |
| 3234 |
monkeypatch.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 3235 |
_write_profile( |
| 3236 |
tmp_path, |
| 3237 |
"default", |
| 3238 |
{"type": "authorized_user", "client_id": "cid"}, |
| 3239 |
{"access_token": "old", "expires_at": int(time.time()) - 1, "refresh_token": "rt"}, |
| 3240 |
) |
| 3241 |
respx_mock.post(TOKEN_URL).mock( |
| 3242 |
return_value=httpx2.Response(200, json={"access_token": "refreshed", "expires_in": 3600}) |
| 3243 |
) |
| 3244 |
_mock_messages_endpoint(respx_mock) |
| 3245 |
client = AsyncAnthropic(credentials=CredentialsFile()) |
| 3246 |
await _send_message_async(client) |
| 3247 |
msg_calls = [ |
| 3248 |
c for c in cast("list[MockRequestCall]", respx_mock.calls) if str(c.request.url).endswith("/v1/messages") |
| 3249 |
] |
| 3250 |
assert msg_calls[0].request.headers["Authorization"] == "Bearer refreshed" |
| 3251 |
|
| 3252 |
@pytest.mark.respx() |
| 3253 |
async def test_async_concurrent_requests_single_flight(self, respx_mock: MockRouter) -> None: |
| 3254 |
"""Concurrent async requests sharing a TokenCache cause at most one |
| 3255 |
provider call — the single-flight guarantee holds across async workers.""" |
| 3256 |
_mock_messages_endpoint(respx_mock) |
| 3257 |
calls: List[int] = [] |
| 3258 |
|
| 3259 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3260 |
calls.append(1) |
| 3261 |
time.sleep(0.05) # widen the window for racing workers |
| 3262 |
return AccessToken(token=f"tok-{len(calls)}", expires_at=None) |
| 3263 |
|
| 3264 |
import asyncio |
| 3265 |
|
| 3266 |
client = AsyncAnthropic(credentials=provider) |
| 3267 |
await asyncio.gather(*(_send_message_async(client) for _ in range(8))) |
| 3268 |
# Exactly one provider call across eight concurrent requests. |
| 3269 |
assert len(calls) == 1 |
| 3270 |
|
| 3271 |
@pytest.mark.respx() |
| 3272 |
async def test_async_401_invalidates_and_retries_once(self, respx_mock: MockRouter) -> None: |
| 3273 |
"""Async client 401 behavior mirrors sync: invalidate the cache and |
| 3274 |
retry the current request once with a freshly minted token.""" |
| 3275 |
respx_mock.post(f"{BASE_URL}/v1/messages").mock( |
| 3276 |
return_value=httpx2.Response(401, json={"error": "unauthorized"}), |
| 3277 |
) |
| 3278 |
provider_calls: List[str] = [] |
| 3279 |
|
| 3280 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3281 |
provider_calls.append("called") |
| 3282 |
return AccessToken(token=f"tok-{len(provider_calls)}", expires_at=None) |
| 3283 |
|
| 3284 |
client = AsyncAnthropic(credentials=provider, max_retries=2) |
| 3285 |
with pytest.raises(anthropic.AuthenticationError): |
| 3286 |
await _send_message_async(client) |
| 3287 |
assert len(provider_calls) == 2 |
| 3288 |
|
| 3289 |
async def test_async_close_cascades_to_credentials(self) -> None: |
| 3290 |
"""AsyncAnthropic.close() cascades to self.credentials.close().""" |
| 3291 |
|
| 3292 |
class TrackedProvider: |
| 3293 |
closed = False |
| 3294 |
|
| 3295 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 3296 |
return AccessToken(token="t", expires_at=None) |
| 3297 |
|
| 3298 |
def close(self) -> None: |
| 3299 |
self.closed = True |
| 3300 |
|
| 3301 |
tracked = TrackedProvider() |
| 3302 |
client = AsyncAnthropic(credentials=tracked) |
| 3303 |
await client.close() |
| 3304 |
assert tracked.closed |
| 3305 |
|
| 3306 |
async def test_async_aclose_via_context_manager(self) -> None: |
| 3307 |
"""`async with AsyncAnthropic(...)` exits cleanly and cascades close.""" |
| 3308 |
|
| 3309 |
class TrackedProvider: |
| 3310 |
closed = False |
| 3311 |
|
| 3312 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 3313 |
return AccessToken(token="t", expires_at=None) |
| 3314 |
|
| 3315 |
def close(self) -> None: |
| 3316 |
self.closed = True |
| 3317 |
|
| 3318 |
tracked = TrackedProvider() |
| 3319 |
async with AsyncAnthropic(credentials=tracked) as _client: |
| 3320 |
pass |
| 3321 |
assert tracked.closed |
| 3322 |
|
| 3323 |
@pytest.mark.respx() |
| 3324 |
async def test_async_max_retries_zero_honored_on_401(self, respx_mock: MockRouter) -> None: |
| 3325 |
"""max_retries=0 means a 401 surfaces immediately — no implicit retry.""" |
| 3326 |
respx_mock.post(f"{BASE_URL}/v1/messages").mock( |
| 3327 |
return_value=httpx2.Response(401, json={"error": "unauthorized"}), |
| 3328 |
) |
| 3329 |
client = AsyncAnthropic(credentials=StaticToken("t"), max_retries=0) |
| 3330 |
with pytest.raises(anthropic.AuthenticationError): |
| 3331 |
await _send_message_async(client) |
| 3332 |
# Exactly one request attempt, not two. |
| 3333 |
assert len(cast("list[MockRequestCall]", respx_mock.calls)) == 1 |
| 3334 |
|
| 3335 |
async def test_async_workload_identity_error_propagates_through_request_flow(self) -> None: |
| 3336 |
"""Async counterpart of the sync regression test: a WorkloadIdentityError |
| 3337 |
raised by the credential provider must bubble out of the async |
| 3338 |
messages.create() as-is, not wrapped in APIConnectionError, and must |
| 3339 |
not trigger retries.""" |
| 3340 |
provider_calls: List[str] = [] |
| 3341 |
|
| 3342 |
def failing_provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3343 |
provider_calls.append("called") |
| 3344 |
raise WorkloadIdentityError( |
| 3345 |
"simulated 403", |
| 3346 |
status_code=403, |
| 3347 |
body={"error": {"type": "permission_error", "message": "Permission denied"}}, |
| 3348 |
) |
| 3349 |
|
| 3350 |
client = AsyncAnthropic(credentials=failing_provider, max_retries=3) |
| 3351 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 3352 |
await _send_message_async(client) |
| 3353 |
assert exc_info.value.status_code == 403 |
| 3354 |
body = cast("Dict[str, Any]", exc_info.value.body) |
| 3355 |
assert body["error"]["type"] == "permission_error" |
| 3356 |
assert len(provider_calls) == 1 |
| 3357 |
|
| 3358 |
|
| 3359 |
def _bearer_tokens(respx_mock: MockRouter) -> List[str]: |
| 3360 |
"""The token on each HTTP request so far, in order.""" |
| 3361 |
return [c.request.headers["Authorization"].split(" ")[1] for c in cast("list[MockRequestCall]", respx_mock.calls)] |
| 3362 |
|
| 3363 |
|
| 3364 |
async def _async_provider_function(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3365 |
return AccessToken("t") |
| 3366 |
|
| 3367 |
|
| 3368 |
class _AsyncProviderObject: |
| 3369 |
async def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 3370 |
return AccessToken("t") |
| 3371 |
|
| 3372 |
async def method(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 3373 |
return AccessToken("t") |
| 3374 |
|
| 3375 |
|
| 3376 |
@pytest.mark.usefixtures("clean_env", "no_default_creds_file") |
| 3377 |
class TestAsyncAccessTokenProvider: |
| 3378 |
@pytest.mark.parametrize( |
| 3379 |
"shape", |
| 3380 |
[ |
| 3381 |
_async_provider_function, |
| 3382 |
functools.partial(_async_provider_function), |
| 3383 |
_AsyncProviderObject(), |
| 3384 |
functools.partial(_AsyncProviderObject()), |
| 3385 |
functools.partial(functools.partial(_AsyncProviderObject())), |
| 3386 |
_AsyncProviderObject().method, |
| 3387 |
], |
| 3388 |
ids=[ |
| 3389 |
"function", |
| 3390 |
"partial-of-function", |
| 3391 |
"callable-object", |
| 3392 |
"partial-of-callable-object", |
| 3393 |
"nested-partial", |
| 3394 |
"bound-method", |
| 3395 |
], |
| 3396 |
) |
| 3397 |
def test_detection(self, shape: Callable[..., Any]) -> None: |
| 3398 |
assert is_async_token_provider(shape) |
| 3399 |
with pytest.raises(TypeError, match="use `AsyncAnthropic` instead"): |
| 3400 |
Anthropic(credentials=shape) # pyright: ignore[reportArgumentType] |
| 3401 |
|
| 3402 |
@pytest.mark.parametrize( |
| 3403 |
"shape", |
| 3404 |
[CountingProvider([]), lambda: AccessToken("t"), functools.partial(CountingProvider([]))], |
| 3405 |
ids=["callable-object", "lambda", "partial-of-callable-object"], |
| 3406 |
) |
| 3407 |
def test_sync_providers_are_not_detected_as_async(self, shape: Callable[..., Any]) -> None: |
| 3408 |
assert not is_async_token_provider(shape) |
| 3409 |
|
| 3410 |
@pytest.mark.respx() |
| 3411 |
async def test_partial_of_a_callable_object_is_awaited(self, respx_mock: MockRouter) -> None: |
| 3412 |
_mock_messages_endpoint(respx_mock) |
| 3413 |
|
| 3414 |
class Provider: |
| 3415 |
async def __call__(self, token: str, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 3416 |
return AccessToken(token) |
| 3417 |
|
| 3418 |
await _send_message_async(AsyncAnthropic(credentials=functools.partial(Provider(), "tok"))) |
| 3419 |
assert _bearer_tokens(respx_mock) == ["tok"] |
| 3420 |
|
| 3421 |
@pytest.mark.respx() |
| 3422 |
async def test_sync_provider_runs_off_the_event_loop_thread(self, respx_mock: MockRouter) -> None: |
| 3423 |
_mock_messages_endpoint(respx_mock) |
| 3424 |
provider_threads: List[int] = [] |
| 3425 |
|
| 3426 |
def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3427 |
provider_threads.append(threading.get_ident()) |
| 3428 |
return AccessToken("tok") |
| 3429 |
|
| 3430 |
await _send_message_async(AsyncAnthropic(credentials=provider)) |
| 3431 |
assert provider_threads and provider_threads != [threading.get_ident()] |
| 3432 |
|
| 3433 |
async def test_sync_callable_returning_a_coroutine_is_rejected(self) -> None: |
| 3434 |
"""`lambda: fetch()` is a sync provider that hands back a coroutine. It fails before any request is sent.""" |
| 3435 |
coroutines: List[Any] = [] |
| 3436 |
|
| 3437 |
def provider(*, force_refresh: bool = False) -> Any: # noqa: ARG001 |
| 3438 |
coroutines.append(_async_provider_function()) |
| 3439 |
return coroutines[-1] |
| 3440 |
|
| 3441 |
with pytest.raises(AnthropicError, match="pass the `async def` function itself"): |
| 3442 |
await _send_message_async(AsyncAnthropic(credentials=provider)) |
| 3443 |
assert coroutines[0].cr_frame is None, "the coroutine should have been closed" |
| 3444 |
|
| 3445 |
@pytest.mark.respx() |
| 3446 |
async def test_awaited_on_the_running_loop_and_cached(self, respx_mock: MockRouter) -> None: |
| 3447 |
_mock_messages_endpoint(respx_mock) |
| 3448 |
loops: List[asyncio.AbstractEventLoop] = [] |
| 3449 |
|
| 3450 |
async def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3451 |
loops.append(asyncio.get_running_loop()) |
| 3452 |
return AccessToken("tok", expires_at=int(time.time()) + 3600) |
| 3453 |
|
| 3454 |
client = AsyncAnthropic(credentials=provider) |
| 3455 |
await _send_message_async(client) |
| 3456 |
await _send_message_async(client) |
| 3457 |
assert loops == [asyncio.get_running_loop()] |
| 3458 |
assert _bearer_tokens(respx_mock) == ["tok", "tok"] |
| 3459 |
|
| 3460 |
async def test_called_again_after_expiry(self) -> None: |
| 3461 |
clock = FakeClock(1000) |
| 3462 |
calls: List[int] = [] |
| 3463 |
|
| 3464 |
async def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3465 |
calls.append(1) |
| 3466 |
return AccessToken(f"tok-{len(calls)}", expires_at=int(clock.now) + 600) |
| 3467 |
|
| 3468 |
cache = TokenCache(provider, time_source=clock) |
| 3469 |
assert await cache.async_get_token() == "tok-1" |
| 3470 |
clock.now += 601 |
| 3471 |
assert await cache.async_get_token() == "tok-2" |
| 3472 |
assert await cache.async_get_token() == "tok-2" |
| 3473 |
|
| 3474 |
@pytest.mark.respx() |
| 3475 |
async def test_401_invalidates_and_retries_with_new_token(self, respx_mock: MockRouter) -> None: |
| 3476 |
"""A provider that takes no arguments still works, on the first call and on the retry after a 401.""" |
| 3477 |
respx_mock.post(f"{BASE_URL}/v1/messages").mock( |
| 3478 |
side_effect=[ |
| 3479 |
httpx2.Response(401, json={"error": "unauthorized"}, headers={"retry-after-ms": "1"}), |
| 3480 |
_message_response(), |
| 3481 |
] |
| 3482 |
) |
| 3483 |
calls: List[int] = [] |
| 3484 |
|
| 3485 |
async def provider() -> AccessToken: |
| 3486 |
calls.append(1) |
| 3487 |
return AccessToken(f"tok-{len(calls)}") |
| 3488 |
|
| 3489 |
await _send_message_async(AsyncAnthropic(credentials=provider)) # pyright: ignore[reportArgumentType] |
| 3490 |
assert _bearer_tokens(respx_mock) == ["tok-1", "tok-2"] |
| 3491 |
|
| 3492 |
@pytest.mark.respx() |
| 3493 |
async def test_401_retry_passes_force_refresh(self, respx_mock: MockRouter) -> None: |
| 3494 |
respx_mock.post(f"{BASE_URL}/v1/messages").mock( |
| 3495 |
side_effect=[ |
| 3496 |
httpx2.Response(401, json={"error": "unauthorized"}, headers={"retry-after-ms": "1"}), |
| 3497 |
_message_response(), |
| 3498 |
_message_response(), |
| 3499 |
] |
| 3500 |
) |
| 3501 |
force_seen: List[bool] = [] |
| 3502 |
|
| 3503 |
async def provider(*, force_refresh: bool = False) -> AccessToken: |
| 3504 |
force_seen.append(force_refresh) |
| 3505 |
return AccessToken(f"tok-{len(force_seen)}") |
| 3506 |
|
| 3507 |
client = AsyncAnthropic(credentials=provider) |
| 3508 |
await _send_message_async(client) |
| 3509 |
await _send_message_async(client) |
| 3510 |
assert force_seen == [False, True] |
| 3511 |
assert _bearer_tokens(respx_mock) == ["tok-1", "tok-2", "tok-2"] |
| 3512 |
|
| 3513 |
async def test_zero_arg_provider_behind_a_decorator_or_call_method(self) -> None: |
| 3514 |
"""`inspect.signature` follows `functools.wraps`, so it sees that the wrapped function takes no arguments.""" |
| 3515 |
|
| 3516 |
def passthrough(fn: Callable[..., Any]) -> Callable[..., Any]: |
| 3517 |
@functools.wraps(fn) |
| 3518 |
async def wrapper(*args: Any, **kwargs: Any) -> Any: |
| 3519 |
return await fn(*args, **kwargs) |
| 3520 |
|
| 3521 |
return wrapper |
| 3522 |
|
| 3523 |
@passthrough |
| 3524 |
async def decorated() -> AccessToken: |
| 3525 |
return AccessToken("decorated", expires_at=0) |
| 3526 |
|
| 3527 |
class ZeroArgCall: |
| 3528 |
async def __call__(self) -> AccessToken: |
| 3529 |
return AccessToken("object", expires_at=0) |
| 3530 |
|
| 3531 |
for provider, token in ((decorated, "decorated"), (ZeroArgCall(), "object")): |
| 3532 |
cache = TokenCache(provider) # pyright: ignore[reportArgumentType] |
| 3533 |
assert await cache.async_get_token() == token |
| 3534 |
cache.invalidate() |
| 3535 |
assert await cache.async_get_token() == token |
| 3536 |
|
| 3537 |
async def test_next_force_preserved_on_provider_failure(self) -> None: |
| 3538 |
force_seen: List[bool] = [] |
| 3539 |
|
| 3540 |
async def provider(*, force_refresh: bool = False) -> AccessToken: |
| 3541 |
force_seen.append(force_refresh) |
| 3542 |
if len(force_seen) == 1: |
| 3543 |
raise RuntimeError("transient") |
| 3544 |
return AccessToken("ok") |
| 3545 |
|
| 3546 |
cache = TokenCache(provider) |
| 3547 |
cache.invalidate() |
| 3548 |
with pytest.raises(RuntimeError): |
| 3549 |
await cache.async_get_token() |
| 3550 |
assert await cache.async_get_token() == "ok" |
| 3551 |
assert force_seen == [True, True] |
| 3552 |
|
| 3553 |
async def test_next_force_preserved_when_provider_returns_non_token(self) -> None: |
| 3554 |
force_seen: List[bool] = [] |
| 3555 |
results = iter([AccessToken("a"), None, AccessToken("b")]) |
| 3556 |
|
| 3557 |
async def provider(*, force_refresh: bool = False) -> AccessToken: |
| 3558 |
force_seen.append(force_refresh) |
| 3559 |
return cast(AccessToken, next(results)) |
| 3560 |
|
| 3561 |
cache = TokenCache(provider) |
| 3562 |
assert await cache.async_get_token() == "a" |
| 3563 |
cache.invalidate() |
| 3564 |
with pytest.raises(AnthropicError, match="credentials provider returned"): |
| 3565 |
await cache.async_get_token() |
| 3566 |
assert await cache.async_get_token() == "b" |
| 3567 |
assert force_seen == [False, True, True] |
| 3568 |
|
| 3569 |
async def test_per_request_mode_still_forces_after_invalidate(self) -> None: |
| 3570 |
force_seen: List[bool] = [] |
| 3571 |
|
| 3572 |
async def provider(*, force_refresh: bool = False) -> AccessToken: |
| 3573 |
force_seen.append(force_refresh) |
| 3574 |
return AccessToken(f"tok-{len(force_seen)}", expires_at=0) |
| 3575 |
|
| 3576 |
cache = TokenCache(provider) |
| 3577 |
await cache.async_get_token() |
| 3578 |
await cache.async_get_token() |
| 3579 |
cache.invalidate() |
| 3580 |
await cache.async_get_token() |
| 3581 |
await cache.async_get_token() |
| 3582 |
assert force_seen == [False, False, True, False] |
| 3583 |
|
| 3584 |
async def test_concurrent_invalidate_survives_non_forced_call(self) -> None: |
| 3585 |
"""An invalidate() that lands during a non-forced call still forces the next call.""" |
| 3586 |
force_seen: List[bool] = [] |
| 3587 |
|
| 3588 |
async def provider(*, force_refresh: bool = False) -> AccessToken: |
| 3589 |
force_seen.append(force_refresh) |
| 3590 |
if len(force_seen) == 2: |
| 3591 |
cache.invalidate() # simulates another request's 401 arriving now |
| 3592 |
return AccessToken(f"tok-{len(force_seen)}", expires_at=0) |
| 3593 |
|
| 3594 |
cache = TokenCache(provider) |
| 3595 |
await cache.async_get_token() # switch to per-request mode |
| 3596 |
await cache.async_get_token() |
| 3597 |
await cache.async_get_token() |
| 3598 |
assert force_seen == [False, False, True] |
| 3599 |
|
| 3600 |
async def test_unforced_result_is_not_cached_after_a_concurrent_invalidate(self) -> None: |
| 3601 |
force_seen: List[bool] = [] |
| 3602 |
|
| 3603 |
async def provider(*, force_refresh: bool = False) -> AccessToken: |
| 3604 |
force_seen.append(force_refresh) |
| 3605 |
if len(force_seen) == 1: |
| 3606 |
cache.invalidate() # simulates another request's 401 arriving now |
| 3607 |
return AccessToken(f"tok-{len(force_seen)}") |
| 3608 |
|
| 3609 |
cache = TokenCache(provider) |
| 3610 |
assert await cache.async_get_token() == "tok-1" |
| 3611 |
assert await cache.async_get_token() == "tok-2" |
| 3612 |
assert await cache.async_get_token() == "tok-2" |
| 3613 |
assert force_seen == [False, True] |
| 3614 |
|
| 3615 |
async def test_one_forced_call_per_invalidate_in_per_request_mode(self) -> None: |
| 3616 |
"""P0 is a per-request call that starts before invalidate() and finishes after it.""" |
| 3617 |
force_seen: List[bool] = [] |
| 3618 |
p0_in, p0_release, leader_in, release_leader = (asyncio.Event() for _ in range(4)) |
| 3619 |
|
| 3620 |
async def provider(*, force_refresh: bool = False) -> AccessToken: |
| 3621 |
force_seen.append(force_refresh) |
| 3622 |
n = len(force_seen) |
| 3623 |
if n == 2: # P0 |
| 3624 |
p0_in.set() |
| 3625 |
await p0_release.wait() |
| 3626 |
elif force_refresh: |
| 3627 |
leader_in.set() |
| 3628 |
await release_leader.wait() |
| 3629 |
return AccessToken(f"tok-{n}", expires_at=0) |
| 3630 |
|
| 3631 |
cache = TokenCache(provider) |
| 3632 |
assert await cache.async_get_token() == "tok-1" # per-request mode |
| 3633 |
p0 = asyncio.ensure_future(cache.async_get_token()) |
| 3634 |
await asyncio.wait_for(p0_in.wait(), timeout=2) |
| 3635 |
cache.invalidate() |
| 3636 |
leader = asyncio.ensure_future(cache.async_get_token()) |
| 3637 |
await asyncio.wait_for(leader_in.wait(), timeout=2) # the forced call is in flight |
| 3638 |
p0_release.set() |
| 3639 |
assert await asyncio.wait_for(p0, timeout=2) == "tok-2" # P0 still uses its own token for its request |
| 3640 |
others = [asyncio.ensure_future(cache.async_get_token()) for _ in range(5)] |
| 3641 |
await asyncio.sleep(0) # let them find the refresh in flight |
| 3642 |
assert not any(task.done() for task in others) |
| 3643 |
assert len(force_seen) == 3 # none of them has called the provider |
| 3644 |
release_leader.set() |
| 3645 |
assert await asyncio.wait_for(leader, timeout=2) == "tok-3" |
| 3646 |
assert sorted(await asyncio.wait_for(asyncio.gather(*others), timeout=2)) == [f"tok-{n}" for n in range(4, 9)] |
| 3647 |
assert force_seen == [False, False, True, False, False, False, False, False] |
| 3648 |
|
| 3649 |
async def test_concurrent_cold_calls_share_one_provider_call(self) -> None: |
| 3650 |
calls: List[int] = [] |
| 3651 |
|
| 3652 |
async def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3653 |
calls.append(1) |
| 3654 |
await asyncio.sleep(0.05) # long enough for the other callers to need the token too |
| 3655 |
return AccessToken("tok") |
| 3656 |
|
| 3657 |
cache = TokenCache(provider) |
| 3658 |
assert await asyncio.gather(*(cache.async_get_token() for _ in range(8))) == ["tok"] * 8 |
| 3659 |
assert calls == [1] |
| 3660 |
|
| 3661 |
async def test_zero_expiry_token_is_not_reused(self) -> None: |
| 3662 |
clock = FakeClock(1000) |
| 3663 |
calls: List[int] = [] |
| 3664 |
|
| 3665 |
async def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3666 |
calls.append(1) |
| 3667 |
return AccessToken(f"tok-{len(calls)}", expires_at=0 if len(calls) < 3 else 1000 + 600) |
| 3668 |
|
| 3669 |
cache = TokenCache(provider, time_source=clock) |
| 3670 |
assert [await cache.async_get_token() for _ in range(4)] == ["tok-1", "tok-2", "tok-3", "tok-3"] |
| 3671 |
|
| 3672 |
@pytest.mark.respx() |
| 3673 |
async def test_zero_expiry_tokens_are_fetched_concurrently(self, respx_mock: MockRouter) -> None: |
| 3674 |
"""Requests don't queue behind each other for a token that can't be shared.""" |
| 3675 |
_mock_messages_endpoint(respx_mock) |
| 3676 |
calls: List[int] = [] |
| 3677 |
all_three_fetching = asyncio.Event() |
| 3678 |
|
| 3679 |
async def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3680 |
calls.append(1) |
| 3681 |
n = len(calls) |
| 3682 |
if n == 4: |
| 3683 |
all_three_fetching.set() |
| 3684 |
if n > 1: |
| 3685 |
await asyncio.wait_for(all_three_fetching.wait(), timeout=2) # times out if they queued |
| 3686 |
return AccessToken(f"tok-{n}", expires_at=0) |
| 3687 |
|
| 3688 |
client = AsyncAnthropic(credentials=provider) |
| 3689 |
await _send_message_async(client) |
| 3690 |
await asyncio.gather(*(_send_message_async(client) for _ in range(3))) |
| 3691 |
assert sorted(_bearer_tokens(respx_mock)) == ["tok-1", "tok-2", "tok-3", "tok-4"] |
| 3692 |
|
| 3693 |
async def test_advisory_failure_serves_cached_and_mandatory_failure_raises(self) -> None: |
| 3694 |
clock = FakeClock(1000) |
| 3695 |
calls: List[int] = [] |
| 3696 |
|
| 3697 |
async def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3698 |
calls.append(1) |
| 3699 |
if len(calls) > 1: |
| 3700 |
raise AnthropicError("token service unavailable") |
| 3701 |
return AccessToken("a", expires_at=1000 + 600) |
| 3702 |
|
| 3703 |
cache = TokenCache(provider, time_source=clock) |
| 3704 |
assert await cache.async_get_token() == "a" |
| 3705 |
clock.now = 1000 + 600 - 60 # advisory window |
| 3706 |
assert await cache.async_get_token() == "a" |
| 3707 |
clock.now = 1000 + 600 - 10 # mandatory window |
| 3708 |
with pytest.raises(AnthropicError, match="unavailable"): |
| 3709 |
await cache.async_get_token() |
| 3710 |
assert len(calls) == 3 |
| 3711 |
|
| 3712 |
async def test_cancelled_leader_releases_waiters(self) -> None: |
| 3713 |
calls: List[int] = [] |
| 3714 |
first_call_started = asyncio.Event() |
| 3715 |
|
| 3716 |
async def provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 3717 |
calls.append(1) |
| 3718 |
if len(calls) == 1: |
| 3719 |
first_call_started.set() |
| 3720 |
await asyncio.sleep(3600) |
| 3721 |
return AccessToken("tok") |
| 3722 |
|
| 3723 |
cache = TokenCache(provider) |
| 3724 |
leader = asyncio.ensure_future(cache.async_get_token()) |
| 3725 |
await asyncio.wait_for(first_call_started.wait(), timeout=2) |
| 3726 |
waiter = asyncio.ensure_future(cache.async_get_token()) |
| 3727 |
await asyncio.sleep(0) # let the waiter find the refresh in flight |
| 3728 |
assert not waiter.done() and len(calls) == 1 |
| 3729 |
leader.cancel() |
| 3730 |
assert await asyncio.wait_for(waiter, timeout=2) == "tok" |
| 3731 |
with pytest.raises(asyncio.CancelledError): |
| 3732 |
await leader |
| 3733 |
assert len(calls) == 2 |
| 3734 |
|
| 3735 |
async def test_provider_must_return_an_access_token(self) -> None: |
| 3736 |
async def provider(*, force_refresh: bool = False) -> Any: # noqa: ARG001 |
| 3737 |
return {"token": "t"} |
| 3738 |
|
| 3739 |
with pytest.raises(AnthropicError, match="returned dict instead of an AccessToken"): |
| 3740 |
await TokenCache(provider).async_get_token() |
| 3741 |
|
| 3742 |
async def test_close_awaits_aclose(self) -> None: |
| 3743 |
closed: List[str] = [] |
| 3744 |
|
| 3745 |
class Provider(_AsyncProviderObject): |
| 3746 |
async def aclose(self) -> None: |
| 3747 |
closed.append("aclose") |
| 3748 |
|
| 3749 |
def close(self) -> None: |
| 3750 |
closed.append("close") |
| 3751 |
|
| 3752 |
await AsyncAnthropic(credentials=Provider()).close() |
| 3753 |
assert closed == ["aclose"], "aclose() wins when a provider has both hooks" |
| 3754 |
|
| 3755 |
async def test_close_awaits_an_async_close(self) -> None: |
| 3756 |
closed: List[str] = [] |
| 3757 |
|
| 3758 |
class Provider(_AsyncProviderObject): |
| 3759 |
async def close(self) -> None: |
| 3760 |
closed.append("close") |
| 3761 |
|
| 3762 |
async with AsyncAnthropic(credentials=Provider()): |
| 3763 |
pass |
| 3764 |
assert closed == ["close"] |
| 3765 |
|
| 3766 |
async def test_close_tolerates_hooks_that_return_nothing_to_await(self) -> None: |
| 3767 |
"""A `Mock` has every attribute, so on Python < 3.12 it looks like it has `aclose()`.""" |
| 3768 |
closed: List[str] = [] |
| 3769 |
|
| 3770 |
class SyncAclose(_AsyncProviderObject): |
| 3771 |
def aclose(self) -> None: |
| 3772 |
closed.append("aclose") |
| 3773 |
|
| 3774 |
await AsyncAnthropic(credentials=SyncAclose()).close() |
| 3775 |
await AsyncAnthropic(credentials=MagicMock(return_value=AccessToken("t"))).close() |
| 3776 |
assert closed == ["aclose"] |
| 3777 |
|
| 3778 |
async def test_close_reaches_a_partial_wrapped_provider(self) -> None: |
| 3779 |
closed: List[str] = [] |
| 3780 |
|
| 3781 |
class Provider: |
| 3782 |
async def __call__(self, tag: str, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 3783 |
return AccessToken(tag) |
| 3784 |
|
| 3785 |
async def aclose(self) -> None: |
| 3786 |
closed.append("aclose") |
| 3787 |
|
| 3788 |
await AsyncAnthropic(credentials=functools.partial(Provider(), "t")).close() |
| 3789 |
assert closed == ["aclose"] |
| 3790 |
|
| 3791 |
@pytest.mark.parametrize("in_a_partial", [False, True], ids=["bare", "partial"]) |
| 3792 |
def test_sync_client_rejects_an_async_close(self, in_a_partial: bool) -> None: |
| 3793 |
class Provider(CountingProvider): |
| 3794 |
async def close(self) -> None: |
| 3795 |
pass |
| 3796 |
|
| 3797 |
provider = Provider([]) |
| 3798 |
with pytest.raises(TypeError, match=r"`async def close\(\)`; use `AsyncAnthropic` instead"): |
| 3799 |
Anthropic(credentials=functools.partial(provider) if in_a_partial else provider) |
| 3800 |
|
| 3801 |
@pytest.mark.parametrize("in_a_partial", [False, True], ids=["bare", "partial"]) |
| 3802 |
def test_sync_client_calls_close_and_ignores_aclose(self, in_a_partial: bool) -> None: |
| 3803 |
closed: List[str] = [] |
| 3804 |
|
| 3805 |
class Provider(CountingProvider): |
| 3806 |
def close(self) -> None: |
| 3807 |
closed.append("close") |
| 3808 |
|
| 3809 |
async def aclose(self) -> None: |
| 3810 |
closed.append("aclose") |
| 3811 |
|
| 3812 |
provider = Provider([]) |
| 3813 |
Anthropic(credentials=functools.partial(provider) if in_a_partial else provider).close() |
| 3814 |
assert closed == ["close"] |
| 3815 |
|
| 3816 |
def test_sync_client_accepts_a_provider_that_only_has_aclose(self) -> None: |
| 3817 |
"""As on the sync client before async providers existed: `aclose()` is not its hook, so it is left alone.""" |
| 3818 |
closed: List[str] = [] |
| 3819 |
|
| 3820 |
class Provider(CountingProvider): |
| 3821 |
async def aclose(self) -> None: |
| 3822 |
closed.append("aclose") |
| 3823 |
|
| 3824 |
Anthropic(credentials=Provider([])).close() |
| 3825 |
assert closed == [] |
| 3826 |
|
| 3827 |
|
| 3828 |
@pytest.mark.usefixtures("clean_env", "no_default_creds_file") |
| 3829 |
class TestTypedCredentialErrors: |
| 3830 |
"""Every exit point in the credentials subsystem raises an `AnthropicError` |
| 3831 |
(or subclass). Anything outside that hierarchy is wrapped as |
| 3832 |
`APIConnectionError` and retried by the base client's `except Exception` |
| 3833 |
handler, hiding the real cause and amplifying load. |
| 3834 |
""" |
| 3835 |
|
| 3836 |
def test_invalid_profile_name_raises_anthropic_error( |
| 3837 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 3838 |
) -> None: |
| 3839 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 3840 |
clean_env.setenv("ANTHROPIC_PROFILE", "work/dev") |
| 3841 |
with pytest.raises(AnthropicError, match="ANTHROPIC_PROFILE"): |
| 3842 |
Anthropic() |
| 3843 |
|
| 3844 |
def test_profile_name_with_dot_prefix_raises_anthropic_error( |
| 3845 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 3846 |
) -> None: |
| 3847 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 3848 |
clean_env.setenv("ANTHROPIC_PROFILE", ".hidden") |
| 3849 |
with pytest.raises(AnthropicError, match="start with a dot"): |
| 3850 |
Anthropic() |
| 3851 |
|
| 3852 |
def test_http_base_url_on_workload_provider_raises_anthropic_error(self) -> None: |
| 3853 |
creds = WorkloadIdentityCredentials( |
| 3854 |
identity_token_provider=lambda: "jwt", |
| 3855 |
federation_rule_id="fdrl_x", |
| 3856 |
organization_id="org_x", |
| 3857 |
) |
| 3858 |
with pytest.raises(AnthropicError, match="https"): |
| 3859 |
creds.bind_base_url("http://evil.example/") |
| 3860 |
|
| 3861 |
def test_http_base_url_in_config_file_raises_anthropic_error( |
| 3862 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 3863 |
) -> None: |
| 3864 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 3865 |
_write_profile( |
| 3866 |
tmp_path, |
| 3867 |
"default", |
| 3868 |
{ |
| 3869 |
"base_url": "http://api.example/", |
| 3870 |
"authentication": {"type": "user_oauth"}, |
| 3871 |
}, |
| 3872 |
{"access_token": "tok"}, |
| 3873 |
) |
| 3874 |
with pytest.raises(AnthropicError, match="https"): |
| 3875 |
CredentialsFile("default")() |
| 3876 |
|
| 3877 |
def test_identity_token_file_permission_error_raises_anthropic_error(self, tmp_path: pathlib.Path) -> None: |
| 3878 |
if os.name != "posix": |
| 3879 |
pytest.skip("chmod semantics only apply on POSIX") |
| 3880 |
if os.geteuid() == 0: |
| 3881 |
pytest.skip("root bypasses POSIX mode bits") |
| 3882 |
f = tmp_path / "token" |
| 3883 |
f.write_text("jwt") |
| 3884 |
f.chmod(0o000) |
| 3885 |
try: |
| 3886 |
provider = IdentityTokenFile(f) |
| 3887 |
with pytest.raises(IdentityTokenFileError, match="not readable|Permission") as exc_info: |
| 3888 |
provider() |
| 3889 |
assert exc_info.value.path == f |
| 3890 |
finally: |
| 3891 |
f.chmod(0o600) |
| 3892 |
|
| 3893 |
def test_identity_token_file_directory_raises_anthropic_error(self, tmp_path: pathlib.Path) -> None: |
| 3894 |
provider = IdentityTokenFile(tmp_path) |
| 3895 |
with pytest.raises(IdentityTokenFileError) as exc_info: |
| 3896 |
provider() |
| 3897 |
assert exc_info.value.path == tmp_path |
| 3898 |
assert isinstance(exc_info.value.__cause__, OSError) |
| 3899 |
|
| 3900 |
def test_identity_token_file_binary_content_raises_anthropic_error(self, tmp_path: pathlib.Path) -> None: |
| 3901 |
f = tmp_path / "token" |
| 3902 |
f.write_bytes(b"\xff\xfe\xfd\x00not-utf8") |
| 3903 |
provider = IdentityTokenFile(f) |
| 3904 |
with pytest.raises(IdentityTokenFileError) as exc_info: |
| 3905 |
provider() |
| 3906 |
assert exc_info.value.path == f |
| 3907 |
|
| 3908 |
def test_identity_token_file_empty_raises_anthropic_error(self, tmp_path: pathlib.Path) -> None: |
| 3909 |
f = tmp_path / "token" |
| 3910 |
f.write_text("") |
| 3911 |
provider = IdentityTokenFile(f) |
| 3912 |
with pytest.raises(IdentityTokenFileError, match="empty") as exc_info: |
| 3913 |
provider() |
| 3914 |
assert exc_info.value.path == f |
| 3915 |
|
| 3916 |
def test_user_oauth_malformed_expires_at_raises_anthropic_error( |
| 3917 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 3918 |
) -> None: |
| 3919 |
"""An ISO8601 string in `expires_at` must raise AnthropicError naming the expected shape.""" |
| 3920 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 3921 |
_write_profile( |
| 3922 |
tmp_path, |
| 3923 |
"default", |
| 3924 |
{"authentication": {"type": "user_oauth"}}, |
| 3925 |
{"access_token": "tok", "expires_at": "2030-01-01T00:00:00Z"}, |
| 3926 |
) |
| 3927 |
with pytest.raises(AnthropicError, match="expires_at"): |
| 3928 |
CredentialsFile("default")() |
| 3929 |
|
| 3930 |
|
| 3931 |
class TestTokenCacheDeadlock: |
| 3932 |
def test_non_anthropic_error_from_provider_releases_waiters(self) -> None: |
| 3933 |
"""A non-`AnthropicError` / non-`httpx2.HTTPError` from the leader |
| 3934 |
provider must still release `_refresh_event` so concurrent waiters |
| 3935 |
don't deadlock.""" |
| 3936 |
import threading as _threading |
| 3937 |
|
| 3938 |
ready = _threading.Event() |
| 3939 |
release_leader = _threading.Event() |
| 3940 |
|
| 3941 |
class FlakyProvider: |
| 3942 |
calls = 0 |
| 3943 |
|
| 3944 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 3945 |
self.calls += 1 |
| 3946 |
if self.calls == 1: |
| 3947 |
ready.set() |
| 3948 |
release_leader.wait(timeout=2) |
| 3949 |
raise RuntimeError("programmer error from a custom provider") |
| 3950 |
return AccessToken("fresh", expires_at=None) |
| 3951 |
|
| 3952 |
provider = FlakyProvider() |
| 3953 |
cache = TokenCache(provider) |
| 3954 |
|
| 3955 |
leader_error: List[BaseException] = [] |
| 3956 |
|
| 3957 |
def run_leader() -> None: |
| 3958 |
try: |
| 3959 |
cache.get_token() |
| 3960 |
except BaseException as err: |
| 3961 |
leader_error.append(err) |
| 3962 |
|
| 3963 |
leader = _threading.Thread(target=run_leader, daemon=True) |
| 3964 |
leader.start() |
| 3965 |
assert ready.wait(timeout=2) |
| 3966 |
|
| 3967 |
waiter_error: List[BaseException] = [] |
| 3968 |
waiter_result: List[str] = [] |
| 3969 |
|
| 3970 |
def run_waiter() -> None: |
| 3971 |
try: |
| 3972 |
waiter_result.append(cache.get_token()) |
| 3973 |
except BaseException as err: |
| 3974 |
waiter_error.append(err) |
| 3975 |
|
| 3976 |
waiter = _threading.Thread(target=run_waiter, daemon=True) |
| 3977 |
waiter.start() |
| 3978 |
|
| 3979 |
release_leader.set() |
| 3980 |
leader.join(timeout=5) |
| 3981 |
assert not leader.is_alive(), "leader deadlocked after provider raised" |
| 3982 |
waiter.join(timeout=5) |
| 3983 |
assert not waiter.is_alive(), "waiter deadlocked after leader failed" |
| 3984 |
|
| 3985 |
assert len(leader_error) == 1 |
| 3986 |
assert isinstance(leader_error[0], RuntimeError) |
| 3987 |
|
| 3988 |
assert cache.get_token() == "fresh" |
| 3989 |
|
| 3990 |
def test_value_error_from_provider_propagates_cleanly(self) -> None: |
| 3991 |
"""A `ValueError` (e.g. from a provider that parses a JWT) escapes |
| 3992 |
but the cache state is clean — the next call succeeds without hanging.""" |
| 3993 |
|
| 3994 |
class P: |
| 3995 |
calls = 0 |
| 3996 |
|
| 3997 |
def __call__(self, *, force_refresh: bool = False) -> AccessToken: # noqa: ARG002 |
| 3998 |
self.calls += 1 |
| 3999 |
if self.calls == 1: |
| 4000 |
raise ValueError("malformed assertion") |
| 4001 |
return AccessToken("ok", expires_at=None) |
| 4002 |
|
| 4003 |
cache = TokenCache(P()) |
| 4004 |
with pytest.raises(ValueError, match="malformed assertion"): |
| 4005 |
cache.get_token() |
| 4006 |
assert cache.get_token() == "ok" |
| 4007 |
|
| 4008 |
|
| 4009 |
@pytest.mark.usefixtures("clean_env", "no_default_creds_file") |
| 4010 |
class TestCredentialPrecedence: |
| 4011 |
"""Credential precedence per the WIF user guide and the credential- |
| 4012 |
resolution spec: explicit ctor args (step 1) beat env vars (step 2), |
| 4013 |
which beat profile / federation auto-discovery (steps 3-5). |
| 4014 |
|
| 4015 |
A static env credential (step 2) shadows auto-discovery (steps 3-5), |
| 4016 |
silently disabling profile / federation — we warn about that. It does |
| 4017 |
NOT shadow an explicit `credentials=` argument (step 1): an explicit |
| 4018 |
credentials provider wins over env `ANTHROPIC_API_KEY` / |
| 4019 |
`ANTHROPIC_AUTH_TOKEN` outright. |
| 4020 |
|
| 4021 |
Passing an explicit `api_key=` or `auth_token=` *argument* alongside |
| 4022 |
an explicit `credentials=` is a separate shadow case: the static |
| 4023 |
credential wins at the header level and we warn. |
| 4024 |
""" |
| 4025 |
|
| 4026 |
@pytest.fixture(autouse=True) |
| 4027 |
def _reset_shadow_one_shot(self) -> None: |
| 4028 |
from anthropic.lib.credentials import _auth |
| 4029 |
|
| 4030 |
_auth._warn_once_seen.clear() |
| 4031 |
|
| 4032 |
@staticmethod |
| 4033 |
def _walk_sync_auth(client: Anthropic) -> httpx2.Request: |
| 4034 |
request = client._build_request(FinalRequestOptions(method="get", url="/foo")) |
| 4035 |
auth = client.custom_auth |
| 4036 |
flow = auth.sync_auth_flow(request) if auth is not None else None |
| 4037 |
if flow is None: |
| 4038 |
return request |
| 4039 |
modified = next(flow) |
| 4040 |
try: |
| 4041 |
flow.send(httpx2.Response(200)) |
| 4042 |
except StopIteration: |
| 4043 |
pass |
| 4044 |
return modified |
| 4045 |
|
| 4046 |
# -- step 1 beats step 2: explicit credentials= beats env static -------- |
| 4047 |
|
| 4048 |
def test_explicit_credentials_beats_env_api_key( |
| 4049 |
self, clean_env: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 4050 |
) -> None: |
| 4051 |
"""Per spec, explicit `credentials=` is step 1 and beats env |
| 4052 |
`ANTHROPIC_API_KEY` (step 2). The credentials provider wins, env |
| 4053 |
api_key is ignored entirely, no X-Api-Key on the wire, no warning.""" |
| 4054 |
clean_env.setenv("ANTHROPIC_API_KEY", "sk-from-env") |
| 4055 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4056 |
client = Anthropic(credentials=StaticToken("bearer-from-creds")) |
| 4057 |
assert client.api_key is None |
| 4058 |
assert client.auth_token is None |
| 4059 |
assert client.credentials is not None |
| 4060 |
req = self._walk_sync_auth(client) |
| 4061 |
assert req.headers.get("X-Api-Key") is None |
| 4062 |
assert req.headers.get("Authorization") == "Bearer bearer-from-creds" |
| 4063 |
assert not any("takes precedence" in r.message for r in caplog.records) |
| 4064 |
|
| 4065 |
def test_explicit_credentials_beats_env_auth_token( |
| 4066 |
self, clean_env: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 4067 |
) -> None: |
| 4068 |
clean_env.setenv("ANTHROPIC_AUTH_TOKEN", "env-auth-token") |
| 4069 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4070 |
client = Anthropic(credentials=StaticToken("bearer-from-creds")) |
| 4071 |
assert client.auth_token is None |
| 4072 |
assert client.credentials is not None |
| 4073 |
req = self._walk_sync_auth(client) |
| 4074 |
assert req.headers.get("Authorization") == "Bearer bearer-from-creds" |
| 4075 |
assert not any("takes precedence" in r.message for r in caplog.records) |
| 4076 |
|
| 4077 |
def test_explicit_config_beats_env_api_key( |
| 4078 |
self, clean_env: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, tmp_path: pathlib.Path |
| 4079 |
) -> None: |
| 4080 |
"""Explicit `config=` is also step 1 and beats env api_key.""" |
| 4081 |
jwt = tmp_path / "jwt" |
| 4082 |
jwt.write_text("ext-jwt.ext-jwt.ext-jwt") |
| 4083 |
clean_env.setenv("ANTHROPIC_API_KEY", "sk-from-env") |
| 4084 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4085 |
client = Anthropic( |
| 4086 |
config={ |
| 4087 |
"organization_id": "org_x", |
| 4088 |
"authentication": { |
| 4089 |
"type": "oidc_federation", |
| 4090 |
"federation_rule_id": "fdrl_x", |
| 4091 |
"identity_token": {"source": "file", "path": str(jwt)}, |
| 4092 |
}, |
| 4093 |
} |
| 4094 |
) |
| 4095 |
assert client.api_key is None |
| 4096 |
assert isinstance(client.credentials, InMemoryConfig) |
| 4097 |
|
| 4098 |
# -- step 1 ∩ step 1: explicit static arg + explicit credentials= -------- |
| 4099 |
|
| 4100 |
def test_explicit_api_key_shadows_explicit_credentials_with_warning(self, caplog: pytest.LogCaptureFixture) -> None: |
| 4101 |
"""When both explicit `api_key=` AND explicit `credentials=` are |
| 4102 |
passed, the static api_key wins at the header level and credentials |
| 4103 |
is silently disabled. Warn.""" |
| 4104 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4105 |
client = Anthropic(api_key="sk-explicit", credentials=StaticToken("bearer-from-creds")) |
| 4106 |
req = self._walk_sync_auth(client) |
| 4107 |
assert req.headers.get("X-Api-Key") == "sk-explicit" |
| 4108 |
assert req.headers.get("Authorization") is None |
| 4109 |
assert any("`api_key=`" in r.message for r in caplog.records) |
| 4110 |
|
| 4111 |
def test_explicit_auth_token_shadows_explicit_credentials_with_warning( |
| 4112 |
self, caplog: pytest.LogCaptureFixture |
| 4113 |
) -> None: |
| 4114 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4115 |
client = Anthropic(auth_token="static-bearer", credentials=StaticToken("bearer-from-creds")) |
| 4116 |
req = self._walk_sync_auth(client) |
| 4117 |
assert req.headers.get("Authorization") == "Bearer static-bearer" |
| 4118 |
assert req.headers.get("X-Api-Key") is None |
| 4119 |
assert any("`auth_token=`" in r.message for r in caplog.records) |
| 4120 |
|
| 4121 |
def test_async_explicit_api_key_shadows_explicit_credentials(self, caplog: pytest.LogCaptureFixture) -> None: |
| 4122 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4123 |
client = AsyncAnthropic(api_key="sk-explicit", credentials=StaticToken("bearer-from-creds")) |
| 4124 |
assert client.api_key == "sk-explicit" |
| 4125 |
assert client.credentials is not None |
| 4126 |
assert any("`api_key=`" in r.message for r in caplog.records) |
| 4127 |
|
| 4128 |
def test_copy_with_explicit_api_key_shadows_inherited_credentials(self, caplog: pytest.LogCaptureFixture) -> None: |
| 4129 |
"""Reviewer ask: copy() should warn when a new explicit `api_key=` |
| 4130 |
shadows an inherited `credentials=` provider from the parent.""" |
| 4131 |
parent = Anthropic(credentials=StaticToken("bearer-parent")) |
| 4132 |
assert parent.api_key is None |
| 4133 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4134 |
shadowed = parent.copy(api_key="sk-new") |
| 4135 |
assert shadowed.api_key == "sk-new" |
| 4136 |
assert shadowed.credentials is parent.credentials |
| 4137 |
req = self._walk_sync_auth(shadowed) |
| 4138 |
assert req.headers.get("X-Api-Key") == "sk-new" |
| 4139 |
assert req.headers.get("Authorization") is None |
| 4140 |
assert any("`api_key=`" in r.message for r in caplog.records) |
| 4141 |
|
| 4142 |
# -- step 2 shadows steps 3-5: env static shadows auto-discovery --------- |
| 4143 |
|
| 4144 |
def test_env_api_key_shadows_env_federation_trio_with_warning( |
| 4145 |
self, clean_env: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, tmp_path: pathlib.Path |
| 4146 |
) -> None: |
| 4147 |
"""Env `ANTHROPIC_API_KEY` + env federation trio → api_key wins |
| 4148 |
(step 2 beats step 4), warn so the user knows WIF is being shadowed.""" |
| 4149 |
jwt = tmp_path / "jwt" |
| 4150 |
jwt.write_text("ext-jwt.ext-jwt.ext-jwt") |
| 4151 |
clean_env.setenv("ANTHROPIC_API_KEY", "sk-from-env") |
| 4152 |
clean_env.setenv("ANTHROPIC_IDENTITY_TOKEN_FILE", str(jwt)) |
| 4153 |
clean_env.setenv("ANTHROPIC_FEDERATION_RULE_ID", "fdrl_01abc") |
| 4154 |
clean_env.setenv("ANTHROPIC_ORGANIZATION_ID", "00000000-0000-0000-0000-000000000000") |
| 4155 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4156 |
client = Anthropic() |
| 4157 |
assert client.api_key == "sk-from-env" |
| 4158 |
assert client.credentials is None |
| 4159 |
assert any("ANTHROPIC_API_KEY" in r.message and "profile / federation" in r.message for r in caplog.records) |
| 4160 |
|
| 4161 |
def test_env_api_key_shadows_env_profile_with_warning( |
| 4162 |
self, clean_env: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 4163 |
) -> None: |
| 4164 |
clean_env.setenv("ANTHROPIC_API_KEY", "sk-from-env") |
| 4165 |
clean_env.setenv("ANTHROPIC_PROFILE", "dev") |
| 4166 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4167 |
client = Anthropic() |
| 4168 |
assert client.api_key == "sk-from-env" |
| 4169 |
assert client.credentials is None |
| 4170 |
assert any("ANTHROPIC_API_KEY" in r.message and "profile / federation" in r.message for r in caplog.records) |
| 4171 |
|
| 4172 |
def test_env_api_key_alone_does_not_warn( |
| 4173 |
self, clean_env: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 4174 |
) -> None: |
| 4175 |
"""No shadow if there's nothing to shadow — env api_key alone (no |
| 4176 |
auto-discoverable credential signals) is just the normal path.""" |
| 4177 |
clean_env.setenv("ANTHROPIC_API_KEY", "sk-from-env") |
| 4178 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4179 |
client = Anthropic() |
| 4180 |
assert client.api_key == "sk-from-env" |
| 4181 |
assert not any("takes precedence" in r.message for r in caplog.records) |
| 4182 |
|
| 4183 |
# -- step 2: empty env values are unset, not empty credentials ----------- |
| 4184 |
|
| 4185 |
@pytest.mark.parametrize("client_cls", [Anthropic, AsyncAnthropic]) |
| 4186 |
def test_empty_env_auth_token_is_unset( |
| 4187 |
self, clean_env: pytest.MonkeyPatch, client_cls: type[Anthropic] | type[AsyncAnthropic] |
| 4188 |
) -> None: |
| 4189 |
"""`ANTHROPIC_AUTH_TOKEN=` (present but empty) must not produce a |
| 4190 |
malformed `Authorization: Bearer ` header alongside the api key.""" |
| 4191 |
clean_env.setenv("ANTHROPIC_API_KEY", "sk-from-env") |
| 4192 |
clean_env.setenv("ANTHROPIC_AUTH_TOKEN", "") |
| 4193 |
client = client_cls() |
| 4194 |
request = client._build_request(FinalRequestOptions(method="get", url="/foo")) |
| 4195 |
assert request.headers.get("Authorization") is None |
| 4196 |
assert request.headers.get("X-Api-Key") == "sk-from-env" |
| 4197 |
assert client.auth_token is None |
| 4198 |
|
| 4199 |
@pytest.mark.parametrize("client_cls", [Anthropic, AsyncAnthropic]) |
| 4200 |
def test_empty_env_credentials_fall_through_to_no_auth( |
| 4201 |
self, clean_env: pytest.MonkeyPatch, client_cls: type[Anthropic] | type[AsyncAnthropic] |
| 4202 |
) -> None: |
| 4203 |
"""Both env vars empty → same "no auth configured" error as unset, |
| 4204 |
rather than sending empty `X-Api-Key` / `Authorization: Bearer `.""" |
| 4205 |
clean_env.setenv("ANTHROPIC_API_KEY", "") |
| 4206 |
clean_env.setenv("ANTHROPIC_AUTH_TOKEN", "") |
| 4207 |
client = client_cls() |
| 4208 |
with pytest.raises(TypeError, match="Could not resolve authentication method"): |
| 4209 |
client._build_request(FinalRequestOptions(method="get", url="/foo")) |
| 4210 |
assert client.api_key is None |
| 4211 |
assert client.auth_token is None |
| 4212 |
|
| 4213 |
# -- step 1 alone: credentials= works normally -------------------------- |
| 4214 |
|
| 4215 |
def test_credentials_only_still_works(self, caplog: pytest.LogCaptureFixture) -> None: |
| 4216 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4217 |
client = Anthropic(credentials=StaticToken("bearer-from-creds")) |
| 4218 |
req = self._walk_sync_auth(client) |
| 4219 |
assert req.headers.get("X-Api-Key") is None |
| 4220 |
assert req.headers.get("Authorization") == "Bearer bearer-from-creds" |
| 4221 |
assert not any("takes precedence" in r.message for r in caplog.records) |
| 4222 |
|
| 4223 |
# -- one-shot warning --------------------------------------------------- |
| 4224 |
|
| 4225 |
def test_shadow_warning_is_one_shot_per_process( |
| 4226 |
self, clean_env: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 4227 |
) -> None: |
| 4228 |
"""The shadow warning is emitted once per shadow-key per process so |
| 4229 |
repeated client construction doesn't spam logs.""" |
| 4230 |
clean_env.setenv("ANTHROPIC_API_KEY", "sk-from-env") |
| 4231 |
clean_env.setenv("ANTHROPIC_PROFILE", "dev") |
| 4232 |
with caplog.at_level(logging.WARNING, logger="anthropic.lib.credentials._auth"): |
| 4233 |
Anthropic() |
| 4234 |
Anthropic() |
| 4235 |
Anthropic() |
| 4236 |
shadow_records = [r for r in caplog.records if "takes precedence" in r.message] |
| 4237 |
assert len(shadow_records) == 1 |
| 4238 |
|
| 4239 |
|
| 4240 |
@pytest.mark.usefixtures("clean_env", "no_default_creds_file") |
| 4241 |
class TestDanglingActiveConfig: |
| 4242 |
"""`active_config` pointer file naming a profile with no matching |
| 4243 |
`configs/<profile>.json` should surface a clear error rather than |
| 4244 |
silently falling through to "no auth configured". |
| 4245 |
""" |
| 4246 |
|
| 4247 |
def test_pointer_at_missing_profile_raises(self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 4248 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4249 |
(tmp_path / "active_config").write_text("prod") |
| 4250 |
with pytest.raises(AnthropicError, match="prod"): |
| 4251 |
default_credentials() |
| 4252 |
|
| 4253 |
def test_pointer_at_missing_profile_raises_via_client( |
| 4254 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4255 |
) -> None: |
| 4256 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4257 |
(tmp_path / "active_config").write_text("prod") |
| 4258 |
with pytest.raises(AnthropicError, match="prod"): |
| 4259 |
Anthropic() |
| 4260 |
|
| 4261 |
def test_empty_pointer_file_is_silent_fallthrough( |
| 4262 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4263 |
) -> None: |
| 4264 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4265 |
(tmp_path / "active_config").write_text("") |
| 4266 |
assert default_credentials() is None |
| 4267 |
|
| 4268 |
def test_pointer_at_present_profile_loads_normally( |
| 4269 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4270 |
) -> None: |
| 4271 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4272 |
(tmp_path / "active_config").write_text("prod") |
| 4273 |
_write_profile(tmp_path, "prod", {"type": "external"}, {"access_token": "from-prod"}) |
| 4274 |
result = default_credentials() |
| 4275 |
assert result is not None |
| 4276 |
assert isinstance(result.provider, CredentialsFile) |
| 4277 |
assert result.provider().token == "from-prod" |
| 4278 |
|
| 4279 |
|
| 4280 |
# --------------------------------------------------------------------------- # |
| 4281 |
# Secret hygiene: masked reprs and traceback frame locals |
| 4282 |
# --------------------------------------------------------------------------- # |
| 4283 |
|
| 4284 |
_SECRET_ASSERTION = "eyJ-SECRET-ASSERTION-MATERIAL-eyJ" |
| 4285 |
_SECRET_MINTED = "sk-ant-oat01-MINTED-SECRET" |
| 4286 |
|
| 4287 |
|
| 4288 |
class TestAccessTokenReprMasking: |
| 4289 |
def test_long_token_masked_to_last_four(self) -> None: |
| 4290 |
tok = AccessToken(token="sk-ant-oat01-SECRETMATERIAL", expires_at=123) |
| 4291 |
assert repr(tok) == "AccessToken(token='...RIAL', expires_at=123)" |
| 4292 |
assert str(tok) == repr(tok) |
| 4293 |
|
| 4294 |
def test_short_token_fully_masked(self) -> None: |
| 4295 |
assert repr(AccessToken(token="hunter2")) == "AccessToken(token='**********', expires_at=None)" |
| 4296 |
|
| 4297 |
def test_non_str_token_does_not_crash_repr(self) -> None: |
| 4298 |
# A malformed token endpoint can produce a non-str token; repr must |
| 4299 |
# not raise (crash reporters call it blindly). |
| 4300 |
assert repr(AccessToken(token=cast(Any, 12345))) == "AccessToken(token='**********', expires_at=None)" |
| 4301 |
|
| 4302 |
|
| 4303 |
class TestEmptySecretFieldFalsiness: |
| 4304 |
"""The missing-token guards test truthiness of SecretStr-wrapped values, |
| 4305 |
which rides on `SecretStr.__len__` (present across the supported |
| 4306 |
pydantic range) — pin empty-string behavior through the public path so a |
| 4307 |
pydantic regression can't silently turn the guards into passes.""" |
| 4308 |
|
| 4309 |
def test_empty_access_token_treated_as_missing(self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 4310 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4311 |
_write_profile( |
| 4312 |
tmp_path, |
| 4313 |
"default", |
| 4314 |
config={"type": "authorized_user", "client_id": "cid"}, |
| 4315 |
credentials={"access_token": "", "refresh_token": "rt"}, |
| 4316 |
) |
| 4317 |
with pytest.raises(AnthropicError, match="missing 'access_token'"): |
| 4318 |
CredentialsFile()() |
| 4319 |
|
| 4320 |
def test_empty_refresh_token_treated_as_missing( |
| 4321 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4322 |
) -> None: |
| 4323 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4324 |
_write_profile( |
| 4325 |
tmp_path, |
| 4326 |
"default", |
| 4327 |
config={"type": "authorized_user", "client_id": "cid"}, |
| 4328 |
credentials={"access_token": "at", "refresh_token": ""}, |
| 4329 |
) |
| 4330 |
with pytest.raises(WorkloadIdentityError, match="must include 'refresh_token'"): |
| 4331 |
CredentialsFile()() |
| 4332 |
|
| 4333 |
|
| 4334 |
def _sdk_frame_locals(exc: BaseException) -> List["tuple[str, Dict[str, Any]]"]: |
| 4335 |
"""(code name, locals) for every traceback frame owned by the anthropic |
| 4336 |
package, across the full `__context__` / `__cause__` chain.""" |
| 4337 |
pkg_root = str(pathlib.Path(anthropic.__file__).parent) |
| 4338 |
out: List["tuple[str, Dict[str, Any]]"] = [] |
| 4339 |
seen: "set[int]" = set() |
| 4340 |
|
| 4341 |
def walk(e: Optional[BaseException]) -> None: |
| 4342 |
if e is None or id(e) in seen: |
| 4343 |
return |
| 4344 |
seen.add(id(e)) |
| 4345 |
tb = e.__traceback__ |
| 4346 |
while tb is not None: |
| 4347 |
code = tb.tb_frame.f_code |
| 4348 |
if code.co_filename.startswith(pkg_root): |
| 4349 |
out.append((code.co_name, dict(tb.tb_frame.f_locals))) |
| 4350 |
tb = tb.tb_next |
| 4351 |
walk(e.__context__) |
| 4352 |
walk(e.__cause__) |
| 4353 |
|
| 4354 |
walk(exc) |
| 4355 |
return out |
| 4356 |
|
| 4357 |
|
| 4358 |
def _assert_not_in_sdk_frame_locals(exc: BaseException, *secrets: str) -> None: |
| 4359 |
frames = _sdk_frame_locals(exc) |
| 4360 |
assert frames, "expected at least one SDK-owned frame in the traceback" |
| 4361 |
for name, frame_locals in frames: |
| 4362 |
for var, value in frame_locals.items(): |
| 4363 |
for secret in secrets: |
| 4364 |
assert secret not in repr(value), f"secret retained in frame {name!r} local {var!r}" |
| 4365 |
|
| 4366 |
|
| 4367 |
class TestNoSecretsInTracebackFrameLocals: |
| 4368 |
"""Exceptions from the token-exchange paths must not retain credential |
| 4369 |
material in traceback frame locals (across the `__traceback__` / |
| 4370 |
`__context__` / `__cause__` chain). Plain `logging.exception` never |
| 4371 |
prints locals, but crash reporters that capture them — stdlib |
| 4372 |
`TracebackException(..., capture_locals=True)`, rich tracebacks, |
| 4373 |
Sentry's default local-variable capture — render each local's `repr`, |
| 4374 |
which is why SecretStr-wrapped locals are safe to retain.""" |
| 4375 |
|
| 4376 |
def _workload_provider(self, handler: Callable[[httpx2.Request], httpx2.Response]) -> WorkloadIdentityCredentials: |
| 4377 |
creds = WorkloadIdentityCredentials( |
| 4378 |
identity_token_provider=lambda: _SECRET_ASSERTION, |
| 4379 |
federation_rule_id="fdrl_01abc", |
| 4380 |
organization_id="org-uuid", |
| 4381 |
http_client=httpx2.Client(transport=httpx2.MockTransport(handler)), |
| 4382 |
) |
| 4383 |
creds.bind_base_url(BASE_URL) |
| 4384 |
return creds |
| 4385 |
|
| 4386 |
def test_http_4xx_does_not_retain_assertion(self) -> None: |
| 4387 |
provider = self._workload_provider(lambda _: httpx2.Response(401, json={"error": "invalid_grant"})) |
| 4388 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 4389 |
provider() |
| 4390 |
_assert_not_in_sdk_frame_locals(exc_info.value, _SECRET_ASSERTION) |
| 4391 |
|
| 4392 |
@pytest.mark.parametrize("expires_in", ['"NaN"', "1e400"], ids=["nan-string", "float-overflow"]) |
| 4393 |
def test_invalid_expires_in_does_not_retain_minted_token(self, expires_in: str) -> None: |
| 4394 |
provider = self._workload_provider( |
| 4395 |
lambda _: httpx2.Response( |
| 4396 |
200, content=f'{{"access_token": "{_SECRET_MINTED}", "expires_in": {expires_in}}}' |
| 4397 |
) |
| 4398 |
) |
| 4399 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 4400 |
provider() |
| 4401 |
_assert_not_in_sdk_frame_locals(exc_info.value, _SECRET_ASSERTION, _SECRET_MINTED) |
| 4402 |
|
| 4403 |
def test_token_type_mismatch_does_not_retain_minted_token(self) -> None: |
| 4404 |
provider = self._workload_provider( |
| 4405 |
lambda _: httpx2.Response( |
| 4406 |
200, json={"access_token": _SECRET_MINTED, "expires_in": 600, "token_type": "MAC"} |
| 4407 |
) |
| 4408 |
) |
| 4409 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 4410 |
provider() |
| 4411 |
_assert_not_in_sdk_frame_locals(exc_info.value, _SECRET_ASSERTION, _SECRET_MINTED) |
| 4412 |
|
| 4413 |
def test_non_json_response_does_not_retain_assertion(self) -> None: |
| 4414 |
provider = self._workload_provider(lambda _: httpx2.Response(200, text="<html>gateway error</html>")) |
| 4415 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 4416 |
provider() |
| 4417 |
_assert_not_in_sdk_frame_locals(exc_info.value, _SECRET_ASSERTION) |
| 4418 |
# The json decoder frames hold the raw response text (which token |
| 4419 |
# endpoints can echo the assertion into); the raise site must have |
| 4420 |
# dropped the chained cause's traceback entirely. |
| 4421 |
cause = exc_info.value.__cause__ |
| 4422 |
assert cause is not None and cause.__traceback__ is None |
| 4423 |
|
| 4424 |
def test_json_string_echo_response_does_not_retain_assertion(self) -> None: |
| 4425 |
"""A 200 whose body is a JSON *string* echoing the assertion must be |
| 4426 |
rejected at the wrap boundary — never bound to a frame local on its |
| 4427 |
way to the type error.""" |
| 4428 |
provider = self._workload_provider(lambda _: httpx2.Response(200, json=_SECRET_ASSERTION)) |
| 4429 |
with pytest.raises(WorkloadIdentityError, match="expected an object") as exc_info: |
| 4430 |
provider() |
| 4431 |
_assert_not_in_sdk_frame_locals(exc_info.value, _SECRET_ASSERTION) |
| 4432 |
|
| 4433 |
def test_transport_error_does_not_retain_assertion(self) -> None: |
| 4434 |
def raise_connect_error(req: httpx2.Request) -> httpx2.Response: |
| 4435 |
raise httpx2.ConnectError("connection refused", request=req) |
| 4436 |
|
| 4437 |
provider = self._workload_provider(raise_connect_error) |
| 4438 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 4439 |
provider() |
| 4440 |
_assert_not_in_sdk_frame_locals(exc_info.value, _SECRET_ASSERTION) |
| 4441 |
# The chained httpx error's frames hold the serialized request body; |
| 4442 |
# the raise site must have dropped its traceback entirely. |
| 4443 |
cause = exc_info.value.__cause__ |
| 4444 |
assert cause is not None and cause.__traceback__ is None |
| 4445 |
|
| 4446 |
def test_oversized_assertion_not_retained(self) -> None: |
| 4447 |
big = "A" * (17 * 1024) |
| 4448 |
provider = WorkloadIdentityCredentials( |
| 4449 |
identity_token_provider=lambda: big, |
| 4450 |
federation_rule_id="fdrl_01abc", |
| 4451 |
organization_id="org-uuid", |
| 4452 |
http_client=httpx2.Client(), |
| 4453 |
) |
| 4454 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 4455 |
provider() |
| 4456 |
_assert_not_in_sdk_frame_locals(exc_info.value, big) |
| 4457 |
|
| 4458 |
def _write_refresh_profile(self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> None: |
| 4459 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4460 |
_write_profile( |
| 4461 |
tmp_path, |
| 4462 |
"default", |
| 4463 |
config={"type": "authorized_user", "client_id": "cid"}, |
| 4464 |
credentials={ |
| 4465 |
"access_token": "old-access-SECRET", |
| 4466 |
"expires_at": int(time.time()) - 1, |
| 4467 |
"refresh_token": "rt-SECRET", |
| 4468 |
}, |
| 4469 |
) |
| 4470 |
|
| 4471 |
@pytest.mark.respx(base_url=BASE_URL) |
| 4472 |
def test_refresh_failure_does_not_retain_refresh_token( |
| 4473 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4474 |
) -> None: |
| 4475 |
self._write_refresh_profile(clean_env, tmp_path) |
| 4476 |
respx_mock.post(TOKEN_ENDPOINT).mock(return_value=httpx2.Response(400, json={"error": "invalid_grant"})) |
| 4477 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 4478 |
CredentialsFile()() |
| 4479 |
_assert_not_in_sdk_frame_locals(exc_info.value, "rt-SECRET", "old-access-SECRET") |
| 4480 |
|
| 4481 |
@pytest.mark.respx(base_url=BASE_URL) |
| 4482 |
@pytest.mark.parametrize("expires_in", ['"NaN"', "1e400"], ids=["nan-string", "float-overflow"]) |
| 4483 |
def test_refresh_invalid_expires_does_not_retain_new_token( |
| 4484 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path, expires_in: str |
| 4485 |
) -> None: |
| 4486 |
self._write_refresh_profile(clean_env, tmp_path) |
| 4487 |
respx_mock.post(TOKEN_ENDPOINT).mock( |
| 4488 |
return_value=httpx2.Response( |
| 4489 |
200, content=f'{{"access_token": "{_SECRET_MINTED}", "expires_in": {expires_in}}}' |
| 4490 |
) |
| 4491 |
) |
| 4492 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 4493 |
CredentialsFile()() |
| 4494 |
_assert_not_in_sdk_frame_locals(exc_info.value, "rt-SECRET", "old-access-SECRET", _SECRET_MINTED) |
| 4495 |
|
| 4496 |
@pytest.mark.respx(base_url=BASE_URL) |
| 4497 |
def test_refresh_non_json_response_raises_redacted_error( |
| 4498 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4499 |
) -> None: |
| 4500 |
"""A non-JSON refresh response raises WorkloadIdentityError (it |
| 4501 |
previously escaped as a raw json ValueError whose `.doc` carries the |
| 4502 |
full response body) and retains no secrets.""" |
| 4503 |
self._write_refresh_profile(clean_env, tmp_path) |
| 4504 |
respx_mock.post(TOKEN_ENDPOINT).mock(return_value=httpx2.Response(200, text="<html>gateway error</html>")) |
| 4505 |
with pytest.raises(WorkloadIdentityError, match="non-JSON") as exc_info: |
| 4506 |
CredentialsFile()() |
| 4507 |
_assert_not_in_sdk_frame_locals(exc_info.value, "rt-SECRET", "old-access-SECRET") |
| 4508 |
# As on the jwt-bearer path: the decoder frames hold the raw body. |
| 4509 |
cause = exc_info.value.__cause__ |
| 4510 |
assert cause is not None and cause.__traceback__ is None |
| 4511 |
|
| 4512 |
@pytest.mark.respx(base_url=BASE_URL) |
| 4513 |
def test_refresh_json_array_response_raises_redacted_error( |
| 4514 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4515 |
) -> None: |
| 4516 |
"""A JSON-but-non-object refresh body (which can echo the request's |
| 4517 |
refresh token) is rejected at the wrap boundary and never bound to a |
| 4518 |
frame local.""" |
| 4519 |
self._write_refresh_profile(clean_env, tmp_path) |
| 4520 |
respx_mock.post(TOKEN_ENDPOINT).mock(return_value=httpx2.Response(200, json=["rt-SECRET"])) |
| 4521 |
with pytest.raises(WorkloadIdentityError, match="expected an object") as exc_info: |
| 4522 |
CredentialsFile()() |
| 4523 |
_assert_not_in_sdk_frame_locals(exc_info.value, "rt-SECRET", "old-access-SECRET") |
| 4524 |
|
| 4525 |
def test_scalar_credentials_file_does_not_retain_token( |
| 4526 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4527 |
) -> None: |
| 4528 |
"""A credentials file whose top level is a JSON string (e.g. a bare |
| 4529 |
token pasted into the file) must raise a clean error without the |
| 4530 |
value surviving in frame locals.""" |
| 4531 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4532 |
_write_profile(tmp_path, "default", config={"type": "authorized_user", "client_id": "cid"}) |
| 4533 |
creds_path = tmp_path / "credentials" / "default.json" |
| 4534 |
creds_path.parent.mkdir(parents=True, exist_ok=True) |
| 4535 |
creds_path.write_text('"rt-SECRET"') # JSON scalar, not an object |
| 4536 |
creds_path.chmod(0o600) |
| 4537 |
with pytest.raises(AnthropicError, match="must contain a JSON object, not str") as exc_info: |
| 4538 |
CredentialsFile()() |
| 4539 |
_assert_not_in_sdk_frame_locals(exc_info.value, "rt-SECRET") |
| 4540 |
|
| 4541 |
@pytest.mark.respx(base_url=BASE_URL) |
| 4542 |
def test_refresh_success_writes_raw_tokens_to_disk_and_wire( |
| 4543 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4544 |
) -> None: |
| 4545 |
"""SecretStr wrapping is an in-memory concern only: the refresh POST |
| 4546 |
body and the persisted credentials file must carry the raw values — |
| 4547 |
including unknown string fields, which are wrapped by default and must |
| 4548 |
round-trip unchanged.""" |
| 4549 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4550 |
_write_profile( |
| 4551 |
tmp_path, |
| 4552 |
"default", |
| 4553 |
config={"type": "authorized_user", "client_id": "cid"}, |
| 4554 |
credentials={ |
| 4555 |
"access_token": "old-access-SECRET", |
| 4556 |
"expires_at": int(time.time()) - 1, |
| 4557 |
"refresh_token": "rt-SECRET", |
| 4558 |
"id_token": "idt-SECRET", |
| 4559 |
}, |
| 4560 |
) |
| 4561 |
respx_mock.post(TOKEN_ENDPOINT).mock( |
| 4562 |
return_value=httpx2.Response( |
| 4563 |
200, json={"access_token": "new-access", "expires_in": 3600, "refresh_token": "rt-NEW"} |
| 4564 |
) |
| 4565 |
) |
| 4566 |
tok = CredentialsFile()() |
| 4567 |
assert tok.token == "new-access" |
| 4568 |
|
| 4569 |
sent = json.loads(cast("List[MockRequestCall]", respx_mock.calls)[-1].request.content) |
| 4570 |
assert sent == {"grant_type": "refresh_token", "refresh_token": "rt-SECRET", "client_id": "cid"} |
| 4571 |
|
| 4572 |
on_disk = json.loads((tmp_path / "credentials" / "default.json").read_text()) |
| 4573 |
assert on_disk["access_token"] == "new-access" |
| 4574 |
assert on_disk["refresh_token"] == "rt-NEW" |
| 4575 |
assert on_disk["id_token"] == "idt-SECRET" |
| 4576 |
|
| 4577 |
def test_missing_access_token_does_not_retain_refresh_token( |
| 4578 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4579 |
) -> None: |
| 4580 |
"""A credentials file that has a refresh_token but no access_token |
| 4581 |
raises before any exchange; the on-disk dict must not survive raw in |
| 4582 |
frame locals.""" |
| 4583 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4584 |
_write_profile( |
| 4585 |
tmp_path, |
| 4586 |
"default", |
| 4587 |
config={"type": "authorized_user", "client_id": "cid"}, |
| 4588 |
credentials={"refresh_token": "rt-SECRET"}, |
| 4589 |
) |
| 4590 |
with pytest.raises(AnthropicError, match="missing 'access_token'") as exc_info: |
| 4591 |
CredentialsFile()() |
| 4592 |
_assert_not_in_sdk_frame_locals(exc_info.value, "rt-SECRET") |
| 4593 |
|
| 4594 |
def test_invalid_json_credentials_does_not_retain_raw_text( |
| 4595 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4596 |
) -> None: |
| 4597 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4598 |
_write_profile(tmp_path, "default", config={"type": "authorized_user", "client_id": "cid"}) |
| 4599 |
creds_path = tmp_path / "credentials" / "default.json" |
| 4600 |
creds_path.parent.mkdir(parents=True, exist_ok=True) |
| 4601 |
creds_path.write_text('{"refresh_token": "rt-SECRET", ') # truncated JSON |
| 4602 |
creds_path.chmod(0o600) |
| 4603 |
with pytest.raises(AnthropicError, match="not valid JSON") as exc_info: |
| 4604 |
CredentialsFile()() |
| 4605 |
_assert_not_in_sdk_frame_locals(exc_info.value, "rt-SECRET") |
| 4606 |
# The json decoder frames hold the raw file text; the raise site must |
| 4607 |
# have dropped the chained cause's traceback entirely. |
| 4608 |
cause = exc_info.value.__cause__ |
| 4609 |
assert cause is not None and cause.__traceback__ is None |
| 4610 |
|
| 4611 |
def test_credentials_type_mismatch_does_not_retain_tokens( |
| 4612 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4613 |
) -> None: |
| 4614 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4615 |
_write_profile( |
| 4616 |
tmp_path, |
| 4617 |
"default", |
| 4618 |
config={"type": "authorized_user", "client_id": "cid"}, |
| 4619 |
credentials={ |
| 4620 |
"type": "wrong_type", |
| 4621 |
"access_token": "at-SECRET", |
| 4622 |
"refresh_token": "rt-SECRET", |
| 4623 |
}, |
| 4624 |
) |
| 4625 |
with pytest.raises(AnthropicError, match="has type") as exc_info: |
| 4626 |
CredentialsFile()() |
| 4627 |
_assert_not_in_sdk_frame_locals(exc_info.value, "at-SECRET", "rt-SECRET") |
| 4628 |
|
| 4629 |
def test_corrupt_expires_at_does_not_retain_tokens( |
| 4630 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4631 |
) -> None: |
| 4632 |
"""`_coerce_expires_at` raises in a secret-free frame, but the error |
| 4633 |
propagates through `_call_user_oauth` whose locals hold the creds |
| 4634 |
dict — those locals must render redacted. The `id_token` field pins |
| 4635 |
the secret-by-default rule: string fields the SDK doesn't know about |
| 4636 |
are wrapped too.""" |
| 4637 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4638 |
_write_profile( |
| 4639 |
tmp_path, |
| 4640 |
"default", |
| 4641 |
config={"type": "authorized_user", "client_id": "cid"}, |
| 4642 |
credentials={ |
| 4643 |
"access_token": "at-SECRET", |
| 4644 |
"expires_at": "tomorrow", |
| 4645 |
"refresh_token": "rt-SECRET", |
| 4646 |
"id_token": "idt-SECRET", |
| 4647 |
}, |
| 4648 |
) |
| 4649 |
with pytest.raises(AnthropicError, match="invalid 'expires_at'") as exc_info: |
| 4650 |
CredentialsFile()() |
| 4651 |
_assert_not_in_sdk_frame_locals(exc_info.value, "at-SECRET", "rt-SECRET", "idt-SECRET") |
| 4652 |
|
| 4653 |
def test_corrupt_expires_at_external_profile_does_not_retain_token( |
| 4654 |
self, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4655 |
) -> None: |
| 4656 |
"""Same as above via the no-client_id (externally rotated) path.""" |
| 4657 |
clean_env.setattr("anthropic.lib.credentials._constants._config_dir", lambda: tmp_path) |
| 4658 |
_write_profile( |
| 4659 |
tmp_path, |
| 4660 |
"default", |
| 4661 |
config={"type": "external"}, |
| 4662 |
credentials={"access_token": "at-SECRET", "expires_at": "tomorrow"}, |
| 4663 |
) |
| 4664 |
with pytest.raises(AnthropicError, match="invalid 'expires_at'") as exc_info: |
| 4665 |
CredentialsFile()() |
| 4666 |
_assert_not_in_sdk_frame_locals(exc_info.value, "at-SECRET") |
| 4667 |
|
| 4668 |
@pytest.mark.respx(base_url=BASE_URL) |
| 4669 |
def test_failed_writeback_after_refresh_does_not_retain_tokens( |
| 4670 |
self, respx_mock: MockRouter, clean_env: pytest.MonkeyPatch, tmp_path: pathlib.Path |
| 4671 |
) -> None: |
| 4672 |
"""A refresh that succeeds but fails to persist raises the write error |
| 4673 |
(the refresh token may have rotated server-side) — but the propagating |
| 4674 |
traceback's frames must not retain the new access token, the new or |
| 4675 |
old refresh token, or the creds dict.""" |
| 4676 |
self._write_refresh_profile(clean_env, tmp_path) |
| 4677 |
respx_mock.post(TOKEN_ENDPOINT).mock( |
| 4678 |
return_value=httpx2.Response( |
| 4679 |
200, json={"access_token": _SECRET_MINTED, "expires_in": 3600, "refresh_token": "rt-NEW-SECRET"} |
| 4680 |
) |
| 4681 |
) |
| 4682 |
|
| 4683 |
# Make persistence fail the way a full disk would: mkstemp raises. |
| 4684 |
def _mkstemp_enospc(*_args: Any, **_kwargs: Any) -> "tuple[int, str]": |
| 4685 |
raise OSError(28, "No space left on device") |
| 4686 |
|
| 4687 |
clean_env.setattr("anthropic.lib.credentials._providers.tempfile.mkstemp", _mkstemp_enospc) |
| 4688 |
with pytest.raises(OSError, match="No space left") as exc_info: |
| 4689 |
CredentialsFile()() |
| 4690 |
_assert_not_in_sdk_frame_locals( |
| 4691 |
exc_info.value, "rt-SECRET", "old-access-SECRET", _SECRET_MINTED, "rt-NEW-SECRET" |
| 4692 |
) |
| 4693 |
|
| 4694 |
def test_oneshot_exchange_failure_does_not_retain_assertion(self) -> None: |
| 4695 |
"""`exchange_federation_assertion` holds the caller's assertion as a |
| 4696 |
parameter in its own (SDK-owned) frame; it is rebound to SecretStr on |
| 4697 |
entry so a failed exchange renders it redacted. The caller's own frame |
| 4698 |
is beyond the SDK's reach.""" |
| 4699 |
with pytest.raises(WorkloadIdentityError) as exc_info: |
| 4700 |
exchange_federation_assertion( |
| 4701 |
assertion=_SECRET_ASSERTION, |
| 4702 |
federation_rule_id="fdrl_01abc", |
| 4703 |
organization_id="org-uuid", |
| 4704 |
base_url=BASE_URL, |
| 4705 |
http_client=httpx2.Client( |
| 4706 |
transport=httpx2.MockTransport(lambda _: httpx2.Response(401, json={"error": "invalid_grant"})) |
| 4707 |
), |
| 4708 |
) |
| 4709 |
_assert_not_in_sdk_frame_locals(exc_info.value, _SECRET_ASSERTION) |