Something went wrong. Try again.
This repository has no description
Something went wrong. Try again.
1.5 kB · 48 lines
Python
at main
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import hmacfrom datetime import datefrom typing import Annotated
from fastapi import Headerfrom loguru import logger
from src.config import configfrom 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")