Files
mtusi2026lab4/src/app/api/attachments.py
T

212 lines
7.7 KiB
Python

"""Вложения (lab4): синхронный binary upload PNG/JPEG, авторизованный download."""
import hashlib
import io
import os
import unicodedata
from datetime import datetime, timezone
from typing import Optional
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi.responses import Response
from PIL import Image, UnidentifiedImageError
from starlette.concurrency import run_in_threadpool
from ..models.schemas import Attachment, User
from ..storage import s3
from ..storage.postgres import storage
from .security import current_user
router = APIRouter(prefix="/api/v1", tags=["attachments"])
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
def _require_member(chat_id: UUID, user_id: UUID):
chat = storage.get_chat(chat_id)
if chat is None or user_id not in chat.member_ids:
raise HTTPException(status_code=404, detail="not_found")
return chat
def _validate_filename(name: str) -> str:
if not name or len(name) > 255:
raise HTTPException(status_code=400, detail="invalid_request")
if name.strip() != name or name.strip() == "":
raise HTTPException(status_code=400, detail="invalid_request")
for ch in name:
if ch in ("/", "\\", "\x00") or unicodedata.category(ch).startswith("C"):
raise HTTPException(status_code=400, detail="invalid_request")
return name
def _detect_content_type(data: bytes) -> Optional[str]:
"""MIME по содержимому, не по заголовку."""
if data.startswith(b"\x89PNG\r\n\x1a\n"):
return "image/png"
if data.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
return None
def _validate_image(data: bytes) -> str:
"""MIME по содержимому + лимит пикселей + полная проверка декодирования.
Полное декодирование (load) выполняется через Pillow, чтобы отвергнуть
повреждённые/обрезанные файлы, которые open() принимает по заголовку.
"""
ctype = _detect_content_type(data)
if ctype is None:
raise HTTPException(status_code=415, detail="unsupported_media_type")
try:
img = Image.open(io.BytesIO(data))
width, height = img.size
if width <= 0 or height <= 0:
raise HTTPException(status_code=415, detail="unsupported_media_type")
if width * height > MAX_IMAGE_PIXELS:
raise HTTPException(status_code=413, detail="payload_too_large")
# Полное декодирование всех данных: битый IDAT / обрезанный файл
# поднимут OSError/ValueError и будут отвергнуты как 415.
img.load()
except HTTPException:
raise
except Image.DecompressionBombError:
# Pillow защищается от «бомб» по собственному порогу: для нас
# это превышение лимита пикселей → 413.
raise HTTPException(status_code=413, detail="payload_too_large")
except Exception:
raise HTTPException(status_code=415, detail="unsupported_media_type")
return ctype
@router.post(
path="/chats/{chat_id}/attachments",
summary="Принять один PNG/JPEG, до 10 MiB",
response_model=Attachment,
status_code=201,
)
async def upload_attachment(
chat_id: UUID,
request: Request,
user: User = Depends(current_user),
filename: str = Query(...),
) -> Attachment:
_require_member(chat_id, user.id)
safe_name = _validate_filename(filename)
# Content-Length — быстрая отсечка; не доверяем полностью.
cl = request.headers.get("content-length")
if cl is not None:
try:
if int(cl) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="payload_too_large")
except ValueError:
raise HTTPException(status_code=400, detail="invalid_request")
# Потоковое чтение с жёстким лимитом.
chunks: list[bytes] = []
total = 0
async for chunk in request.stream():
if not chunk:
continue
total += len(chunk)
if total > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="payload_too_large")
chunks.append(chunk)
body = b"".join(chunks)
if not body:
raise HTTPException(status_code=400, detail="invalid_request")
# Pillow — в threadpool, чтобы не блокировать event loop.
content_type = await run_in_threadpool(_validate_image, body)
sha256 = hashlib.sha256(body).hexdigest()
attachment_id = uuid4()
object_key = s3.original_key(chat_id, attachment_id)
# 1) Сначала сохраняем в S3. Если следующий шаг упадёт — компенсируем.
try:
await run_in_threadpool(s3.put_bytes, object_key, body, content_type)
except Exception as exc: # noqa: BLE001
raise HTTPException(status_code=503, detail="unavailable") from exc
now = datetime.now(timezone.utc)
att = Attachment(
id=attachment_id,
chat_id=chat_id,
owner_id=user.id,
filename=safe_name,
content_type=content_type,
size_bytes=len(body),
sha256=sha256,
status="ready",
variants=[],
error_code=None,
created_at=now,
updated_at=now,
)
# 2) INSERT в БД. При ЛЮБОМ исключении удаляем S3-объект (компенсация).
try:
await run_in_threadpool(storage.create_attachment, att, object_key)
except Exception:
try:
await run_in_threadpool(s3.delete_object, object_key)
except Exception:
pass
raise HTTPException(status_code=503, detail="unavailable")
return att
@router.get(
path="/attachments/{attachment_id}",
summary="Метаданные вложения, доступ участникам чата",
response_model=Attachment,
)
def get_attachment(
attachment_id: UUID,
user: User = Depends(current_user),
) -> Attachment:
pair = storage.get_attachment_with_key(attachment_id)
if pair is None:
raise HTTPException(status_code=404, detail="not_found")
att, _key = pair
_require_member(att.chat_id, user.id)
return att
@router.get(
path="/attachments/{attachment_id}/content",
summary="Скачать байты через авторизованный API",
)
def download_attachment(
attachment_id: UUID,
user: User = Depends(current_user),
variant: str = Query("original"),
):
if variant != "original":
raise HTTPException(status_code=404, detail="not_found")
pair = storage.get_attachment_with_key(attachment_id)
if pair is None:
raise HTTPException(status_code=404, detail="not_found")
att, object_key = pair
_require_member(att.chat_id, user.id)
if att.status != "ready":
raise HTTPException(status_code=409, detail="conflict")
try:
data, ctype = s3.get_object(object_key)
except Exception as exc: # noqa: BLE001
# Объект отсутствует при готовых метаданных: 404.
if exc.__class__.__name__ == "NoSuchKey":
raise HTTPException(status_code=404, detail="not_found")
raise HTTPException(status_code=503, detail="unavailable") from exc
return Response(
content=data,
media_type=ctype,
headers={"Content-Length": str(len(data))},
)