S3-хранилище и вложения, трек 1

This commit is contained in:
Queenfish
2026-10-29 00:03:34 +03:00
parent ec540a1a72
commit 32e105cc87
66 changed files with 5265 additions and 30 deletions
+294
View File
@@ -0,0 +1,294 @@
import hashlib
import re
import uuid
from io import BytesIO
from fastapi import APIRouter, Header, Request
from fastapi.responses import JSONResponse, StreamingResponse
from PIL import Image, UnidentifiedImageError
from app.security import get_current_user
router = APIRouter(tags=["attachments"])
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
ALLOWED = {"PNG": "image/png", "JPEG": "image/jpeg"}
BAD_FILENAME = re.compile(r'[/\\\x00-\x1f]')
BEARER_CHALLENGE = 'Bearer realm="messenger"'
CHUNK = 64 * 1024
PRESIGN_TTL_SECONDS = 300
def error_response(status, code, message, request_id, headers=None):
return JSONResponse(
status_code=status,
content={"error": {"code": code, "message": message, "request_id": request_id}},
headers=headers or {},
)
def validate_image(data: bytes) -> tuple[str, int, int, str]:
if len(data) == 0:
raise ValueError("unsupported_media_type")
if len(data) > MAX_BYTES:
raise ValueError("payload_too_large")
try:
img = Image.open(BytesIO(data))
img.verify()
img = Image.open(BytesIO(data))
fmt = img.format
w, h = img.size
except (UnidentifiedImageError, OSError, ValueError):
raise ValueError("unsupported_media_type")
if fmt not in ALLOWED:
raise ValueError("unsupported_media_type")
if w * h > MAX_PIXELS:
raise ValueError("payload_too_large")
return ALLOWED[fmt], w, h, hashlib.sha256(data).hexdigest()
def safe_filename(name: str) -> str:
if not name or len(name) > 255:
raise ValueError("invalid_request")
if BAD_FILENAME.search(name):
raise ValueError("invalid_request")
return name
async def _auth(request, authorization):
try:
user, _ = await get_current_user(request, authorization)
return user, None
except Exception:
return None, error_response(
401, "unauthorized", "unauthorized", request.state.request_id,
headers={"WWW-Authenticate": BEARER_CHALLENGE},
)
async def _read_limited(request, limit: int) -> bytes:
buf = bytearray()
async for chunk in request.stream():
buf.extend(chunk)
if len(buf) > limit:
raise ValueError("payload_too_large")
return bytes(buf)
@router.post("/chats/{chat_id}/attachments", status_code=201)
async def upload_attachment(
chat_id: str,
filename: str,
request: Request,
authorization: str | None = Header(default=None),
):
rid = request.state.request_id
try:
uuid.UUID(chat_id)
except (ValueError, TypeError):
return error_response(400, "invalid_request", "invalid uuid", rid)
user, err = await _auth(request, authorization)
if err is not None:
return err
if not await request.app.state.storage.is_chat_member(chat_id, user["id"]):
return error_response(404, "not_found", "chat not found", rid)
try:
safe_filename(filename)
except ValueError:
return error_response(400, "invalid_request", "invalid filename", rid)
try:
data = await _read_limited(request, MAX_BYTES)
except ValueError:
return error_response(413, "payload_too_large", "payload_too_large", rid)
try:
content_type, w, h, sha = validate_image(data)
except ValueError as e:
code = str(e)
status = 413 if code == "payload_too_large" else 415
return error_response(status, code, code, rid)
att_id = str(uuid.uuid4())
object_key = f"{chat_id}/{att_id}"
try:
request.app.state.s3.put(object_key, data, content_type)
except Exception:
return error_response(503, "unavailable", "storage unavailable", rid)
try:
att = await request.app.state.storage.create_attachment(
att_id, chat_id, user["id"], object_key,
filename, content_type, len(data), sha,
)
except Exception:
try:
request.app.state.s3.remove(object_key)
except Exception:
pass
return error_response(503, "unavailable", "storage inconsistent", rid)
return att
@router.post("/chats/{chat_id}/attachments/presign", status_code=201)
async def presign_upload(
chat_id: str,
filename: str,
size: int,
content_type: str,
request: Request,
authorization: str | None = Header(default=None),
):
rid = request.state.request_id
try:
uuid.UUID(chat_id)
except (ValueError, TypeError):
return error_response(400, "invalid_request", "invalid uuid", rid)
user, err = await _auth(request, authorization)
if err is not None:
return err
if not await request.app.state.storage.is_chat_member(chat_id, user["id"]):
return error_response(404, "not_found", "chat not found", rid)
try:
safe_filename(filename)
except ValueError:
return error_response(400, "invalid_request", "invalid filename", rid)
if size <= 0 or size > MAX_BYTES:
return error_response(413, "payload_too_large", "payload_too_large", rid)
if content_type not in ("image/png", "image/jpeg"):
return error_response(415, "unsupported_media_type", "unsupported_media_type", rid)
att_id = str(uuid.uuid4())
object_key = f"uploads/{chat_id}/{att_id}"
await request.app.state.storage.create_pending_attachment(
att_id, chat_id, user["id"], object_key,
filename, content_type, size,
)
url = request.app.state.s3.presigned_put(object_key, PRESIGN_TTL_SECONDS)
return {
"upload_url": url,
"attachment_id": att_id,
"expires_in": PRESIGN_TTL_SECONDS,
}
@router.post("/attachments/{attachment_id}/complete", status_code=201)
async def complete_upload(
attachment_id: str,
request: Request,
authorization: str | None = Header(default=None),
):
rid = request.state.request_id
try:
uuid.UUID(attachment_id)
except (ValueError, TypeError):
return error_response(400, "invalid_request", "invalid uuid", rid)
user, err = await _auth(request, authorization)
if err is not None:
return err
att = await request.app.state.storage.get_attachment(attachment_id)
if att is None:
return error_response(404, "not_found", "attachment not found", rid)
if not await request.app.state.storage.is_chat_member(att["chat_id"], user["id"]):
return error_response(404, "not_found", "attachment not found", rid)
if att["status"] != "pending":
return error_response(409, "conflict", "attachment not pending", rid)
object_key = att["_object_key"]
try:
stat = request.app.state.s3.stat(object_key)
except Exception:
return error_response(409, "conflict", "object not uploaded", rid)
if stat.size != att["size_bytes"]:
return error_response(409, "conflict", "size mismatch", rid)
try:
obj = request.app.state.s3.get(object_key)
data = obj.read()
except Exception:
return error_response(503, "unavailable", "storage unavailable", rid)
try:
detected_type, w, h, sha = validate_image(data)
except ValueError as e:
code = str(e)
status = 413 if code == "payload_too_large" else 415
return error_response(status, code, code, rid)
if detected_type != att["content_type"]:
return error_response(409, "conflict", "content_type mismatch", rid)
ready = await request.app.state.storage.complete_attachment(
attachment_id, sha, len(data),
)
if ready is None:
return error_response(409, "conflict", "attachment not pending", rid)
return ready
@router.get("/attachments/{attachment_id}")
async def get_attachment(
attachment_id: str,
request: Request,
authorization: str | None = Header(default=None),
):
rid = request.state.request_id
try:
uuid.UUID(attachment_id)
except (ValueError, TypeError):
return error_response(400, "invalid_request", "invalid uuid", rid)
user, err = await _auth(request, authorization)
if err is not None:
return err
att = await request.app.state.storage.get_attachment(attachment_id)
if att is None:
return error_response(404, "not_found", "attachment not found", rid)
if not await request.app.state.storage.is_chat_member(att["chat_id"], user["id"]):
return error_response(404, "not_found", "attachment not found", rid)
att.pop("_object_key", None)
return att
@router.get("/attachments/{attachment_id}/content")
async def download_attachment(
attachment_id: str,
request: Request,
variant: str = "original",
authorization: str | None = Header(default=None),
):
rid = request.state.request_id
try:
uuid.UUID(attachment_id)
except (ValueError, TypeError):
return error_response(400, "invalid_request", "invalid uuid", rid)
user, err = await _auth(request, authorization)
if err is not None:
return err
att = await request.app.state.storage.get_attachment(attachment_id)
if att is None:
return error_response(404, "not_found", "attachment not found", rid)
if not await request.app.state.storage.is_chat_member(att["chat_id"], user["id"]):
return error_response(404, "not_found", "attachment not found", rid)
if variant != "original":
return error_response(404, "not_found", "variant not found", rid)
try:
obj = request.app.state.s3.get(att["_object_key"])
except Exception:
return error_response(503, "unavailable", "storage unavailable", rid)
return StreamingResponse(
obj.stream(CHUNK),
media_type=att["content_type"],
headers={"Content-Length": str(att["size_bytes"])},
)