40 lines
1.6 KiB
Python
40 lines
1.6 KiB
Python
"""Аутентификация X-API-Key (FR-004, docs/05 §5.2): 401 — нет, 403 — неверен."""
|
|
from __future__ import annotations
|
|
|
|
import secrets
|
|
|
|
from fastapi import Request
|
|
|
|
from app.api.errors import ApiError
|
|
|
|
ALLOWED_IMAGE_CONTENT_TYPES = {"image/jpeg", "image/png", "image/webp"}
|
|
|
|
|
|
def require_api_key(request: Request) -> None:
|
|
provided = request.headers.get("x-api-key")
|
|
if not provided:
|
|
raise ApiError(401, "UNAUTHORIZED", "Требуется заголовок X-API-Key")
|
|
expected = request.app.state.config.api_key
|
|
if not secrets.compare_digest(provided.encode(), expected.encode()):
|
|
raise ApiError(403, "FORBIDDEN", "Неверный API-ключ")
|
|
|
|
|
|
def check_image_content_type(content_type: str | None, part: str) -> None:
|
|
"""415, если часть заявлена как изображение недопустимого типа.
|
|
|
|
application/octet-stream пропускаем: фактический формат определяет
|
|
декодер, а не заголовок части (docs/05 §5.5-1).
|
|
"""
|
|
if content_type is None:
|
|
return
|
|
base = content_type.split(";", 1)[0].strip().lower()
|
|
if base == "application/octet-stream":
|
|
return
|
|
if base.startswith("image/") and base not in ALLOWED_IMAGE_CONTENT_TYPES:
|
|
raise ApiError(
|
|
415,
|
|
"UNSUPPORTED_MEDIA_TYPE",
|
|
f"Часть {part}: формат {base} не поддерживается; разрешены JPEG, PNG, WebP",
|
|
{"part": part, "content_type": base},
|
|
)
|