forked from mtusi2026/mtusi2026lab3
FastAPI + PostgreSQL как единый источник истины: пользователи, Basic/Bearer-сессии, чаты, сообщения. Сессии и идемпотентные ключи хранятся в БД, поэтому реплики взаимозаменяемы. Общая идемпотентность POST сообщения по Idempotency-Key, включая конкурентный повтор через разные реплики. compose.yaml: postgres, one-shot migrate, api1, api2 и nginx как единственная публичная точка входа. Добавлены scripts/stop-one.sh и scripts/restart.sh, student-tests, evidence и заполненный REPORT.md.
100 lines
3.1 KiB
Python
100 lines
3.1 KiB
Python
"""Strict request validation matching contracts/README.md."""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import uuid
|
|
from typing import Any, Iterable
|
|
|
|
from fastapi import Request
|
|
|
|
from .errors import ApiError
|
|
|
|
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}")
|
|
IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
|
|
|
|
|
def invalid(message: str) -> ApiError:
|
|
return ApiError(400, "invalid_request", message)
|
|
|
|
|
|
def reject_unknown_fields(data: dict[str, Any], allowed: Iterable[str]) -> None:
|
|
unknown = set(data) - set(allowed)
|
|
if unknown:
|
|
raise invalid("Request contains unknown fields")
|
|
|
|
|
|
def require_string(data: dict[str, Any], field: str) -> str:
|
|
value = data.get(field)
|
|
if not isinstance(value, str):
|
|
raise invalid(f"Field '{field}' must be a string")
|
|
return value
|
|
|
|
|
|
def validate_username(value: str) -> str:
|
|
if USERNAME_RE.fullmatch(value) is None:
|
|
raise invalid("username must match [a-z0-9_]{3,32}")
|
|
return value
|
|
|
|
|
|
def validate_display_name(value: str) -> str:
|
|
if not 1 <= len(value) <= 100 or not value.strip():
|
|
raise invalid("display_name must contain 1..100 non-blank characters")
|
|
return value
|
|
|
|
|
|
def validate_password(value: str) -> str:
|
|
if not 12 <= len(value) <= 128 or not value.strip():
|
|
raise invalid("password must contain 12..128 non-blank characters")
|
|
return value
|
|
|
|
|
|
def validate_title(value: str) -> str:
|
|
if not 1 <= len(value) <= 100 or not value.strip():
|
|
raise invalid("title must contain 1..100 non-blank characters")
|
|
return value
|
|
|
|
|
|
def validate_message_text(value: str) -> str:
|
|
if not 1 <= len(value) <= 4000 or not value.strip():
|
|
raise invalid("text must contain 1..4000 non-blank characters")
|
|
return value
|
|
|
|
|
|
def parse_uuid(value: str, field: str = "id") -> uuid.UUID:
|
|
try:
|
|
return uuid.UUID(value)
|
|
except (ValueError, AttributeError, TypeError) as exc:
|
|
raise invalid(f"'{field}' must be a UUID") from exc
|
|
|
|
|
|
def validate_member_ids(value: Any) -> list[uuid.UUID]:
|
|
if not isinstance(value, list) or not 1 <= len(value) <= 100:
|
|
raise invalid("member_ids must contain 1..100 UUIDs")
|
|
members: list[uuid.UUID] = []
|
|
for item in value:
|
|
if not isinstance(item, str):
|
|
raise invalid("member_ids must contain UUID strings")
|
|
members.append(parse_uuid(item, "member_ids"))
|
|
if len(set(members)) != len(members):
|
|
raise invalid("member_ids must not contain duplicates")
|
|
return members
|
|
|
|
|
|
def validate_idempotency_key(request: Request) -> str:
|
|
key = request.headers.get("Idempotency-Key")
|
|
if key is None or IDEMPOTENCY_KEY_RE.fullmatch(key) is None:
|
|
raise invalid("Idempotency-Key is required and must match [A-Za-z0-9._:-]{1,128}")
|
|
return key
|
|
|
|
|
|
def parse_limit(request: Request) -> int:
|
|
raw = request.query_params.get("limit")
|
|
if raw is None:
|
|
return 50
|
|
if re.fullmatch(r"[0-9]{1,3}", raw) is None:
|
|
raise invalid("limit must be an integer between 1 and 100")
|
|
value = int(raw)
|
|
if not 1 <= value <= 100:
|
|
raise invalid("limit must be an integer between 1 and 100")
|
|
return value
|