Реализовала требования лабы 4 на оценку 4

This commit is contained in:
vasyukova
2026-10-17 23:53:17 +03:00
parent 2d50adb37c
commit 442cd82653
9 changed files with 674 additions and 70 deletions
+238
View File
@@ -0,0 +1,238 @@
"""Вложения (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 ..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 _read_limited_body(request: Request) -> bytes:
"""Читает тело запроса с жёстким лимитом MAX_UPLOAD_BYTES.
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 = []
total = 0
# Синхронное чтение — FastAPI уже выполнил sync-endpoint в threadpool.
iterator = request.stream()
import asyncio
loop = asyncio.new_event_loop()
try:
while True:
try:
chunk = loop.run_until_complete(iterator.__anext__())
except StopAsyncIteration:
break
if not chunk:
continue
total += len(chunk)
if total > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="payload_too_large")
chunks.append(chunk)
finally:
loop.close()
return b"".join(chunks)
def _validate_image(data: bytes) -> str:
"""Проверяет формат по содержимому и лимит пикселей до полной распаковки."""
ctype = _detect_content_type(data)
if ctype is None:
raise HTTPException(status_code=415, detail="unsupported_media_type")
# Pillow позволяет узнать размеры без полной распаковки.
try:
img = Image.open(io.BytesIO(data))
width, height = img.size
except (UnidentifiedImageError, OSError):
raise HTTPException(status_code=415, detail="unsupported_media_type")
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")
# Реальное декодирование пикселей для проверки целостности (bomb-защита
# уже отработала по лимиту выше).
try:
img.load()
except Exception:
raise HTTPException(status_code=415, detail="unsupported_media_type")
return ctype
def _attachment_response(att: Attachment) -> Attachment:
return att
@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.
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 len(body) == 0:
raise HTTPException(status_code=400, detail="invalid_request")
if len(body) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="payload_too_large")
content_type = _validate_image(body)
sha256 = hashlib.sha256(body).hexdigest()
attachment_id = uuid4()
object_key = s3.original_key(chat_id, attachment_id)
# 1) Сначала сохраняем в S3. Если следующий шаг упадёт — компенсируем.
try:
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:
storage.create_attachment(att, object_key)
except Exception:
try:
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))},
)