Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(sdk): accept origin-confined configured HTTP clients (#539)
Krisztian Gajdardea0ca1f771a
diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 0f884581a..e6c82ee73 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -294,6 +294,12 @@ def _close_transport(transport: httpx.Client) -> None:transport.close()+def _confine_injected_client_origin(request: httpx.Request, *, base_url: str) -> None:+ """Keep a configured transport's credentials on its intended origin."""+ if not request_matches_base_url_origin(base_url, str(request.url)):+ raise httpx.RequestError("configured HTTP client refused a different origin", request=request)++def _attach_origin_scoped_headers(request: httpx.Request,*,@@ -428,6 +434,15 @@ class SIEClient:while it loads, and a model served only remotely answers ``400``.``None`` (default) leaves the choice to the model's routing policy.The setting applies to every call made with this client.+ http_client: Optional configured synchronous HTTP client for custom+ transports, proxy/TLS policy, or dynamic authentication. Its base+ URL must match ``base_url`` exactly and redirects must be disabled.+ SDK headers are added and requests stay confined to the gateway+ origin; a control plane on another origin is unavailable with this+ option. Existing hooks, authentication, and transport settings are+ preserved. Pass ``api_key=""`` to avoid SDK environment credentials+ when the HTTP client supplies its own authentication. The SDK owns+ and closes this client; do not share it with another owner.Example:>>> client = SIEClient("http://localhost:8080")@@ -469,6 +484,7 @@ class SIEClient:connect_timeout_s: float | None = None,read_timeout_s: float | None = None,remote: Literal["forbid"] | None = None,+ http_client: httpx.Client | None = None,) -> None:base_url = resolve_base_url(base_url)api_key = resolve_api_key(api_key, base_url, control_plane_url)@@ -545,7 +561,21 @@ class SIEClient:max_connections=max_connections,max_keepalive_connections=max_connections,)- self._client = httpx.Client(**client_kwargs)+ if http_client is None:+ self._client = httpx.Client(**client_kwargs)+ else:+ if str(http_client.base_url).rstrip("/") != str(httpx.URL(self._base_url)).rstrip("/"):+ raise ValueError("http_client base URL must match base_url")+ if http_client.is_closed or http_client.follow_redirects:+ raise ValueError("http_client must be open with redirects disabled")+ if max_connections is not None:+ raise ValueError("configure connection limits on http_client instead")+ if self._control_plane_url and not request_matches_base_url_origin(self._base_url, self._control_plane_url):+ raise ValueError("http_client cannot serve a control plane on another origin")+ http_client.headers.update(headers)+ http_client.event_hooks["request"].append(partial(_confine_injected_client_origin, base_url=self._base_url))+ http_client.event_hooks["request"].extend(client_kwargs.get("event_hooks", {}).get("request", []))+ self._client = http_client# Per-thread request evidence lets benchmark callers account for SDK# retries without changing normal response payloads.self._request_state = threading.local()diff --git a/packages/sie_sdk/tests/client/test_http_client.py b/packages/sie_sdk/tests/client/test_http_client.pynew file mode 100644index 000000000..fa48eca40--- /dev/null+++ b/packages/sie_sdk/tests/client/test_http_client.py@@ -0,0 +1,99 @@+"""Configured SDK transports retain egress ownership and origin confinement."""++from collections.abc import Generator++import httpx+import pytest+from sie_sdk import SIEClient++BASE = "https://upstream.example.test/prefix"+++def test_metadata_preserves_dynamic_auth_hooks_timeout_and_cleanup(monkeypatch) -> None:+ monkeypatch.setenv("SIE_BASE_URL", BASE)+ monkeypatch.setenv("SIE_API_KEY", "ambient-key")+ observed = []+ hooks = []++ class DynamicAuth(httpx.Auth):+ def auth_flow(self, request) -> Generator[httpx.Request, httpx.Response, None]:+ request.headers["Authorization"] = "Bearer dynamic-key"+ yield request++ def handle(request):+ observed.append(request)+ return httpx.Response(200, json={"name": "model", "profiles": []})++ transport = httpx.Client(+ base_url=BASE,+ auth=DynamicAuth(),+ transport=httpx.MockTransport(handle),+ trust_env=False,+ timeout=3,+ follow_redirects=False,+ event_hooks={"request": [lambda request: hooks.append(request.url)]},+ )+ with SIEClient(BASE, api_key="", remote="forbid", http_client=transport) as client:+ assert client.get_model("model")["name"] == "model"+ assert client.get_model("model")["name"] == "model"+ assert len(hooks) == 2+ assert observed[0].url.path == "/prefix/v1/models/model"+ assert observed[0].headers["Authorization"] == "Bearer dynamic-key"+ assert observed[0].headers["X-SIE-Remote"] == "forbid"+ assert observed[0].headers["Accept"] == "application/json"+ assert observed[0].extensions["timeout"]["read"] == 3+ assert not transport.is_closed+ assert transport.is_closed+++ "base",+ ["https://other.example.test/prefix", "https://upstream.example.test/other", "http://upstream.example.test/prefix"],+)+def test_mismatched_base_rejected_without_adopting_client(base) -> None:+ with httpx.Client(base_url=base) as transport:+ with pytest.raises(ValueError, match="base URL"):+ SIEClient(BASE, http_client=transport)+ assert not transport.is_closed++[email protected]("kwargs", [{"max_connections": 4}, {"control_plane_url": "https://control.example.test"}])+def test_conflicting_configuration_is_rejected(kwargs) -> None:+ with httpx.Client(base_url=BASE) as transport:+ with pytest.raises(ValueError, match=r"connection limits|control plane"):+ SIEClient(BASE, http_client=transport, **kwargs)+ assert not transport.is_closed+++def test_redirect_following_and_closed_client_rejected() -> None:+ with httpx.Client(base_url=BASE, follow_redirects=True) as transport:+ with pytest.raises(ValueError, match="redirects disabled"):+ SIEClient(BASE, http_client=transport)+ with pytest.raises(ValueError, match="must be open"):+ SIEClient(BASE, http_client=transport)+++def test_origin_guard_prevents_cross_origin_transport_dispatch() -> None:+ calls = []+ transport = httpx.Client(base_url=BASE, transport=httpx.MockTransport(calls.append))+ with SIEClient(BASE, http_client=transport):+ with pytest.raises(httpx.RequestError, match="different origin"):+ transport.get("https://attacker.example.test/model")+ assert not calls+++def test_existing_hook_cannot_change_origin_before_dispatch() -> None:+ calls = []++ def rewrite(request):+ request.url = httpx.URL("https://attacker.example.test/model")++ transport = httpx.Client(+ base_url=BASE,+ event_hooks={"request": [rewrite]},+ transport=httpx.MockTransport(calls.append),+ )+ with SIEClient(BASE, http_client=transport) as client:+ with pytest.raises(httpx.RequestError, match="different origin"):+ client.get_model("model")+ assert not calls