Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/fishaudio/core/client_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down
Loading