2026-03-11 10:27:18 -04:00
|
|
|
"""API key authentication dependency."""
|
|
|
|
|
|
2026-03-31 13:51:10 -04:00
|
|
|
import hmac
|
|
|
|
|
import logging
|
|
|
|
|
|
2026-03-11 10:27:18 -04:00
|
|
|
from fastapi import Depends, HTTPException, Request, status
|
|
|
|
|
from fastapi.security import APIKeyHeader
|
|
|
|
|
|
|
|
|
|
_api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
|
2026-03-31 13:51:10 -04:00
|
|
|
logger = logging.getLogger(__name__)
|
2026-03-11 10:27:18 -04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
async def require_api_key(
|
|
|
|
|
request: Request,
|
|
|
|
|
api_key: str | None = Depends(_api_key_header),
|
|
|
|
|
) -> None:
|
|
|
|
|
"""FastAPI dependency that enforces X-API-Key header authentication.
|
|
|
|
|
|
|
|
|
|
If no API key is configured on the server (empty string), all requests
|
|
|
|
|
are allowed — this is intended for local development only.
|
|
|
|
|
"""
|
|
|
|
|
expected: str = request.app.state.api_key
|
|
|
|
|
if not expected:
|
|
|
|
|
return # dev mode: no key set, allow all
|
2026-03-31 13:51:10 -04:00
|
|
|
if not hmac.compare_digest(api_key or "", expected):
|
|
|
|
|
client = getattr(request.client, "host", "unknown")
|
|
|
|
|
logger.warning(
|
|
|
|
|
"Authentication failure from %s — %s %s",
|
|
|
|
|
client,
|
|
|
|
|
request.method,
|
|
|
|
|
request.url.path,
|
|
|
|
|
)
|
2026-03-11 10:27:18 -04:00
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
|
|
|
detail="Invalid or missing API key",
|
|
|
|
|
)
|