Skip to content
Closed
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
3 changes: 2 additions & 1 deletion saas_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ async def require_api_key(request: Request, call_next):
if configured_keys and not (request.method == "GET" and request.url.path == "/"):
provided_key = request.headers.get("x-api-key", "")
if not any(
hmac.compare_digest(provided_key, key) for key in configured_keys
hmac.compare_digest(provided_key.encode("utf-8"), key.encode("utf-8"))
for key in configured_keys
):
return JSONResponse(
status_code=401,
Expand Down
23 changes: 23 additions & 0 deletions tests/test_saas_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,29 @@ def test_missing_header_rejected_when_keys_configured(self):
self.assertEqual(response.json(), {"error": "Invalid or missing API key"})
self.assertNotIn("secret-key", response.text)

def test_non_ascii_key_does_not_crash(self):
with patch.dict(os.environ, {"CODEC_CARVER_API_KEYS": "secret-key"}):
# Using raw ASGI scope to bypass HTTPX ASCII limitations on headers
import fastapi
import asyncio
import json
import saas_web
scope = {
"type": "http",
"method": "POST",
"path": "/shrink",
"headers": [(b"x-api-key", "한글".encode("utf-8"))]
}
request = fastapi.Request(scope)

async def dummy_call_next(req):
return fastapi.responses.JSONResponse({"success": True})

response = asyncio.run(saas_web.require_api_key(request, dummy_call_next))

self.assertEqual(response.status_code, 401)
self.assertEqual(json.loads(response.body), {"error": "Invalid or missing API key"})

def test_wrong_key_rejected(self):
with patch.dict(os.environ, {"CODEC_CARVER_API_KEYS": "secret-key"}):
response = self._post_shrink(headers={"X-API-Key": "wrong-key"})
Expand Down
Loading