"""FastAPI application implementing the lab3 HTTP contract. Canonical contract: ``contracts/openapi.json`` and ``contracts/README.md``. PostgreSQL is the source of truth; Valkey is a best-effort session cache. Every response carries a non-empty ``X-Request-Id`` and ``X-Instance-Id``. Messages are idempotent per ``Idempotency-Key`` across all replicas. """ from __future__ import annotations import base64 import binascii import logging import re import uuid from typing import Dict, List, Optional from fastapi import Depends, FastAPI, Query, Request, Response from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import BaseModel, ConfigDict, Field, field_validator from psycopg import InterfaceError, OperationalError from psycopg_pool import PoolTimeout from starlette.exceptions import HTTPException as StarletteHTTPException from . import repositories as repo from . import security, sessions, state from .config import settings from .db import pool from .errors import ApiError from .instance import INSTANCE_ID from .pagination import bound_cursor, encode_cursor logger = logging.getLogger("messenger") BEARER_CHALLENGE = 'Bearer realm="messenger"' BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' _BEARER_RE = re.compile(r"^Bearer\s+(\S+)$", re.IGNORECASE) _IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") _STATUS_CODES = { 400: "invalid_request", 401: "unauthorized", 404: "not_found", 405: "invalid_request", 409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type", 429: "rate_limited", 503: "unavailable", } app = FastAPI( title="MTUSI Messenger — лабораторная 3", version="1.3.0", docs_url=None, redoc_url=None, openapi_url=None, ) # --------------------------------------------------------------------------- # # Error envelope # --------------------------------------------------------------------------- # def _request_id(request: Request) -> str: return getattr(request.state, "request_id", None) or uuid.uuid4().hex def error_response( request: Request, status: int, code: str, message: str, challenge: Optional[str] = None ) -> JSONResponse: rid = _request_id(request) headers = {"X-Request-Id": rid, "X-Instance-Id": INSTANCE_ID} if challenge: headers["WWW-Authenticate"] = challenge return JSONResponse( status_code=status, content={"error": {"code": code, "message": message, "request_id": rid}}, headers=headers, ) @app.middleware("http") async def request_context(request: Request, call_next): rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex request.state.request_id = rid try: response = await call_next(request) except Exception as exc: # noqa: BLE001 - never leak internals logging.getLogger("messenger").error("unhandled error: %s", type(exc).__name__) logging.getLogger("messenger").debug("traceback", exc_info=exc) response = error_response(request, 500, "internal_error", "Внутренняя ошибка") response.headers["X-Request-Id"] = rid response.headers["X-Instance-Id"] = INSTANCE_ID return response @app.exception_handler(ApiError) async def handle_api_error(request: Request, exc: ApiError) -> JSONResponse: challenge = exc.challenge or (BEARER_CHALLENGE if exc.status == 401 else None) return error_response(request, exc.status, exc.code, exc.message, challenge) @app.exception_handler(RequestValidationError) async def handle_validation(request: Request, exc: RequestValidationError) -> JSONResponse: return error_response(request, 400, "invalid_request", "Некорректный запрос") @app.exception_handler(StarletteHTTPException) async def handle_http_error(request: Request, exc: StarletteHTTPException) -> JSONResponse: code = _STATUS_CODES.get(exc.status_code, "invalid_request") challenge = BEARER_CHALLENGE if exc.status_code == 401 else None return error_response(request, exc.status_code, code, "Ошибка запроса", challenge) def _handle_db_error(request: Request, exc: Exception) -> JSONResponse: logger.warning("database unavailable: %s", type(exc).__name__) return error_response(request, 503, "unavailable", "База данных недоступна") app.add_exception_handler(OperationalError, _handle_db_error) app.add_exception_handler(InterfaceError, _handle_db_error) app.add_exception_handler(PoolTimeout, _handle_db_error) # --------------------------------------------------------------------------- # # Request schemas # --------------------------------------------------------------------------- # class CreateUser(BaseModel): model_config = ConfigDict(extra="forbid") 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 _not_blank(cls, value: str) -> str: if not value.strip(): raise ValueError("display_name must not be blank") return value class CreateChat(BaseModel): model_config = ConfigDict(extra="forbid") title: str = Field(min_length=1, max_length=100) member_ids: List[uuid.UUID] = Field(min_length=1, max_length=100) @field_validator("title") @classmethod def _not_blank(cls, value: str) -> str: if not value.strip(): raise ValueError("title must not be blank") return value class CreateMessage(BaseModel): model_config = ConfigDict(extra="forbid") text: str = Field(min_length=1, max_length=4000) @field_validator("text") @classmethod def _not_blank(cls, value: str) -> str: if not value.strip(): raise ValueError("text must not be blank") return value # --------------------------------------------------------------------------- # # Dependencies and helpers # --------------------------------------------------------------------------- # def get_conn(): with pool().connection() as conn: yield conn def _canonical_uuid(value: str) -> str: try: return str(uuid.UUID(value)) except (ValueError, AttributeError, TypeError): raise ApiError(400, "invalid_request", "Некорректный идентификатор") def _parse_basic(request: Request) -> tuple[str, str]: header = request.headers.get("Authorization", "").strip() if not header.lower().startswith("basic "): raise ApiError(401, "unauthorized", "Требуется Basic-аутентификация", challenge=BASIC_CHALLENGE) encoded = header[6:].strip() try: decoded = base64.b64decode(encoded, validate=True).decode("utf-8") except (binascii.Error, ValueError, UnicodeDecodeError): raise ApiError(401, "unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE) if ":" not in decoded: raise ApiError(401, "unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE) username, password = decoded.split(":", 1) return username, password def _bearer_token(request: Request) -> str: header = request.headers.get("Authorization", "").strip() match = _BEARER_RE.match(header) if not match: raise ApiError(401, "unauthorized", "Требуется Bearer-токен", challenge=BEARER_CHALLENGE) return match.group(1) def _idempotency_key(request: Request) -> str: value = (request.headers.get("Idempotency-Key") or "").strip() if not value or not _IDEMPOTENCY_RE.match(value): raise ApiError(400, "invalid_request", "Требуется корректный Idempotency-Key") return value def current_user(request: Request, conn=Depends(get_conn)) -> Dict: # Session validity is always checked against PostgreSQL; the cache may only # serve the immutable user profile, never an access decision. token = _bearer_token(request) user_id = sessions.resolve(conn, token) if user_id is None: raise ApiError(401, "unauthorized", "Сессия недействительна", challenge=BEARER_CHALLENGE) user = sessions.cached_user(conn, user_id) if user is None: raise ApiError(401, "unauthorized", "Сессия недействительна", challenge=BEARER_CHALLENGE) return user def _require_chat(conn, chat_id: str, user_id: str) -> str: canonical = _canonical_uuid(chat_id) if repo.get_chat_for(conn, canonical, user_id) is None: raise ApiError(404, "not_found", "Чат недоступен") return canonical # --------------------------------------------------------------------------- # # Health # --------------------------------------------------------------------------- # @app.get("/health/live") def liveness() -> dict: return {"status": "ok"} @app.get("/health/ready") def readiness() -> dict: if state.is_shutting_down(): raise ApiError(503, "unavailable", "Реплика останавливается") try: with pool().connection(timeout=2) as conn: conn.execute("select 1") except (OperationalError, InterfaceError, PoolTimeout): raise ApiError(503, "unavailable", "База данных недоступна") return {"status": "ok"} # --------------------------------------------------------------------------- # # Users and sessions # --------------------------------------------------------------------------- # @app.post("/api/v1/users", status_code=201) def register_user(payload: CreateUser, conn=Depends(get_conn)) -> dict: password_hash = security.hash_password(payload.password) row = repo.create_user(conn, payload.username, payload.display_name, password_hash) return repo.user_json(row) @app.post("/api/v1/auth/sessions", status_code=201) def create_session(request: Request, conn=Depends(get_conn)) -> dict: username, password = _parse_basic(request) row = repo.get_user_with_hash_by_username(conn, username) if row is None or not security.verify_password(row["password_hash"], password): raise ApiError(401, "unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE) token, expires_at = sessions.create(conn, str(row["id"])) return { "token": token, "token_type": "Bearer", "expires_at": repo.rfc3339(expires_at), "user": repo.user_json(row), } @app.delete("/api/v1/auth/sessions/current", status_code=204) def revoke_session( request: Request, user: Dict = Depends(current_user), conn=Depends(get_conn), ) -> Response: sessions.revoke(conn, _bearer_token(request)) return Response(status_code=204) @app.get("/api/v1/users/me") def current_user_endpoint(user: Dict = Depends(current_user)) -> dict: return user # --------------------------------------------------------------------------- # # Chats # --------------------------------------------------------------------------- # @app.post("/api/v1/chats", status_code=201) def create_chat(payload: CreateChat, user: Dict = Depends(current_user), conn=Depends(get_conn)) -> dict: members = [str(member) for member in payload.member_ids] if len(set(members)) != len(members): raise ApiError(400, "invalid_request", "Дубликаты участников") if str(user["id"]) not in members: raise ApiError(400, "invalid_request", "Вызывающий должен входить в участников") if repo.count_users(conn, members) != len(set(members)): raise ApiError(400, "invalid_request", "Неизвестный участник") row = repo.create_chat(conn, payload.title, members) return repo.chat_json(row) @app.get("/api/v1/chats") def list_chats( limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None), user: Dict = Depends(current_user), conn=Depends(get_conn), ) -> dict: key = bound_cursor(cursor, "chats") rows = repo.list_chats(conn, str(user["id"]), limit + 1, key) page = rows[:limit] next_cursor = None if len(rows) > limit: next_cursor = encode_cursor("chats", page[-1]["created_at"], str(page[-1]["id"])) return {"items": [repo.chat_json(row) for row in page], "next_cursor": next_cursor} @app.get("/api/v1/chats/{chat_id}") def get_chat(chat_id: str, user: Dict = Depends(current_user), conn=Depends(get_conn)) -> dict: canonical = _require_chat(conn, chat_id, str(user["id"])) row = repo.get_chat_for(conn, canonical, str(user["id"])) return repo.chat_json(row) # --------------------------------------------------------------------------- # # Messages # --------------------------------------------------------------------------- # @app.post("/api/v1/chats/{chat_id}/messages", status_code=201) def create_message( chat_id: str, payload: CreateMessage, request: Request, user: Dict = Depends(current_user), conn=Depends(get_conn), ) -> dict: canonical = _require_chat(conn, chat_id, str(user["id"])) key = _idempotency_key(request) scope = f"POST /api/v1/chats/{canonical}/messages" return repo.create_message_idempotent( conn, canonical, str(user["id"]), payload.text, scope, key, settings.idempotency_ttl_seconds, ) @app.get("/api/v1/chats/{chat_id}/messages") def list_messages( chat_id: str, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None), user: Dict = Depends(current_user), conn=Depends(get_conn), ) -> dict: canonical = _require_chat(conn, chat_id, str(user["id"])) key = bound_cursor(cursor, canonical) rows = repo.list_messages(conn, canonical, limit + 1, key) page = rows[:limit] next_cursor = None if len(rows) > limit: next_cursor = encode_cursor(canonical, page[-1]["created_at"], str(page[-1]["id"])) return {"items": [repo.message_json(row) for row in page], "next_cursor": next_cursor}