import base64 import binascii import asyncio import hashlib import io import json import logging import os import re import secrets import socket import tempfile import uuid from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone from typing import Any, Dict, List, Optional, Tuple import boto3 import botocore from botocore.config import Config import psycopg import redis from PIL import Image, UnidentifiedImageError from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError from fastapi import Depends, FastAPI, Header, Query, Request, Response from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import BaseModel, ConfigDict, Field, field_validator from psycopg.errors import UniqueViolation from psycopg.rows import dict_row from psycopg_pool import ConnectionPool, PoolTimeout from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.concurrency import run_in_threadpool from app.settings import database_connection, read_setting, session_ttl_seconds logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO")) logger = logging.getLogger("messenger") PASSWORD_HASHER = PasswordHasher() USERNAME_PATTERN = re.compile(r"^[a-z0-9_]{3,32}$") CURSOR_VERSION = 1 MAX_POOL_SIZE = int(os.environ.get("DB_POOL_MAX_SIZE", "10")) if MAX_POOL_SIZE < 1 or MAX_POOL_SIZE > 50: raise RuntimeError("DB_POOL_MAX_SIZE must be between 1 and 50") MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", str(10 * 1024 * 1024))) MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000")) UPLOAD_CONCURRENCY = int(os.environ.get("UPLOAD_CONCURRENCY", "1")) if MAX_UPLOAD_BYTES != 10 * 1024 * 1024 or MAX_IMAGE_PIXELS != 40_000_000: raise RuntimeError("Upload byte/pixel limits must match the public contract") if UPLOAD_CONCURRENCY < 1 or UPLOAD_CONCURRENCY > 4: raise RuntimeError("UPLOAD_CONCURRENCY must be between 1 and 4") Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS class APIError(Exception): def __init__( self, status_code: int, code: str, message: str, challenge: Optional[str] = None ) -> None: self.status_code = status_code self.code = code self.message = message self.challenge = challenge class StrictModel(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) class UserInput(StrictModel): username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") display_name: str = Field(min_length=1, max_length=100) password: str = Field(min_length=12, max_length=128) @field_validator("display_name") @classmethod def display_name_not_blank(cls, value: str) -> str: if not value.strip(): raise ValueError("display_name must not be blank") return value @field_validator("password") @classmethod def password_no_nul(cls, value: str) -> str: if "\x00" in value: raise ValueError("password contains an invalid character") return value class ChatInput(StrictModel): title: str = Field(min_length=1, max_length=100) member_ids: List[str] = Field(min_length=1, max_length=100) @field_validator("title") @classmethod def title_not_blank(cls, value: str) -> str: if not value.strip(): raise ValueError("title must not be blank") return value class MessageInput(StrictModel): text: str = Field(max_length=4000) attachment_ids: List[str] = Field(default_factory=list, max_length=10) @field_validator("attachment_ids") @classmethod def unique_attachment_ids(cls, value: List[str]) -> List[str]: if len(set(value)) != len(value): raise ValueError("attachment_ids must be unique") return value def utc_string(value: datetime) -> str: return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace( "+00:00", "Z" ) def user_json(row: Dict[str, Any]) -> Dict[str, str]: return { "id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], "created_at": utc_string(row["created_at"]), } def chat_json(row: Dict[str, Any], member_ids: List[str]) -> Dict[str, Any]: return { "id": str(row["id"]), "title": row["title"], "member_ids": member_ids, "created_at": utc_string(row["created_at"]), } def message_json(row: Dict[str, Any]) -> Dict[str, Any]: return { "id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": utc_string(row["created_at"]), "attachment_ids": [str(value) for value in row.get("attachment_ids", [])], } def db_unavailable() -> APIError: return APIError(503, "unavailable", "Сервис временно недоступен") def get_connection(): pool: ConnectionPool = app.state.pool try: with pool.connection(timeout=2) as connection: yield connection except (psycopg.OperationalError, PoolTimeout) as exc: logger.warning("database connection unavailable: %s", type(exc).__name__) raise db_unavailable() from None @asynccontextmanager async def lifespan(application: FastAPI): session_ttl_seconds() application.state.pool = ConnectionPool( conninfo="", kwargs={ **database_connection(), "autocommit": True, "row_factory": dict_row, }, min_size=1, max_size=MAX_POOL_SIZE, timeout=2, max_lifetime=1800, open=True, name="messenger-api", ) redis_url = os.environ.get("REDIS_URL", "redis://localhost:6379/0") application.state.redis = redis.Redis.from_url( redis_url, socket_connect_timeout=1, socket_timeout=1, decode_responses=True, health_check_interval=30, ) application.state.instance_id = socket.gethostname() s3_config = Config( connect_timeout=2, read_timeout=5, retries={"max_attempts": 2, "mode": "standard"}, signature_version="s3v4", ) application.state.s3 = boto3.client( "s3", endpoint_url=os.environ.get("S3_ENDPOINT", "http://s3:9000"), region_name=os.environ.get("S3_REGION", "us-east-1"), aws_access_key_id=read_setting("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE"), aws_secret_access_key=read_setting("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE"), config=s3_config, ) application.state.s3_bucket = os.environ.get("S3_BUCKET", "messenger-attachments") application.state.upload_slots = asyncio.Semaphore(UPLOAD_CONCURRENCY) try: yield finally: application.state.redis.close() application.state.pool.close() application.state.s3.close() app = FastAPI(title="Messenger API", version="1.0.0", lifespan=lifespan) @app.middleware("http") async def request_metadata(request: Request, call_next): request_id = request.headers.get("X-Request-Id", "") if not request_id or len(request_id) > 128: request_id = str(uuid.uuid4()) request.state.request_id = request_id try: response = await call_next(request) except Exception: logger.exception("unhandled request failure") response = JSONResponse( status_code=500, content={ "error": { "code": "internal_error", "message": "Внутренняя ошибка", "request_id": request_id, } }, ) response.headers["X-Request-Id"] = request_id response.headers["X-Instance-Id"] = request.app.state.instance_id return response @app.exception_handler(APIError) async def handle_api_error(request: Request, exc: APIError): headers = {"WWW-Authenticate": exc.challenge} if exc.challenge else None return JSONResponse( status_code=exc.status_code, content={ "error": { "code": exc.code, "message": exc.message, "request_id": request.state.request_id, } }, headers=headers, ) @app.exception_handler(RequestValidationError) async def handle_validation_error(request: Request, exc: RequestValidationError): return JSONResponse( status_code=400, content={ "error": { "code": "invalid_request", "message": "Некорректный запрос", "request_id": request.state.request_id, } }, ) @app.exception_handler(StarletteHTTPException) async def handle_http_error(request: Request, exc: StarletteHTTPException): status = 404 if exc.status_code == 404 else exc.status_code code = "not_found" if status == 404 else "invalid_request" return JSONResponse( status_code=status, content={ "error": { "code": code, "message": "Объект не найден" if status == 404 else "Некорректный запрос", "request_id": request.state.request_id, } }, ) @app.exception_handler(psycopg.Error) async def handle_database_error(request: Request, exc: psycopg.Error): logger.warning("database operation failed: %s", type(exc).__name__) return JSONResponse( status_code=503, content={ "error": { "code": "unavailable", "message": "Сервис временно недоступен", "request_id": request.state.request_id, } }, ) @app.exception_handler(PoolTimeout) async def handle_pool_timeout(request: Request, exc: PoolTimeout): return JSONResponse( status_code=503, content={ "error": { "code": "unavailable", "message": "Сервис временно недоступен", "request_id": request.state.request_id, } }, ) def auth_error(challenge: str = 'Bearer realm="messenger"') -> APIError: return APIError(401, "unauthorized", "Требуется действительная аутентификация", challenge) def parse_uuid(value: str) -> uuid.UUID: try: return uuid.UUID(value) except (ValueError, AttributeError, TypeError): raise APIError(400, "invalid_request", "Некорректный UUID") from None def authenticated_user( request: Request, authorization: Optional[str] = Header(default=None), connection=Depends(get_connection), ) -> Dict[str, Any]: if not authorization or not authorization.startswith("Bearer "): raise auth_error() token = authorization[7:] if not token or len(token) > 256: raise auth_error() token_hash = hashlib.sha256(token.encode("utf-8")).digest() now = datetime.now(timezone.utc) cache = request.app.state.redis cache_key = "session:" + token_hash.hex() cached: Optional[Dict[str, Any]] = None try: raw = cache.get(cache_key) if raw: cached_value = json.loads(raw) if isinstance(cached_value, dict): cached = cached_value else: logger.warning("session cache entry has an invalid shape") except (redis.RedisError, json.JSONDecodeError): logger.warning("session cache read failed; using PostgreSQL") try: session = connection.execute( """ SELECT s.user_id, s.expires_at, s.revoked_at FROM sessions AS s WHERE s.token_hash = %s """, (token_hash,), ).fetchone() except psycopg.Error as exc: logger.warning("session lookup failed: %s", type(exc).__name__) raise db_unavailable() from None if not session or session["revoked_at"] is not None or session["expires_at"] <= now: try: cache.delete(cache_key) except redis.RedisError: logger.warning("expired session cache invalidation failed") raise auth_error() # PostgreSQL remains authoritative for expiry and revocation. Redis avoids # a user-profile query on a cache hit. if cached and cached.get("user_id") == str(session["user_id"]): profile = cached.get("user") if isinstance(profile, dict) and profile.get("id") == str(session["user_id"]): user = profile else: cached = None else: cached = None if not cached: profile_row = connection.execute( """ SELECT id, username, display_name, created_at FROM users WHERE id = %s """, (session["user_id"],), ).fetchone() if not profile_row: raise auth_error() user = user_json(profile_row) remaining = max(1, int((session["expires_at"] - now).total_seconds())) try: cache.set( cache_key, json.dumps({"user_id": str(session["user_id"]), "user": user}), ex=remaining, ) except redis.RedisError: logger.warning("session cache write failed; continuing with PostgreSQL") request.state.token_hash = token_hash return user @app.get("/health/live") def live() -> Dict[str, str]: return {"status": "ok"} @app.get("/health/ready") def ready(request: Request, connection=Depends(get_connection)) -> Dict[str, str]: try: connection.execute("SELECT 1") request.app.state.s3.head_bucket(Bucket=request.app.state.s3_bucket) except psycopg.Error: raise db_unavailable() from None except botocore.exceptions.BotoCoreError: raise APIError(503, "unavailable", "S3-хранилище временно недоступно") from None except botocore.exceptions.ClientError: raise APIError(503, "unavailable", "S3-хранилище временно недоступно") from None return {"status": "ok"} @app.post("/api/v1/users", status_code=201) def register_user(payload: UserInput, connection=Depends(get_connection)): user_id = uuid.uuid4() password_hash = PASSWORD_HASHER.hash(payload.password) try: with connection.transaction(): row = connection.execute( """ INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s) RETURNING id, username, display_name, created_at """, (user_id, payload.username, payload.display_name, password_hash), ).fetchone() except UniqueViolation: raise APIError(409, "conflict", "Имя пользователя уже занято") from None except psycopg.Error as exc: logger.warning("user registration failed: %s", type(exc).__name__) raise db_unavailable() from None return user_json(row) def decode_basic_credentials(authorization: Optional[str]) -> Tuple[str, str]: challenge = 'Basic realm="messenger", charset="UTF-8"' if not authorization or not authorization.startswith("Basic "): raise auth_error(challenge) try: raw = base64.b64decode(authorization[6:], validate=True).decode("utf-8") username, password = raw.split(":", 1) except (binascii.Error, UnicodeDecodeError, ValueError): raise auth_error(challenge) from None if not USERNAME_PATTERN.fullmatch(username) or not 12 <= len(password) <= 128: raise auth_error(challenge) return username, password @app.post("/api/v1/auth/sessions", status_code=201) def create_session( request: Request, authorization: Optional[str] = Header(default=None), connection=Depends(get_connection), ): username, password = decode_basic_credentials(authorization) row = connection.execute( """ SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s """, (username,), ).fetchone() if not row: raise auth_error('Basic realm="messenger", charset="UTF-8"') try: PASSWORD_HASHER.verify(row["password_hash"], password) except (VerifyMismatchError, VerificationError, InvalidHashError): raise auth_error('Basic realm="messenger", charset="UTF-8"') from None token = secrets.token_urlsafe(32) token_hash = hashlib.sha256(token.encode("utf-8")).digest() expires_at = datetime.now(timezone.utc) + timedelta(seconds=session_ttl_seconds()) try: with connection.transaction(): connection.execute( """ INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s) """, (token_hash, row["id"], expires_at), ) except psycopg.Error as exc: logger.warning("session creation failed: %s", type(exc).__name__) raise db_unavailable() from None user = user_json(row) try: request.app.state.redis.set( "session:" + token_hash.hex(), json.dumps({"user_id": str(row["id"]), "user": user}), ex=session_ttl_seconds(), ) except redis.RedisError: logger.warning("session cache write failed; session remains durable in PostgreSQL") return { "token": token, "token_type": "Bearer", "expires_at": utc_string(expires_at), "user": user, } @app.delete("/api/v1/auth/sessions/current", status_code=204) def revoke_session( request: Request, user: Dict[str, Any] = Depends(authenticated_user), connection=Depends(get_connection), ): token_hash: bytes = request.state.token_hash try: with connection.transaction(): result = connection.execute( """ UPDATE sessions SET revoked_at = clock_timestamp() WHERE token_hash = %s AND revoked_at IS NULL """, (token_hash,), ) if result.rowcount != 1: raise auth_error() except APIError: raise except psycopg.Error as exc: logger.warning("session revocation failed: %s", type(exc).__name__) raise db_unavailable() from None try: request.app.state.redis.delete("session:" + token_hash.hex()) except redis.RedisError: logger.warning("revoked session cache invalidation failed") return Response(status_code=204) @app.get("/api/v1/users/me") def current_user(user: Dict[str, Any] = Depends(authenticated_user)): return user def member_ids_for(connection, chat_id: uuid.UUID) -> List[str]: rows = connection.execute( "SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id", (chat_id,), ).fetchall() return [str(row["user_id"]) for row in rows] def require_chat_member( connection, chat_id: uuid.UUID, user_id: uuid.UUID ) -> Dict[str, Any]: row = connection.execute( """ SELECT c.id, c.title, c.created_at FROM chats AS c JOIN chat_members AS cm ON cm.chat_id = c.id WHERE c.id = %s AND cm.user_id = %s """, (chat_id, user_id), ).fetchone() if not row: raise APIError(404, "not_found", "Объект не найден") return row @app.post("/api/v1/chats", status_code=201) def create_chat( payload: ChatInput, user: Dict[str, Any] = Depends(authenticated_user), connection=Depends(get_connection), ): ids = [parse_uuid(member_id) for member_id in payload.member_ids] if len(set(ids)) != len(ids) or uuid.UUID(user["id"]) not in ids: raise APIError(400, "invalid_request", "Некорректный список участников") chat_id = uuid.uuid4() try: with connection.transaction(): found = connection.execute( "SELECT id FROM users WHERE id = ANY(%s)", (ids,), ).fetchall() if len(found) != len(ids): raise APIError(400, "invalid_request", "Участник не существует") chat = connection.execute( """ INSERT INTO chats (id, title) VALUES (%s, %s) RETURNING id, title, created_at """, (chat_id, payload.title), ).fetchone() for member_id in ids: connection.execute( "INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", (chat_id, member_id), ) except APIError: raise except psycopg.Error as exc: logger.warning("chat creation rolled back: %s", type(exc).__name__) raise db_unavailable() from None return chat_json(chat, [str(member_id) for member_id in sorted(ids)]) @app.get("/api/v1/chats") def list_chats( user: Dict[str, Any] = Depends(authenticated_user), connection=Depends(get_connection), limit: int = 50, cursor: Optional[str] = None, ): if limit < 1 or limit > 100: raise APIError(400, "invalid_request", "limit должен быть от 1 до 100") cursor_values = decode_cursor(cursor, "chats") if cursor else None parameters: List[Any] = [uuid.UUID(user["id"])] clause = "" if cursor_values: clause = "AND (c.created_at, c.id) > (%s, %s)" parameters.extend(cursor_values) parameters.append(limit + 1) rows = connection.execute( """ SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id = c.id WHERE cm.user_id = %s """ + clause + " ORDER BY c.created_at, c.id LIMIT %s", parameters, ).fetchall() has_more = len(rows) > limit rows = rows[:limit] items = [ chat_json(row, member_ids_for(connection, row["id"])) for row in rows ] next_cursor = encode_cursor("chats", rows[-1]) if has_more and rows else None return {"items": items, "next_cursor": next_cursor} @app.get("/api/v1/chats/{chat_id}") def get_chat( chat_id: str, user: Dict[str, Any] = Depends(authenticated_user), connection=Depends(get_connection), ): parsed_id = parse_uuid(chat_id) row = require_chat_member(connection, parsed_id, uuid.UUID(user["id"])) return chat_json(row, member_ids_for(connection, parsed_id)) def encode_cursor(kind: str, row: Dict[str, Any]) -> str: payload = json.dumps( [CURSOR_VERSION, kind, str(row["created_at"]), str(row["id"])], separators=(",", ":"), ).encode("utf-8") return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=") def decode_cursor(value: str, kind: str) -> Tuple[datetime, uuid.UUID]: try: padded = value + "=" * (-len(value) % 4) decoded = json.loads(base64.urlsafe_b64decode(padded.encode("ascii"))) if ( not isinstance(decoded, list) or len(decoded) != 4 or decoded[0] != CURSOR_VERSION or decoded[1] != kind ): raise ValueError created_at = datetime.fromisoformat(decoded[2]) if created_at.tzinfo is None: raise ValueError return created_at, uuid.UUID(decoded[3]) except (ValueError, TypeError, UnicodeError, json.JSONDecodeError): raise APIError(400, "invalid_request", "Некорректный cursor") from None @app.post("/api/v1/chats/{chat_id}/messages", status_code=201) def create_message( chat_id: str, payload: MessageInput, idempotency_key: Optional[str] = Header(default=None, alias="Idempotency-Key"), user: Dict[str, Any] = Depends(authenticated_user), connection=Depends(get_connection), ): if not idempotency_key or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", idempotency_key): raise APIError(400, "invalid_request", "Некорректный Idempotency-Key") parsed_chat_id = parse_uuid(chat_id) chat = require_chat_member(connection, parsed_chat_id, uuid.UUID(user["id"])) if not payload.text.strip() and not payload.attachment_ids: raise APIError(400, "invalid_request", "Сообщение не может быть пустым") attachment_ids = [parse_uuid(value) for value in payload.attachment_ids] sender_id = uuid.UUID(user["id"]) request_hash = hashlib.sha256( json.dumps( {"text": payload.text, "attachment_ids": [str(value) for value in attachment_ids]}, ensure_ascii=False, sort_keys=True, ).encode("utf-8") ).digest() legacy_request_hash = hashlib.sha256( json.dumps({"text": payload.text}, ensure_ascii=False, sort_keys=True).encode("utf-8") ).digest() try: with connection.transaction(): if attachment_ids: attachments = connection.execute( """ SELECT id, status FROM attachments WHERE chat_id = %s AND id = ANY(%s) """, (chat["id"], attachment_ids), ).fetchall() if len(attachments) != len(attachment_ids): raise APIError(404, "not_found", "Объект не найден") if any(row["status"] != "ready" for row in attachments): raise APIError(409, "conflict", "Вложение ещё не готово") claim = connection.execute( """ INSERT INTO idempotency_keys (user_id, chat_id, idempotency_key, request_hash) VALUES (%s, %s, %s, %s) ON CONFLICT (user_id, chat_id, idempotency_key) DO UPDATE SET request_hash = EXCLUDED.request_hash, message_id = NULL, created_at = clock_timestamp() WHERE idempotency_keys.created_at < clock_timestamp() - interval '24 hours' RETURNING user_id """, (sender_id, chat["id"], idempotency_key, request_hash), ).fetchone() if claim: row = connection.execute( """ INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s) RETURNING id, chat_id, sender_id, text, created_at """, (uuid.uuid4(), chat["id"], sender_id, payload.text), ).fetchone() for ordinal, attachment_id in enumerate(attachment_ids): connection.execute( """ INSERT INTO message_attachments (message_id, chat_id, attachment_id, ordinal) VALUES (%s, %s, %s, %s) """, (row["id"], chat["id"], attachment_id, ordinal), ) row["attachment_ids"] = attachment_ids result = message_json(row) connection.execute( """ UPDATE idempotency_keys SET message_id = %s WHERE user_id = %s AND chat_id = %s AND idempotency_key = %s """, (row["id"], sender_id, chat["id"], idempotency_key), ) else: existing = connection.execute( """ SELECT request_hash, message_id FROM idempotency_keys WHERE user_id = %s AND chat_id = %s AND idempotency_key = %s """, (sender_id, chat["id"], idempotency_key), ).fetchone() compatible_hashes = {request_hash} if not attachment_ids: compatible_hashes.add(legacy_request_hash) if not existing or existing["request_hash"] not in compatible_hashes: raise APIError(409, "conflict", "Ключ идемпотентности уже использован") row = connection.execute( """ SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, COALESCE(array_agg(ma.attachment_id ORDER BY ma.ordinal) FILTER (WHERE ma.attachment_id IS NOT NULL), '{}') AS attachment_ids FROM messages AS m LEFT JOIN message_attachments AS ma ON ma.message_id = m.id WHERE m.id = %s GROUP BY m.id """, (existing["message_id"],), ).fetchone() if not row: raise APIError(503, "unavailable", "Результат запроса временно недоступен") result = message_json(row) except APIError: raise except psycopg.Error as exc: logger.warning("message write failed: %s", type(exc).__name__) raise db_unavailable() from None return result @app.get("/api/v1/chats/{chat_id}/messages") def list_messages( chat_id: str, user: Dict[str, Any] = Depends(authenticated_user), connection=Depends(get_connection), limit: int = 50, cursor: Optional[str] = None, ): if limit < 1 or limit > 100: raise APIError(400, "invalid_request", "limit должен быть от 1 до 100") parsed_chat_id = parse_uuid(chat_id) chat = require_chat_member(connection, parsed_chat_id, uuid.UUID(user["id"])) cursor_values = decode_cursor(cursor, str(parsed_chat_id)) if cursor else None parameters: List[Any] = [chat["id"]] clause = "" if cursor_values: clause = "AND (created_at, id) > (%s, %s)" parameters.extend(cursor_values) parameters.append(limit + 1) rows = connection.execute( """ SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, COALESCE(array_agg(ma.attachment_id ORDER BY ma.ordinal) FILTER (WHERE ma.attachment_id IS NOT NULL), '{}') AS attachment_ids FROM messages AS m LEFT JOIN message_attachments AS ma ON ma.message_id = m.id WHERE m.chat_id = %s """ + clause + " GROUP BY m.id ORDER BY m.created_at, m.id LIMIT %s", parameters, ).fetchall() has_more = len(rows) > limit rows = rows[:limit] items = [message_json(row) for row in rows] next_cursor = encode_cursor(str(parsed_chat_id), rows[-1]) if has_more and rows else None return {"items": items, "next_cursor": next_cursor} def attachment_json(row: Dict[str, Any]) -> Dict[str, Any]: return { "id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]), "filename": row["filename"], "content_type": row["content_type"], "size_bytes": row["size_bytes"], "sha256": row["sha256"].strip(), "status": row["status"], "variants": [], "error_code": None, "created_at": utc_string(row["created_at"]), "updated_at": utc_string(row["updated_at"]), } def attachment_for_member(connection, attachment_id: uuid.UUID, user_id: uuid.UUID): row = connection.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 JOIN chat_members AS cm ON cm.chat_id = a.chat_id WHERE a.id = %s AND cm.user_id = %s """, (attachment_id, user_id), ).fetchone() if not row: raise APIError(404, "not_found", "Объект не найден") return row def image_details(upload, declared_type: str) -> Tuple[str, int, int]: try: upload.seek(0) with Image.open(upload) as image: actual_type = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format) if actual_type != declared_type: raise APIError(415, "unsupported_media_type", "Тип файла не соответствует содержимому") width, height = image.size if width < 1 or height < 1 or width * height > MAX_IMAGE_PIXELS: raise APIError(413, "payload_too_large", "Превышен лимит размера изображения") image.verify() upload.seek(0) with Image.open(upload) as image: image.load() except APIError: raise except (Image.DecompressionBombError, Image.DecompressionBombWarning): raise APIError(413, "payload_too_large", "Превышен лимит размера изображения") from None except (UnidentifiedImageError, OSError, ValueError): raise APIError(415, "unsupported_media_type", "Повреждённое или неподдерживаемое изображение") from None upload.seek(0) return declared_type, width, height def s3_unavailable() -> APIError: return APIError(503, "unavailable", "Файловое хранилище временно недоступно") @app.post("/api/v1/chats/{chat_id}/attachments", status_code=201) async def upload_attachment( chat_id: str, request: Request, filename: str = Query(..., min_length=1, max_length=255), user: Dict[str, Any] = Depends(authenticated_user), connection=Depends(get_connection), ): parsed_chat_id = parse_uuid(chat_id) require_chat_member(connection, parsed_chat_id, uuid.UUID(user["id"])) if any(char in filename for char in ("/", "\\", "\x00")) or any( ord(char) < 32 or 127 <= ord(char) <= 159 for char in filename ): raise APIError(400, "invalid_request", "Некорректное имя файла") declared_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower() if declared_type not in {"image/png", "image/jpeg"}: raise APIError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG") content_length = request.headers.get("content-length") if content_length: try: if int(content_length) > MAX_UPLOAD_BYTES: raise APIError(413, "payload_too_large", "Файл превышает лимит 10 MiB") except ValueError: raise APIError(400, "invalid_request", "Некорректный Content-Length") from None async with request.app.state.upload_slots: digest = hashlib.sha256() size = 0 with tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b") as upload: async for chunk in request.stream(): size += len(chunk) if size > MAX_UPLOAD_BYTES: raise APIError(413, "payload_too_large", "Файл превышает лимит 10 MiB") digest.update(chunk) upload.write(chunk) if size == 0: raise APIError(400, "invalid_request", "Файл не может быть пустым") actual_type, _, _ = image_details(upload, declared_type) attachment_id = uuid.uuid4() object_key = "attachments/" + str(attachment_id) s3 = request.app.state.s3 bucket = request.app.state.s3_bucket try: await run_in_threadpool( s3.upload_fileobj, upload, bucket, object_key, ExtraArgs={ "ContentType": actual_type, "Metadata": {"sha256": digest.hexdigest()}, }, ) except botocore.exceptions.BotoCoreError: logger.warning("S3 upload failed: %s", object_key) raise s3_unavailable() from None except botocore.exceptions.ClientError: logger.warning("S3 upload failed: %s", object_key) raise s3_unavailable() from None try: with connection.transaction(): row = connection.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, parsed_chat_id, uuid.UUID(user["id"]), filename, actual_type, size, digest.hexdigest(), object_key, ), ).fetchone() except psycopg.Error as exc: logger.warning("attachment metadata write failed: %s", type(exc).__name__) try: await run_in_threadpool(s3.delete_object, Bucket=bucket, Key=object_key) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError): logger.exception("S3 compensation failed for %s", object_key) raise db_unavailable() from None return attachment_json(row) @app.get("/api/v1/attachments/{attachment_id}") def get_attachment( attachment_id: str, user: Dict[str, Any] = Depends(authenticated_user), connection=Depends(get_connection), ): row = attachment_for_member( connection, parse_uuid(attachment_id), uuid.UUID(user["id"]) ) return attachment_json(row) @app.get("/api/v1/attachments/{attachment_id}/content") def download_attachment( attachment_id: str, request: Request, user: Dict[str, Any] = Depends(authenticated_user), connection=Depends(get_connection), variant: str = "original", ): if variant != "original": raise APIError(404, "not_found", "Объект не найден") row = attachment_for_member( connection, parse_uuid(attachment_id), uuid.UUID(user["id"]) ) try: result = request.app.state.s3.get_object( Bucket=request.app.state.s3_bucket, Key=row["object_key"] ) with result["Body"] as body: content = body.read(MAX_UPLOAD_BYTES + 1) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError): logger.warning("S3 download failed for attachment %s", row["id"]) raise s3_unavailable() from None if len(content) != row["size_bytes"] or hashlib.sha256(content).hexdigest() != row["sha256"].strip(): logger.error("S3 object integrity check failed for attachment %s", row["id"]) raise s3_unavailable() return Response(content=content, media_type=row["content_type"])