From f58580347a9de2df8cdff268548f91e2e0c699d1 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:47:45 -0800 Subject: [PATCH] fix: ignore whitespace around the API key A key read from a file or an environment variable often ends with a newline. httpx refused the resulting Authorization header with an error that printed it, key included. The key is now stripped where it is read, so such a key simply works. --- src/fishaudio/core/client_wrapper.py | 5 ++++- tests/unit/test_core.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index be74c73..a321e9c 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -57,7 +57,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 ce38383..b1879e6 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."""