"""API key authentication.""" import hmac import os import boto3 from fastapi import Security, HTTPException from fastapi.security.api_key import APIKeyHeader from ai_evals import config _cached_key: str | None = None api_key_header = APIKeyHeader(name="X-API-Key") def _fetch_from_secrets_manager() -> str: client = boto3.client("secretsmanager") return client.get_secret_value(SecretId=config.API_KEY_SECRET_NAME)["SecretString"] def get_expected_key() -> str: global _cached_key if config.ENVIRONMENT == "dev": return os.environ.get("DEV_API_KEY", "dev-key") if _cached_key is None: _cached_key = _fetch_from_secrets_manager() return _cached_key def invalidate_key_cache() -> None: global _cached_key _cached_key = None async def verify_api_key(api_key: str = Security(api_key_header)) -> None: expected = get_expected_key() if not hmac.compare_digest(api_key, expected): raise HTTPException(status_code=403, detail="Invalid API key")