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/AGENTS.md b/AGENTS.md index 22bd9987..acd7dc4b 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` diff --git a/README.md b/README.md index 95d94023..151be69f 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,29 @@ The SDK automatically discovers credentials from these environment variables: **Precedence:** Explicit parameters > Environment variables +### 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: + +```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. + +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 0a603832..c64f9f13 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,9 +28,11 @@ import os import types +import urllib.parse 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 @@ -35,6 +41,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. @@ -57,6 +79,150 @@ def _get_headers_with_bearer(_self: Any) -> Dict[str, str]: client_wrapper.httpx_client.base_headers = client_wrapper.get_headers +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: + # 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 + + 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 + + def _get_headers_without_auth(_self: Any) -> Dict[str, str]: + # 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 + _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" +_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. + + 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. + """ + 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 False + 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, 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: + 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 +231,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 +251,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 +278,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, final_session_id) # Install custom WebSocket transport if provided. Auto-disable # `reconnect`: a custom transport owns its retry lifecycle, so flip @@ -155,6 +310,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 +330,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 +357,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, final_session_id) # 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..e463b627 --- /dev/null +++ b/tests/custom/test_self_hosted_no_auth.py @@ -0,0 +1,438 @@ +""" +``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.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 +from deepgram.transport import restore_transport + +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 + + +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) + return httpx.Response(200, json={}) + + return httpx.MockTransport(handler) + + +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 + + +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, + headers={"authorization": "Token client-header"}, + httpx_client=httpx.Client(transport=_capturing_transport(seen)), + ) + 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_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( + 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 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_only_strips_authorization_from_its_own_httpx_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 not None + + +async def test_async_auth_false_sends_no_authorization_over_http() -> None: + seen: typing.List[httpx.Request] = [] + client = AsyncDeepgramClient( + 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"}} + ) + assert len(seen) == 1 + _assert_no_authorization(seen[0].headers) + + +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"}, + 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 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_only_strips_authorization_from_its_own_httpx_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 not 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(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(f"ws://127.0.0.1:8000{path}") + _assert_no_authorization(capture.headers) + assert "x-deepgram-session-id" in capture.headers + + +@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(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) + + +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: + 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) + + +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