import hmac from datetime import date from typing import Annotated from fastapi import Header from loguru import logger from src.config import config from src.exceptions import UnauthorizedError def verify_admin_key(x_admin_key: Annotated[str, Header()]) -> str: """Validate the admin API key from the X-Admin-Key header. Two keys are accepted: - ``admin_key``: the primary admin key, no expiry. - ``tross_key`` (\"Tross Key\"): a secondary key valid only through ``tross_key_valid_until`` (inclusive). From the day after that date it is rejected with an "expired" error. Comparisons use ``hmac.compare_digest`` to avoid timing leaks of the key values. Args: x_admin_key: The API key provided via the `X-Admin-Key` header. Returns: The validated API key string. Raises: UnauthorizedError: If the key matches neither configured key, or if it is the Tross Key and today is past its valid-until date. """ if hmac.compare_digest(x_admin_key, config.admin_key): return x_admin_key if hmac.compare_digest(x_admin_key, config.tross_key): if date.today() <= config.tross_key_valid_until: return x_admin_key logger.warning( "rejected expired Tross Key (valid_until={}, today={})", config.tross_key_valid_until, date.today(), ) raise UnauthorizedError("Tross Key has expired") raise UnauthorizedError("Invalid or missing admin API key")