The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(anthropic): Omit() guard reads the sentinel straight off the pinned SDK
kshitijk4poor9ee217c06396
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.pyindex bd11b96db25..44684b58646 100644--- a/agent/anthropic_adapter.py+++ b/agent/anthropic_adapter.py@@ -342,34 +342,6 @@ def _build_anthropic_client_with_bearer_hook(return _new_sdk_client(sdk, kwargs, headers)-def _sdk_omit_sentinel(sdk) -> Optional[Any]:- """``anthropic._types.Omit`` instance from the caller's SDK, or ``None`` when unavailable- (SDK too old / exotic import layout) so the caller can skip the copy-safe guard."""- try:- from anthropic._types import Omit- except Exception:- return None- return Omit()---def _header_stripping_http_client(kwargs: Dict[str, Any], header: str):- """An ``httpx.Client`` that deletes ``header`` from every outgoing request. Copy-safe- fallback for :func:`_new_sdk_client` when the SDK's ``Omit`` sentinel is unavailable: the- SDK copies ``http_client`` into every ``with_options()``/``copy()`` clone (see its- ``copy()``), so the strip applies to the original client and all copies, with no dependency- on the SDK's header-omission internals. Mirrors the custom-client pattern already used by- :func:`_build_anthropic_client_with_bearer_hook`."""- import httpx- target = header.lower()-- def _strip(request: "httpx.Request") -> None:- # httpx headers are case-insensitive; pop by any casing the SDK wrote.- for name in [k for k in request.headers if k.lower() == target]:- del request.headers[name]-- return httpx.Client(timeout=kwargs.get("timeout"), event_hooks={"request": [_strip]})--def _new_sdk_client(sdk, kwargs: Dict[str, Any], headers: Dict[str, str]):"""``sdk.Anthropic(**kwargs)`` with ``headers`` attached. Bearer-only construction leaves``api_key`` unset, so the SDK fills it from ANTHROPIC_API_KEY (loaded from ~/.hermes/.env) and@@ -381,21 +353,10 @@ def _new_sdk_client(sdk, kwargs: Dict[str, Any], headers: Dict[str, str]):if headers:kwargs["default_headers"] = headersif "api_key" in kwargs and "auth_token" not in kwargs:- # Copy-safe sentinel: a None attribute clear does not survive with_options(), which- # re-runs the constructor and re-reads ANTHROPIC_AUTH_TOKEN from the environment.- # An Omit() default header propagates through client copies, so the sentinel Bearer- # never reaches the wire on the original client or on any with_options() copy.- omit = _sdk_omit_sentinel(sdk)- if omit is not None:- merged = dict(kwargs.get("default_headers") or {})- merged["Authorization"] = omit- kwargs["default_headers"] = merged- elif "http_client" not in kwargs:- # Omit unavailable (old/exotic SDK): do NOT fall through to a client that leaks the- # env-derived Bearer. Fail closed onto a copy-safe request hook that strips- # Authorization on the wire — http_client propagates through with_options()/copy(),- # so the original client and every copy are covered.- kwargs["http_client"] = _header_stripping_http_client(kwargs, "Authorization")+ # A `client.auth_token = None` clear does not survive with_options(): the copy re-runs+ # the constructor and re-reads ANTHROPIC_AUTH_TOKEN. An Omit() default header rides+ # along on every copy, so the ambient Bearer never reaches the wire.+ kwargs["default_headers"] = {**(kwargs.get("default_headers") or {}), "Authorization": sdk.Omit()}client = sdk.Anthropic(**kwargs)if "auth_token" in kwargs and "api_key" not in kwargs:client.api_key = Nonediff --git a/tests/agent/test_anthropic_client_auth.py b/tests/agent/test_anthropic_client_auth.pyindex cb4390dd552..f922dcd4333 100644--- a/tests/agent/test_anthropic_client_auth.py+++ b/tests/agent/test_anthropic_client_auth.py@@ -1,45 +1,60 @@"""Auth-boundary shard for the Anthropic adapter.-Credential-isolation regressions (api-key construction vs the ambient-ANTHROPIC_AUTH_TOKEN bearer, fail-closed fallback when the SDK Omit-sentinel is unavailable) live here rather than in the main adapter-suite to respect the 2,000-line per-file ceiling. Both suites run-together in CI; coverage is unchanged.+An api-key-style client must not inherit ANTHROPIC_AUTH_TOKEN from the environment: the SDK+fills an unset ``auth_token`` from that variable and then sends ``Authorization: Bearer ***``+alongside ``x-api-key`` on every request, shipping a foreign shell credential to third-party+Anthropic-compatible endpoints (#105774). Kept out of ``test_anthropic_adapter.py`` for the+per-file line ceiling."""import pytest+from agent.anthropic_adapter import build_anthropic_client-def _final_request_options(anthropic_sdk):+SENTINEL = "sentinel-env-token-DO-NOT-SEND"+++def test_api_key_client_and_its_copies_never_carry_the_env_bearer(monkeypatch):+ """The guard is a copy-safe Omit() default header: ``with_options()`` re-runs the constructor+ and re-reads ANTHROPIC_AUTH_TOKEN, so an attribute clear alone would re-leak on the copy."""+ anthropic_sdk = pytest.importorskip("anthropic")from anthropic._models import FinalRequestOptions- return FinalRequestOptions(method="post", url="/v1/messages", json_data={})+ monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", SENTINEL)+ from agent.anthropic_adapter import _new_sdk_client++ client = _new_sdk_client(anthropic_sdk, {"api_key": "provider-key", "base_url": "http://127.0.0.1:1"}, {})+ for wire_client in (client, client.with_options(timeout=30)):+ headers = dict(wire_client._build_headers(+ FinalRequestOptions(method="post", url="/v1/messages", json_data={})))+ assert headers.get("x-api-key") == "provider-key"+ assert "authorization" not in headers++ # The mirror case is untouched: bearer-style construction still clears the env api key.+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sentinel-env-key-DO-NOT-SEND")+ bearer = _new_sdk_client(anthropic_sdk, {"auth_token": "bearer-secret", "base_url": "http://127.0.0.1:1"}, {})+ assert bearer.api_key is None+ assert bearer.auth_headers == {"Authorization": "Bearer bearer-secret"}-def _start_header_capturing_server():- """Local HTTP server that records the headers of each POST and returns a minimal Messages- response. Returns ``(server, captured)``; the caller derives the base_url from- ``server.server_port`` and must call ``server.shutdown()``. Used by the fail-closed fallback- tests, where the strip happens at the httpx transport layer (not in ``_build_headers``) and so- can only be observed on a real request."""- import json as _json+def test_third_party_request_on_the_wire_carries_no_foreign_bearer(monkeypatch):+ """End-to-end through ``build_anthropic_client`` against a local header-capturing server."""+ pytest.importorskip("anthropic")+ import jsonimport threadingfrom http.server import BaseHTTPRequestHandler, HTTPServer+ monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", SENTINEL)captured = {}class _Handler(BaseHTTPRequestHandler):def do_POST(self):captured["headers"] = {k.lower(): v for k, v in self.headers.items()}self.rfile.read(int(self.headers.get("content-length", 0)))- body = _json.dumps({- "id": "msg_test",- "type": "message",- "role": "assistant",- "content": [{"type": "text", "text": "ok"}],- "model": "test",- "stop_reason": "end_turn",- "usage": {"input_tokens": 1, "output_tokens": 1},+ body = json.dumps({+ "id": "msg_test", "type": "message", "role": "assistant",+ "content": [{"type": "text", "text": "ok"}], "model": "test",+ "stop_reason": "end_turn", "usage": {"input_tokens": 1, "output_tokens": 1},}).encode()self.send_response(200)self.send_header("content-type", "application/json")@@ -52,183 +67,12 @@ def _start_header_capturing_server():server = HTTPServer(("127.0.0.1", 0), _Handler)threading.Thread(target=server.serve_forever, daemon=True).start()- return server, captured---class TestApiKeyConstructionClearsEnvBearerToken:- """Api-key-style clients must not inherit ANTHROPIC_AUTH_TOKEN from the environment.-- The Anthropic SDK fills an unset ``auth_token`` from ANTHROPIC_AUTH_TOKEN and then sends- ``Authorization: Bearer ***`` alongside ``x-api-key`` on every request, shipping a- foreign shell credential to third-party Anthropic-compatible endpoints.- """-- def test_api_key_style_client_drops_env_derived_auth_token(self, monkeypatch):- anthropic_sdk = pytest.importorskip("anthropic")- monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "sentinel-env-token-DO-NOT-SEND")- from agent.anthropic_adapter import _new_sdk_client-- client = _new_sdk_client(- anthropic_sdk,- {"api_key": "provider-key", "base_url": "http://127.0.0.1:1"},- {},- )- assert client.api_key == "provider-key"- # The guard is a copy-safe Omit() default header: the SDK keeps the env-derived- # auth_token attribute, but the request headers (what reaches the wire) never- # contain Authorization — on the original client and on any with_options() copy.- for wire_client in (client, client.with_options(timeout=30)):- headers = dict(- wire_client._build_headers(_final_request_options(anthropic_sdk))- )- assert headers.get("x-api-key") == "provider-key"- assert "authorization" not in headers-- def test_bearer_style_client_keeps_its_auth_token(self, monkeypatch):- anthropic_sdk = pytest.importorskip("anthropic")- monkeypatch.setenv("ANTHROPIC_API_KEY", "sentinel-env-key-DO-NOT-SEND")- from agent.anthropic_adapter import _new_sdk_client-- client = _new_sdk_client(- anthropic_sdk,- {"auth_token": "bearer-secret", "base_url": "http://127.0.0.1:1"},- {},- )- assert client.auth_token == "bearer-secret"- assert client.api_key is None- assert client.auth_headers == {"Authorization": "Bearer bearer-secret"}-- def test_third_party_request_carries_no_foreign_bearer(self, monkeypatch):- """End-to-end over a local header-capturing server: x-api-key intact, sentinel absent."""- anthropic_sdk = pytest.importorskip("anthropic")- http_server = pytest.importorskip("http.server")- monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "sentinel-env-token-DO-NOT-SEND")-- import json as _json- import threading-- captured = {}-- class _Handler(http_server.BaseHTTPRequestHandler):- def do_POST(self):- captured["headers"] = {k.lower(): v for k, v in self.headers.items()}- self.rfile.read(int(self.headers.get("content-length", 0)))- body = _json.dumps({- "id": "msg_test",- "type": "message",- "role": "assistant",- "content": [{"type": "text", "text": "ok"}],- "model": "test",- "stop_reason": "end_turn",- "usage": {"input_tokens": 1, "output_tokens": 1},- }).encode()- self.send_response(200)- self.send_header("content-type", "application/json")- self.send_header("content-length", str(len(body)))- self.end_headers()- self.wfile.write(body)-- def log_message(self, *args):- pass-- server = http_server.HTTPServer(("127.0.0.1", 0), _Handler)- threading.Thread(target=server.serve_forever, daemon=True).start()- try:- client = build_anthropic_client(- "third-party-provider-key",- base_url=f"http://127.0.0.1:{server.server_port}",- )- client.messages.create(- model="test-model",- max_tokens=8,- messages=[{"role": "user", "content": "hi"}],- )- finally:- server.shutdown()-- headers = captured["headers"]- assert headers.get("x-api-key") == "third-party-provider-key"- assert "sentinel-env-token-DO-NOT-SEND" not in headers.get("authorization", "")-- def test_with_options_copy_carries_no_foreign_bearer(self, monkeypatch):- """``with_options()`` re-runs the constructor with ``auth_token=None``, so an attribute- clear would re-leak ANTHROPIC_AUTH_TOKEN on the copy; the Omit() default header- propagates through copies and keeps the sentinel off the wire."""- anthropic_sdk = pytest.importorskip("anthropic")- http_server = pytest.importorskip("http.server")- monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "sentinel-env-token-DO-NOT-SEND")-- import json as _json- import threading-- captured = {}-- class _Handler(http_server.BaseHTTPRequestHandler):- def do_POST(self):- captured["headers"] = {k.lower(): v for k, v in self.headers.items()}- self.rfile.read(int(self.headers.get("content-length", 0)))- body = _json.dumps({- "id": "msg_test",- "type": "message",- "role": "assistant",- "content": [{"type": "text", "text": "ok"}],- "model": "test",- "stop_reason": "end_turn",- "usage": {"input_tokens": 1, "output_tokens": 1},- }).encode()- self.send_response(200)- self.send_header("content-type", "application/json")- self.send_header("content-length", str(len(body)))- self.end_headers()- self.wfile.write(body)-- def log_message(self, *args):- pass-- server = http_server.HTTPServer(("127.0.0.1", 0), _Handler)- threading.Thread(target=server.serve_forever, daemon=True).start()- try:- client = build_anthropic_client(- "third-party-provider-key",- base_url=f"http://127.0.0.1:{server.server_port}",- )- client.with_options(timeout=30).messages.create(- model="test-model",- max_tokens=8,- messages=[{"role": "user", "content": "hi"}],- )- finally:- server.shutdown()-- headers = captured["headers"]- assert headers.get("x-api-key") == "third-party-provider-key"- assert "sentinel-env-token-DO-NOT-SEND" not in headers.get("authorization", "")-- def test_api_key_style_fails_closed_when_omit_unavailable(self, monkeypatch):- """When ``anthropic._types.Omit`` cannot be imported, the copy-safe Omit default header- is unavailable — but the api-key path must still not leak ANTHROPIC_AUTH_TOKEN. It falls- back to a request hook that strips Authorization on the wire (the strip is at the httpx- transport layer, hence the real request), on the original client AND on a with_options()- copy, while x-api-key and request success are preserved."""- anthropic_sdk = pytest.importorskip("anthropic")- monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "sentinel-env-token-DO-NOT-SEND")- monkeypatch.setattr("agent.anthropic_adapter._sdk_omit_sentinel", lambda sdk: None)-- server, captured = _start_header_capturing_server()- try:- client = build_anthropic_client(- "third-party-provider-key",- base_url=f"http://127.0.0.1:{server.server_port}",- )- for wire_client in (client, client.with_options(timeout=30)):- captured.clear()- wire_client.messages.create(- model="test-model",- max_tokens=8,- messages=[{"role": "user", "content": "hi"}],- )- headers = captured["headers"]- assert headers.get("x-api-key") == "third-party-provider-key"- assert "sentinel-env-token-DO-NOT-SEND" not in headers.get("authorization", "")- finally:- server.shutdown()+ try:+ client = build_anthropic_client("third-party-provider-key", base_url=f"http://127.0.0.1:{server.server_port}")+ client.with_options(timeout=30).messages.create(+ model="test-model", max_tokens=8, messages=[{"role": "user", "content": "hi"}])+ finally:+ server.shutdown()++ assert captured["headers"].get("x-api-key") == "third-party-provider-key"+ assert SENTINEL not in captured["headers"].get("authorization", "")