Debian Codegraph @

tests/lib/test_aws.py

raw
1 import re
2 import threading
3 from typing import Dict, List, Type, Union, Optional, cast
4 from typing_extensions import Protocol
5
6 import httpx2
7 import pytest
8 from respx import MockRouter
9
10 from anthropic import AnthropicAWS, AsyncAnthropicAWS, omit
11 from anthropic._exceptions import AnthropicError
12 from anthropic.lib.credentials import StaticToken
13
14
15 class MockRequestCall(Protocol):
16 request: httpx2.Request
17
18
19 _AWSClientClass = Union[Type[AnthropicAWS], Type[AsyncAnthropicAWS]]
20 _aws_client_classes = pytest.mark.parametrize("client_cls", [AnthropicAWS, AsyncAnthropicAWS], ids=["sync", "async"])
21
22
23 # --- Initialization ---
24
25
26 def test_init_api_key_mode() -> None:
27 client = AnthropicAWS(api_key="test-key", aws_region="us-east-1", workspace_id="ws-123")
28 assert client.api_key == "test-key"
29 assert client._use_sigv4 is False
30
31
32 def test_init_sigv4_explicit_creds() -> None:
33 client = AnthropicAWS(
34 aws_access_key="AKID",
35 aws_secret_key="secret",
36 aws_region="us-west-2",
37 workspace_id="ws-123",
38 )
39 assert client._use_sigv4 is True
40 assert client.api_key is None
41 assert client.aws_access_key == "AKID"
42 assert client.aws_secret_key == "secret"
43
44
45 def test_init_sigv4_profile() -> None:
46 client = AnthropicAWS(aws_profile="my-profile", aws_region="eu-west-1", workspace_id="ws-123")
47 assert client._use_sigv4 is True
48 assert client.aws_profile == "my-profile"
49
50
51 def test_init_sigv4_default_credential_chain() -> None:
52 client = AnthropicAWS(aws_region="us-east-1", workspace_id="ws-123")
53 assert client._use_sigv4 is True
54 assert client.api_key is None
55
56
57 def test_init_requires_region_for_sigv4(monkeypatch: pytest.MonkeyPatch) -> None:
58 monkeypatch.delenv("AWS_REGION", raising=False)
59 with pytest.raises(AnthropicError, match="No AWS region was provided"):
60 AnthropicAWS(aws_access_key="AKID", aws_secret_key="secret", workspace_id="ws-123")
61
62
63 def test_init_requires_workspace_id(monkeypatch: pytest.MonkeyPatch) -> None:
64 monkeypatch.delenv("ANTHROPIC_AWS_WORKSPACE_ID", raising=False)
65 with pytest.raises(AnthropicError, match="No workspace ID found"):
66 AnthropicAWS(api_key="test-key", aws_region="us-east-1")
67
68
69 def test_init_workspace_id_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
70 monkeypatch.setenv("ANTHROPIC_AWS_WORKSPACE_ID", "env-workspace")
71 client = AnthropicAWS(api_key="test-key", aws_region="us-east-1")
72 assert client.workspace_id == "env-workspace"
73
74
75 def test_init_async_api_key_mode() -> None:
76 client = AsyncAnthropicAWS(api_key="test-key", aws_region="us-east-1", workspace_id="ws-123")
77 assert client.api_key == "test-key"
78 assert client._use_sigv4 is False
79
80
81 def test_init_async_sigv4() -> None:
82 client = AsyncAnthropicAWS(
83 aws_access_key="AKID",
84 aws_secret_key="secret",
85 aws_region="us-west-2",
86 workspace_id="ws-123",
87 )
88 assert client._use_sigv4 is True
89
90
91 def test_init_async_requires_workspace_id(monkeypatch: pytest.MonkeyPatch) -> None:
92 monkeypatch.delenv("ANTHROPIC_AWS_WORKSPACE_ID", raising=False)
93 with pytest.raises(AnthropicError, match="No workspace ID found"):
94 AsyncAnthropicAWS(api_key="test-key", aws_region="us-east-1")
95
96
97 # --- Partial credential validation ---
98
99
100 def test_partial_creds_access_key_only() -> None:
101 with pytest.raises(ValueError, match="aws_access_key.*without.*aws_secret_key"):
102 AnthropicAWS(aws_access_key="AKID", aws_region="us-east-1", workspace_id="ws-123")
103
104
105 def test_partial_creds_secret_key_only() -> None:
106 with pytest.raises(ValueError, match="aws_secret_key.*without.*aws_access_key"):
107 AnthropicAWS(aws_secret_key="secret", aws_region="us-east-1", workspace_id="ws-123")
108
109
110 def test_partial_creds_async_access_key_only() -> None:
111 with pytest.raises(ValueError, match="aws_access_key.*without.*aws_secret_key"):
112 AsyncAnthropicAWS(aws_access_key="AKID", aws_region="us-east-1", workspace_id="ws-123")
113
114
115 # --- skipAuth ---
116
117
118 def test_skip_auth_no_workspace_required(monkeypatch: pytest.MonkeyPatch) -> None:
119 monkeypatch.delenv("ANTHROPIC_AWS_WORKSPACE_ID", raising=False)
120 client = AnthropicAWS(skip_auth=True, base_url="https://custom.example.com")
121 assert client._skip_auth is True
122 assert client._use_sigv4 is False
123 assert client.workspace_id is None
124
125
126 def _clear_aws_url_env(monkeypatch: pytest.MonkeyPatch) -> None:
127 for var in (
128 "AWS_REGION",
129 "AWS_DEFAULT_REGION",
130 "AWS_PROFILE",
131 "ANTHROPIC_AWS_BASE_URL",
132 "ANTHROPIC_AWS_WORKSPACE_ID",
133 "ANTHROPIC_BASE_URL",
134 ):
135 monkeypatch.delenv(var, raising=False)
136
137
138 def _set_ambient_first_party_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
139 monkeypatch.setenv("ANTHROPIC_API_KEY", "ambient-key")
140 monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "ambient-token")
141
142
143 @_aws_client_classes
144 def test_skip_auth_requires_region_or_base_url(client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch) -> None:
145 _clear_aws_url_env(monkeypatch)
146 monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://first-party.example.com")
147 with pytest.raises(AnthropicError, match="No AWS region was provided and no base_url"):
148 client_cls(skip_auth=True)
149
150
151 @_aws_client_classes
152 def test_skip_auth_base_url_from_region_arg(client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch) -> None:
153 _clear_aws_url_env(monkeypatch)
154 client = client_cls(skip_auth=True, aws_region="eu-west-1")
155 assert client.aws_region == "eu-west-1"
156 assert str(client.base_url).rstrip("/") == "https://aws-external-anthropic.eu-west-1.api.aws"
157
158
159 @_aws_client_classes
160 def test_skip_auth_base_url_from_region_env(client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch) -> None:
161 _clear_aws_url_env(monkeypatch)
162 monkeypatch.setenv("AWS_REGION", "ap-southeast-1")
163 client = client_cls(skip_auth=True)
164 assert str(client.base_url).rstrip("/") == "https://aws-external-anthropic.ap-southeast-1.api.aws"
165
166
167 @_aws_client_classes
168 def test_skip_auth_base_url_env_overrides_region(client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch) -> None:
169 _clear_aws_url_env(monkeypatch)
170 monkeypatch.setenv("ANTHROPIC_AWS_BASE_URL", "https://custom-gateway.example.com")
171 client = client_cls(skip_auth=True, aws_region="eu-west-1")
172 assert str(client.base_url).rstrip("/") == "https://custom-gateway.example.com"
173
174
175 @_aws_client_classes
176 def test_skip_auth_explicit_base_url_wins(client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch) -> None:
177 _clear_aws_url_env(monkeypatch)
178 monkeypatch.setenv("ANTHROPIC_AWS_BASE_URL", "https://custom-gateway.example.com")
179 client = client_cls(skip_auth=True, aws_region="eu-west-1", base_url="https://custom.example.com")
180 assert str(client.base_url).rstrip("/") == "https://custom.example.com"
181
182
183 def test_skip_auth_async(monkeypatch: pytest.MonkeyPatch) -> None:
184 monkeypatch.delenv("ANTHROPIC_AWS_WORKSPACE_ID", raising=False)
185 client = AsyncAnthropicAWS(skip_auth=True, base_url="https://custom.example.com")
186 assert client._skip_auth is True
187 assert client._use_sigv4 is False
188
189
190 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
191 @pytest.mark.respx()
192 def test_skip_auth_no_auth_headers(respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None:
193 _set_ambient_first_party_credentials(monkeypatch)
194 respx_mock.post(re.compile(r"https://custom\.example\.com/.*")).mock(
195 return_value=httpx2.Response(200, json={"foo": "bar"})
196 )
197
198 client = AnthropicAWS(skip_auth=True, base_url="https://custom.example.com")
199 client.messages.create(
200 max_tokens=1024,
201 messages=[{"role": "user", "content": "Hello"}],
202 model="claude-sonnet-4-20250514",
203 )
204
205 calls = cast("list[MockRequestCall]", respx_mock.calls)
206 assert len(calls) == 1
207 assert "X-Api-Key" not in calls[0].request.headers
208 assert "Authorization" not in calls[0].request.headers
209 assert "X-Amz-Date" not in calls[0].request.headers
210 assert "anthropic-workspace-id" not in calls[0].request.headers
211
212
213 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
214 @pytest.mark.respx()
215 @pytest.mark.asyncio()
216 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
217 async def test_skip_auth_region_request_url(
218 sync: bool, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch
219 ) -> None:
220 _clear_aws_url_env(monkeypatch)
221 monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://first-party.example.com")
222 _set_ambient_first_party_credentials(monkeypatch)
223 respx_mock.post(re.compile(r"https://aws-external-anthropic\.eu-west-1\.api\.aws/.*")).mock(
224 return_value=httpx2.Response(200, json={"foo": "bar"})
225 )
226
227 if sync:
228 AnthropicAWS(skip_auth=True, aws_region="eu-west-1", workspace_id="ws-123").messages.create(
229 max_tokens=1024,
230 messages=[{"role": "user", "content": "Hello"}],
231 model="claude-sonnet-4-20250514",
232 )
233 else:
234 await AsyncAnthropicAWS(skip_auth=True, aws_region="eu-west-1", workspace_id="ws-123").messages.create(
235 max_tokens=1024,
236 messages=[{"role": "user", "content": "Hello"}],
237 model="claude-sonnet-4-20250514",
238 )
239
240 calls = cast("list[MockRequestCall]", respx_mock.calls)
241 assert len(calls) == 1
242 assert str(calls[0].request.url) == "https://aws-external-anthropic.eu-west-1.api.aws/v1/messages"
243 assert calls[0].request.headers["anthropic-workspace-id"] == "ws-123"
244 assert "X-Api-Key" not in calls[0].request.headers
245 assert "Authorization" not in calls[0].request.headers
246
247
248 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
249 @pytest.mark.respx()
250 @pytest.mark.asyncio()
251 @pytest.mark.parametrize("via", ["copy", "scoped_helper"])
252 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
253 async def test_skip_auth_explicit_auth_token_on_copy_is_sent(
254 sync: bool, via: str, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch
255 ) -> None:
256 from anthropic.lib._scoped_client import _copy_client_with_bearer_auth
257
258 _clear_aws_url_env(monkeypatch)
259 _set_ambient_first_party_credentials(monkeypatch)
260 respx_mock.post(re.compile(r"https://aws-external-anthropic\.eu-west-1\.api\.aws/.*")).mock(
261 return_value=httpx2.Response(200, json={"foo": "bar"})
262 )
263
264 if sync:
265 client = AnthropicAWS(skip_auth=True, aws_region="eu-west-1", workspace_id="ws-123")
266 scoped = (
267 client.copy(auth_token="scoped-token")
268 if via == "copy"
269 else _copy_client_with_bearer_auth(client, auth_token="scoped-token", helper="environments-worker")
270 )
271 scoped.messages.create(
272 max_tokens=1024, messages=[{"role": "user", "content": "Hello"}], model="claude-sonnet-4-20250514"
273 )
274 else:
275 async_client = AsyncAnthropicAWS(skip_auth=True, aws_region="eu-west-1", workspace_id="ws-123")
276 async_scoped = (
277 async_client.copy(auth_token="scoped-token")
278 if via == "copy"
279 else _copy_client_with_bearer_auth(async_client, auth_token="scoped-token", helper="environments-worker")
280 )
281 await async_scoped.messages.create(
282 max_tokens=1024, messages=[{"role": "user", "content": "Hello"}], model="claude-sonnet-4-20250514"
283 )
284
285 calls = cast("list[MockRequestCall]", respx_mock.calls)
286 assert len(calls) == 1
287 assert calls[0].request.headers["Authorization"] == "Bearer scoped-token"
288 assert "X-Api-Key" not in calls[0].request.headers
289
290
291 # --- Environment Variables ---
292
293
294 def test_env_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
295 monkeypatch.setenv("ANTHROPIC_AWS_API_KEY", "env-key")
296 monkeypatch.delenv("AWS_REGION", raising=False)
297 client = AnthropicAWS(base_url="https://example.com", workspace_id="ws-123")
298 assert client.api_key == "env-key"
299 assert client._use_sigv4 is False
300
301
302 def test_env_region(monkeypatch: pytest.MonkeyPatch) -> None:
303 monkeypatch.setenv("AWS_REGION", "ap-southeast-1")
304 client = AnthropicAWS(api_key="test-key", workspace_id="ws-123")
305 assert client.aws_region == "ap-southeast-1"
306
307
308 def test_env_base_url(monkeypatch: pytest.MonkeyPatch) -> None:
309 monkeypatch.setenv("ANTHROPIC_AWS_BASE_URL", "https://custom-gateway.example.com")
310 client = AnthropicAWS(api_key="test-key", workspace_id="ws-123")
311 assert str(client.base_url).rstrip("/") == "https://custom-gateway.example.com"
312
313
314 # --- Auth Precedence ---
315
316
317 def test_api_key_arg_takes_precedence_over_env(monkeypatch: pytest.MonkeyPatch) -> None:
318 monkeypatch.setenv("ANTHROPIC_AWS_API_KEY", "env-key")
319 client = AnthropicAWS(api_key="arg-key", aws_region="us-east-1", workspace_id="ws-123")
320 assert client.api_key == "arg-key"
321 assert client._use_sigv4 is False
322
323
324 def test_explicit_aws_creds_suppress_env_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
325 """Explicit SigV4 constructor args should suppress ANTHROPIC_AWS_API_KEY env var."""
326 monkeypatch.setenv("ANTHROPIC_AWS_API_KEY", "env-key")
327 client = AnthropicAWS(
328 aws_access_key="AKID",
329 aws_secret_key="secret",
330 aws_region="us-east-1",
331 workspace_id="ws-123",
332 )
333 assert client._use_sigv4 is True
334 assert client.api_key is None
335
336
337 def test_aws_profile_suppresses_env_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
338 monkeypatch.setenv("ANTHROPIC_AWS_API_KEY", "env-key")
339 client = AnthropicAWS(aws_profile="my-profile", aws_region="us-east-1", workspace_id="ws-123")
340 assert client._use_sigv4 is True
341 assert client.api_key is None
342
343
344 # --- Region / Base URL ---
345
346
347 def test_region_from_constructor() -> None:
348 client = AnthropicAWS(api_key="test-key", aws_region="eu-central-1", workspace_id="ws-123")
349 assert client.aws_region == "eu-central-1"
350 assert str(client.base_url).rstrip("/") == "https://aws-external-anthropic.eu-central-1.api.aws"
351
352
353 def test_region_constructor_overrides_env(monkeypatch: pytest.MonkeyPatch) -> None:
354 monkeypatch.setenv("AWS_REGION", "us-west-2")
355 client = AnthropicAWS(api_key="test-key", aws_region="eu-west-1", workspace_id="ws-123")
356 assert client.aws_region == "eu-west-1"
357 assert str(client.base_url).rstrip("/") == "https://aws-external-anthropic.eu-west-1.api.aws"
358
359
360 def test_base_url_override() -> None:
361 client = AnthropicAWS(
362 api_key="test-key",
363 aws_region="us-east-1",
364 base_url="https://custom.example.com",
365 workspace_id="ws-123",
366 )
367 assert str(client.base_url).rstrip("/") == "https://custom.example.com"
368
369
370 def test_api_key_mode_no_region_with_base_url() -> None:
371 """API key mode should work without a region if base_url is provided."""
372 client = AnthropicAWS(api_key="test-key", base_url="https://custom.example.com", workspace_id="ws-123")
373 assert client.aws_region is None
374 assert client._use_sigv4 is False
375
376
377 def test_api_key_mode_no_region_no_base_url_errors(monkeypatch: pytest.MonkeyPatch) -> None:
378 """API key mode without region or base_url should error."""
379 monkeypatch.delenv("AWS_REGION", raising=False)
380 monkeypatch.delenv("ANTHROPIC_AWS_BASE_URL", raising=False)
381 with pytest.raises(AnthropicError, match="No AWS region was provided and no base_url"):
382 AnthropicAWS(api_key="test-key", workspace_id="ws-123")
383
384
385 # --- Resources ---
386
387
388 def test_has_all_resources() -> None:
389 client = AnthropicAWS(api_key="test-key", aws_region="us-east-1", workspace_id="ws-123")
390 assert client.messages is not None
391 assert client.beta is not None
392 assert client.models is not None
393
394
395 def test_async_has_all_resources() -> None:
396 client = AsyncAnthropicAWS(api_key="test-key", aws_region="us-east-1", workspace_id="ws-123")
397 assert client.messages is not None
398 assert client.beta is not None
399 assert client.models is not None
400
401
402 # --- Request behavior (API key mode) ---
403
404
405 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
406 @pytest.mark.respx()
407 def test_api_key_request(respx_mock: MockRouter) -> None:
408 respx_mock.post(re.compile(r"https://aws-external-anthropic\.us-east-1\.api\.aws/.*")).mock(
409 return_value=httpx2.Response(200, json={"foo": "bar"})
410 )
411
412 client = AnthropicAWS(api_key="test-key", aws_region="us-east-1", workspace_id="ws-123")
413 client.messages.create(
414 max_tokens=1024,
415 messages=[{"role": "user", "content": "Hello"}],
416 model="claude-sonnet-4-20250514",
417 )
418
419 calls = cast("list[MockRequestCall]", respx_mock.calls)
420 assert len(calls) == 1
421 assert str(calls[0].request.url) == "https://aws-external-anthropic.us-east-1.api.aws/v1/messages"
422 assert calls[0].request.headers["X-Api-Key"] == "test-key"
423
424
425 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
426 @pytest.mark.respx()
427 @pytest.mark.asyncio()
428 async def test_api_key_request_async(respx_mock: MockRouter) -> None:
429 respx_mock.post(re.compile(r"https://aws-external-anthropic\.us-east-1\.api\.aws/.*")).mock(
430 return_value=httpx2.Response(200, json={"foo": "bar"})
431 )
432
433 client = AsyncAnthropicAWS(api_key="test-key", aws_region="us-east-1", workspace_id="ws-123")
434 await client.messages.create(
435 max_tokens=1024,
436 messages=[{"role": "user", "content": "Hello"}],
437 model="claude-sonnet-4-20250514",
438 )
439
440 calls = cast("list[MockRequestCall]", respx_mock.calls)
441 assert len(calls) == 1
442 assert str(calls[0].request.url) == "https://aws-external-anthropic.us-east-1.api.aws/v1/messages"
443 assert calls[0].request.headers["X-Api-Key"] == "test-key"
444
445
446 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
447 @pytest.mark.respx()
448 @pytest.mark.parametrize(
449 "request_workspace_id, expected",
450 [(None, "ws-client"), ("ws-request", "ws-request")],
451 )
452 def test_workspace_id_header(respx_mock: MockRouter, request_workspace_id: Optional[str], expected: str) -> None:
453 respx_mock.post(re.compile(r"https://aws-external-anthropic\.us-east-1\.api\.aws/.*")).mock(
454 return_value=httpx2.Response(200, json={"foo": "bar"})
455 )
456
457 client = AnthropicAWS(api_key="test-key", aws_region="us-east-1", workspace_id="ws-client")
458 client.messages.create(
459 max_tokens=1024,
460 messages=[{"role": "user", "content": "Hello"}],
461 model="claude-sonnet-4-20250514",
462 workspace_id=request_workspace_id if request_workspace_id is not None else omit,
463 )
464
465 calls = cast("list[MockRequestCall]", respx_mock.calls)
466 assert calls[0].request.headers.get("anthropic-workspace-id") == expected
467
468
469 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
470 @pytest.mark.respx()
471 @pytest.mark.asyncio()
472 @pytest.mark.parametrize(
473 "request_workspace_id, expected",
474 [(None, "ws-client"), ("ws-request", "ws-request")],
475 )
476 async def test_workspace_id_header_async(
477 respx_mock: MockRouter, request_workspace_id: Optional[str], expected: str
478 ) -> None:
479 respx_mock.post(re.compile(r"https://aws-external-anthropic\.us-east-1\.api\.aws/.*")).mock(
480 return_value=httpx2.Response(200, json={"foo": "bar"})
481 )
482
483 client = AsyncAnthropicAWS(api_key="test-key", aws_region="us-east-1", workspace_id="ws-client")
484 await client.messages.create(
485 max_tokens=1024,
486 messages=[{"role": "user", "content": "Hello"}],
487 model="claude-sonnet-4-20250514",
488 workspace_id=request_workspace_id if request_workspace_id is not None else omit,
489 )
490
491 calls = cast("list[MockRequestCall]", respx_mock.calls)
492 assert calls[0].request.headers.get("anthropic-workspace-id") == expected
493
494
495 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
496 @pytest.mark.respx()
497 def test_retries(respx_mock: MockRouter) -> None:
498 respx_mock.post(re.compile(r"https://aws-external-anthropic\.us-east-1\.api\.aws/.*")).mock(
499 side_effect=[
500 httpx2.Response(500, json={"error": "server error"}, headers={"retry-after-ms": "10"}),
501 httpx2.Response(200, json={"foo": "bar"}),
502 ]
503 )
504
505 client = AnthropicAWS(api_key="test-key", aws_region="us-east-1", workspace_id="ws-123")
506 client.messages.create(
507 max_tokens=1024,
508 messages=[{"role": "user", "content": "Hello"}],
509 model="claude-sonnet-4-20250514",
510 )
511
512 calls = cast("list[MockRequestCall]", respx_mock.calls)
513 assert len(calls) == 2
514
515
516 # --- Request behavior (SigV4 mode) ---
517
518
519 @pytest.mark.respx()
520 @pytest.mark.asyncio()
521 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
522 async def test_sigv4_binary_file_upload(sync: bool, respx_mock: MockRouter) -> None:
523 respx_mock.post(re.compile(r"https://aws-external-anthropic\.us-east-1\.api\.aws/.*")).mock(
524 return_value=httpx2.Response(200, json={"id": "file_123", "type": "file"})
525 )
526 png = b"\x89PNG\r\n\x1a\n\x00\xff\xfe"
527
528 if sync:
529 AnthropicAWS(
530 aws_access_key="AKID", aws_secret_key="secret", aws_region="us-east-1", workspace_id="ws-123"
531 ).files.upload(file=("x.png", png, "image/png"))
532 else:
533 await AsyncAnthropicAWS(
534 aws_access_key="AKID", aws_secret_key="secret", aws_region="us-east-1", workspace_id="ws-123"
535 ).files.upload(file=("x.png", png, "image/png"))
536
537 calls = cast("list[MockRequestCall]", respx_mock.calls)
538 assert len(calls) == 1
539 assert str(calls[0].request.url) == "https://aws-external-anthropic.us-east-1.api.aws/v1/files"
540 assert png in calls[0].request.content
541 assert calls[0].request.headers["Authorization"].startswith("AWS4-HMAC-SHA256 ")
542
543
544 @pytest.mark.filterwarnings("ignore::DeprecationWarning")
545 @pytest.mark.respx()
546 @pytest.mark.asyncio()
547 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
548 async def test_sigv4_with_options_ignores_ambient_first_party_credentials(
549 sync: bool, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch
550 ) -> None:
551 _clear_aws_url_env(monkeypatch)
552 _set_ambient_first_party_credentials(monkeypatch)
553 respx_mock.post(re.compile(r"https://aws-external-anthropic\.us-west-2\.api\.aws/.*")).mock(
554 return_value=httpx2.Response(200, json={"foo": "bar"})
555 )
556
557 if sync:
558 client = AnthropicAWS(
559 aws_access_key="AKID", aws_secret_key="secret", aws_region="eu-west-1", workspace_id="ws-123"
560 )
561 assert client.api_key is None
562 assert client.auth_token is None
563 client.with_options(aws_region="us-west-2").messages.create(
564 max_tokens=1024, messages=[{"role": "user", "content": "Hello"}], model="claude-sonnet-4-20250514"
565 )
566 else:
567 async_client = AsyncAnthropicAWS(
568 aws_access_key="AKID", aws_secret_key="secret", aws_region="eu-west-1", workspace_id="ws-123"
569 )
570 assert async_client.api_key is None
571 assert async_client.auth_token is None
572 await async_client.with_options(aws_region="us-west-2").messages.create(
573 max_tokens=1024, messages=[{"role": "user", "content": "Hello"}], model="claude-sonnet-4-20250514"
574 )
575
576 calls = cast("list[MockRequestCall]", respx_mock.calls)
577 assert len(calls) == 1
578 assert str(calls[0].request.url) == "https://aws-external-anthropic.us-west-2.api.aws/v1/messages"
579 authorization = calls[0].request.headers["Authorization"]
580 assert authorization.startswith("AWS4-HMAC-SHA256 ")
581 assert "/us-west-2/" in authorization
582 assert "X-Api-Key" not in calls[0].request.headers
583
584
585 # --- copy / with_options ---
586
587
588 def test_copy_preserves_aws_options() -> None:
589 client = AnthropicAWS(
590 aws_access_key="AKID",
591 aws_secret_key="secret",
592 aws_region="us-east-1",
593 aws_profile="my-profile",
594 aws_session_token="token",
595 workspace_id="ws-123",
596 )
597 copied = client.copy()
598 assert copied.aws_access_key == "AKID"
599 assert copied.aws_secret_key == "secret"
600 assert copied.aws_region == "us-east-1"
601 assert copied.aws_profile == "my-profile"
602 assert copied.aws_session_token == "token"
603 assert copied._use_sigv4 is True
604
605
606 def test_copy_overrides_aws_options() -> None:
607 client = AnthropicAWS(
608 aws_access_key="AKID",
609 aws_secret_key="secret",
610 aws_region="us-east-1",
611 workspace_id="ws-123",
612 )
613 copied = client.copy(aws_access_key="AKID2", aws_secret_key="secret2", workspace_id="ws-456")
614 assert copied.aws_access_key == "AKID2"
615 assert copied.aws_secret_key == "secret2"
616 assert copied.workspace_id == "ws-456"
617 assert copied.aws_region == "us-east-1"
618 assert str(copied.base_url).rstrip("/") == "https://aws-external-anthropic.us-east-1.api.aws"
619
620
621 @_aws_client_classes
622 def test_copy_region_change_rederives_base_url(client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch) -> None:
623 _clear_aws_url_env(monkeypatch)
624 _set_ambient_first_party_credentials(monkeypatch)
625 client = client_cls(aws_access_key="AKID", aws_secret_key="secret", aws_region="eu-west-1", workspace_id="ws-123")
626 assert str(client.base_url).rstrip("/") == "https://aws-external-anthropic.eu-west-1.api.aws"
627
628 copied = client.with_options(aws_region="us-west-2")
629 assert copied.aws_region == "us-west-2"
630 assert str(copied.base_url).rstrip("/") == "https://aws-external-anthropic.us-west-2.api.aws"
631 assert copied.api_key is None and copied.auth_token is None
632 assert client.aws_region == "eu-west-1"
633 assert str(client.base_url).rstrip("/") == "https://aws-external-anthropic.eu-west-1.api.aws"
634
635 chained = copied.with_options(aws_region="ap-northeast-1")
636 assert str(chained.base_url).rstrip("/") == "https://aws-external-anthropic.ap-northeast-1.api.aws"
637
638
639 @_aws_client_classes
640 def test_copy_region_change_rederives_base_url_api_key_mode(
641 client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch
642 ) -> None:
643 _clear_aws_url_env(monkeypatch)
644 client = client_cls(api_key="test-key", aws_region="eu-west-1", workspace_id="ws-123")
645 copied = client.with_options(aws_region="us-west-2")
646 assert str(copied.base_url).rstrip("/") == "https://aws-external-anthropic.us-west-2.api.aws"
647
648
649 @_aws_client_classes
650 def test_copy_region_change_rederives_base_url_skip_auth(
651 client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch
652 ) -> None:
653 _clear_aws_url_env(monkeypatch)
654 _set_ambient_first_party_credentials(monkeypatch)
655 monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://first-party.example.com")
656 client = client_cls(skip_auth=True, aws_region="eu-west-1")
657 copied = client.with_options(aws_region="us-west-2")
658 assert copied.aws_region == "us-west-2"
659 assert str(copied.base_url).rstrip("/") == "https://aws-external-anthropic.us-west-2.api.aws"
660 assert copied.api_key is None and copied.auth_token is None
661
662
663 @_aws_client_classes
664 def test_copy_region_change_explicit_base_url_wins(
665 client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch
666 ) -> None:
667 _clear_aws_url_env(monkeypatch)
668 client = client_cls(aws_access_key="AKID", aws_secret_key="secret", aws_region="eu-west-1", workspace_id="ws-123")
669 copied = client.with_options(aws_region="us-west-2", base_url="https://custom.example.com")
670 assert copied.aws_region == "us-west-2"
671 assert str(copied.base_url).rstrip("/") == "https://custom.example.com"
672
673 chained = copied.with_options(aws_region="ap-northeast-1")
674 assert chained.aws_region == "ap-northeast-1"
675 assert str(chained.base_url).rstrip("/") == "https://custom.example.com"
676
677
678 @_aws_client_classes
679 def test_copy_region_change_keeps_custom_base_url(client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch) -> None:
680 _clear_aws_url_env(monkeypatch)
681 client = client_cls(
682 aws_access_key="AKID",
683 aws_secret_key="secret",
684 aws_region="eu-west-1",
685 base_url="https://custom.example.com",
686 workspace_id="ws-123",
687 )
688 copied = client.with_options(aws_region="us-west-2")
689 assert copied.aws_region == "us-west-2"
690 assert str(copied.base_url).rstrip("/") == "https://custom.example.com"
691 assert str(client.with_options(workspace_id="ws-456").base_url).rstrip("/") == "https://custom.example.com"
692
693
694 @_aws_client_classes
695 def test_copy_region_change_keeps_env_base_url(client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch) -> None:
696 _clear_aws_url_env(monkeypatch)
697 monkeypatch.setenv("ANTHROPIC_AWS_BASE_URL", "https://custom-gateway.example.com")
698 client = client_cls(aws_access_key="AKID", aws_secret_key="secret", aws_region="eu-west-1", workspace_id="ws-123")
699 copied = client.with_options(aws_region="us-west-2")
700 assert copied.aws_region == "us-west-2"
701 assert str(copied.base_url).rstrip("/") == "https://custom-gateway.example.com"
702
703
704 @_aws_client_classes
705 def test_copy_region_change_keeps_base_url_assigned_after_construction(
706 client_cls: _AWSClientClass, monkeypatch: pytest.MonkeyPatch
707 ) -> None:
708 _clear_aws_url_env(monkeypatch)
709 client = client_cls(aws_access_key="AKID", aws_secret_key="secret", aws_region="eu-west-1", workspace_id="ws-123")
710 client.base_url = "https://gateway.example.com"
711 copied = client.with_options(aws_region="us-west-2")
712 assert copied.aws_region == "us-west-2"
713 assert str(copied.base_url).rstrip("/") == "https://gateway.example.com"
714
715
716 def test_copy_accepts_credentials_none_noop() -> None:
717 # `credentials=None` is accepted as a no-op: the AWS client authenticates with
718 # SigV4, not a token provider, so there is nothing to clear. The copy stays SigV4.
719 client = AnthropicAWS(
720 aws_access_key="AKID",
721 aws_secret_key="secret",
722 aws_region="us-east-1",
723 workspace_id="ws-123",
724 )
725 copied = client.copy(credentials=None)
726 assert copied._use_sigv4 is True
727 assert copied.workspace_id == "ws-123"
728 assert copied.aws_region == "us-east-1"
729
730
731 def test_copy_accepts_credentials_none_noop_async() -> None:
732 client = AsyncAnthropicAWS(
733 aws_access_key="AKID",
734 aws_secret_key="secret",
735 aws_region="us-east-1",
736 workspace_id="ws-123",
737 )
738 copied = client.copy(credentials=None)
739 assert copied._use_sigv4 is True
740 assert copied.workspace_id == "ws-123"
741 assert copied.aws_region == "us-east-1"
742
743
744 def test_copy_rejects_real_credentials_provider() -> None:
745 client = AnthropicAWS(
746 aws_access_key="AKID",
747 aws_secret_key="secret",
748 aws_region="us-east-1",
749 workspace_id="ws-123",
750 )
751 with pytest.raises(TypeError, match="does not support a `credentials` provider"):
752 client.copy(credentials=StaticToken("token"))
753
754
755 def test_copy_rejects_real_credentials_provider_async() -> None:
756 client = AsyncAnthropicAWS(
757 aws_access_key="AKID",
758 aws_secret_key="secret",
759 aws_region="us-east-1",
760 workspace_id="ws-123",
761 )
762 with pytest.raises(TypeError, match="does not support a `credentials` provider"):
763 client.copy(credentials=StaticToken("token"))
764
765
766 def test_scoped_bearer_client_helper_on_aws() -> None:
767 # Regression: the environment poller / worker / session-tool-runner build a
768 # scoped sub-client via `_copy_client_with_bearer_auth`, which calls
769 # `client.copy(credentials=None, ...)`. That must work on the AWS client and
770 # yield a client that still signs with SigV4 (the bearer token is unused).
771 from anthropic.lib._scoped_client import _copy_client_with_bearer_auth
772
773 client = AnthropicAWS(
774 aws_access_key="AKID",
775 aws_secret_key="secret",
776 aws_region="us-east-1",
777 workspace_id="ws-123",
778 )
779 scoped = _copy_client_with_bearer_auth(client, auth_token="unused-under-sigv4", helper="environments-work-poller")
780 assert isinstance(scoped, AnthropicAWS)
781 assert scoped._use_sigv4 is True
782 assert scoped.workspace_id == "ws-123"
783
784
785 def test_scoped_bearer_client_helper_on_aws_async() -> None:
786 from anthropic.lib._scoped_client import _copy_client_with_bearer_auth
787
788 client = AsyncAnthropicAWS(
789 aws_access_key="AKID",
790 aws_secret_key="secret",
791 aws_region="us-east-1",
792 workspace_id="ws-123",
793 )
794 scoped = _copy_client_with_bearer_auth(client, auth_token="unused-under-sigv4", helper="environments-worker")
795 assert isinstance(scoped, AsyncAnthropicAWS)
796 assert scoped._use_sigv4 is True
797 assert scoped.workspace_id == "ws-123"
798
799
800 @pytest.mark.asyncio()
801 async def test_sigv4_signing_runs_off_event_loop_async(monkeypatch: pytest.MonkeyPatch) -> None:
802 client = AsyncAnthropicAWS(
803 aws_access_key="AKID",
804 aws_secret_key="secret",
805 aws_region="us-east-1",
806 workspace_id="ws-123",
807 )
808 signing_threads: List[int] = []
809
810 def fake_get_auth_headers(**_: object) -> Dict[str, str]:
811 signing_threads.append(threading.get_ident())
812 return {"Authorization": "AWS4-HMAC-SHA256 stub"}
813
814 monkeypatch.setattr("anthropic.lib.aws._auth.get_auth_headers", fake_get_auth_headers)
815
816 request = httpx2.Request("POST", "https://aws-external-anthropic.us-east-1.api.aws/v1/messages", content=b"{}")
817 await client._prepare_request(request)
818
819 assert len(signing_threads) == 1
820 assert signing_threads[0] != threading.get_ident()
821 assert request.headers["Authorization"] == "AWS4-HMAC-SHA256 stub"