Implement lab4 S3 attachments and reliability checks
This commit is contained in:
@@ -0,0 +1,272 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
from contextlib import asynccontextmanager
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import Response
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from app.db import pool
|
||||
from app.dependencies import accessible_chat, current_user
|
||||
from app.errors import ApiError, invalid, not_found
|
||||
from app.images import MAX_BYTES, inspect_image, validate_filename
|
||||
from app.object_locks import object_lock_id
|
||||
from app.responses import json_response
|
||||
from app.storage import bucket_name, get_object, put_object
|
||||
from app.validation import parse_uuid
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
binary_slot = asyncio.Semaphore(1)
|
||||
|
||||
PUBLIC_FIELDS = (
|
||||
"id",
|
||||
"chat_id",
|
||||
"owner_id",
|
||||
"filename",
|
||||
"content_type",
|
||||
"size_bytes",
|
||||
"sha256",
|
||||
"status",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def binary_operation():
|
||||
try:
|
||||
await asyncio.wait_for(binary_slot.acquire(), timeout=3)
|
||||
except TimeoutError:
|
||||
raise ApiError(
|
||||
503,
|
||||
"unavailable",
|
||||
"Обработка файлов временно занята",
|
||||
) from None
|
||||
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
binary_slot.release()
|
||||
|
||||
|
||||
def public_attachment(row: dict) -> dict:
|
||||
result = {field: row[field] for field in PUBLIC_FIELDS}
|
||||
result["variants"] = []
|
||||
result["error_code"] = None
|
||||
return result
|
||||
|
||||
|
||||
async def read_image_body(request: Request) -> bytes:
|
||||
lengths = request.headers.getlist("content-length")
|
||||
|
||||
if len(lengths) > 1:
|
||||
raise invalid("Некорректный Content-Length")
|
||||
|
||||
expected = None
|
||||
if lengths:
|
||||
value = lengths[0]
|
||||
if not value.isascii() or not value.isdecimal():
|
||||
raise invalid("Некорректный Content-Length")
|
||||
|
||||
if len(value) > 20:
|
||||
raise ApiError(
|
||||
413, "payload_too_large", "Файл превышает 10 MiB"
|
||||
)
|
||||
|
||||
expected = int(value)
|
||||
if expected > MAX_BYTES:
|
||||
raise ApiError(
|
||||
413, "payload_too_large", "Файл превышает 10 MiB"
|
||||
)
|
||||
|
||||
data = bytearray()
|
||||
|
||||
async for chunk in request.stream():
|
||||
if len(data) + len(chunk) > MAX_BYTES:
|
||||
raise ApiError(
|
||||
413, "payload_too_large", "Файл превышает 10 MiB"
|
||||
)
|
||||
data.extend(chunk)
|
||||
|
||||
if expected is not None and len(data) != expected:
|
||||
raise invalid("Размер тела не соответствует Content-Length")
|
||||
|
||||
return bytes(data)
|
||||
|
||||
|
||||
async def accessible_attachment(
|
||||
attachment_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dict:
|
||||
async with pool.connection() as conn:
|
||||
cursor = await conn.execute(
|
||||
"""
|
||||
SELECT a.id, a.chat_id, a.owner_id,
|
||||
a.filename, a.content_type, a.size_bytes,
|
||||
a.sha256, a.object_key, a.status,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments AS a
|
||||
WHERE a.id = %s
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members AS cm
|
||||
WHERE cm.chat_id = a.chat_id
|
||||
AND cm.user_id = %s
|
||||
)
|
||||
""",
|
||||
(attachment_id, user_id),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
|
||||
if row is None:
|
||||
raise not_found()
|
||||
|
||||
return row
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/attachments")
|
||||
async def upload_attachment(chat_id: str, request: Request):
|
||||
user, _ = await current_user(request)
|
||||
chat_uuid, _ = await accessible_chat(chat_id, user["id"])
|
||||
|
||||
filenames = request.query_params.getlist("filename")
|
||||
if len(filenames) != 1:
|
||||
raise invalid("Требуется одно имя файла")
|
||||
|
||||
filename = validate_filename(filenames[0])
|
||||
|
||||
content_types = request.headers.getlist("content-type")
|
||||
if len(content_types) != 1:
|
||||
raise ApiError(
|
||||
415,
|
||||
"unsupported_media_type",
|
||||
"Требуется Content-Type изображения",
|
||||
)
|
||||
|
||||
declared_type = content_types[0].split(";", 1)[0].strip().lower()
|
||||
if declared_type not in ("image/png", "image/jpeg"):
|
||||
raise ApiError(
|
||||
415,
|
||||
"unsupported_media_type",
|
||||
"Допустимы только image/png и image/jpeg",
|
||||
)
|
||||
|
||||
async with binary_operation():
|
||||
try:
|
||||
data = await asyncio.wait_for(
|
||||
read_image_body(request),
|
||||
timeout=60,
|
||||
)
|
||||
except ClientDisconnect:
|
||||
raise invalid("Загрузка файла прервана") from None
|
||||
except TimeoutError:
|
||||
raise invalid("Превышено время загрузки файла") from None
|
||||
|
||||
content_type = await run_in_threadpool(
|
||||
inspect_image,
|
||||
data,
|
||||
declared_type,
|
||||
)
|
||||
|
||||
attachment_id = uuid4()
|
||||
object_key = f"originals/{attachment_id}"
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
|
||||
async with pool.connection() as conn:
|
||||
await conn.execute(
|
||||
"SET LOCAL idle_in_transaction_session_timeout = '60s'"
|
||||
)
|
||||
await conn.execute(
|
||||
"SELECT pg_advisory_xact_lock(%s)",
|
||||
(object_lock_id(bucket_name(), object_key),),
|
||||
)
|
||||
|
||||
await put_object(object_key, data, content_type)
|
||||
|
||||
cursor = await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename,
|
||||
content_type, size_bytes, sha256, object_key
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, chat_id, owner_id, filename,
|
||||
content_type, size_bytes, sha256,
|
||||
status, created_at, updated_at
|
||||
""",
|
||||
(
|
||||
attachment_id,
|
||||
chat_uuid,
|
||||
user["id"],
|
||||
filename,
|
||||
content_type,
|
||||
len(data),
|
||||
digest,
|
||||
object_key,
|
||||
),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
|
||||
return json_response(public_attachment(row), 201)
|
||||
|
||||
|
||||
@router.get("/api/v1/attachments/{attachment_id}")
|
||||
async def get_attachment(attachment_id: str, request: Request):
|
||||
user, _ = await current_user(request)
|
||||
|
||||
row = await accessible_attachment(
|
||||
parse_uuid(attachment_id),
|
||||
user["id"],
|
||||
)
|
||||
|
||||
return json_response(public_attachment(row))
|
||||
|
||||
|
||||
@router.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def download_attachment(attachment_id: str, request: Request):
|
||||
user, _ = await current_user(request)
|
||||
|
||||
row = await accessible_attachment(
|
||||
parse_uuid(attachment_id),
|
||||
user["id"],
|
||||
)
|
||||
|
||||
variants = request.query_params.getlist("variant")
|
||||
if len(variants) > 1:
|
||||
raise invalid("Допускается один вариант изображения")
|
||||
if variants and variants[0] != "original":
|
||||
raise not_found()
|
||||
|
||||
if row["status"] != "ready":
|
||||
raise ApiError(
|
||||
409,
|
||||
"conflict",
|
||||
"Вложение ещё не готово",
|
||||
)
|
||||
|
||||
async with binary_operation():
|
||||
data = await get_object(row["object_key"])
|
||||
|
||||
if (
|
||||
len(data) != row["size_bytes"]
|
||||
or hashlib.sha256(data).hexdigest() != row["sha256"]
|
||||
):
|
||||
raise ApiError(
|
||||
503,
|
||||
"unavailable",
|
||||
"Оригинал временно недоступен",
|
||||
)
|
||||
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=row["content_type"],
|
||||
headers={
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,74 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.dependencies import accessible_chat, current_user
|
||||
from app.errors import invalid
|
||||
from app.pagination import page_response, pagination
|
||||
from app.responses import json_response
|
||||
from app.store import InvalidMembersError, store
|
||||
from app.validation import parse_uuid, read_payload, valid_text
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/chats")
|
||||
async def create_chat(request: Request):
|
||||
user, _ = await current_user(request)
|
||||
|
||||
payload = await read_payload(
|
||||
request,
|
||||
{"title", "member_ids"},
|
||||
)
|
||||
|
||||
if not valid_text(payload["title"], 100):
|
||||
raise invalid("Некорректный title")
|
||||
|
||||
raw_members = payload["member_ids"]
|
||||
|
||||
if (
|
||||
not isinstance(raw_members, list)
|
||||
or not 1 <= len(raw_members) <= 100
|
||||
):
|
||||
raise invalid("Некорректный member_ids")
|
||||
|
||||
member_ids = [parse_uuid(item) for item in raw_members]
|
||||
|
||||
if len(set(member_ids)) != len(member_ids):
|
||||
raise invalid("В member_ids есть дубликаты")
|
||||
|
||||
if user["id"] not in member_ids:
|
||||
raise invalid("Создатель должен входить в member_ids")
|
||||
|
||||
try:
|
||||
chat = await store.create_chat(
|
||||
payload["title"],
|
||||
member_ids,
|
||||
)
|
||||
except InvalidMembersError:
|
||||
raise invalid(
|
||||
"В member_ids есть неизвестный пользователь"
|
||||
) from None
|
||||
|
||||
return json_response(chat, 201)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats")
|
||||
async def list_chats(request: Request):
|
||||
user, _ = await current_user(request)
|
||||
|
||||
scope = f"chats:{user['id']}"
|
||||
limit, after = pagination(request, scope)
|
||||
|
||||
rows = await store.list_chats(user["id"], limit, after)
|
||||
|
||||
return page_response(rows, limit, scope)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
user, _ = await current_user(request)
|
||||
|
||||
_, chat = await accessible_chat(chat_id, user["id"])
|
||||
|
||||
return json_response(chat)
|
||||
@@ -0,0 +1,20 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.db import check_db
|
||||
from app.storage import check_storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
async def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
async def health_ready():
|
||||
await check_db()
|
||||
await check_storage()
|
||||
return {"status": "ok"}
|
||||
@@ -0,0 +1,90 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.dependencies import accessible_chat, current_user
|
||||
from app.errors import invalid
|
||||
from app.idempotency import create_message_once
|
||||
from app.pagination import page_response, pagination
|
||||
from app.responses import json_response
|
||||
from app.store import store
|
||||
from app.validation import parse_uuid, read_payload
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}", re.ASCII)
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages")
|
||||
async def create_message(chat_id: str, request: Request):
|
||||
user, _ = await current_user(request)
|
||||
|
||||
chat_uuid, _ = await accessible_chat(
|
||||
chat_id,
|
||||
user["id"],
|
||||
)
|
||||
|
||||
keys = request.headers.getlist("idempotency-key")
|
||||
if len(keys) != 1 or KEY_RE.fullmatch(keys[0]) is None:
|
||||
raise invalid("Требуется корректный Idempotency-Key")
|
||||
|
||||
payload = await read_payload(
|
||||
request,
|
||||
{"text"},
|
||||
optional_fields={"attachment_ids"},
|
||||
)
|
||||
|
||||
text = payload["text"]
|
||||
if not isinstance(text, str) or len(text) > 4000:
|
||||
raise invalid("Некорректный текст сообщения")
|
||||
|
||||
raw_attachment_ids = payload.get("attachment_ids", [])
|
||||
if (
|
||||
not isinstance(raw_attachment_ids, list)
|
||||
or len(raw_attachment_ids) > 10
|
||||
):
|
||||
raise invalid("Допускается список максимум из 10 вложений")
|
||||
|
||||
attachment_ids = [
|
||||
parse_uuid(value)
|
||||
for value in raw_attachment_ids
|
||||
]
|
||||
|
||||
if len(set(attachment_ids)) != len(attachment_ids):
|
||||
raise invalid("Вложения не должны повторяться")
|
||||
|
||||
if not text.strip() and not attachment_ids:
|
||||
raise invalid("Сообщение должно содержать текст или вложение")
|
||||
|
||||
message = await create_message_once(
|
||||
chat_uuid,
|
||||
user["id"],
|
||||
text,
|
||||
keys[0],
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
|
||||
return json_response(message, 201)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: str, request: Request):
|
||||
user, _ = await current_user(request)
|
||||
|
||||
chat_uuid, _ = await accessible_chat(
|
||||
chat_id,
|
||||
user["id"],
|
||||
)
|
||||
|
||||
scope = f"messages:{chat_uuid}"
|
||||
limit, after = pagination(request, scope)
|
||||
|
||||
rows = await store.list_messages(
|
||||
chat_uuid,
|
||||
limit,
|
||||
after,
|
||||
)
|
||||
|
||||
return page_response(rows, limit, scope)
|
||||
@@ -0,0 +1,82 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import Response
|
||||
|
||||
from app.auth import (
|
||||
DUMMY_PASSWORD_HASH,
|
||||
generate_token,
|
||||
hash_token,
|
||||
parse_basic_credentials,
|
||||
verify_password,
|
||||
)
|
||||
from app.config import SESSION_TTL_SECONDS
|
||||
from app.dependencies import current_user
|
||||
from app.errors import invalid, unauthorized
|
||||
from app.responses import json_response
|
||||
from app.store import store
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions")
|
||||
async def create_session(request: Request):
|
||||
credentials = parse_basic_credentials(
|
||||
request.headers.get("authorization")
|
||||
)
|
||||
|
||||
if credentials is None:
|
||||
raise unauthorized("Basic")
|
||||
|
||||
username, password = credentials
|
||||
|
||||
user = await store.get_user_for_login(username)
|
||||
|
||||
stored_hash = (
|
||||
DUMMY_PASSWORD_HASH
|
||||
if user is None
|
||||
else user["password_hash"]
|
||||
)
|
||||
|
||||
password_ok = await verify_password(stored_hash, password)
|
||||
|
||||
if user is None or not password_ok:
|
||||
raise unauthorized("Basic")
|
||||
|
||||
if await request.body():
|
||||
raise invalid("Тело запроса при входе не допускается")
|
||||
|
||||
token = generate_token()
|
||||
|
||||
session = await store.create_session(
|
||||
user["id"],
|
||||
hash_token(token),
|
||||
SESSION_TTL_SECONDS,
|
||||
)
|
||||
|
||||
public_user = {
|
||||
field: user[field]
|
||||
for field in ("id", "username", "display_name", "created_at")
|
||||
}
|
||||
|
||||
return json_response(
|
||||
{
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": session["expires_at"],
|
||||
"user": public_user,
|
||||
},
|
||||
201,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current")
|
||||
async def revoke_session(request: Request):
|
||||
_, token_digest = await current_user(request)
|
||||
|
||||
revoked = await store.revoke_session(token_digest)
|
||||
|
||||
if not revoked:
|
||||
raise unauthorized()
|
||||
|
||||
return Response(status_code=204)
|
||||
@@ -0,0 +1,59 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.auth import USERNAME_RE, hash_password
|
||||
from app.dependencies import current_user
|
||||
from app.errors import ApiError, invalid
|
||||
from app.responses import json_response
|
||||
from app.store import store
|
||||
from app.validation import read_payload, valid_text
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/users")
|
||||
async def create_user(request: Request):
|
||||
payload = await read_payload(
|
||||
request,
|
||||
{"username", "display_name", "password"},
|
||||
)
|
||||
|
||||
username = payload["username"]
|
||||
display_name = payload["display_name"]
|
||||
password = payload["password"]
|
||||
|
||||
if (
|
||||
not isinstance(username, str)
|
||||
or USERNAME_RE.fullmatch(username) is None
|
||||
):
|
||||
raise invalid("Некорректный username")
|
||||
|
||||
if not valid_text(display_name, 100):
|
||||
raise invalid("Некорректное display_name")
|
||||
|
||||
if not valid_text(password, 128) or len(password) < 12:
|
||||
raise invalid("Пароль должен содержать от 12 до 128 символов")
|
||||
|
||||
password_digest = await hash_password(password)
|
||||
|
||||
user = await store.create_user(
|
||||
username,
|
||||
display_name,
|
||||
password_digest,
|
||||
)
|
||||
|
||||
if user is None:
|
||||
raise ApiError(
|
||||
409,
|
||||
"conflict",
|
||||
"Username уже занят",
|
||||
)
|
||||
|
||||
return json_response(user, 201)
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me")
|
||||
async def get_current_user(request: Request):
|
||||
user, _ = await current_user(request)
|
||||
return json_response(user)
|
||||
Reference in New Issue
Block a user