| 1 |
"""Direct unit tests for `_copy_client_with_bearer_auth`. |
| 2 |
|
| 3 |
These verify the load-bearing invariants of the util — auth replaced, parent |
| 4 |
not mutated, helper-telemetry header set — without re-exercising `copy()`'s |
| 5 |
own inheritance contract (which is the SDK's job to keep working). Both sync |
| 6 |
and async client paths are covered so the `ClientT` generic threads through. |
| 7 |
""" |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import httpx2 |
| 12 |
import pytest |
| 13 |
|
| 14 |
from anthropic import Anthropic, AsyncAnthropic |
| 15 |
from anthropic.lib._scoped_client import _copy_client_with_bearer_auth |
| 16 |
|
| 17 |
|
| 18 |
def test_sets_bearer_auth_token_on_copy() -> None: |
| 19 |
parent = Anthropic(api_key="parent-key") |
| 20 |
scoped = _copy_client_with_bearer_auth(parent, auth_token="env-key", helper="environments-work-poller") |
| 21 |
assert scoped.auth_token == "env-key" |
| 22 |
|
| 23 |
|
| 24 |
def test_clears_parent_api_key_on_copy() -> None: |
| 25 |
"""The post-hoc `scoped.api_key = None` mutation is the only thing |
| 26 |
keeping the parent's `X-Api-Key` off the sub-client's wire. If this ever |
| 27 |
starts returning a sub-client with `api_key` set, the parent's API |
| 28 |
credential would silently authenticate every helper request.""" |
| 29 |
parent = Anthropic(api_key="parent-key") |
| 30 |
scoped = _copy_client_with_bearer_auth(parent, auth_token="env-key", helper="environments-work-poller") |
| 31 |
assert scoped.api_key is None |
| 32 |
|
| 33 |
|
| 34 |
def test_clears_inherited_credentials_provider() -> None: |
| 35 |
"""When the parent client carries a credentials provider (e.g. workload |
| 36 |
identity), the sub-client must use the explicit bearer token as the |
| 37 |
unambiguous credential — not stack the provider's auth on top of it.""" |
| 38 |
from anthropic.lib.credentials._types import AccessToken |
| 39 |
|
| 40 |
def fake_provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001 |
| 41 |
return AccessToken(token="provider-token") |
| 42 |
|
| 43 |
parent = Anthropic(api_key="parent-key", credentials=fake_provider) |
| 44 |
scoped = _copy_client_with_bearer_auth(parent, auth_token="env-key", helper="environments-work-poller") |
| 45 |
assert scoped.credentials is None |
| 46 |
|
| 47 |
|
| 48 |
def test_stamps_helper_telemetry_header() -> None: |
| 49 |
parent = Anthropic(api_key="parent-key") |
| 50 |
scoped = _copy_client_with_bearer_auth(parent, auth_token="env-key", helper="environments-worker") |
| 51 |
assert scoped._custom_headers.get("x-stainless-helper") == "environments-worker" |
| 52 |
|
| 53 |
|
| 54 |
def test_does_not_mutate_parent_client() -> None: |
| 55 |
"""Building the sub-client must not touch the parent's auth state. |
| 56 |
|
| 57 |
Without this, a long-lived parent client could be silently re-credentialed |
| 58 |
every time a runner helper started.""" |
| 59 |
parent = Anthropic(api_key="parent-key") |
| 60 |
_copy_client_with_bearer_auth(parent, auth_token="env-key", helper="environments-work-poller") |
| 61 |
assert parent.api_key == "parent-key" |
| 62 |
assert parent.auth_token is None |
| 63 |
|
| 64 |
|
| 65 |
def test_empty_auth_token_raises() -> None: |
| 66 |
"""An empty `auth_token` would silently fall back to the parent's |
| 67 |
`auth_token` via `copy()`'s truthy-or, producing a sub-client with no |
| 68 |
intentional credential set.""" |
| 69 |
parent = Anthropic(api_key="parent-key") |
| 70 |
with pytest.raises(ValueError, match="auth_token"): |
| 71 |
_copy_client_with_bearer_auth(parent, auth_token="", helper="environments-work-poller") |
| 72 |
|
| 73 |
|
| 74 |
@pytest.mark.asyncio() |
| 75 |
async def test_async_client_path_clears_api_key_and_sets_bearer() -> None: |
| 76 |
"""The same invariants hold for `AsyncAnthropic` — verifies the |
| 77 |
`ClientT` typevar threads sync/async correctly through `copy()`.""" |
| 78 |
parent = AsyncAnthropic(api_key="parent-key") |
| 79 |
scoped = _copy_client_with_bearer_auth(parent, auth_token="env-key", helper="session-tool-runner") |
| 80 |
assert isinstance(scoped, AsyncAnthropic) |
| 81 |
assert scoped.api_key is None |
| 82 |
assert scoped.auth_token == "env-key" |
| 83 |
assert scoped._custom_headers.get("x-stainless-helper") == "session-tool-runner" |
| 84 |
|
| 85 |
|
| 86 |
def test_strips_inherited_authorization_from_parent_default_headers() -> None: |
| 87 |
"""If the parent client was configured with a custom |
| 88 |
`default_headers={"Authorization": ...}` (or `X-Api-Key`), those would |
| 89 |
otherwise win over the bearer we just set because |
| 90 |
`AsyncAnthropic.default_headers` merges `_custom_headers` after |
| 91 |
`auth_headers`. The helper strips them from the sub-client's custom |
| 92 |
headers so the bearer is unambiguous on the wire.""" |
| 93 |
parent = Anthropic( |
| 94 |
api_key="parent-key", |
| 95 |
default_headers={"Authorization": "Bearer parent-token", "X-Api-Key": "parent-key"}, |
| 96 |
) |
| 97 |
scoped = _copy_client_with_bearer_auth(parent, auth_token="env-key", helper="environments-worker") |
| 98 |
|
| 99 |
# Strip is case-insensitive, so neither name leaks through under any |
| 100 |
# casing. |
| 101 |
custom = {k.lower() for k in scoped._custom_headers} |
| 102 |
assert "authorization" not in custom |
| 103 |
assert "x-api-key" not in custom |
| 104 |
# Parent client is unmutated — its custom headers still carry the original |
| 105 |
# entries. |
| 106 |
parent_custom = {k.lower(): v for k, v in parent._custom_headers.items()} |
| 107 |
assert parent_custom["authorization"] == "Bearer parent-token" |
| 108 |
assert parent_custom["x-api-key"] == "parent-key" |
| 109 |
|
| 110 |
|
| 111 |
@pytest.mark.asyncio() |
| 112 |
async def test_scoped_sub_client_sends_only_bearer_on_the_wire() -> None: |
| 113 |
"""Integration-level check: send a real HTTP request through the scoped |
| 114 |
sub-client (via `httpx2.MockTransport`) and inspect the headers actually |
| 115 |
on the wire. Asserts exactly one auth credential is sent — the bearer — |
| 116 |
and the parent's `X-Api-Key` doesn't leak. |
| 117 |
|
| 118 |
This is the surface that the case-mismatch bug fixed by this whole |
| 119 |
refactor lived on. The unit tests above check the sub-client's *state*; |
| 120 |
this one checks the request the SDK builds *from* that state. If a future |
| 121 |
change to `_build_headers` reverses the merge order or |
| 122 |
`_copy_client_with_bearer_auth` stops stripping the parent's |
| 123 |
`X-Api-Key`, this is the test that catches it.""" |
| 124 |
captured: list[httpx2.Request] = [] |
| 125 |
|
| 126 |
async def handler(req: httpx2.Request) -> httpx2.Response: |
| 127 |
captured.append(req) |
| 128 |
return httpx2.Response(200, json={"id": "agent_test"}) |
| 129 |
|
| 130 |
transport = httpx2.MockTransport(handler) |
| 131 |
http_client = httpx2.AsyncClient(transport=transport) |
| 132 |
# Parent has *every* way a credential could leak: an api_key, an |
| 133 |
# Authorization in default_headers, AND an X-Api-Key in default_headers. |
| 134 |
parent = AsyncAnthropic( |
| 135 |
api_key="parent-key", |
| 136 |
default_headers={ |
| 137 |
"Authorization": "Bearer parent-token", |
| 138 |
"X-Api-Key": "parent-key", |
| 139 |
}, |
| 140 |
http_client=http_client, |
| 141 |
) |
| 142 |
|
| 143 |
scoped = _copy_client_with_bearer_auth(parent, auth_token="env-key", helper="environments-worker") |
| 144 |
# Any GET that doesn't require a body — agents.retrieve is a thin GET that |
| 145 |
# exercises the same auth path the worker / poller use. |
| 146 |
await scoped.beta.agents.retrieve("agent_test") |
| 147 |
|
| 148 |
assert len(captured) == 1 |
| 149 |
req = captured[0] |
| 150 |
# `httpx2.Headers` is case-insensitive, so .get() catches any casing. |
| 151 |
assert req.headers.get("authorization") == "Bearer env-key" |
| 152 |
# The parent's `X-Api-Key` must NOT be on the wire — that was the bug. |
| 153 |
assert req.headers.get("x-api-key") is None |
| 154 |
# Helper telemetry is on every scoped request. |
| 155 |
assert req.headers.get("x-stainless-helper") == "environments-worker" |