import hmac from typing import Optional from fastapi import Depends, HTTPException, Security, status from fastapi.security import APIKeyHeader from app.config import settings api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False) async def verify_api_key( api_key: Optional[str] = Security(api_key_header), ) -> str: """Validate X-API-Key header. Skipped when AI_API_KEY is not configured.""" if not settings.api_key: return "no-auth" if not api_key or not hmac.compare_digest(api_key, settings.api_key): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing API key", ) return api_key