"""Shared FastAPI dependencies for routers. Centralizes DB session management and API-key authentication so routers no longer re-declare these helpers themselves. """ from typing import Optional from fastapi import Depends, Header, HTTPException, status from agenteval.config import get_settings from agenteval.storage.db import get_session def get_db(): """Yield a SQLModel Session and guarantee close() on request completion.""" session = get_session() try: yield session finally: session.close() def require_api_key(x_api_key: Optional[str] = Header(default=None)) -> None: """Enforce X-API-Key header when AGENTEVAL_API_KEY is configured. When the setting is empty (default), the check is a no-op so local dev keeps working without extra configuration. """ configured = get_settings().api_key if not configured: return if not x_api_key or x_api_key != configured: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing X-API-Key", ) # Convenience alias used by routers via ``dependencies=[Depends(auth_required)]``. auth_required = Depends(require_api_key)