feat: ЛР4 - S3 хранилище MinIO, загрузка вложений и защита от атак

This commit is contained in:
Ильяс
2026-11-06 15:59:44 +03:00
parent 9b574fa5e9
commit 4979731408
24 changed files with 1418 additions and 72 deletions
+85
View File
@@ -0,0 +1,85 @@
from uuid import UUID
from fastapi import APIRouter, Depends, Query, Request, Response, status
from app.dependencies import get_current_user
from app.errors import InvalidRequestError
from app.schemas import AttachmentResponse, UserResponse
from app.storage import storage
router = APIRouter(tags=["attachments"])
def validate_uuid(value: str, field_name: str = "id") -> str:
try:
UUID(value)
return value
except ValueError as exc:
raise InvalidRequestError(f"Поле '{field_name}' не является валидным UUID") from exc
@router.post(
"/api/v1/chats/{chat_id}/attachments",
response_model=AttachmentResponse,
status_code=status.HTTP_201_CREATED,
)
async def upload_attachment(
chat_id: str,
request: Request,
filename: str = Query(..., min_length=1, max_length=255),
current_user: UserResponse = Depends(get_current_user),
) -> AttachmentResponse:
"""Загрузка бинарного вложения в чат."""
valid_chat_id = validate_uuid(chat_id, "chat_id")
content_type = request.headers.get("content-type") or ""
data = await request.body()
return await storage.upload_attachment(
caller_id=current_user.id,
chat_id=valid_chat_id,
filename=filename,
content_type=content_type,
data=data,
)
@router.get(
"/api/v1/attachments/{attachment_id}",
response_model=AttachmentResponse,
status_code=status.HTTP_200_OK,
)
async def get_attachment_metadata(
attachment_id: str,
current_user: UserResponse = Depends(get_current_user),
) -> AttachmentResponse:
"""Получение метаданных вложения."""
valid_att_id = validate_uuid(attachment_id, "attachment_id")
return await storage.get_attachment(
caller_id=current_user.id,
attachment_id=valid_att_id,
)
@router.get(
"/api/v1/attachments/{attachment_id}/content",
status_code=status.HTTP_200_OK,
)
async def download_attachment_content(
attachment_id: str,
variant: str | None = Query(default=None),
current_user: UserResponse = Depends(get_current_user),
) -> Response:
"""Скачивание бинарного содержимого вложения."""
valid_att_id = validate_uuid(attachment_id, "attachment_id")
data, content_type = await storage.get_attachment_content(
caller_id=current_user.id,
attachment_id=valid_att_id,
variant=variant,
)
return Response(
content=data,
media_type=content_type,
headers={
"Content-Length": str(len(data)),
},
)
+1
View File
@@ -47,6 +47,7 @@ async def create_message(
chat_id=valid_id,
text=body.text,
idempotency_key=idempotency_key,
attachment_ids=body.attachment_ids,
)
return msg