"""API key authentication dependency.""" import hmac import logging from fastapi import Depends, HTTPException, Request, status from fastapi.security import APIKeyHeader _api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False) logger = logging.getLogger(__name__) 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 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, ) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Invalid or missing API key", )