maskingmasking / auth.py
zombee11's picture
Upload 20 files
4de67a0 verified
Raw
History Blame Contribute Delete
1.11 kB
"""Simple API-key bearer authentication."""
import os
import logging
from fastapi import HTTPException, Security, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
logger = logging.getLogger(__name__)
_security = HTTPBearer(auto_error=False)
# In production, load from vault / env. Multiple keys supported (comma-separated).
_RAW = os.environ.get("API_KEYS", "demo-key-12345,test-key-67890")
VALID_KEYS: set[str] = {k.strip() for k in _RAW.split(",") if k.strip()}
def verify_api_key(
credentials: HTTPAuthorizationCredentials = Security(_security),
) -> str:
if credentials is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing Authorization header. Use: Bearer <API_KEY>",
)
token = credentials.credentials
if token not in VALID_KEYS:
logger.warning("Rejected invalid API key (last4=%s)", token[-4:] if len(token) >= 4 else "??")
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid API key.",
)
return token