File size: 821 Bytes
9fe5a30
 
781f7b0
9fe5a30
 
 
 
781f7b0
9fe5a30
781f7b0
 
9fe5a30
 
781f7b0
9fe5a30
 
781f7b0
9fe5a30
 
 
 
 
 
781f7b0
 
9fe5a30
781f7b0
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""Security utilities for API key verification."""

import secrets
from app.core.config import settings
from app.core.exceptions import AuthenticationError


def verify_api_key(api_key: str) -> bool:
    """
    Verify if the provided API key is valid using timing-safe comparison.

    Args:
        api_key: The API key to verify

    Returns:
        True if the API key is valid

    Raises:
        AuthenticationError: If the API key is invalid or missing
    """
    if not api_key:
        raise AuthenticationError("Missing API key")

    if not settings.api_keys_set:
        raise AuthenticationError("No API keys configured on server")

    for valid_key in settings.api_keys_set:
        if secrets.compare_digest(api_key, valid_key):
            return True

    raise AuthenticationError("Invalid API key")