| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import re |
| 4 |
import sys |
| 5 |
import json |
| 6 |
import time |
| 7 |
import logging |
| 8 |
import pathlib |
| 9 |
import threading |
| 10 |
from typing import Any, cast |
| 11 |
|
| 12 |
import httpx2 |
| 13 |
import pytest |
| 14 |
from respx import MockRouter |
| 15 |
|
| 16 |
from anthropic._exceptions import AnthropicError |
| 17 |
from anthropic.lib.google_cloud import AnthropicGoogleCloud, AsyncAnthropicGoogleCloud, _client as google_cloud_module |
| 18 |
from anthropic.lib._extras._common import MissingDependencyError |
| 19 |
|
| 20 |
# httpx normalizes the client base URL with a trailing slash. |
| 21 |
DERIVED_BASE_URL = ( |
| 22 |
"https://claude.googleapis.com/v1alpha/projects/my-project/locations/us-central1/workspaces/wrkspc_x/invoke/" |
| 23 |
) |
| 24 |
GLOBAL_DERIVED_BASE_URL = ( |
| 25 |
"https://claude.googleapis.com/v1alpha/projects/my-project/locations/global/workspaces/wrkspc_x/invoke/" |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
@pytest.fixture(autouse=True) |
| 30 |
def _isolate_environment(monkeypatch: pytest.MonkeyPatch) -> None: # pyright: ignore[reportUnusedFunction] |
| 31 |
"""Ambient first-party / google-cloud env vars must not leak into these tests.""" |
| 32 |
for name in ( |
| 33 |
"ANTHROPIC_GOOGLE_CLOUD_PROJECT", |
| 34 |
"ANTHROPIC_GOOGLE_CLOUD_LOCATION", |
| 35 |
"ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID", |
| 36 |
"ANTHROPIC_GOOGLE_CLOUD_BASE_URL", |
| 37 |
"GOOGLE_CLOUD_PROJECT", |
| 38 |
"ANTHROPIC_API_KEY", |
| 39 |
"ANTHROPIC_AUTH_TOKEN", |
| 40 |
"ANTHROPIC_BASE_URL", |
| 41 |
"ANTHROPIC_CUSTOM_HEADERS", |
| 42 |
"ANTHROPIC_WEBHOOK_SIGNING_KEY", |
| 43 |
"ANTHROPIC_CONFIG_DIR", |
| 44 |
"ANTHROPIC_PROFILE", |
| 45 |
): |
| 46 |
monkeypatch.delenv(name, raising=False) |
| 47 |
|
| 48 |
|
| 49 |
class _FakeCredentials: |
| 50 |
"""Duck-typed stand-in for a `google.auth` Credentials object.""" |
| 51 |
|
| 52 |
def __init__(self, token: str | None, *, expired: bool = False, project_id: str | None = None) -> None: |
| 53 |
self.token = token |
| 54 |
self.expired = expired |
| 55 |
self.project_id = project_id |
| 56 |
self.refresh_calls = 0 |
| 57 |
|
| 58 |
def refresh(self, _request: object) -> None: |
| 59 |
self.refresh_calls += 1 |
| 60 |
self.token = "refreshed-token" |
| 61 |
self.expired = False |
| 62 |
|
| 63 |
|
| 64 |
# --------------------------------------------------------------------------- |
| 65 |
# Initialization / base URL / workspace |
| 66 |
# --------------------------------------------------------------------------- |
| 67 |
|
| 68 |
|
| 69 |
class TestAnthropicGoogleCloud: |
| 70 |
def test_init_with_token_provider_and_base_url(self) -> None: |
| 71 |
client = AnthropicGoogleCloud( |
| 72 |
base_url="https://example.test/", |
| 73 |
workspace_id="wrkspc_x", |
| 74 |
token_provider=lambda: "tok", |
| 75 |
) |
| 76 |
assert str(client.base_url) == "https://example.test/" |
| 77 |
assert client.workspace_id == "wrkspc_x" |
| 78 |
|
| 79 |
def test_explicit_base_url_needs_no_location(self) -> None: |
| 80 |
# No project / location required when base_url is explicit. |
| 81 |
client = AnthropicGoogleCloud(base_url="https://example.test/", workspace_id="wrkspc_x") |
| 82 |
assert str(client.base_url) == "https://example.test/" |
| 83 |
|
| 84 |
def test_base_url_derived_from_project_and_location(self) -> None: |
| 85 |
client = AnthropicGoogleCloud( |
| 86 |
project="my-project", |
| 87 |
location="us-central1", |
| 88 |
workspace_id="wrkspc_x", |
| 89 |
token_provider=lambda: "tok", |
| 90 |
) |
| 91 |
assert str(client.base_url) == DERIVED_BASE_URL |
| 92 |
|
| 93 |
def test_location_defaults_to_global(self) -> None: |
| 94 |
client = AnthropicGoogleCloud(project="my-project", workspace_id="wrkspc_x", token_provider=lambda: "tok") |
| 95 |
assert str(client.base_url) == GLOBAL_DERIVED_BASE_URL |
| 96 |
|
| 97 |
def test_missing_project_defers_without_construct_error(self) -> None: |
| 98 |
# The project is back-filled from Google credentials on the first request. |
| 99 |
AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x") |
| 100 |
|
| 101 |
def test_skip_auth_deriving_base_url_requires_project(self) -> None: |
| 102 |
# With skip_auth there are no Google credentials to back-fill the project from. |
| 103 |
with pytest.raises(ValueError, match="project"): |
| 104 |
AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x", skip_auth=True) |
| 105 |
|
| 106 |
def test_skip_auth_deriving_base_url_requires_workspace(self) -> None: |
| 107 |
# The workspace ID is part of the derived URL, so skip_auth alone no longer |
| 108 |
# waives it — only an explicit base_url does. |
| 109 |
with pytest.raises(ValueError, match=r"(?s)workspace_id.*ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID"): |
| 110 |
AnthropicGoogleCloud(project="my-project", skip_auth=True) |
| 111 |
|
| 112 |
def test_skip_auth_derives_url_with_workspace(self) -> None: |
| 113 |
client = AnthropicGoogleCloud(project="my-project", workspace_id="wrkspc_x", skip_auth=True) |
| 114 |
assert str(client.base_url) == GLOBAL_DERIVED_BASE_URL |
| 115 |
|
| 116 |
def test_env_resolution(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 117 |
monkeypatch.setenv("ANTHROPIC_GOOGLE_CLOUD_BASE_URL", "https://env.test/") |
| 118 |
monkeypatch.setenv("ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID", "wrkspc_env") |
| 119 |
client = AnthropicGoogleCloud(token_provider=lambda: "tok") |
| 120 |
assert str(client.base_url) == "https://env.test/" |
| 121 |
assert client.workspace_id == "wrkspc_env" |
| 122 |
|
| 123 |
def test_explicit_project_arg_beats_env(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 124 |
monkeypatch.setenv("ANTHROPIC_GOOGLE_CLOUD_PROJECT", "env-project") |
| 125 |
client = AnthropicGoogleCloud( |
| 126 |
project="arg-project", location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 127 |
) |
| 128 |
assert "/projects/arg-project/" in str(client.base_url) |
| 129 |
assert "env-project" not in str(client.base_url) |
| 130 |
|
| 131 |
def test_location_from_env(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 132 |
monkeypatch.setenv("ANTHROPIC_GOOGLE_CLOUD_LOCATION", "europe-west4") |
| 133 |
client = AnthropicGoogleCloud(project="my-project", workspace_id="wrkspc_x", token_provider=lambda: "tok") |
| 134 |
assert str(client.base_url).startswith("https://claude.googleapis.com/") |
| 135 |
assert "/locations/europe-west4/" in str(client.base_url) |
| 136 |
|
| 137 |
def test_explicit_location_arg_beats_env(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 138 |
monkeypatch.setenv("ANTHROPIC_GOOGLE_CLOUD_LOCATION", "env-location") |
| 139 |
client = AnthropicGoogleCloud( |
| 140 |
project="my-project", location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 141 |
) |
| 142 |
assert str(client.base_url) == DERIVED_BASE_URL |
| 143 |
|
| 144 |
def test_project_falls_back_to_google_cloud_project_env(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 145 |
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "gcp-env-project") |
| 146 |
client = AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok") |
| 147 |
assert "/projects/gcp-env-project/" in str(client.base_url) |
| 148 |
|
| 149 |
def test_anthropic_project_env_beats_google_cloud_project(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 150 |
monkeypatch.setenv("ANTHROPIC_GOOGLE_CLOUD_PROJECT", "anthropic-env-project") |
| 151 |
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "gcp-env-project") |
| 152 |
client = AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok") |
| 153 |
assert "/projects/anthropic-env-project/" in str(client.base_url) |
| 154 |
assert "gcp-env-project" not in str(client.base_url) |
| 155 |
|
| 156 |
def test_workspace_required(self) -> None: |
| 157 |
with pytest.raises(ValueError, match="workspace ID"): |
| 158 |
AnthropicGoogleCloud(base_url="https://example.test/", token_provider=lambda: "tok") |
| 159 |
|
| 160 |
def test_api_key_and_auth_token_rejected(self) -> None: |
| 161 |
with pytest.raises(TypeError): |
| 162 |
AnthropicGoogleCloud(base_url="https://example.test/", workspace_id="wrkspc_x", api_key="sk-ant-x") # type: ignore[call-arg] |
| 163 |
with pytest.raises(TypeError): |
| 164 |
AnthropicGoogleCloud(base_url="https://example.test/", workspace_id="wrkspc_x", auth_token="tok") # type: ignore[call-arg] |
| 165 |
|
| 166 |
def test_skip_auth_mutually_exclusive_with_credentials(self) -> None: |
| 167 |
with pytest.raises(ValueError, match="mutually exclusive"): |
| 168 |
AnthropicGoogleCloud(base_url="https://example.test/", skip_auth=True, token_provider=lambda: "tok") |
| 169 |
with pytest.raises(ValueError, match="mutually exclusive"): |
| 170 |
AnthropicGoogleCloud( |
| 171 |
base_url="https://example.test/", |
| 172 |
skip_auth=True, |
| 173 |
credentials=cast(Any, _FakeCredentials(token="tok")), |
| 174 |
) |
| 175 |
|
| 176 |
def test_project_backfilled_from_explicit_credentials(self) -> None: |
| 177 |
# Service-account-style credentials expose their project; the base URL can |
| 178 |
# then be derived at construction without an explicit `project`. |
| 179 |
creds = _FakeCredentials(token="tok", project_id="creds-project") |
| 180 |
client = AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x", credentials=cast(Any, creds)) |
| 181 |
assert "/projects/creds-project/" in str(client.base_url) |
| 182 |
|
| 183 |
def test_google_credentials_exposed_without_shadowing_base_attribute(self) -> None: |
| 184 |
creds = _FakeCredentials(token="tok") |
| 185 |
client = AnthropicGoogleCloud( |
| 186 |
base_url="https://example.test/", workspace_id="wrkspc_x", credentials=cast(Any, creds) |
| 187 |
) |
| 188 |
assert client.google_credentials is creds |
| 189 |
# `.credentials` is the base client's first-party provider slot — never the |
| 190 |
# Google credentials, and never engaged on this client. |
| 191 |
assert client.credentials is None |
| 192 |
|
| 193 |
def test_full_surface_present(self) -> None: |
| 194 |
client = AnthropicGoogleCloud( |
| 195 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 196 |
) |
| 197 |
assert client.messages is not None |
| 198 |
assert client.models is not None |
| 199 |
assert client.beta is not None |
| 200 |
assert client.messages.batches is not None |
| 201 |
|
| 202 |
def test_no_spurious_env_shadow_warning(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 203 |
# The base client's "unset ANTHROPIC_API_KEY" credential-precedence warning |
| 204 |
# is about its auto-discovery chain, which never engages for this subclass. |
| 205 |
calls: list[Any] = [] |
| 206 |
|
| 207 |
def _record(**kwargs: object) -> None: |
| 208 |
calls.append(kwargs) |
| 209 |
|
| 210 |
monkeypatch.setattr("anthropic._client._warn_env_shadow", _record) |
| 211 |
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-x") |
| 212 |
AnthropicGoogleCloud(base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok") |
| 213 |
assert calls == [] |
| 214 |
|
| 215 |
|
| 216 |
# --------------------------------------------------------------------------- |
| 217 |
# Auth attachment |
| 218 |
# --------------------------------------------------------------------------- |
| 219 |
|
| 220 |
|
| 221 |
@pytest.mark.respx() |
| 222 |
def test_token_provider_attaches_bearer(respx_mock: MockRouter) -> None: |
| 223 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 224 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 225 |
) |
| 226 |
|
| 227 |
client = AnthropicGoogleCloud( |
| 228 |
base_url="https://example.test/", |
| 229 |
workspace_id="wrkspc_x", |
| 230 |
token_provider=lambda: "provided-token", |
| 231 |
) |
| 232 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 233 |
|
| 234 |
calls = cast("list[Any]", respx_mock.calls) |
| 235 |
assert len(calls) == 1 |
| 236 |
req = calls[0].request |
| 237 |
assert req.headers["Authorization"] == "Bearer provided-token" |
| 238 |
# The workspace id travels in the URL path only — never as a header. |
| 239 |
assert "anthropic-workspace-id" not in req.headers |
| 240 |
|
| 241 |
|
| 242 |
@pytest.mark.respx() |
| 243 |
async def test_token_provider_attaches_bearer_async(respx_mock: MockRouter) -> None: |
| 244 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 245 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 246 |
) |
| 247 |
|
| 248 |
async def provider() -> str: |
| 249 |
return "async-token" |
| 250 |
|
| 251 |
client = AsyncAnthropicGoogleCloud( |
| 252 |
base_url="https://example.test/", |
| 253 |
workspace_id="wrkspc_x", |
| 254 |
token_provider=provider, |
| 255 |
) |
| 256 |
await client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 257 |
|
| 258 |
calls = cast("list[Any]", respx_mock.calls) |
| 259 |
assert len(calls) == 1 |
| 260 |
assert calls[0].request.headers["Authorization"] == "Bearer async-token" |
| 261 |
assert "anthropic-workspace-id" not in calls[0].request.headers |
| 262 |
|
| 263 |
|
| 264 |
@pytest.mark.respx() |
| 265 |
async def test_sync_token_provider_on_async_client_runs_off_event_loop( |
| 266 |
respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch |
| 267 |
) -> None: |
| 268 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 269 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 270 |
) |
| 271 |
|
| 272 |
offloaded: list[Any] = [] |
| 273 |
real_asyncify = google_cloud_module.asyncify |
| 274 |
|
| 275 |
def spy(fn: Any) -> Any: |
| 276 |
offloaded.append(fn) |
| 277 |
return real_asyncify(fn) |
| 278 |
|
| 279 |
monkeypatch.setattr("anthropic.lib.google_cloud._client.asyncify", spy) |
| 280 |
|
| 281 |
def provider() -> str: |
| 282 |
return "sync-token" |
| 283 |
|
| 284 |
client = AsyncAnthropicGoogleCloud( |
| 285 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=provider |
| 286 |
) |
| 287 |
await client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 288 |
|
| 289 |
calls = cast("list[Any]", respx_mock.calls) |
| 290 |
assert calls[0].request.headers["Authorization"] == "Bearer sync-token" |
| 291 |
assert provider in offloaded # sync providers may block — they must not run inline on the loop |
| 292 |
|
| 293 |
|
| 294 |
def test_async_token_provider_on_sync_client_rejected_clearly() -> None: |
| 295 |
async def provider() -> str: |
| 296 |
return "tok" |
| 297 |
|
| 298 |
client = AnthropicGoogleCloud( |
| 299 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=cast(Any, provider) |
| 300 |
) |
| 301 |
# Also implicitly asserts no "coroutine was never awaited" RuntimeWarning |
| 302 |
# escapes (filterwarnings=error would fail the test). |
| 303 |
with pytest.raises(AnthropicError, match="AsyncAnthropicGoogleCloud"): |
| 304 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 305 |
|
| 306 |
|
| 307 |
@pytest.mark.respx() |
| 308 |
def test_credentials_object_attaches_bearer(respx_mock: MockRouter) -> None: |
| 309 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 310 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 311 |
) |
| 312 |
|
| 313 |
creds = _FakeCredentials(token="cred-token") |
| 314 |
client = AnthropicGoogleCloud( |
| 315 |
base_url="https://example.test/", |
| 316 |
workspace_id="wrkspc_x", |
| 317 |
credentials=cast(Any, creds), |
| 318 |
) |
| 319 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 320 |
|
| 321 |
calls = cast("list[Any]", respx_mock.calls) |
| 322 |
assert calls[0].request.headers["Authorization"] == "Bearer cred-token" |
| 323 |
assert creds.refresh_calls == 0 # fresh creds aren't refreshed |
| 324 |
|
| 325 |
|
| 326 |
@pytest.mark.respx() |
| 327 |
def test_expired_credentials_refreshed(respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: |
| 328 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 329 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 330 |
) |
| 331 |
|
| 332 |
# Avoid the real google-auth Request import (optional dep, not installed here). |
| 333 |
def _fake_refresh(creds: _FakeCredentials) -> None: |
| 334 |
creds.refresh(None) |
| 335 |
|
| 336 |
monkeypatch.setattr("anthropic.lib.google_cloud._client._refresh_credentials", _fake_refresh) |
| 337 |
creds = _FakeCredentials(token="stale", expired=True) |
| 338 |
client = AnthropicGoogleCloud( |
| 339 |
base_url="https://example.test/", |
| 340 |
workspace_id="wrkspc_x", |
| 341 |
credentials=cast(Any, creds), |
| 342 |
) |
| 343 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 344 |
|
| 345 |
calls = cast("list[Any]", respx_mock.calls) |
| 346 |
assert creds.refresh_calls == 1 |
| 347 |
assert calls[0].request.headers["Authorization"] == "Bearer refreshed-token" |
| 348 |
|
| 349 |
|
| 350 |
def test_refresh_without_google_auth_raises_actionable_error(monkeypatch: pytest.MonkeyPatch) -> None: |
| 351 |
# `None` in sys.modules makes the import fail even when google-auth is installed. |
| 352 |
monkeypatch.setitem(sys.modules, "google.auth.transport.requests", cast(Any, None)) |
| 353 |
with pytest.raises(MissingDependencyError, match=r"anthropic\[google_cloud\]"): |
| 354 |
google_cloud_module._refresh_credentials(cast(Any, _FakeCredentials(token=None))) |
| 355 |
|
| 356 |
|
| 357 |
@pytest.mark.respx() |
| 358 |
def test_adc_path(respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: |
| 359 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 360 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 361 |
) |
| 362 |
|
| 363 |
monkeypatch.setattr( |
| 364 |
"anthropic.lib.google_cloud._client._load_adc_credentials", |
| 365 |
lambda: (_FakeCredentials(token="adc-token"), None), |
| 366 |
) |
| 367 |
client = AnthropicGoogleCloud(base_url="https://example.test/", workspace_id="wrkspc_x") |
| 368 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 369 |
|
| 370 |
calls = cast("list[Any]", respx_mock.calls) |
| 371 |
assert calls[0].request.headers["Authorization"] == "Bearer adc-token" |
| 372 |
|
| 373 |
|
| 374 |
@pytest.mark.respx() |
| 375 |
@pytest.mark.parametrize( |
| 376 |
"kwarg", |
| 377 |
[ |
| 378 |
{"token_provider": lambda: "tok"}, |
| 379 |
{"credentials": _FakeCredentials(token="tok")}, |
| 380 |
], |
| 381 |
ids=["token_provider", "credentials"], |
| 382 |
) |
| 383 |
def test_explicit_credential_suppresses_adc( |
| 384 |
respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch, kwarg: dict[str, Any] |
| 385 |
) -> None: |
| 386 |
# With any explicit credential source set, ADC discovery must never run. |
| 387 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 388 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 389 |
) |
| 390 |
|
| 391 |
def _fail() -> Any: |
| 392 |
raise AssertionError("ADC discovery must not run when an explicit credential source is set") |
| 393 |
|
| 394 |
monkeypatch.setattr("anthropic.lib.google_cloud._client._load_adc_credentials", _fail) |
| 395 |
|
| 396 |
client = AnthropicGoogleCloud(base_url="https://example.test/", workspace_id="wrkspc_x", **kwarg) |
| 397 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 398 |
|
| 399 |
calls = cast("list[Any]", respx_mock.calls) |
| 400 |
assert calls[0].request.headers["Authorization"] == "Bearer tok" |
| 401 |
|
| 402 |
|
| 403 |
@pytest.mark.respx() |
| 404 |
async def test_explicit_credential_suppresses_adc_async( |
| 405 |
respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch |
| 406 |
) -> None: |
| 407 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 408 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 409 |
) |
| 410 |
|
| 411 |
def _fail() -> Any: |
| 412 |
raise AssertionError("ADC discovery must not run when an explicit credential source is set") |
| 413 |
|
| 414 |
monkeypatch.setattr("anthropic.lib.google_cloud._client._load_adc_credentials", _fail) |
| 415 |
|
| 416 |
client = AsyncAnthropicGoogleCloud( |
| 417 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 418 |
) |
| 419 |
await client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 420 |
|
| 421 |
calls = cast("list[Any]", respx_mock.calls) |
| 422 |
assert calls[0].request.headers["Authorization"] == "Bearer tok" |
| 423 |
|
| 424 |
|
| 425 |
def test_concurrent_first_token_resolution_loads_adc_once(monkeypatch: pytest.MonkeyPatch) -> None: |
| 426 |
load_calls = 0 |
| 427 |
|
| 428 |
def slow_load() -> Any: |
| 429 |
nonlocal load_calls |
| 430 |
load_calls += 1 |
| 431 |
time.sleep(0.05) |
| 432 |
return _FakeCredentials(token="adc-token"), None |
| 433 |
|
| 434 |
monkeypatch.setattr("anthropic.lib.google_cloud._client._load_adc_credentials", slow_load) |
| 435 |
client = AnthropicGoogleCloud(base_url="https://example.test/", workspace_id="wrkspc_x") |
| 436 |
|
| 437 |
tokens: list[str] = [] |
| 438 |
threads = [threading.Thread(target=lambda: tokens.append(client._get_token())) for _ in range(4)] |
| 439 |
for thread in threads: |
| 440 |
thread.start() |
| 441 |
for thread in threads: |
| 442 |
thread.join() |
| 443 |
|
| 444 |
assert tokens == ["adc-token"] * 4 |
| 445 |
assert load_calls == 1 # the lazy load is serialized, not raced |
| 446 |
|
| 447 |
|
| 448 |
@pytest.mark.respx() |
| 449 |
def test_bearer_token_not_in_debug_logs(respx_mock: MockRouter, caplog: pytest.LogCaptureFixture) -> None: |
| 450 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 451 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 452 |
) |
| 453 |
caplog.set_level(logging.DEBUG) |
| 454 |
|
| 455 |
client = AnthropicGoogleCloud( |
| 456 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "super-secret-gcp-token" |
| 457 |
) |
| 458 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 459 |
|
| 460 |
calls = cast("list[Any]", respx_mock.calls) |
| 461 |
assert calls[0].request.headers["Authorization"] == "Bearer super-secret-gcp-token" |
| 462 |
assert "super-secret-gcp-token" not in caplog.text |
| 463 |
|
| 464 |
|
| 465 |
# --------------------------------------------------------------------------- |
| 466 |
# Caller-supplied headers win, exactly once, regardless of case / source |
| 467 |
# --------------------------------------------------------------------------- |
| 468 |
|
| 469 |
|
| 470 |
@pytest.mark.respx() |
| 471 |
def test_lowercase_authorization_header_respected(respx_mock: MockRouter) -> None: |
| 472 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 473 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 474 |
) |
| 475 |
|
| 476 |
client = AnthropicGoogleCloud( |
| 477 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "gcp-token" |
| 478 |
) |
| 479 |
client.messages.create( |
| 480 |
max_tokens=16, |
| 481 |
messages=[{"role": "user", "content": "hi"}], |
| 482 |
model="claude-haiku-4-5", |
| 483 |
extra_headers={"authorization": "Bearer caller-token"}, |
| 484 |
) |
| 485 |
|
| 486 |
calls = cast("list[Any]", respx_mock.calls) |
| 487 |
assert calls[0].request.headers.get_list("authorization") == ["Bearer caller-token"] |
| 488 |
|
| 489 |
|
| 490 |
@pytest.mark.respx() |
| 491 |
def test_custom_headers_env_flows_through(respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: |
| 492 |
# ANTHROPIC_CUSTOM_HEADERS behaves like it does on other SDK clients. |
| 493 |
monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "x-custom-header: hello") |
| 494 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 495 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 496 |
) |
| 497 |
|
| 498 |
client = AnthropicGoogleCloud( |
| 499 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "gcp-token" |
| 500 |
) |
| 501 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 502 |
|
| 503 |
calls = cast("list[Any]", respx_mock.calls) |
| 504 |
req = calls[0].request |
| 505 |
assert req.headers["x-custom-header"] == "hello" |
| 506 |
assert req.headers["Authorization"] == "Bearer gcp-token" |
| 507 |
|
| 508 |
|
| 509 |
@pytest.mark.respx() |
| 510 |
def test_custom_headers_env_authorization_never_conflicts( |
| 511 |
respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch |
| 512 |
) -> None: |
| 513 |
# An env-supplied Authorization wins under the only-if-absent contract — and |
| 514 |
# exactly one Authorization header goes out, never two conflicting ones. |
| 515 |
monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "Authorization: Bearer env-token") |
| 516 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 517 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 518 |
) |
| 519 |
|
| 520 |
client = AnthropicGoogleCloud( |
| 521 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "gcp-token" |
| 522 |
) |
| 523 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 524 |
|
| 525 |
calls = cast("list[Any]", respx_mock.calls) |
| 526 |
assert calls[0].request.headers.get_list("authorization") == ["Bearer env-token"] |
| 527 |
|
| 528 |
|
| 529 |
# --------------------------------------------------------------------------- |
| 530 |
# Lazy project back-fill: base URL derived on the first request from the project |
| 531 |
# that ADC resolves |
| 532 |
# --------------------------------------------------------------------------- |
| 533 |
|
| 534 |
ADC_DERIVED_BASE_URL = ( |
| 535 |
"https://claude.googleapis.com/v1alpha/projects/adc-project/locations/us-central1/workspaces/wrkspc_x/invoke/" |
| 536 |
) |
| 537 |
|
| 538 |
|
| 539 |
@pytest.mark.respx() |
| 540 |
def test_project_backfilled_from_adc_on_first_request(respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: |
| 541 |
respx_mock.post(re.compile(r"https://claude\.googleapis\.com/.*")).mock( |
| 542 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 543 |
) |
| 544 |
|
| 545 |
load_calls = 0 |
| 546 |
|
| 547 |
def fake_load() -> Any: |
| 548 |
nonlocal load_calls |
| 549 |
load_calls += 1 |
| 550 |
return _FakeCredentials(token="adc-token"), "adc-project" |
| 551 |
|
| 552 |
monkeypatch.setattr("anthropic.lib.google_cloud._client._load_adc_credentials", fake_load) |
| 553 |
|
| 554 |
client = AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x") |
| 555 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 556 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 557 |
|
| 558 |
calls = cast("list[Any]", respx_mock.calls) |
| 559 |
assert len(calls) == 2 |
| 560 |
for call in calls: |
| 561 |
assert str(call.request.url).startswith(ADC_DERIVED_BASE_URL.rstrip("/")) |
| 562 |
assert call.request.headers["Authorization"] == "Bearer adc-token" |
| 563 |
# The derived URL carries the workspace in its path; still no header. |
| 564 |
assert "anthropic-workspace-id" not in call.request.headers |
| 565 |
assert str(client.base_url) == ADC_DERIVED_BASE_URL |
| 566 |
assert load_calls == 1 # the ADC load (and the back-fill) happens once |
| 567 |
|
| 568 |
|
| 569 |
@pytest.mark.respx() |
| 570 |
def test_backfill_happens_even_with_caller_authorization( |
| 571 |
respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch |
| 572 |
) -> None: |
| 573 |
# The back-fill is decoupled from token attachment: a first request carrying |
| 574 |
# its own Authorization header must still resolve the deferred base URL. |
| 575 |
respx_mock.post(re.compile(r"https://claude\.googleapis\.com/.*")).mock( |
| 576 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 577 |
) |
| 578 |
monkeypatch.setattr( |
| 579 |
"anthropic.lib.google_cloud._client._load_adc_credentials", |
| 580 |
lambda: (_FakeCredentials(token="adc-token"), "adc-project"), |
| 581 |
) |
| 582 |
|
| 583 |
client = AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x") |
| 584 |
client.messages.create( |
| 585 |
max_tokens=16, |
| 586 |
messages=[{"role": "user", "content": "hi"}], |
| 587 |
model="claude-haiku-4-5", |
| 588 |
extra_headers={"Authorization": "Bearer caller-token"}, |
| 589 |
) |
| 590 |
|
| 591 |
calls = cast("list[Any]", respx_mock.calls) |
| 592 |
req = calls[0].request |
| 593 |
assert str(req.url).startswith(ADC_DERIVED_BASE_URL.rstrip("/")) |
| 594 |
assert req.headers.get_list("authorization") == ["Bearer caller-token"] |
| 595 |
|
| 596 |
|
| 597 |
def test_adc_without_project_raises_on_first_request(monkeypatch: pytest.MonkeyPatch) -> None: |
| 598 |
# Plain user ADC resolves no project; the error surfaces on the first request. |
| 599 |
monkeypatch.setattr( |
| 600 |
"anthropic.lib.google_cloud._client._load_adc_credentials", |
| 601 |
lambda: (_FakeCredentials(token="adc-token"), None), |
| 602 |
) |
| 603 |
client = AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x") |
| 604 |
with pytest.raises(AnthropicError, match="ANTHROPIC_GOOGLE_CLOUD_PROJECT"): |
| 605 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 606 |
|
| 607 |
|
| 608 |
def test_token_provider_without_project_raises_on_first_request() -> None: |
| 609 |
# A token provider bypasses ADC entirely, so there is nothing to back-fill from. |
| 610 |
client = AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok") |
| 611 |
with pytest.raises(AnthropicError, match="project"): |
| 612 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 613 |
|
| 614 |
|
| 615 |
@pytest.mark.respx() |
| 616 |
def test_post_construction_base_url_assignment_wins(respx_mock: MockRouter) -> None: |
| 617 |
# Assigning base_url on a deferred-project client cancels the pending back-fill |
| 618 |
# instead of being clobbered (or raising a spurious missing-project error). |
| 619 |
respx_mock.post(re.compile(r"https://my-gateway\.test/.*")).mock( |
| 620 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 621 |
) |
| 622 |
|
| 623 |
client = AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok") |
| 624 |
client.base_url = "https://my-gateway.test/" |
| 625 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 626 |
|
| 627 |
calls = cast("list[Any]", respx_mock.calls) |
| 628 |
req = calls[0].request |
| 629 |
assert req.url.host == "my-gateway.test" |
| 630 |
assert req.headers["Authorization"] == "Bearer tok" |
| 631 |
|
| 632 |
|
| 633 |
@pytest.mark.respx() |
| 634 |
def test_copy_of_deferred_client_still_backfills_and_shares_adc( |
| 635 |
respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch |
| 636 |
) -> None: |
| 637 |
respx_mock.post(re.compile(r"https://claude\.googleapis\.com/.*")).mock( |
| 638 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 639 |
) |
| 640 |
load_calls = 0 |
| 641 |
|
| 642 |
def fake_load() -> Any: |
| 643 |
nonlocal load_calls |
| 644 |
load_calls += 1 |
| 645 |
return _FakeCredentials(token="adc-token"), "adc-project" |
| 646 |
|
| 647 |
monkeypatch.setattr("anthropic.lib.google_cloud._client._load_adc_credentials", fake_load) |
| 648 |
|
| 649 |
client = AnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x") |
| 650 |
clone = client.with_options(timeout=10) |
| 651 |
clone.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 652 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 653 |
|
| 654 |
calls = cast("list[Any]", respx_mock.calls) |
| 655 |
assert len(calls) == 2 |
| 656 |
for call in calls: |
| 657 |
assert str(call.request.url).startswith(ADC_DERIVED_BASE_URL.rstrip("/")) |
| 658 |
assert load_calls == 1 # clones share the lazily-loaded ADC credentials |
| 659 |
|
| 660 |
|
| 661 |
@pytest.mark.respx() |
| 662 |
async def test_project_backfilled_from_adc_on_first_request_async( |
| 663 |
respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch |
| 664 |
) -> None: |
| 665 |
respx_mock.post(re.compile(r"https://claude\.googleapis\.com/.*")).mock( |
| 666 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 667 |
) |
| 668 |
monkeypatch.setattr( |
| 669 |
"anthropic.lib.google_cloud._client._load_adc_credentials", |
| 670 |
lambda: (_FakeCredentials(token="adc-token"), "adc-project"), |
| 671 |
) |
| 672 |
|
| 673 |
client = AsyncAnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x") |
| 674 |
await client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 675 |
|
| 676 |
calls = cast("list[Any]", respx_mock.calls) |
| 677 |
assert str(calls[0].request.url).startswith(ADC_DERIVED_BASE_URL.rstrip("/")) |
| 678 |
assert "anthropic-workspace-id" not in calls[0].request.headers |
| 679 |
assert str(client.base_url) == ADC_DERIVED_BASE_URL |
| 680 |
|
| 681 |
|
| 682 |
async def test_adc_without_project_raises_on_first_request_async(monkeypatch: pytest.MonkeyPatch) -> None: |
| 683 |
monkeypatch.setattr( |
| 684 |
"anthropic.lib.google_cloud._client._load_adc_credentials", |
| 685 |
lambda: (_FakeCredentials(token="adc-token"), None), |
| 686 |
) |
| 687 |
client = AsyncAnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x") |
| 688 |
with pytest.raises(AnthropicError, match="ANTHROPIC_GOOGLE_CLOUD_PROJECT"): |
| 689 |
await client.messages.create( |
| 690 |
max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5" |
| 691 |
) |
| 692 |
|
| 693 |
|
| 694 |
# --------------------------------------------------------------------------- |
| 695 |
# copy() / with_options() coherence |
| 696 |
# --------------------------------------------------------------------------- |
| 697 |
|
| 698 |
|
| 699 |
class TestCopy: |
| 700 |
def test_copy_project_rederives_base_url(self) -> None: |
| 701 |
client = AnthropicGoogleCloud( |
| 702 |
project="my-project", location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 703 |
) |
| 704 |
clone = client.copy(project="other-project") |
| 705 |
assert "/projects/other-project/" in str(clone.base_url) |
| 706 |
|
| 707 |
def test_copy_location_rederives_base_url(self) -> None: |
| 708 |
client = AnthropicGoogleCloud( |
| 709 |
project="my-project", location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 710 |
) |
| 711 |
clone = client.copy(location="europe-west4") |
| 712 |
assert str(clone.base_url).startswith("https://claude.googleapis.com/") |
| 713 |
assert "/locations/europe-west4/" in str(clone.base_url) |
| 714 |
|
| 715 |
def test_copy_keeps_user_supplied_base_url(self) -> None: |
| 716 |
client = AnthropicGoogleCloud( |
| 717 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 718 |
) |
| 719 |
clone = client.copy(project="other-project") |
| 720 |
assert str(clone.base_url) == "https://example.test/" |
| 721 |
|
| 722 |
def test_copy_plain_roundtrip_keeps_derived_base_url(self) -> None: |
| 723 |
client = AnthropicGoogleCloud( |
| 724 |
project="my-project", location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 725 |
) |
| 726 |
clone = client.copy() |
| 727 |
assert str(clone.base_url) == DERIVED_BASE_URL |
| 728 |
|
| 729 |
@pytest.mark.respx() |
| 730 |
def test_copy_lower_tier_credential_takes_effect(self, respx_mock: MockRouter) -> None: |
| 731 |
# copy(credentials=...) on a token_provider client must not keep calling |
| 732 |
# the inherited (higher-precedence) provider. |
| 733 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 734 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 735 |
) |
| 736 |
|
| 737 |
def provider() -> str: |
| 738 |
raise AssertionError("inherited token_provider must not be used after copy(credentials=...)") |
| 739 |
|
| 740 |
client = AnthropicGoogleCloud( |
| 741 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=provider |
| 742 |
) |
| 743 |
clone = client.copy(credentials=cast(Any, _FakeCredentials(token="cred-token"))) |
| 744 |
clone.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 745 |
|
| 746 |
calls = cast("list[Any]", respx_mock.calls) |
| 747 |
assert calls[0].request.headers["Authorization"] == "Bearer cred-token" |
| 748 |
|
| 749 |
@pytest.mark.respx() |
| 750 |
def test_copy_token_provider_replaces_credentials(self, respx_mock: MockRouter) -> None: |
| 751 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 752 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 753 |
) |
| 754 |
|
| 755 |
client = AnthropicGoogleCloud( |
| 756 |
base_url="https://example.test/", |
| 757 |
workspace_id="wrkspc_x", |
| 758 |
credentials=cast(Any, _FakeCredentials(token="stale")), |
| 759 |
) |
| 760 |
clone = client.copy(token_provider=lambda: "fresh-token") |
| 761 |
clone.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 762 |
|
| 763 |
calls = cast("list[Any]", respx_mock.calls) |
| 764 |
assert calls[0].request.headers["Authorization"] == "Bearer fresh-token" |
| 765 |
|
| 766 |
@pytest.mark.respx() |
| 767 |
def test_copy_skip_auth_clears_workspace_and_credentials(self, respx_mock: MockRouter) -> None: |
| 768 |
# The documented pre-authenticated-proxy derivation: no bearer, and the |
| 769 |
# workspace ID is clearable on the clone. |
| 770 |
respx_mock.post(re.compile(r"https://proxy\.test/.*")).mock( |
| 771 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 772 |
) |
| 773 |
|
| 774 |
client = AnthropicGoogleCloud( |
| 775 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 776 |
) |
| 777 |
proxy = client.copy(skip_auth=True, workspace_id=None, base_url="https://proxy.test/") |
| 778 |
proxy.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 779 |
|
| 780 |
calls = cast("list[Any]", respx_mock.calls) |
| 781 |
req = calls[0].request |
| 782 |
assert "Authorization" not in req.headers |
| 783 |
assert "anthropic-workspace-id" not in req.headers |
| 784 |
|
| 785 |
def test_copy_workspace_required_when_cleared_without_skip_auth(self) -> None: |
| 786 |
client = AnthropicGoogleCloud( |
| 787 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 788 |
) |
| 789 |
with pytest.raises(ValueError, match="workspace ID"): |
| 790 |
client.copy(workspace_id=None) |
| 791 |
|
| 792 |
def test_copy_rejects_first_party_kwargs(self) -> None: |
| 793 |
client = AnthropicGoogleCloud( |
| 794 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 795 |
) |
| 796 |
with pytest.raises(TypeError): |
| 797 |
client.copy(auth_token="environment-key") # type: ignore[call-arg] |
| 798 |
with pytest.raises(TypeError): |
| 799 |
client.copy(api_key="sk-ant-x") # type: ignore[call-arg] |
| 800 |
|
| 801 |
def test_async_copy_parity(self) -> None: |
| 802 |
client = AsyncAnthropicGoogleCloud( |
| 803 |
project="my-project", location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 804 |
) |
| 805 |
clone = client.copy(project="other-project") |
| 806 |
assert "/projects/other-project/" in str(clone.base_url) |
| 807 |
proxy = client.copy(skip_auth=True, workspace_id=None, base_url="https://proxy.test/") |
| 808 |
assert proxy.workspace_id is None |
| 809 |
with pytest.raises(TypeError): |
| 810 |
client.copy(auth_token="environment-key") # type: ignore[call-arg] |
| 811 |
|
| 812 |
|
| 813 |
# --------------------------------------------------------------------------- |
| 814 |
# skip_auth |
| 815 |
# --------------------------------------------------------------------------- |
| 816 |
|
| 817 |
|
| 818 |
@pytest.mark.respx() |
| 819 |
def test_skip_auth_sends_neither_header(respx_mock: MockRouter) -> None: |
| 820 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 821 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 822 |
) |
| 823 |
|
| 824 |
client = AnthropicGoogleCloud(base_url="https://example.test/", skip_auth=True) |
| 825 |
assert client.workspace_id is None |
| 826 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 827 |
|
| 828 |
calls = cast("list[Any]", respx_mock.calls) |
| 829 |
req = calls[0].request |
| 830 |
assert "Authorization" not in req.headers |
| 831 |
assert "anthropic-workspace-id" not in req.headers |
| 832 |
|
| 833 |
|
| 834 |
# --------------------------------------------------------------------------- |
| 835 |
# Credential isolation: the first-party ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN / |
| 836 |
# ANTHROPIC_BASE_URL environment variables and the base SDK credential-discovery |
| 837 |
# chain must never affect requests made by this client. |
| 838 |
# --------------------------------------------------------------------------- |
| 839 |
|
| 840 |
|
| 841 |
@pytest.mark.respx() |
| 842 |
def test_no_api_key_leak(respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: |
| 843 |
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-leak") |
| 844 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 845 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 846 |
) |
| 847 |
|
| 848 |
client = AnthropicGoogleCloud( |
| 849 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 850 |
) |
| 851 |
assert client.api_key is None |
| 852 |
assert client.auth_headers == {} |
| 853 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 854 |
|
| 855 |
calls = cast("list[Any]", respx_mock.calls) |
| 856 |
req = calls[0].request |
| 857 |
assert "x-api-key" not in {k.lower() for k in req.headers.keys()} |
| 858 |
assert req.headers["Authorization"] == "Bearer tok" |
| 859 |
|
| 860 |
|
| 861 |
@pytest.mark.respx() |
| 862 |
async def test_no_api_key_leak_async(respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: |
| 863 |
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-leak") |
| 864 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 865 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 866 |
) |
| 867 |
|
| 868 |
client = AsyncAnthropicGoogleCloud( |
| 869 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 870 |
) |
| 871 |
assert client.api_key is None |
| 872 |
await client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 873 |
|
| 874 |
calls = cast("list[Any]", respx_mock.calls) |
| 875 |
req = calls[0].request |
| 876 |
assert "x-api-key" not in {k.lower() for k in req.headers.keys()} |
| 877 |
|
| 878 |
|
| 879 |
@pytest.mark.respx() |
| 880 |
def test_no_auth_token_leak(respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: |
| 881 |
# An ANTHROPIC_AUTH_TOKEN in the env must never become the Authorization header — |
| 882 |
# the bearer token sent is always the one this client resolved itself. |
| 883 |
monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "first-party-leak") |
| 884 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 885 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 886 |
) |
| 887 |
|
| 888 |
client = AnthropicGoogleCloud( |
| 889 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "gcp-token" |
| 890 |
) |
| 891 |
assert client.auth_token is None |
| 892 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 893 |
|
| 894 |
calls = cast("list[Any]", respx_mock.calls) |
| 895 |
assert calls[0].request.headers["Authorization"] == "Bearer gcp-token" |
| 896 |
|
| 897 |
|
| 898 |
@pytest.mark.respx() |
| 899 |
async def test_no_auth_token_leak_async(respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: |
| 900 |
monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "first-party-leak") |
| 901 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 902 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 903 |
) |
| 904 |
|
| 905 |
client = AsyncAnthropicGoogleCloud( |
| 906 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "gcp-token" |
| 907 |
) |
| 908 |
assert client.auth_token is None |
| 909 |
await client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 910 |
|
| 911 |
calls = cast("list[Any]", respx_mock.calls) |
| 912 |
assert calls[0].request.headers["Authorization"] == "Bearer gcp-token" |
| 913 |
|
| 914 |
|
| 915 |
@pytest.mark.respx() |
| 916 |
def test_env_base_url_does_not_override_derived_url(respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: |
| 917 |
# ANTHROPIC_BASE_URL configures the first-party client only; the gateway URL |
| 918 |
# derived from project/location always wins here. |
| 919 |
monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://first-party.test/") |
| 920 |
respx_mock.post(re.compile(r"https://claude\.googleapis\.com/.*")).mock( |
| 921 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 922 |
) |
| 923 |
|
| 924 |
client = AnthropicGoogleCloud( |
| 925 |
project="my-project", location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 926 |
) |
| 927 |
assert str(client.base_url) == DERIVED_BASE_URL |
| 928 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 929 |
|
| 930 |
calls = cast("list[Any]", respx_mock.calls) |
| 931 |
assert str(calls[0].request.url).startswith(DERIVED_BASE_URL.rstrip("/")) |
| 932 |
|
| 933 |
|
| 934 |
async def test_env_base_url_does_not_override_derived_url_async(monkeypatch: pytest.MonkeyPatch) -> None: |
| 935 |
monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://first-party.test/") |
| 936 |
client = AsyncAnthropicGoogleCloud( |
| 937 |
project="my-project", location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 938 |
) |
| 939 |
assert str(client.base_url) == DERIVED_BASE_URL |
| 940 |
|
| 941 |
|
| 942 |
def _assert_credential_chain_off(client: AnthropicGoogleCloud | AsyncAnthropicGoogleCloud) -> None: |
| 943 |
from anthropic._client import _is_base_client |
| 944 |
|
| 945 |
assert _is_base_client(client) is False |
| 946 |
assert client.credentials is None |
| 947 |
assert client.api_key is None |
| 948 |
assert client.auth_token is None |
| 949 |
|
| 950 |
|
| 951 |
def test_base_credential_chain_never_engages(monkeypatch: pytest.MonkeyPatch) -> None: |
| 952 |
# The base client's credential auto-discovery (profiles / workload identity / |
| 953 |
# token cache) is gated on `_is_base_client()`; pin that it never runs for |
| 954 |
# this subclass even when no other credential source is configured. |
| 955 |
def _fail(*_args: Any, **_kwargs: Any) -> Any: |
| 956 |
raise AssertionError("base credential-discovery chain must not engage for AnthropicGoogleCloud") |
| 957 |
|
| 958 |
monkeypatch.setattr("anthropic._client.default_credentials", _fail) |
| 959 |
|
| 960 |
client = AnthropicGoogleCloud( |
| 961 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 962 |
) |
| 963 |
_assert_credential_chain_off(client) |
| 964 |
|
| 965 |
|
| 966 |
async def test_base_credential_chain_never_engages_async(monkeypatch: pytest.MonkeyPatch) -> None: |
| 967 |
def _fail(*_args: Any, **_kwargs: Any) -> Any: |
| 968 |
raise AssertionError("base credential-discovery chain must not engage for AsyncAnthropicGoogleCloud") |
| 969 |
|
| 970 |
monkeypatch.setattr("anthropic._client.default_credentials", _fail) |
| 971 |
|
| 972 |
client = AsyncAnthropicGoogleCloud( |
| 973 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 974 |
) |
| 975 |
_assert_credential_chain_off(client) |
| 976 |
|
| 977 |
|
| 978 |
@pytest.fixture |
| 979 |
def profile_config_dir(tmp_path: pathlib.Path) -> pathlib.Path: |
| 980 |
"""A fully-resolvable Anthropic profile (config + oauth credentials + base_url) |
| 981 |
that the base client's credential chain would adopt if it ever ran.""" |
| 982 |
(tmp_path / "configs").mkdir() |
| 983 |
(tmp_path / "credentials").mkdir() |
| 984 |
(tmp_path / "configs" / "default.json").write_text( |
| 985 |
json.dumps( |
| 986 |
{ |
| 987 |
"version": "1.0", |
| 988 |
"organization_id": "org_profile_should_not_leak", |
| 989 |
"base_url": "https://profile-gateway.example.com", |
| 990 |
"authentication": {"type": "user_oauth"}, |
| 991 |
} |
| 992 |
) |
| 993 |
) |
| 994 |
(tmp_path / "credentials" / "default.json").write_text( |
| 995 |
json.dumps( |
| 996 |
{ |
| 997 |
"version": "1.0", |
| 998 |
"type": "oauth_token", |
| 999 |
"access_token": "profile-oauth-token-should-not-leak", |
| 1000 |
"refresh_token": "profile-refresh-token", |
| 1001 |
"expires_at": 4102444800000, |
| 1002 |
} |
| 1003 |
) |
| 1004 |
) |
| 1005 |
return tmp_path |
| 1006 |
|
| 1007 |
|
| 1008 |
@pytest.mark.respx() |
| 1009 |
def test_resolvable_profile_cannot_leak( |
| 1010 |
respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch, profile_config_dir: pathlib.Path |
| 1011 |
) -> None: |
| 1012 |
# An ANTHROPIC_PROFILE / ANTHROPIC_CONFIG_DIR pointing at a real on-disk profile |
| 1013 |
# must not be able to attach its base_url or oauth token to this client's requests. |
| 1014 |
monkeypatch.setenv("ANTHROPIC_CONFIG_DIR", str(profile_config_dir)) |
| 1015 |
monkeypatch.setenv("ANTHROPIC_PROFILE", "default") |
| 1016 |
respx_mock.post(re.compile(r"https://claude\.googleapis\.com/.*")).mock( |
| 1017 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 1018 |
) |
| 1019 |
|
| 1020 |
client = AnthropicGoogleCloud( |
| 1021 |
project="my-project", location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "gcp-token" |
| 1022 |
) |
| 1023 |
_assert_credential_chain_off(client) |
| 1024 |
client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 1025 |
|
| 1026 |
calls = cast("list[Any]", respx_mock.calls) |
| 1027 |
req = calls[0].request |
| 1028 |
assert req.url.host == "claude.googleapis.com" |
| 1029 |
assert "profile-gateway.example.com" not in str(req.url) |
| 1030 |
assert req.headers.get_list("authorization") == ["Bearer gcp-token"] |
| 1031 |
assert "profile-oauth-token-should-not-leak" not in repr(req.headers) |
| 1032 |
|
| 1033 |
|
| 1034 |
@pytest.mark.respx() |
| 1035 |
async def test_resolvable_profile_cannot_leak_async( |
| 1036 |
respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch, profile_config_dir: pathlib.Path |
| 1037 |
) -> None: |
| 1038 |
monkeypatch.setenv("ANTHROPIC_CONFIG_DIR", str(profile_config_dir)) |
| 1039 |
monkeypatch.setenv("ANTHROPIC_PROFILE", "default") |
| 1040 |
respx_mock.post(re.compile(r"https://example\.test/.*")).mock( |
| 1041 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 1042 |
) |
| 1043 |
|
| 1044 |
client = AsyncAnthropicGoogleCloud( |
| 1045 |
base_url="https://example.test/", workspace_id="wrkspc_x", token_provider=lambda: "gcp-token" |
| 1046 |
) |
| 1047 |
_assert_credential_chain_off(client) |
| 1048 |
await client.messages.create(max_tokens=16, messages=[{"role": "user", "content": "hi"}], model="claude-haiku-4-5") |
| 1049 |
|
| 1050 |
calls = cast("list[Any]", respx_mock.calls) |
| 1051 |
req = calls[0].request |
| 1052 |
assert req.headers.get_list("authorization") == ["Bearer gcp-token"] |
| 1053 |
assert "profile-oauth-token-should-not-leak" not in repr(req.headers) |
| 1054 |
|
| 1055 |
|
| 1056 |
# --------------------------------------------------------------------------- |
| 1057 |
# Async init parity |
| 1058 |
# --------------------------------------------------------------------------- |
| 1059 |
|
| 1060 |
|
| 1061 |
class TestAsyncAnthropicGoogleCloud: |
| 1062 |
async def test_workspace_required(self) -> None: |
| 1063 |
with pytest.raises(ValueError, match="workspace ID"): |
| 1064 |
AsyncAnthropicGoogleCloud(base_url="https://example.test/", token_provider=lambda: "tok") |
| 1065 |
|
| 1066 |
async def test_api_key_and_auth_token_rejected(self) -> None: |
| 1067 |
with pytest.raises(TypeError): |
| 1068 |
AsyncAnthropicGoogleCloud(base_url="https://example.test/", workspace_id="wrkspc_x", api_key="sk-ant-x") # type: ignore[call-arg] |
| 1069 |
with pytest.raises(TypeError): |
| 1070 |
AsyncAnthropicGoogleCloud(base_url="https://example.test/", workspace_id="wrkspc_x", auth_token="tok") # type: ignore[call-arg] |
| 1071 |
|
| 1072 |
async def test_skip_auth_mutually_exclusive_with_credentials(self) -> None: |
| 1073 |
with pytest.raises(ValueError, match="mutually exclusive"): |
| 1074 |
AsyncAnthropicGoogleCloud(base_url="https://example.test/", skip_auth=True, token_provider=lambda: "tok") |
| 1075 |
|
| 1076 |
async def test_base_url_derived(self) -> None: |
| 1077 |
client = AsyncAnthropicGoogleCloud( |
| 1078 |
project="my-project", location="us-central1", workspace_id="wrkspc_x", token_provider=lambda: "tok" |
| 1079 |
) |
| 1080 |
assert str(client.base_url) == DERIVED_BASE_URL |
| 1081 |
|
| 1082 |
async def test_location_defaults_to_global(self) -> None: |
| 1083 |
client = AsyncAnthropicGoogleCloud(project="my-project", workspace_id="wrkspc_x", token_provider=lambda: "tok") |
| 1084 |
assert str(client.base_url) == GLOBAL_DERIVED_BASE_URL |
| 1085 |
|
| 1086 |
async def test_missing_project_defers_without_construct_error(self) -> None: |
| 1087 |
AsyncAnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x") |
| 1088 |
|
| 1089 |
async def test_skip_auth_deriving_base_url_requires_project(self) -> None: |
| 1090 |
with pytest.raises(ValueError, match="project"): |
| 1091 |
AsyncAnthropicGoogleCloud(location="us-central1", workspace_id="wrkspc_x", skip_auth=True) |
| 1092 |
|
| 1093 |
async def test_skip_auth_deriving_base_url_requires_workspace(self) -> None: |
| 1094 |
with pytest.raises(ValueError, match=r"(?s)workspace_id.*ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID"): |
| 1095 |
AsyncAnthropicGoogleCloud(project="my-project", skip_auth=True) |
| 1096 |
|
| 1097 |
async def test_skip_auth_derives_url_with_workspace(self) -> None: |
| 1098 |
client = AsyncAnthropicGoogleCloud(project="my-project", workspace_id="wrkspc_x", skip_auth=True) |
| 1099 |
assert str(client.base_url) == GLOBAL_DERIVED_BASE_URL |