From e707fd254b3e3723e77e1ecfb06bfe303a1f3673 Mon Sep 17 00:00:00 2001 From: Greg Holmes Date: Thu, 19 Nov 2026 17:24:38 +0000 Subject: [PATCH 1/8] feat(auth): add auth=False for self-hosted servers without authentication Self-hosted and local Deepgram servers can run without request authentication, but the client could not be constructed without an API key, so there was no way to connect without inventing one. DeepgramClient and AsyncDeepgramClient now accept auth=False: no key is required, DEEPGRAM_API_KEY is ignored, and no Authorization header is sent on HTTP requests or WebSocket handshakes. It cannot be combined with api_key or access_token. When no key is available and the environment is not a Deepgram host, the missing-key error now suggests auth=False. The message for Deepgram's hosted API is unchanged apart from fixing "instantiated be either". Also documents the self-hosted setup in the README. --- .fernignore | 2 + README.md | 21 +++ src/deepgram/client.py | 138 +++++++++++----- tests/custom/test_self_hosted_no_auth.py | 199 +++++++++++++++++++++++ 4 files changed, 322 insertions(+), 38 deletions(-) create mode 100644 tests/custom/test_self_hosted_no_auth.py diff --git a/.fernignore b/.fernignore index caea8da9..65bd927c 100644 --- a/.fernignore +++ b/.fernignore @@ -1,5 +1,6 @@ # Custom client implementation extending BaseClient with additional features: # - access_token parameter support (Bearer token authentication) +# - auth=False for self-hosted servers without authentication (no key, no Authorization header) # - Automatic session ID generation and header injection (x-deepgram-session-id) # - transport_factory parameter for plugging in a custom WebSocket transport # - reconnect flag (default True) — declarative flag indicating whether the SDK @@ -280,6 +281,7 @@ tests/custom/test_model_dict_compat.py tests/custom/test_query_encoder.py tests/custom/test_regen_response_fields.py tests/custom/test_secure_logging.py +tests/custom/test_self_hosted_no_auth.py tests/custom/test_socket_client_shims.py tests/custom/test_socket_unknown_fallback.py tests/custom/test_speak_v2_connect_wire.py diff --git a/README.md b/README.md index 95d94023..07bc415b 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,27 @@ The SDK automatically discovers credentials from these environment variables: **Precedence:** Explicit parameters > Environment variables +### Self-Hosted and Local Servers Without Authentication + +A self-hosted or local Deepgram server may not require request authentication. Point the client at it with a custom environment and pass `auth=False` so the SDK doesn't ask for an API key: + +```python +from deepgram import DeepgramClient +from deepgram.environment import DeepgramClientEnvironment + +client = DeepgramClient( + environment=DeepgramClientEnvironment( + base="http://127.0.0.1:8000", + production="ws://127.0.0.1:8000", + agent="ws://127.0.0.1:8000", + agent_rest="http://127.0.0.1:8000", + ), + auth=False, +) +``` + +With `auth=False` no `Authorization` header is sent on HTTP requests or WebSocket connections, and `DEEPGRAM_API_KEY` is ignored. It can't be combined with `api_key` or `access_token`; if your server does require a key, pass `api_key` as usual. + ## Async Client The SDK provides full async/await support for non-blocking operations: diff --git a/src/deepgram/client.py b/src/deepgram/client.py index 0a603832..e6d82ccf 100644 --- a/src/deepgram/client.py +++ b/src/deepgram/client.py @@ -6,6 +6,10 @@ - If `access_token` is provided, it takes precedence and sets `Authorization: bearer ` - When `access_token` is used, `api_key` is forced to "token" to satisfy the generator, but the Authorization header is overridden for all HTTP and WebSocket requests. +- `auth=False` for self-hosted or local Deepgram servers that don't require authentication: + - No API key is needed, and no Authorization header is sent on HTTP or WebSocket requests. + - When no key is available and the environment is not a Deepgram host, the missing-key + error suggests `auth=False`. - `session_id` as a header sent with every request and websocket connection: - If `session_id` is provided, it will be used; otherwise, a UUID is auto-generated - The session_id is sent as the `x-deepgram-session-id` header @@ -24,6 +28,7 @@ import os import types +import urllib.parse import uuid from typing import Any, Callable, Dict, Optional @@ -57,6 +62,85 @@ def _get_headers_with_bearer(_self: Any) -> Dict[str, str]: client_wrapper.httpx_client.base_headers = client_wrapper.get_headers +def _apply_no_authorization_override(client_wrapper: BaseClientWrapper) -> None: + """Drop the Authorization header from every HTTP and WebSocket request (``auth=False``).""" + original_get_headers = client_wrapper.get_headers + + def _get_headers_without_auth(_self: Any) -> Dict[str, str]: + headers = original_get_headers() + headers.pop("Authorization", None) + return headers + + client_wrapper.get_headers = types.MethodType(_get_headers_without_auth, client_wrapper) # type: ignore[method-assign] + + if hasattr(client_wrapper, "httpx_client") and hasattr(client_wrapper.httpx_client, "base_headers"): + client_wrapper.httpx_client.base_headers = client_wrapper.get_headers + + +_MISSING_KEY_MESSAGE = "The client must be instantiated by either passing in api_key or setting DEEPGRAM_API_KEY" +_SELF_HOSTED_NO_AUTH_HINT = ( + "If you are connecting to a self-hosted or local Deepgram server that does not require " + "authentication, pass auth=False when initializing the client." +) + + +def _is_deepgram_hosted(environment: Any) -> bool: + """Whether the environment's REST base is Deepgram's hosted API. + + Unknown or unparseable environments count as hosted, so the standard missing-key message is + kept unless the host is clearly somewhere else. + """ + base = getattr(environment, "base", None) + if not isinstance(base, str) or not base: + return True + try: + host = (urllib.parse.urlparse(base).hostname or "").lower() + except ValueError: + return True + if not host: + return True + return host == "deepgram.com" or host.endswith(".deepgram.com") + + +def _missing_key_error(environment: Any) -> ApiError: + body = _MISSING_KEY_MESSAGE + if not _is_deepgram_hosted(environment): + body = f"{body}. {_SELF_HOSTED_NO_AUTH_HINT}" + return ApiError(body=body) + + +def _resolve_credentials(kwargs: Dict[str, Any], access_token: Optional[str], auth: Any) -> None: + """Fill ``kwargs["api_key"]`` for the generated base client, or raise if no credential is available. + + Shared by the sync and async clients. The generated base client requires an api_key, so + ``access_token`` and ``auth=False`` set a placeholder; the Authorization header is then + replaced (Bearer) or removed after construction. + """ + if auth is not None and auth is not False: + raise ValueError("auth only accepts False, to disable authentication for self-hosted servers") + + environment = kwargs.get("environment") + if auth is False: + if access_token is not None or kwargs.get("api_key") is not None: + raise ValueError("auth=False cannot be combined with api_key or access_token") + kwargs["api_key"] = "" + elif access_token is not None: + # access_token takes precedence over api_key; the header becomes Bearer after construction. + if kwargs.get("api_key") is None: + kwargs["api_key"] = "token" + elif "api_key" in kwargs and kwargs["api_key"] is None: + # Fern now resolves None to DEEPGRAM_API_KEY in the base client. Preserve the SDK + # contract that an explicit None disables ambient lookup. + raise _missing_key_error(environment) + elif "api_key" not in kwargs: + # The generated base client takes os.getenv("DEEPGRAM_API_KEY") as a default argument, so + # it is read once at import. Re-read it here so a key set after import (load_dotenv below + # the imports) is still picked up. + kwargs["api_key"] = os.getenv("DEEPGRAM_API_KEY") + if kwargs["api_key"] is None: + raise _missing_key_error(environment) + + class DeepgramClient(BaseClient): """ Custom Deepgram client that extends the generated BaseClient. @@ -65,6 +149,8 @@ class DeepgramClient(BaseClient): - `session_id`: Optional session identifier. If not provided, a UUID is auto-generated. Sent as `x-deepgram-session-id` header in all requests and websocket connections. - `access_token`: Alternative to `api_key`. If provided, uses Bearer token authentication. + - `auth`: Pass ``False`` for a self-hosted or local Deepgram server that doesn't require + authentication. No API key is needed and no Authorization header is sent. - `transport_factory`: Custom sync WebSocket transport factory. A callable ``factory(url, headers) -> transport`` whose return value must support ``send()``, ``recv()``, iteration, and ``close()``. @@ -83,6 +169,7 @@ class DeepgramClient(BaseClient): def __init__(self, *args, **kwargs) -> None: access_token: Optional[str] = kwargs.pop("access_token", None) + auth: Any = kwargs.pop("auth", None) session_id: Optional[str] = kwargs.pop("session_id", None) transport_factory: Optional[Callable] = kwargs.pop("transport_factory", None) reconnect: bool = bool(kwargs.pop("reconnect", True)) @@ -109,31 +196,17 @@ def __init__(self, *args, **kwargs) -> None: # Ensure every request has a session identifier header headers["x-deepgram-session-id"] = final_session_id - # Handle access_token: if provided, it takes precedence over api_key - # The base client requires api_key, so we set a placeholder if needed - # The Authorization header will be overridden to use Bearer token - if access_token is not None: - # Set a placeholder api_key if none provided (base client requires it) - if kwargs.get("api_key") is None: - kwargs["api_key"] = "token" - elif "api_key" in kwargs and kwargs["api_key"] is None: - # Fern now resolves None to DEEPGRAM_API_KEY in BaseClient. Preserve - # the SDK contract that an explicit None disables ambient lookup. - raise ApiError( - body="The client must be instantiated by either passing in api_key or setting DEEPGRAM_API_KEY" - ) - elif "api_key" not in kwargs: - # The generated base client takes os.getenv("DEEPGRAM_API_KEY") as a default - # argument, so it is read once at import. Re-read it here so a key set after - # import (load_dotenv below the imports) is still picked up. - kwargs["api_key"] = os.getenv("DEEPGRAM_API_KEY") + _resolve_credentials(kwargs, access_token, auth) super().__init__(*args, **kwargs) self.session_id = final_session_id - # Override Authorization header to use Bearer token if access_token was provided + # Override Authorization header to use Bearer token if access_token was provided, + # or drop it entirely for auth=False if access_token is not None: _apply_bearer_authorization_override(self._client_wrapper, access_token) + elif auth is False: + _apply_no_authorization_override(self._client_wrapper) # Install custom WebSocket transport if provided. Auto-disable # `reconnect`: a custom transport owns its retry lifecycle, so flip @@ -155,6 +228,8 @@ class AsyncDeepgramClient(AsyncBaseClient): - `session_id`: Optional session identifier. If not provided, a UUID is auto-generated. Sent as `x-deepgram-session-id` header in all requests and websocket connections. - `access_token`: Alternative to `api_key`. If provided, uses Bearer token authentication. + - `auth`: Pass ``False`` for a self-hosted or local Deepgram server that doesn't require + authentication. No API key is needed and no Authorization header is sent. - `transport_factory`: Custom async WebSocket transport factory. A callable ``factory(url, headers) -> transport`` whose return value must support ``send()``, ``recv()``, async iteration, and ``close()``. @@ -173,6 +248,7 @@ class AsyncDeepgramClient(AsyncBaseClient): def __init__(self, *args, **kwargs) -> None: access_token: Optional[str] = kwargs.pop("access_token", None) + auth: Any = kwargs.pop("auth", None) session_id: Optional[str] = kwargs.pop("session_id", None) transport_factory: Optional[Callable] = kwargs.pop("transport_factory", None) reconnect: bool = bool(kwargs.pop("reconnect", True)) @@ -199,31 +275,17 @@ def __init__(self, *args, **kwargs) -> None: # Ensure every request has a session identifier header headers["x-deepgram-session-id"] = final_session_id - # Handle access_token: if provided, it takes precedence over api_key - # The base client requires api_key, so we set a placeholder if needed - # The Authorization header will be overridden to use Bearer token - if access_token is not None: - # Set a placeholder api_key if none provided (base client requires it) - if kwargs.get("api_key") is None: - kwargs["api_key"] = "token" - elif "api_key" in kwargs and kwargs["api_key"] is None: - # Fern now resolves None to DEEPGRAM_API_KEY in AsyncBaseClient. - # Preserve the SDK contract that explicit None disables ambient lookup. - raise ApiError( - body="The client must be instantiated by either passing in api_key or setting DEEPGRAM_API_KEY" - ) - elif "api_key" not in kwargs: - # The generated base client takes os.getenv("DEEPGRAM_API_KEY") as a default - # argument, so it is read once at import. Re-read it here so a key set after - # import (load_dotenv below the imports) is still picked up. - kwargs["api_key"] = os.getenv("DEEPGRAM_API_KEY") + _resolve_credentials(kwargs, access_token, auth) super().__init__(*args, **kwargs) self.session_id = final_session_id - # Override Authorization header to use Bearer token if access_token was provided + # Override Authorization header to use Bearer token if access_token was provided, + # or drop it entirely for auth=False if access_token is not None: _apply_bearer_authorization_override(self._client_wrapper, access_token) + elif auth is False: + _apply_no_authorization_override(self._client_wrapper) # Install custom WebSocket transport if provided. Auto-disable # `reconnect`: a custom transport owns its retry lifecycle, so flip diff --git a/tests/custom/test_self_hosted_no_auth.py b/tests/custom/test_self_hosted_no_auth.py new file mode 100644 index 00000000..e9d9eaa5 --- /dev/null +++ b/tests/custom/test_self_hosted_no_auth.py @@ -0,0 +1,199 @@ +""" +``auth=False`` for self-hosted and local Deepgram servers that don't require authentication. + +Pins that: + + * the client constructs without an API key (and ignores ``DEEPGRAM_API_KEY``), + * no ``Authorization`` header is sent on HTTP requests or WebSocket handshakes, + * ``auth=False`` can't be combined with a credential, and only ``False`` is accepted, + * the missing-key error suggests ``auth=False`` when the environment isn't a Deepgram host, + and stays unchanged for Deepgram's hosted API, + * a key passed for a self-hosted environment is still sent. + +Hand-written and frozen in ``.fernignore``. +""" + +import typing +from unittest.mock import patch + +import httpx +import pytest + +import deepgram.listen.v2.client as listen_v2_client +from deepgram import AsyncDeepgramClient, DeepgramClient +from deepgram.core.api_error import ApiError +from deepgram.environment import DeepgramClientEnvironment + +LOCAL = DeepgramClientEnvironment( + base="http://127.0.0.1:8000", + production="ws://127.0.0.1:8000", + agent="ws://127.0.0.1:8000", + agent_rest="http://127.0.0.1:8000", +) +MISSING_KEY = "The client must be instantiated by either passing in api_key or setting DEEPGRAM_API_KEY" + + +@pytest.fixture(autouse=True) +def no_env_key(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("DEEPGRAM_API_KEY", raising=False) + + +class _CaptureConnect: + """Stands in for ``websockets(.sync).connect`` and records the handshake headers.""" + + def __init__(self) -> None: + self.url: typing.Optional[str] = None + self.headers: typing.Dict[str, str] = {} + + def __call__(self, url: str, **kwargs: typing.Any) -> "_CaptureConnect": + self.url = url + self.headers = dict(kwargs.get("additional_headers") or kwargs.get("extra_headers") or {}) + return self + + def __enter__(self) -> object: + return object() + + def __exit__(self, *exc: typing.Any) -> bool: + return False + + async def __aenter__(self) -> object: + return object() + + async def __aexit__(self, *exc: typing.Any) -> bool: + return False + + +def _capturing_transport(seen: typing.List[httpx.Request]) -> httpx.MockTransport: + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + return httpx.Response(200, json={}) + + return httpx.MockTransport(handler) + + +# --------------------------------------------------------------------------- construction + + +def test_auth_false_constructs_without_a_key() -> None: + DeepgramClient(environment=LOCAL, auth=False) + AsyncDeepgramClient(environment=LOCAL, auth=False) + + +def test_auth_false_ignores_the_environment_key(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("DEEPGRAM_API_KEY", "from-env") + client = DeepgramClient(environment=LOCAL, auth=False) + assert "Authorization" not in client._client_wrapper.get_headers() + + +@pytest.mark.parametrize("credential", [{"api_key": "key"}, {"access_token": "token"}]) +def test_auth_false_rejects_a_credential(credential: typing.Dict[str, str]) -> None: + with pytest.raises(ValueError, match="auth=False cannot be combined"): + DeepgramClient(environment=LOCAL, auth=False, **credential) + with pytest.raises(ValueError, match="auth=False cannot be combined"): + AsyncDeepgramClient(environment=LOCAL, auth=False, **credential) + + +@pytest.mark.parametrize("value", [True, "none", 0]) +def test_auth_accepts_only_false(value: typing.Any) -> None: + with pytest.raises(ValueError, match="auth only accepts False"): + DeepgramClient(environment=LOCAL, auth=value, api_key="key") + + +# --------------------------------------------------------------------------- headers on the wire + + +def test_auth_false_sends_no_authorization_over_http() -> None: + seen: typing.List[httpx.Request] = [] + client = DeepgramClient( + environment=LOCAL, auth=False, httpx_client=httpx.Client(transport=_capturing_transport(seen)) + ) + client.manage.v1.models.list() + assert len(seen) == 1 + assert str(seen[0].url).startswith("http://127.0.0.1:8000/v1/models") + assert "authorization" not in seen[0].headers + + +async def test_async_auth_false_sends_no_authorization_over_http() -> None: + seen: typing.List[httpx.Request] = [] + client = AsyncDeepgramClient( + environment=LOCAL, auth=False, httpx_client=httpx.AsyncClient(transport=_capturing_transport(seen)) + ) + await client.manage.v1.models.list() + assert len(seen) == 1 + assert "authorization" not in seen[0].headers + + +def test_auth_false_sends_no_authorization_on_websocket_handshake() -> None: + capture = _CaptureConnect() + with patch.object(listen_v2_client.websockets_sync_client, "connect", capture): + with DeepgramClient(environment=LOCAL, auth=False).listen.v2.connect(model="flux-general-en"): + pass + assert capture.url is not None and capture.url.startswith("ws://127.0.0.1:8000/v2/listen") + assert "Authorization" not in capture.headers + assert "x-deepgram-session-id" in capture.headers + + +async def test_async_auth_false_sends_no_authorization_on_websocket_handshake() -> None: + capture = _CaptureConnect() + with patch.object(listen_v2_client, "websockets_client_connect", capture): + async with AsyncDeepgramClient(environment=LOCAL, auth=False).listen.v2.connect(model="flux-general-en"): + pass + assert "Authorization" not in capture.headers + + +def test_a_key_is_still_sent_to_a_self_hosted_server() -> None: + seen: typing.List[httpx.Request] = [] + client = DeepgramClient( + environment=LOCAL, api_key="local-key", httpx_client=httpx.Client(transport=_capturing_transport(seen)) + ) + client.manage.v1.models.list() + assert seen[0].headers["authorization"] == "Token local-key" + + +# --------------------------------------------------------------------------- missing-key error + + +def _missing_key_body(**kwargs: typing.Any) -> str: + with pytest.raises(ApiError) as caught: + DeepgramClient(**kwargs) + return str(caught.value.body) + + +def test_missing_key_error_suggests_auth_false_for_a_self_hosted_environment() -> None: + body = _missing_key_body(environment=LOCAL) + assert body.startswith(MISSING_KEY) + assert "auth=False" in body + + +def test_explicit_none_key_also_gets_the_hint_for_a_self_hosted_environment() -> None: + assert "auth=False" in _missing_key_body(environment=LOCAL, api_key=None) + + +def test_async_missing_key_error_suggests_auth_false() -> None: + with pytest.raises(ApiError) as caught: + AsyncDeepgramClient(environment=LOCAL) + assert "auth=False" in str(caught.value.body) + + +def test_missing_key_error_is_unchanged_for_the_hosted_api() -> None: + assert _missing_key_body() == MISSING_KEY + + +def test_missing_key_error_is_unchanged_for_a_regional_deepgram_host() -> None: + eu = DeepgramClientEnvironment( + base="https://api.eu.deepgram.com", + production="wss://api.eu.deepgram.com", + agent="wss://agent.deepgram.com", + agent_rest="https://agent.deepgram.com", + ) + assert _missing_key_body(environment=eu) == MISSING_KEY + + +def test_a_look_alike_host_is_not_treated_as_deepgram() -> None: + lookalike = DeepgramClientEnvironment( + base="https://notdeepgram.com", + production="wss://notdeepgram.com", + agent="wss://notdeepgram.com", + agent_rest="https://notdeepgram.com", + ) + assert "auth=False" in _missing_key_body(environment=lookalike) From aaffba6577b5a8b85f49b360f8cc7759f7ff0f78 Mon Sep 17 00:00:00 2001 From: Greg Holmes Date: Tue, 24 Nov 2026 12:52:28 +0000 Subject: [PATCH 2/8] fix(auth): show the auth=False hint when the base URL has no host An environment base with the scheme left off, such as "127.0.0.1:8000", parses with no hostname. It was treated as Deepgram's hosted API, so the developer got the bare missing-key error with no hint. A base that can't be parsed or has no host can never be Deepgram's; only an unset environment counts as hosted. --- src/deepgram/client.py | 15 ++++++++------- tests/custom/test_self_hosted_no_auth.py | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/deepgram/client.py b/src/deepgram/client.py index e6d82ccf..74a9ca76 100644 --- a/src/deepgram/client.py +++ b/src/deepgram/client.py @@ -87,18 +87,19 @@ def _get_headers_without_auth(_self: Any) -> Dict[str, str]: def _is_deepgram_hosted(environment: Any) -> bool: """Whether the environment's REST base is Deepgram's hosted API. - Unknown or unparseable environments count as hosted, so the standard missing-key message is - kept unless the host is clearly somewhere else. + Only an unset environment counts as hosted, because the client then uses + ``DeepgramClientEnvironment.PRODUCTION``. A base that can't be parsed or has no host (for + example ``"127.0.0.1:8000"``, with the scheme left off) can never be Deepgram's host. """ - base = getattr(environment, "base", None) - if not isinstance(base, str) or not base: + if environment is None: return True + base = getattr(environment, "base", None) + if not isinstance(base, str): + return False try: host = (urllib.parse.urlparse(base).hostname or "").lower() except ValueError: - return True - if not host: - return True + return False return host == "deepgram.com" or host.endswith(".deepgram.com") diff --git a/tests/custom/test_self_hosted_no_auth.py b/tests/custom/test_self_hosted_no_auth.py index e9d9eaa5..8805ce24 100644 --- a/tests/custom/test_self_hosted_no_auth.py +++ b/tests/custom/test_self_hosted_no_auth.py @@ -197,3 +197,17 @@ def test_a_look_alike_host_is_not_treated_as_deepgram() -> None: agent_rest="https://notdeepgram.com", ) assert "auth=False" in _missing_key_body(environment=lookalike) + + +def test_a_base_without_a_scheme_gets_the_hint() -> None: + # An easy mistake with a local server: "127.0.0.1:8000" parses with no host, and a base with + # no host can never be Deepgram's. + schemeless = DeepgramClientEnvironment( + base="127.0.0.1:8000", + production="127.0.0.1:8000", + agent="127.0.0.1:8000", + agent_rest="127.0.0.1:8000", + ) + body = _missing_key_body(environment=schemeless) + assert body.startswith(MISSING_KEY) + assert "auth=False" in body From 9a7b1bcfd458aec8b3962e1566f00666889c8a19 Mon Sep 17 00:00:00 2001 From: Greg Holmes Date: Tue, 24 Nov 2026 16:26:08 +0000 Subject: [PATCH 3/8] fix(auth): suppress override headers with auth false --- .fernignore | 5 ++ src/deepgram/client.py | 27 +++++++- src/deepgram/core/http_client.py | 15 +++++ tests/custom/test_self_hosted_no_auth.py | 78 ++++++++++++++++++++---- 4 files changed, 111 insertions(+), 14 deletions(-) diff --git a/.fernignore b/.fernignore index 65bd927c..7e26f766 100644 --- a/.fernignore +++ b/.fernignore @@ -10,6 +10,11 @@ # This file is manually maintained and should not be regenerated src/deepgram/client.py +# ``auth=False`` needs an HTTP final-header filter because generated endpoint +# and request-option headers are merged after the custom client's base headers. +# [temporarily frozen — remove when Fern exposes a no-auth client mode] +src/deepgram/core/http_client.py + # Hand-written security utility: installs a logging.Filter on the third-party # `websockets` client/server loggers that masks the Authorization header (API # key / access token) in DEBUG handshake logs. No Fern-generated counterpart. diff --git a/src/deepgram/client.py b/src/deepgram/client.py index 74a9ca76..7b9ccbfa 100644 --- a/src/deepgram/client.py +++ b/src/deepgram/client.py @@ -40,6 +40,22 @@ from deepgram.core.client_wrapper import BaseClientWrapper +class _NoAuthorizationHeaders(Dict[str, str]): + """A header map that permanently drops case-insensitive Authorization keys.""" + + def __init__(self, headers: Dict[str, str]) -> None: + super().__init__() + self.update(headers) + + def __setitem__(self, key: str, value: str) -> None: + if key.lower() != "authorization": + super().__setitem__(key, value) + + def update(self, *args: Any, **kwargs: str) -> None: + for key, value in dict(*args, **kwargs).items(): + self[key] = value + + def _apply_bearer_authorization_override(client_wrapper: BaseClientWrapper, bearer_token: str) -> None: """Override header providers to always use a Bearer authorization token. @@ -67,14 +83,19 @@ def _apply_no_authorization_override(client_wrapper: BaseClientWrapper) -> None: original_get_headers = client_wrapper.get_headers def _get_headers_without_auth(_self: Any) -> Dict[str, str]: - headers = original_get_headers() - headers.pop("Authorization", None) - return headers + # Generated WebSocket clients append their per-call ``authorization`` and + # ``additional_headers`` after invoking this provider. Return a mapping + # that keeps suppressing the header through those later mutations. + return _NoAuthorizationHeaders(original_get_headers()) client_wrapper.get_headers = types.MethodType(_get_headers_without_auth, client_wrapper) # type: ignore[method-assign] if hasattr(client_wrapper, "httpx_client") and hasattr(client_wrapper.httpx_client, "base_headers"): client_wrapper.httpx_client.base_headers = client_wrapper.get_headers + # HTTP clients merge endpoint and request-option headers after + # ``base_headers``. Mark this client so the final merged map also drops + # Authorization before the request is sent. + client_wrapper.httpx_client.auth_disabled = True # type: ignore[attr-defined] _MISSING_KEY_MESSAGE = "The client must be instantiated by either passing in api_key or setting DEEPGRAM_API_KEY" diff --git a/src/deepgram/core/http_client.py b/src/deepgram/core/http_client.py index 2cac2aec..82aa99d1 100644 --- a/src/deepgram/core/http_client.py +++ b/src/deepgram/core/http_client.py @@ -187,6 +187,11 @@ def _should_retry(response: httpx.Response) -> bool: _AUTH_HEADERS: typing.FrozenSet[str] = frozenset({"authorization"}) +def _without_authorization(headers: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]: + """Remove Authorization headers case-insensitively for no-auth clients.""" + return {key: value for key, value in headers.items() if key.lower() != "authorization"} + + def _redact_headers(headers: typing.Dict[str, str]) -> typing.Dict[str, str]: return { k: ("[REDACTED]" if k.lower() in _SENSITIVE_HEADERS or k.lower() in _AUTH_HEADERS else v) @@ -369,6 +374,7 @@ def __init__( self.base_max_retries = base_max_retries self.httpx_client = httpx_client self.logger = create_logger(logging_config) + self.auth_disabled = False def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = maybe_base_url @@ -457,6 +463,8 @@ def request( ) ) ) + if self.auth_disabled: + _request_headers = _without_authorization(_request_headers) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) @@ -631,6 +639,8 @@ def stream( ) ) ) + if self.auth_disabled: + _request_headers = _without_authorization(_request_headers) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) @@ -676,6 +686,7 @@ def __init__( self.async_base_headers = async_base_headers self.httpx_client = httpx_client self.logger = create_logger(logging_config) + self.auth_disabled = False async def _get_headers(self) -> typing.Dict[str, str]: if self.async_base_headers is not None: @@ -772,6 +783,8 @@ async def request( ) ) ) + if self.auth_disabled: + _request_headers = _without_authorization(_request_headers) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) @@ -949,6 +962,8 @@ async def stream( ) ) ) + if self.auth_disabled: + _request_headers = _without_authorization(_request_headers) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) diff --git a/tests/custom/test_self_hosted_no_auth.py b/tests/custom/test_self_hosted_no_auth.py index 8805ce24..44a34a66 100644 --- a/tests/custom/test_self_hosted_no_auth.py +++ b/tests/custom/test_self_hosted_no_auth.py @@ -20,9 +20,11 @@ import pytest import deepgram.listen.v2.client as listen_v2_client +import deepgram.listen.v2.raw_client as listen_v2_raw_client from deepgram import AsyncDeepgramClient, DeepgramClient from deepgram.core.api_error import ApiError from deepgram.environment import DeepgramClientEnvironment +from deepgram.transport import restore_transport LOCAL = DeepgramClientEnvironment( base="http://127.0.0.1:8000", @@ -63,6 +65,11 @@ async def __aexit__(self, *exc: typing.Any) -> bool: return False +class _CloseOnlyTransport: + def close(self) -> None: + pass + + def _capturing_transport(seen: typing.List[httpx.Request]) -> httpx.MockTransport: def handler(request: httpx.Request) -> httpx.Response: seen.append(request) @@ -71,6 +78,10 @@ def handler(request: httpx.Request) -> httpx.Response: return httpx.MockTransport(handler) +def _assert_no_authorization(headers: typing.Mapping[str, str]) -> None: + assert all(key.lower() != "authorization" for key in headers) + + # --------------------------------------------------------------------------- construction @@ -105,40 +116,85 @@ def test_auth_accepts_only_false(value: typing.Any) -> None: def test_auth_false_sends_no_authorization_over_http() -> None: seen: typing.List[httpx.Request] = [] client = DeepgramClient( - environment=LOCAL, auth=False, httpx_client=httpx.Client(transport=_capturing_transport(seen)) + environment=LOCAL, + auth=False, + headers={"authorization": "Token client-header"}, + httpx_client=httpx.Client(transport=_capturing_transport(seen)), ) - client.manage.v1.models.list() + client.manage.v1.models.list(request_options={"additional_headers": {"Authorization": "Token request-header"}}) assert len(seen) == 1 assert str(seen[0].url).startswith("http://127.0.0.1:8000/v1/models") - assert "authorization" not in seen[0].headers + _assert_no_authorization(seen[0].headers) async def test_async_auth_false_sends_no_authorization_over_http() -> None: seen: typing.List[httpx.Request] = [] client = AsyncDeepgramClient( - environment=LOCAL, auth=False, httpx_client=httpx.AsyncClient(transport=_capturing_transport(seen)) + environment=LOCAL, + auth=False, + headers={"authorization": "Token client-header"}, + httpx_client=httpx.AsyncClient(transport=_capturing_transport(seen)), + ) + await client.manage.v1.models.list( + request_options={"additional_headers": {"Authorization": "Token request-header"}} ) - await client.manage.v1.models.list() assert len(seen) == 1 - assert "authorization" not in seen[0].headers + _assert_no_authorization(seen[0].headers) def test_auth_false_sends_no_authorization_on_websocket_handshake() -> None: capture = _CaptureConnect() with patch.object(listen_v2_client.websockets_sync_client, "connect", capture): - with DeepgramClient(environment=LOCAL, auth=False).listen.v2.connect(model="flux-general-en"): + with DeepgramClient( + environment=LOCAL, auth=False, headers={"authorization": "Token client-header"} + ).listen.v2.connect( + model="flux-general-en", + authorization="Token connect-argument", + request_options={"additional_headers": {"Authorization": "Token request-header"}}, + ): pass assert capture.url is not None and capture.url.startswith("ws://127.0.0.1:8000/v2/listen") - assert "Authorization" not in capture.headers + _assert_no_authorization(capture.headers) assert "x-deepgram-session-id" in capture.headers async def test_async_auth_false_sends_no_authorization_on_websocket_handshake() -> None: capture = _CaptureConnect() - with patch.object(listen_v2_client, "websockets_client_connect", capture): - async with AsyncDeepgramClient(environment=LOCAL, auth=False).listen.v2.connect(model="flux-general-en"): + with patch.object(listen_v2_raw_client, "websockets_client_connect", capture): + async with AsyncDeepgramClient( + environment=LOCAL, auth=False, headers={"authorization": "Token client-header"} + ).listen.v2.with_raw_response.connect( + model="flux-general-en", + authorization="Token connect-argument", + request_options={"additional_headers": {"Authorization": "Token request-header"}}, + ): pass - assert "Authorization" not in capture.headers + _assert_no_authorization(capture.headers) + + +def test_auth_false_sends_no_authorization_to_a_custom_websocket_transport() -> None: + captured: typing.Dict[str, str] = {} + + def factory(_url: str, headers: typing.Dict[str, str]) -> _CloseOnlyTransport: + captured.update(headers) + return _CloseOnlyTransport() + + try: + with DeepgramClient( + environment=LOCAL, + auth=False, + headers={"authorization": "Token client-header"}, + transport_factory=factory, + ).listen.v2.connect( + model="flux-general-en", + authorization="Token connect-argument", + request_options={"additional_headers": {"Authorization": "Token request-header"}}, + ): + pass + finally: + restore_transport() + + _assert_no_authorization(captured) def test_a_key_is_still_sent_to_a_self_hosted_server() -> None: From a0dd0326ef3a7d953214b35a64f51454bedfa813 Mon Sep 17 00:00:00 2001 From: Greg Holmes Date: Tue, 24 Nov 2026 16:27:31 +0000 Subject: [PATCH 4/8] fix(auth): disable supplied HTTP client authentication --- src/deepgram/client.py | 2 +- src/deepgram/core/http_client.py | 20 +++++++++++++++++ tests/custom/test_self_hosted_no_auth.py | 28 ++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/deepgram/client.py b/src/deepgram/client.py index 7b9ccbfa..0ebfb8fc 100644 --- a/src/deepgram/client.py +++ b/src/deepgram/client.py @@ -95,7 +95,7 @@ def _get_headers_without_auth(_self: Any) -> Dict[str, str]: # HTTP clients merge endpoint and request-option headers after # ``base_headers``. Mark this client so the final merged map also drops # Authorization before the request is sent. - client_wrapper.httpx_client.auth_disabled = True # type: ignore[attr-defined] + client_wrapper.httpx_client.disable_authentication() # type: ignore[attr-defined] _MISSING_KEY_MESSAGE = "The client must be instantiated by either passing in api_key or setting DEEPGRAM_API_KEY" diff --git a/src/deepgram/core/http_client.py b/src/deepgram/core/http_client.py index 82aa99d1..4d1278cb 100644 --- a/src/deepgram/core/http_client.py +++ b/src/deepgram/core/http_client.py @@ -192,6 +192,14 @@ def _without_authorization(headers: typing.Dict[str, typing.Any]) -> typing.Dict return {key: value for key, value in headers.items() if key.lower() != "authorization"} +def _disable_httpx_authentication(client: typing.Union[httpx.Client, httpx.AsyncClient]) -> None: + """Remove authentication configured directly on a caller-provided HTTPX client.""" + for key in list(client.headers): + if key.lower() == "authorization": + del client.headers[key] + client.auth = None + + def _redact_headers(headers: typing.Dict[str, str]) -> typing.Dict[str, str]: return { k: ("[REDACTED]" if k.lower() in _SENSITIVE_HEADERS or k.lower() in _AUTH_HEADERS else v) @@ -376,6 +384,10 @@ def __init__( self.logger = create_logger(logging_config) self.auth_disabled = False + def disable_authentication(self) -> None: + self.auth_disabled = True + _disable_httpx_authentication(self.httpx_client) + def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = maybe_base_url if self.base_url is not None and base_url is None: @@ -465,6 +477,7 @@ def request( ) if self.auth_disabled: _request_headers = _without_authorization(_request_headers) + _disable_httpx_authentication(self.httpx_client) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) @@ -641,6 +654,7 @@ def stream( ) if self.auth_disabled: _request_headers = _without_authorization(_request_headers) + _disable_httpx_authentication(self.httpx_client) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) @@ -688,6 +702,10 @@ def __init__( self.logger = create_logger(logging_config) self.auth_disabled = False + def disable_authentication(self) -> None: + self.auth_disabled = True + _disable_httpx_authentication(self.httpx_client) + async def _get_headers(self) -> typing.Dict[str, str]: if self.async_base_headers is not None: return await self.async_base_headers() @@ -785,6 +803,7 @@ async def request( ) if self.auth_disabled: _request_headers = _without_authorization(_request_headers) + _disable_httpx_authentication(self.httpx_client) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) @@ -964,6 +983,7 @@ async def stream( ) if self.auth_disabled: _request_headers = _without_authorization(_request_headers) + _disable_httpx_authentication(self.httpx_client) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) diff --git a/tests/custom/test_self_hosted_no_auth.py b/tests/custom/test_self_hosted_no_auth.py index 44a34a66..a82acaf8 100644 --- a/tests/custom/test_self_hosted_no_auth.py +++ b/tests/custom/test_self_hosted_no_auth.py @@ -127,6 +127,20 @@ def test_auth_false_sends_no_authorization_over_http() -> None: _assert_no_authorization(seen[0].headers) +def test_auth_false_removes_authorization_from_a_supplied_httpx_client() -> None: + seen: typing.List[httpx.Request] = [] + httpx_client = httpx.Client( + headers={"Authorization": "Token httpx-client"}, + auth=("username", "password"), + transport=_capturing_transport(seen), + ) + client = DeepgramClient(environment=LOCAL, auth=False, httpx_client=httpx_client) + client.manage.v1.models.list() + + _assert_no_authorization(seen[0].headers) + assert httpx_client.auth is None + + async def test_async_auth_false_sends_no_authorization_over_http() -> None: seen: typing.List[httpx.Request] = [] client = AsyncDeepgramClient( @@ -142,6 +156,20 @@ async def test_async_auth_false_sends_no_authorization_over_http() -> None: _assert_no_authorization(seen[0].headers) +async def test_async_auth_false_removes_authorization_from_a_supplied_httpx_client() -> None: + seen: typing.List[httpx.Request] = [] + httpx_client = httpx.AsyncClient( + headers={"Authorization": "Token httpx-client"}, + auth=("username", "password"), + transport=_capturing_transport(seen), + ) + client = AsyncDeepgramClient(environment=LOCAL, auth=False, httpx_client=httpx_client) + await client.manage.v1.models.list() + + _assert_no_authorization(seen[0].headers) + assert httpx_client.auth is None + + def test_auth_false_sends_no_authorization_on_websocket_handshake() -> None: capture = _CaptureConnect() with patch.object(listen_v2_client.websockets_sync_client, "connect", capture): From 9a72c16147a9800d1695ccbe6c38b8802f594a5c Mon Sep 17 00:00:00 2001 From: Greg Holmes Date: Tue, 24 Nov 2026 16:27:59 +0000 Subject: [PATCH 5/8] test(auth): cover HTTP stream header suppression --- tests/custom/test_self_hosted_no_auth.py | 39 ++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/custom/test_self_hosted_no_auth.py b/tests/custom/test_self_hosted_no_auth.py index a82acaf8..ef049fbc 100644 --- a/tests/custom/test_self_hosted_no_auth.py +++ b/tests/custom/test_self_hosted_no_auth.py @@ -141,6 +141,26 @@ def test_auth_false_removes_authorization_from_a_supplied_httpx_client() -> None assert httpx_client.auth is None +def test_auth_false_removes_authorization_from_a_supplied_httpx_client_on_streams() -> None: + seen: typing.List[httpx.Request] = [] + httpx_client = httpx.Client( + headers={"Authorization": "Token httpx-client"}, + auth=("username", "password"), + transport=_capturing_transport(seen), + ) + client = DeepgramClient(environment=LOCAL, auth=False, httpx_client=httpx_client) + + list( + client.speak.v1.audio.generate( + text="test", + request_options={"additional_headers": {"authorization": "Token request-header"}}, + ) + ) + + _assert_no_authorization(seen[0].headers) + assert httpx_client.auth is None + + async def test_async_auth_false_sends_no_authorization_over_http() -> None: seen: typing.List[httpx.Request] = [] client = AsyncDeepgramClient( @@ -170,6 +190,25 @@ async def test_async_auth_false_removes_authorization_from_a_supplied_httpx_clie assert httpx_client.auth is None +async def test_async_auth_false_removes_authorization_from_a_supplied_httpx_client_on_streams() -> None: + seen: typing.List[httpx.Request] = [] + httpx_client = httpx.AsyncClient( + headers={"Authorization": "Token httpx-client"}, + auth=("username", "password"), + transport=_capturing_transport(seen), + ) + client = AsyncDeepgramClient(environment=LOCAL, auth=False, httpx_client=httpx_client) + + async for _ in client.speak.v1.audio.generate( + text="test", + request_options={"additional_headers": {"authorization": "Token request-header"}}, + ): + pass + + _assert_no_authorization(seen[0].headers) + assert httpx_client.auth is None + + def test_auth_false_sends_no_authorization_on_websocket_handshake() -> None: capture = _CaptureConnect() with patch.object(listen_v2_client.websockets_sync_client, "connect", capture): From 308df642b3ff927144821172f0f865057e2e76fe Mon Sep 17 00:00:00 2001 From: Greg Holmes Date: Tue, 24 Nov 2026 16:30:00 +0000 Subject: [PATCH 6/8] docs(regen): record no-auth frozen files --- AGENTS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 22bd9987..576e7610 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,6 +45,7 @@ Current permanently frozen files: - `tests/custom/test_query_encoder.py` — hand-written regression test that `core/query_encoder.py` coerces Python bools to lowercase `"true"`/`"false"` before `urlencode` so websocket query strings stay wire-correct - `tests/custom/test_regen_response_fields.py` — hand-written regression test guarding response fields added by recent regenerations: `ListenV1Response/ResultsMetadata.diarize_info` (`model_uuid`, `arch`), per-word `speaker` / `speaker_confidence`, Nova-3 multilingual `languages` / `languages_hinted` / word and utterance `language`, and `ListenV2TurnInfo.trigger`. Same rationale as `test_latency_report_stt_compat.py`: `UncheckedBaseModel` + `skip_validation` makes response parsing lenient, so a future spec removal would silently turn these into `None` rather than failing. Fixtures are real captured payloads; the `trigger` cases pin the parsing contract for the values the server sends (`model` / `manual` / `timeout`) plus the absent case, which is what a deployment without ForceEndTurn enabled (self-hosted without the feature flag) returns. Live coverage of the same field lives in `tests/manual/listen/v2/force_end_turn/` - `tests/custom/test_secure_logging.py` — hand-written regression test that the `websockets` Authorization-header DEBUG logs are redacted (API key never logged in clear text) +- `tests/custom/test_self_hosted_no_auth.py` — hand-written regression coverage for `auth=False` against generated API-key headers, caller-provided and per-request HTTP headers, supplied HTTPX client defaults/auth, HTTP streams, public/raw WebSocket paths, and custom transports. Keeps the self-hosted no-auth guarantee intact across sync and async clients. - `tests/custom/test_socket_unknown_fallback.py` — hand-written regression coverage that every generated socket client returns an unknown server frame as a dictionary; Speak V1 remains a strict expected failure until Fern fixes the undiscriminated-union coercion tracked above - `tests/custom/test_speak_v2_interrupt_configure.py` — hand-written coverage for the Speak V2 barge-in / mid-stream reconfigure surface (`send_interrupt`, `send_configure`, `SpeechInterrupted`, `ConfigureSuccess`/`ConfigureFailure`, and the `speed`/`expressivity` connect params) - `tests/custom/test_voice_agent_force_end_turn_example.py` — hand-written regression coverage that the Voice Agent ForceEndTurn example waits for a rejection queued after `AgentAudioDone` @@ -77,6 +78,7 @@ Current temporarily frozen files: - `src/deepgram/agent/v1/types/agent_v1settings_agent_context.py`, `src/deepgram/agent/v1/types/agent_v1settings_agent.py`, `src/deepgram/agent/v1/types/agent_v1settings.py`, `src/deepgram/agent/v1/requests/agent_v1settings_agent_context.py`, `src/deepgram/agent/v1/requests/agent_v1settings_agent.py`, `src/deepgram/agent/v1/requests/agent_v1settings.py` — backward-compat patches for the 2026-05-05 Agent Settings schema restructure. These preserve callable `AgentV1SettingsAgent(...)`, keep `AgentV1Settings.agent` accepting both that wrapper and `agent_id` strings, restore the legacy request TypedDict shapes, remap legacy `messages=[...]` / nested `context=AgentV1SettingsAgentContext(messages=[...])` usage into the new `context={"messages": [...]}` wire shape, and keep read-side `obj.messages` access working. - `src/deepgram/core/api_error.py`, `src/deepgram/core/parse_error.py` — credential redaction. Every websocket `connect()` path raises `ApiError(headers=dict(headers), ...)` with the full request headers, and both error types stringify that dict, so an unredacted `Authorization` reached `str(e)`, tracebacks, log aggregators and error trackers (which serialise attributes as well as the message). Both now mask credential values at construction via `_secure_logging.redact_sensitive_headers`, preserving non-sensitive headers (`dg-request-id`) for debugging. This is the same threat `_secure_logging.py` covers for the `websockets` DEBUG handshake logs, via the other path to it. Regression coverage in `tests/custom/test_api_error_redaction.py`. Unfreeze if the generator starts redacting credentials itself. - `src/deepgram/core/query_encoder.py` — coerces Python bools to lowercase `"true"`/`"false"` before they reach `urllib.parse.urlencode` (which would otherwise produce `"True"`/`"False"` via `str()` and break websocket query strings). Only the four `*/connect()` paths call `urlencode`; HTTP raw clients hand params to httpx, which lowercases bools itself, so the patch is a no-op for the HTTP path. Once Fern's websocket codegen normalizes bools (or the spec types these as `boolean` end-to-end), this can be unfrozen. +- `src/deepgram/core/http_client.py` — `auth=False` removes `Authorization` after generated endpoints merge their base, endpoint, and request-option headers, and disables credentials configured directly on a caller-provided HTTPX client. Unfreeze when Fern exposes a no-auth client mode. - `src/deepgram/listen/v2/types/listen_v2connected.py`, `src/deepgram/listen/v2/types/listen_v2turn_info.py`, `src/deepgram/listen/v2/types/listen_v2turn_info_words_item.py`, `src/deepgram/listen/v2/types/listen_v2configure_success.py`, `src/deepgram/listen/v2/types/listen_v2configure_success_thresholds.py`, `src/deepgram/listen/v2/types/listen_v2configure_failure.py`, `src/deepgram/listen/v2/types/listen_v2fatal_error.py`, `src/deepgram/listen/v2/types/listen_v2warning.py` — read-side compatibility for the SDK 7.7 Listen V2 response retype. Through 7.6, `V2SocketClientResponse` contained `typing.Any`, so every response was returned as a raw dict; fixing the union made responses typed models and broke callers using `response["field"]`. These generated response classes inherit the hand-written base above, preserving read-only wire-key subscript access alongside canonical attribute access. Restore direct `UncheckedBaseModel` inheritance and unfreeze these files in the next major release. - `src/deepgram/types/deepgram_listen_provider_v2.py`, `src/deepgram/agent/v1/types/agent_v1settings_agent_listen_provider.py`, `src/deepgram/agent/v1/types/agent_v1settings_agent_context_listen_provider.py` — behavioural back-compat shim for the `language_hint` -> `language_hints` rename (2026-06-15 regen). The public field was historically (incorrectly) singular and accepted a str or a list; the API field is `language_hints` (a list, and the server uses `deny_unknown_fields` so the singular key is rejected on the wire). Each carries a hand-added `model_validator(mode='before')` / `root_validator(pre=True)` that remaps a legacy `language_hint=` kwarg and drops the dead singular key. Remove and unfreeze the language alias when it is retired in a future major. - `src/deepgram/types/shared_topics.py`, `src/deepgram/types/shared_intents.py`, `src/deepgram/requests/shared_topics.py`, `src/deepgram/requests/shared_intents.py`, and the generated root/type/request barrels — direct Topics and Intents segments plus their generated exports remain Fern-owned, but carry the v7 deprecated `results` construction facade and Params shape for the hand-written wrappers above. The models normalize legacy `results.{topics,intents}.segments` input to direct `segments` while preserving direct fields and deprecated read facades. Freeze these generated files during the parent reconciliation; retain all direct generated segments and exports alongside the compatibility surface. From ccbfc250d863f73ac9c699c2fbd39c6922c49184 Mon Sep 17 00:00:00 2001 From: Greg Holmes Date: Wed, 25 Nov 2026 14:22:40 +0000 Subject: [PATCH 7/8] fix(auth): preserve shared httpx client authentication --- .fernignore | 5 - AGENTS.md | 1 - README.md | 4 +- src/deepgram/client.py | 74 +++++++++++-- src/deepgram/core/http_client.py | 35 ------ tests/custom/test_self_hosted_no_auth.py | 132 ++++++++++++++++++----- 6 files changed, 175 insertions(+), 76 deletions(-) diff --git a/.fernignore b/.fernignore index 7e26f766..65bd927c 100644 --- a/.fernignore +++ b/.fernignore @@ -10,11 +10,6 @@ # This file is manually maintained and should not be regenerated src/deepgram/client.py -# ``auth=False`` needs an HTTP final-header filter because generated endpoint -# and request-option headers are merged after the custom client's base headers. -# [temporarily frozen — remove when Fern exposes a no-auth client mode] -src/deepgram/core/http_client.py - # Hand-written security utility: installs a logging.Filter on the third-party # `websockets` client/server loggers that masks the Authorization header (API # key / access token) in DEBUG handshake logs. No Fern-generated counterpart. diff --git a/AGENTS.md b/AGENTS.md index 576e7610..acd7dc4b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,7 +78,6 @@ Current temporarily frozen files: - `src/deepgram/agent/v1/types/agent_v1settings_agent_context.py`, `src/deepgram/agent/v1/types/agent_v1settings_agent.py`, `src/deepgram/agent/v1/types/agent_v1settings.py`, `src/deepgram/agent/v1/requests/agent_v1settings_agent_context.py`, `src/deepgram/agent/v1/requests/agent_v1settings_agent.py`, `src/deepgram/agent/v1/requests/agent_v1settings.py` — backward-compat patches for the 2026-05-05 Agent Settings schema restructure. These preserve callable `AgentV1SettingsAgent(...)`, keep `AgentV1Settings.agent` accepting both that wrapper and `agent_id` strings, restore the legacy request TypedDict shapes, remap legacy `messages=[...]` / nested `context=AgentV1SettingsAgentContext(messages=[...])` usage into the new `context={"messages": [...]}` wire shape, and keep read-side `obj.messages` access working. - `src/deepgram/core/api_error.py`, `src/deepgram/core/parse_error.py` — credential redaction. Every websocket `connect()` path raises `ApiError(headers=dict(headers), ...)` with the full request headers, and both error types stringify that dict, so an unredacted `Authorization` reached `str(e)`, tracebacks, log aggregators and error trackers (which serialise attributes as well as the message). Both now mask credential values at construction via `_secure_logging.redact_sensitive_headers`, preserving non-sensitive headers (`dg-request-id`) for debugging. This is the same threat `_secure_logging.py` covers for the `websockets` DEBUG handshake logs, via the other path to it. Regression coverage in `tests/custom/test_api_error_redaction.py`. Unfreeze if the generator starts redacting credentials itself. - `src/deepgram/core/query_encoder.py` — coerces Python bools to lowercase `"true"`/`"false"` before they reach `urllib.parse.urlencode` (which would otherwise produce `"True"`/`"False"` via `str()` and break websocket query strings). Only the four `*/connect()` paths call `urlencode`; HTTP raw clients hand params to httpx, which lowercases bools itself, so the patch is a no-op for the HTTP path. Once Fern's websocket codegen normalizes bools (or the spec types these as `boolean` end-to-end), this can be unfrozen. -- `src/deepgram/core/http_client.py` — `auth=False` removes `Authorization` after generated endpoints merge their base, endpoint, and request-option headers, and disables credentials configured directly on a caller-provided HTTPX client. Unfreeze when Fern exposes a no-auth client mode. - `src/deepgram/listen/v2/types/listen_v2connected.py`, `src/deepgram/listen/v2/types/listen_v2turn_info.py`, `src/deepgram/listen/v2/types/listen_v2turn_info_words_item.py`, `src/deepgram/listen/v2/types/listen_v2configure_success.py`, `src/deepgram/listen/v2/types/listen_v2configure_success_thresholds.py`, `src/deepgram/listen/v2/types/listen_v2configure_failure.py`, `src/deepgram/listen/v2/types/listen_v2fatal_error.py`, `src/deepgram/listen/v2/types/listen_v2warning.py` — read-side compatibility for the SDK 7.7 Listen V2 response retype. Through 7.6, `V2SocketClientResponse` contained `typing.Any`, so every response was returned as a raw dict; fixing the union made responses typed models and broke callers using `response["field"]`. These generated response classes inherit the hand-written base above, preserving read-only wire-key subscript access alongside canonical attribute access. Restore direct `UncheckedBaseModel` inheritance and unfreeze these files in the next major release. - `src/deepgram/types/deepgram_listen_provider_v2.py`, `src/deepgram/agent/v1/types/agent_v1settings_agent_listen_provider.py`, `src/deepgram/agent/v1/types/agent_v1settings_agent_context_listen_provider.py` — behavioural back-compat shim for the `language_hint` -> `language_hints` rename (2026-06-15 regen). The public field was historically (incorrectly) singular and accepted a str or a list; the API field is `language_hints` (a list, and the server uses `deny_unknown_fields` so the singular key is rejected on the wire). Each carries a hand-added `model_validator(mode='before')` / `root_validator(pre=True)` that remaps a legacy `language_hint=` kwarg and drops the dead singular key. Remove and unfreeze the language alias when it is retired in a future major. - `src/deepgram/types/shared_topics.py`, `src/deepgram/types/shared_intents.py`, `src/deepgram/requests/shared_topics.py`, `src/deepgram/requests/shared_intents.py`, and the generated root/type/request barrels — direct Topics and Intents segments plus their generated exports remain Fern-owned, but carry the v7 deprecated `results` construction facade and Params shape for the hand-written wrappers above. The models normalize legacy `results.{topics,intents}.segments` input to direct `segments` while preserving direct fields and deprecated read facades. Freeze these generated files during the parent reconciliation; retain all direct generated segments and exports alongside the compatibility surface. diff --git a/README.md b/README.md index 07bc415b..151be69f 100644 --- a/README.md +++ b/README.md @@ -231,7 +231,7 @@ The SDK automatically discovers credentials from these environment variables: **Precedence:** Explicit parameters > Environment variables -### Self-Hosted and Local Servers Without Authentication +### Self-Hosted Servers Without Authentication A self-hosted or local Deepgram server may not require request authentication. Point the client at it with a custom environment and pass `auth=False` so the SDK doesn't ask for an API key: @@ -252,6 +252,8 @@ client = DeepgramClient( With `auth=False` no `Authorization` header is sent on HTTP requests or WebSocket connections, and `DEEPGRAM_API_KEY` is ignored. It can't be combined with `api_key` or `access_token`; if your server does require a key, pass `api_key` as usual. +If you pass your own `httpx_client` with `auth=False`, the SDK removes authentication only from its requests to the configured Deepgram server. Other requests made with that client keep their `Authorization` header and `auth` setting. + ## Async Client The SDK provides full async/await support for non-blocking operations: diff --git a/src/deepgram/client.py b/src/deepgram/client.py index 0ebfb8fc..ee7e1563 100644 --- a/src/deepgram/client.py +++ b/src/deepgram/client.py @@ -32,6 +32,7 @@ import uuid from typing import Any, Callable, Dict, Optional +import httpx from ._secure_logging import install_websocket_log_redaction from .base_client import AsyncBaseClient, BaseClient from .core.api_error import ApiError @@ -78,7 +79,60 @@ def _get_headers_with_bearer(_self: Any) -> Dict[str, str]: client_wrapper.httpx_client.base_headers = client_wrapper.get_headers -def _apply_no_authorization_override(client_wrapper: BaseClientWrapper) -> None: +def _origin(url: str) -> Optional[tuple[str, str, Optional[int]]]: + try: + parsed = urllib.parse.urlparse(url) + if parsed.scheme not in ("http", "https") or parsed.hostname is None: + return None + scheme = parsed.scheme.lower() + port = parsed.port + if (scheme == "http" and port == 80) or (scheme == "https" and port == 443): + port = None + return scheme, parsed.hostname.lower(), port + except ValueError: + return None + + +def _environment_origins(environment: Any) -> set[tuple[str, str, Optional[int]]]: + return { + origin + for name in ("base", "agent_rest") + if isinstance(url := getattr(environment, name, None), str) + if (origin := _origin(url)) is not None + } + + +def _remove_authorization_from_request( + request: httpx.Request, target_origins: set[tuple[str, str, Optional[int]]], session_id: str +) -> None: + request_origin = (request.url.scheme, request.url.host, request.url.port) + if request_origin not in target_origins or request.headers.get("x-deepgram-session-id") != session_id: + return + + for header in list(request.headers): + if header.lower() == "authorization": + del request.headers[header] + + +def _install_no_authorization_request_hook( + httpx_client: Any, target_origins: set[tuple[str, str, Optional[int]]], session_id: str +) -> None: + """Strip Authorization only from this client's requests to its Deepgram origins.""" + + def sync_request_hook(request: httpx.Request) -> None: + _remove_authorization_from_request(request, target_origins, session_id) + + if isinstance(httpx_client, httpx.AsyncClient): + + async def async_request_hook(request: httpx.Request) -> None: + _remove_authorization_from_request(request, target_origins, session_id) + + httpx_client.event_hooks.setdefault("request", []).append(async_request_hook) + else: + httpx_client.event_hooks.setdefault("request", []).append(sync_request_hook) + + +def _apply_no_authorization_override(client_wrapper: BaseClientWrapper, session_id: str) -> None: """Drop the Authorization header from every HTTP and WebSocket request (``auth=False``).""" original_get_headers = client_wrapper.get_headers @@ -92,10 +146,11 @@ def _get_headers_without_auth(_self: Any) -> Dict[str, str]: if hasattr(client_wrapper, "httpx_client") and hasattr(client_wrapper.httpx_client, "base_headers"): client_wrapper.httpx_client.base_headers = client_wrapper.get_headers - # HTTP clients merge endpoint and request-option headers after - # ``base_headers``. Mark this client so the final merged map also drops - # Authorization before the request is sent. - client_wrapper.httpx_client.disable_authentication() # type: ignore[attr-defined] + _install_no_authorization_request_hook( + client_wrapper.httpx_client.httpx_client, + _environment_origins(client_wrapper.get_environment()), + session_id, + ) _MISSING_KEY_MESSAGE = "The client must be instantiated by either passing in api_key or setting DEEPGRAM_API_KEY" @@ -139,7 +194,10 @@ def _resolve_credentials(kwargs: Dict[str, Any], access_token: Optional[str], au replaced (Bearer) or removed after construction. """ if auth is not None and auth is not False: - raise ValueError("auth only accepts False, to disable authentication for self-hosted servers") + raise ValueError( + "auth only accepts False, which disables authentication for self-hosted servers. " + "To authenticate, omit auth and pass api_key or access_token." + ) environment = kwargs.get("environment") if auth is False: @@ -228,7 +286,7 @@ def __init__(self, *args, **kwargs) -> None: if access_token is not None: _apply_bearer_authorization_override(self._client_wrapper, access_token) elif auth is False: - _apply_no_authorization_override(self._client_wrapper) + _apply_no_authorization_override(self._client_wrapper, final_session_id) # Install custom WebSocket transport if provided. Auto-disable # `reconnect`: a custom transport owns its retry lifecycle, so flip @@ -307,7 +365,7 @@ def __init__(self, *args, **kwargs) -> None: if access_token is not None: _apply_bearer_authorization_override(self._client_wrapper, access_token) elif auth is False: - _apply_no_authorization_override(self._client_wrapper) + _apply_no_authorization_override(self._client_wrapper, final_session_id) # Install custom WebSocket transport if provided. Auto-disable # `reconnect`: a custom transport owns its retry lifecycle, so flip diff --git a/src/deepgram/core/http_client.py b/src/deepgram/core/http_client.py index 4d1278cb..2cac2aec 100644 --- a/src/deepgram/core/http_client.py +++ b/src/deepgram/core/http_client.py @@ -187,19 +187,6 @@ def _should_retry(response: httpx.Response) -> bool: _AUTH_HEADERS: typing.FrozenSet[str] = frozenset({"authorization"}) -def _without_authorization(headers: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]: - """Remove Authorization headers case-insensitively for no-auth clients.""" - return {key: value for key, value in headers.items() if key.lower() != "authorization"} - - -def _disable_httpx_authentication(client: typing.Union[httpx.Client, httpx.AsyncClient]) -> None: - """Remove authentication configured directly on a caller-provided HTTPX client.""" - for key in list(client.headers): - if key.lower() == "authorization": - del client.headers[key] - client.auth = None - - def _redact_headers(headers: typing.Dict[str, str]) -> typing.Dict[str, str]: return { k: ("[REDACTED]" if k.lower() in _SENSITIVE_HEADERS or k.lower() in _AUTH_HEADERS else v) @@ -382,11 +369,6 @@ def __init__( self.base_max_retries = base_max_retries self.httpx_client = httpx_client self.logger = create_logger(logging_config) - self.auth_disabled = False - - def disable_authentication(self) -> None: - self.auth_disabled = True - _disable_httpx_authentication(self.httpx_client) def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = maybe_base_url @@ -475,9 +457,6 @@ def request( ) ) ) - if self.auth_disabled: - _request_headers = _without_authorization(_request_headers) - _disable_httpx_authentication(self.httpx_client) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) @@ -652,9 +631,6 @@ def stream( ) ) ) - if self.auth_disabled: - _request_headers = _without_authorization(_request_headers) - _disable_httpx_authentication(self.httpx_client) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) @@ -700,11 +676,6 @@ def __init__( self.async_base_headers = async_base_headers self.httpx_client = httpx_client self.logger = create_logger(logging_config) - self.auth_disabled = False - - def disable_authentication(self) -> None: - self.auth_disabled = True - _disable_httpx_authentication(self.httpx_client) async def _get_headers(self) -> typing.Dict[str, str]: if self.async_base_headers is not None: @@ -801,9 +772,6 @@ async def request( ) ) ) - if self.auth_disabled: - _request_headers = _without_authorization(_request_headers) - _disable_httpx_authentication(self.httpx_client) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) @@ -981,9 +949,6 @@ async def stream( ) ) ) - if self.auth_disabled: - _request_headers = _without_authorization(_request_headers) - _disable_httpx_authentication(self.httpx_client) _request_headers = drop_content_type_without_body( _request_headers, json_body=json_body, data_body=data_body, optional_body=optional_body ) diff --git a/tests/custom/test_self_hosted_no_auth.py b/tests/custom/test_self_hosted_no_auth.py index ef049fbc..dd8fa89e 100644 --- a/tests/custom/test_self_hosted_no_auth.py +++ b/tests/custom/test_self_hosted_no_auth.py @@ -19,8 +19,16 @@ import httpx import pytest +import deepgram.agent.v1.client as agent_v1_client +import deepgram.agent.v1.raw_client as agent_v1_raw_client +import deepgram.listen.v1.client as listen_v1_client +import deepgram.listen.v1.raw_client as listen_v1_raw_client import deepgram.listen.v2.client as listen_v2_client import deepgram.listen.v2.raw_client as listen_v2_raw_client +import deepgram.speak.v1.client as speak_v1_client +import deepgram.speak.v1.raw_client as speak_v1_raw_client +import deepgram.speak.v2.client as speak_v2_client +import deepgram.speak.v2.raw_client as speak_v2_raw_client from deepgram import AsyncDeepgramClient, DeepgramClient from deepgram.core.api_error import ApiError from deepgram.environment import DeepgramClientEnvironment @@ -82,6 +90,60 @@ def _assert_no_authorization(headers: typing.Mapping[str, str]) -> None: assert all(key.lower() != "authorization" for key in headers) +def _connection_options(model: typing.Optional[str] = None) -> typing.Dict[str, typing.Any]: + options: typing.Dict[str, typing.Any] = { + "authorization": "Token connect-argument", + "request_options": {"additional_headers": {"Authorization": "Token request-header"}}, + } + if model is not None: + options["model"] = model + return options + + +_WEBSOCKET_CASES = [ + ( + "listen v1", + listen_v1_client, + listen_v1_raw_client, + lambda client: client.listen.v1.connect(**_connection_options("nova-3")), + lambda client: client.listen.v1.with_raw_response.connect(**_connection_options("nova-3")), + "/v1/listen", + ), + ( + "listen v2", + listen_v2_client, + listen_v2_raw_client, + lambda client: client.listen.v2.connect(**_connection_options("flux-general-en")), + lambda client: client.listen.v2.with_raw_response.connect(**_connection_options("flux-general-en")), + "/v2/listen", + ), + ( + "speak v1", + speak_v1_client, + speak_v1_raw_client, + lambda client: client.speak.v1.connect(**_connection_options("aura-2-thalia-en")), + lambda client: client.speak.v1.with_raw_response.connect(**_connection_options("aura-2-thalia-en")), + "/v1/speak", + ), + ( + "speak v2", + speak_v2_client, + speak_v2_raw_client, + lambda client: client.speak.v2.connect(**_connection_options("aura-2-thalia-en")), + lambda client: client.speak.v2.with_raw_response.connect(**_connection_options("aura-2-thalia-en")), + "/v2/speak", + ), + ( + "agent v1", + agent_v1_client, + agent_v1_raw_client, + lambda client: client.agent.v1.connect(**_connection_options()), + lambda client: client.agent.v1.with_raw_response.connect(**_connection_options()), + "/v1/agent/converse", + ), +] + + # --------------------------------------------------------------------------- construction @@ -127,7 +189,7 @@ def test_auth_false_sends_no_authorization_over_http() -> None: _assert_no_authorization(seen[0].headers) -def test_auth_false_removes_authorization_from_a_supplied_httpx_client() -> None: +def test_auth_false_only_strips_authorization_from_its_own_httpx_requests() -> None: seen: typing.List[httpx.Request] = [] httpx_client = httpx.Client( headers={"Authorization": "Token httpx-client"}, @@ -138,10 +200,13 @@ def test_auth_false_removes_authorization_from_a_supplied_httpx_client() -> None client.manage.v1.models.list() _assert_no_authorization(seen[0].headers) - assert httpx_client.auth is None + assert httpx_client.auth is not None + httpx_client.get("http://127.0.0.1:8000/not-an-sdk-request") + assert "authorization" in seen[1].headers -def test_auth_false_removes_authorization_from_a_supplied_httpx_client_on_streams() -> None: + +def test_auth_false_only_strips_authorization_from_its_own_httpx_streams() -> None: seen: typing.List[httpx.Request] = [] httpx_client = httpx.Client( headers={"Authorization": "Token httpx-client"}, @@ -158,7 +223,7 @@ def test_auth_false_removes_authorization_from_a_supplied_httpx_client_on_stream ) _assert_no_authorization(seen[0].headers) - assert httpx_client.auth is None + assert httpx_client.auth is not None async def test_async_auth_false_sends_no_authorization_over_http() -> None: @@ -176,7 +241,7 @@ async def test_async_auth_false_sends_no_authorization_over_http() -> None: _assert_no_authorization(seen[0].headers) -async def test_async_auth_false_removes_authorization_from_a_supplied_httpx_client() -> None: +async def test_async_auth_false_only_strips_authorization_from_its_own_httpx_requests() -> None: seen: typing.List[httpx.Request] = [] httpx_client = httpx.AsyncClient( headers={"Authorization": "Token httpx-client"}, @@ -187,10 +252,13 @@ async def test_async_auth_false_removes_authorization_from_a_supplied_httpx_clie await client.manage.v1.models.list() _assert_no_authorization(seen[0].headers) - assert httpx_client.auth is None + assert httpx_client.auth is not None + + await httpx_client.get("http://127.0.0.1:8000/not-an-sdk-request") + assert "authorization" in seen[1].headers -async def test_async_auth_false_removes_authorization_from_a_supplied_httpx_client_on_streams() -> None: +async def test_async_auth_false_only_strips_authorization_from_its_own_httpx_streams() -> None: seen: typing.List[httpx.Request] = [] httpx_client = httpx.AsyncClient( headers={"Authorization": "Token httpx-client"}, @@ -206,34 +274,46 @@ async def test_async_auth_false_removes_authorization_from_a_supplied_httpx_clie pass _assert_no_authorization(seen[0].headers) - assert httpx_client.auth is None + assert httpx_client.auth is not None -def test_auth_false_sends_no_authorization_on_websocket_handshake() -> None: +@pytest.mark.parametrize( + "_name,client_module,_raw_client_module,connect,_raw_connect,path", + _WEBSOCKET_CASES, +) +def test_auth_false_sends_no_authorization_on_websocket_handshakes( + _name: str, + client_module: typing.Any, + _raw_client_module: typing.Any, + connect: typing.Callable[[DeepgramClient], typing.ContextManager[typing.Any]], + _raw_connect: typing.Callable[[DeepgramClient], typing.ContextManager[typing.Any]], + path: str, +) -> None: capture = _CaptureConnect() - with patch.object(listen_v2_client.websockets_sync_client, "connect", capture): - with DeepgramClient( - environment=LOCAL, auth=False, headers={"authorization": "Token client-header"} - ).listen.v2.connect( - model="flux-general-en", - authorization="Token connect-argument", - request_options={"additional_headers": {"Authorization": "Token request-header"}}, - ): + with patch.object(client_module.websockets_sync_client, "connect", capture): + with connect(DeepgramClient(environment=LOCAL, auth=False, headers={"authorization": "Token client-header"})): pass - assert capture.url is not None and capture.url.startswith("ws://127.0.0.1:8000/v2/listen") + assert capture.url is not None and capture.url.startswith(f"ws://127.0.0.1:8000{path}") _assert_no_authorization(capture.headers) assert "x-deepgram-session-id" in capture.headers -async def test_async_auth_false_sends_no_authorization_on_websocket_handshake() -> None: +@pytest.mark.parametrize( + "_name,_client_module,raw_client_module,_connect,raw_connect,_path", + _WEBSOCKET_CASES, +) +async def test_async_auth_false_sends_no_authorization_on_websocket_handshakes( + _name: str, + _client_module: typing.Any, + raw_client_module: typing.Any, + _connect: typing.Callable[[AsyncDeepgramClient], typing.AsyncContextManager[typing.Any]], + raw_connect: typing.Callable[[AsyncDeepgramClient], typing.AsyncContextManager[typing.Any]], + _path: str, +) -> None: capture = _CaptureConnect() - with patch.object(listen_v2_raw_client, "websockets_client_connect", capture): - async with AsyncDeepgramClient( - environment=LOCAL, auth=False, headers={"authorization": "Token client-header"} - ).listen.v2.with_raw_response.connect( - model="flux-general-en", - authorization="Token connect-argument", - request_options={"additional_headers": {"Authorization": "Token request-header"}}, + with patch.object(raw_client_module, "websockets_client_connect", capture): + async with raw_connect( + AsyncDeepgramClient(environment=LOCAL, auth=False, headers={"authorization": "Token client-header"}) ): pass _assert_no_authorization(capture.headers) From 838df8dc4f3ba889902afcd841cba62186ef2916 Mon Sep 17 00:00:00 2001 From: Corey Weathers Date: Wed, 25 Nov 2026 11:59:18 -0500 Subject: [PATCH 8/8] fix(auth): normalize request origin before the no-auth match httpx keeps an explicit default port when the URL scheme is uppercase, so an environment base like HTTP://localhost:80 produced request.url.port == 80 while _origin had normalized it to None and the Authorization strip was skipped. Run the request URL through the same helper so both sides agree. Co-Authored-By: Claude Fable 5.1 --- src/deepgram/client.py | 4 +++- tests/custom/test_self_hosted_no_auth.py | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/deepgram/client.py b/src/deepgram/client.py index ee7e1563..c64f9f13 100644 --- a/src/deepgram/client.py +++ b/src/deepgram/client.py @@ -105,7 +105,9 @@ def _environment_origins(environment: Any) -> set[tuple[str, str, Optional[int]] def _remove_authorization_from_request( request: httpx.Request, target_origins: set[tuple[str, str, Optional[int]]], session_id: str ) -> None: - request_origin = (request.url.scheme, request.url.host, request.url.port) + # Normalize the request URL with the same helper used for the environment so an + # explicit default port survives httpx's scheme-case-sensitive port handling. + request_origin = _origin(str(request.url)) if request_origin not in target_origins or request.headers.get("x-deepgram-session-id") != session_id: return diff --git a/tests/custom/test_self_hosted_no_auth.py b/tests/custom/test_self_hosted_no_auth.py index dd8fa89e..e463b627 100644 --- a/tests/custom/test_self_hosted_no_auth.py +++ b/tests/custom/test_self_hosted_no_auth.py @@ -189,6 +189,28 @@ def test_auth_false_sends_no_authorization_over_http() -> None: _assert_no_authorization(seen[0].headers) +def test_auth_false_matches_origin_with_uppercase_scheme_and_default_port() -> None: + # httpx keeps an explicit default port when the scheme is uppercase, so the hook + # must normalize the request URL the same way it normalizes the environment. + seen: typing.List[httpx.Request] = [] + environment = DeepgramClientEnvironment( + base="HTTP://localhost:80", + production="ws://localhost:80", + agent="ws://localhost:80", + agent_rest="HTTP://localhost:80", + ) + client = DeepgramClient( + environment=environment, + auth=False, + httpx_client=httpx.Client( + headers={"Authorization": "Token httpx-client"}, transport=_capturing_transport(seen) + ), + ) + client.manage.v1.models.list(request_options={"additional_headers": {"Authorization": "Token request-header"}}) + assert len(seen) == 1 + _assert_no_authorization(seen[0].headers) + + def test_auth_false_only_strips_authorization_from_its_own_httpx_requests() -> None: seen: typing.List[httpx.Request] = [] httpx_client = httpx.Client(