diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index aa3e755..79f1423 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -142,7 +142,10 @@ def __init__( api_key: Optional[str] = None, base_url: str = "https://api.fish.audio", ): - self.api_key = api_key or os.getenv("FISH_API_KEY") + # Without the whitespace around it: a key read from a file or an + # environment variable often ends with a newline, which httpx refuses + # with an error that prints the whole Authorization header. + self.api_key = (api_key or os.getenv("FISH_API_KEY") or "").strip() if not self.api_key: raise ValueError( "API key must be provided either as argument or via FISH_API_KEY environment variable" diff --git a/tests/unit/test_core.py b/tests/unit/test_core.py index 85bec3a..5f20d72 100644 --- a/tests/unit/test_core.py +++ b/tests/unit/test_core.py @@ -125,6 +125,34 @@ def test_get_headers_with_additional(self, mock_api_key): assert headers["Authorization"] == f"Bearer {mock_api_key}" +class TestApiKeyWhitespace: + """A key read from a file or the environment often ends with a newline.""" + + @pytest.mark.parametrize("source", ["argument", "environment"]) + def test_whitespace_around_the_key_is_not_sent(self, monkeypatch, source): + seen = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request.headers["authorization"]) + return httpx.Response(200, json={}) + + http = httpx.Client( + base_url="https://api.test", transport=httpx.MockTransport(handler) + ) + if source == "argument": + wrapper = ClientWrapper(api_key=" secret-key\r\n", httpx_client=http) + else: + monkeypatch.setenv("FISH_API_KEY", "secret-key\n") + wrapper = ClientWrapper(httpx_client=http) + wrapper.request("GET", "/x") + assert seen == ["Bearer secret-key"] + + def test_a_key_of_only_whitespace_is_missing(self, monkeypatch): + monkeypatch.delenv("FISH_API_KEY", raising=False) + with pytest.raises(ValueError, match="API key must be provided"): + ClientWrapper(api_key=" \n") + + class TestRequestHeaders: """Headers passed by a method win over RequestOptions, whatever their case."""