Files
mtusi2026lab2/app/main.py

434 lines
17 KiB
Python

"""Lab2 messenger HTTP layer. Contract: contracts/openapi.json.
State lives in PostgreSQL: users, chats, memberships, messages and sessions.
Basic is accepted only on POST /auth/sessions; every other protected route needs Bearer.
"""
import base64
import binascii
import datetime as dt
import json
import logging
import os
import re
import uuid
from contextlib import asynccontextmanager
import psycopg
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from starlette.datastructures import MutableHeaders
from starlette.exceptions import HTTPException as StarletteHTTPException
from .db import chat_public, db, message_public, user_public, utc_text
from .security import bearer_token, hash_password, parse_basic, token_hash, verify_password
log = logging.getLogger("messenger")
MAX_BODY_BYTES = 1 << 20
DEFAULT_LIMIT, MAX_LIMIT = 50, 100
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}\Z")
UUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\Z")
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
INSTANCE_ID = os.environ.get("INSTANCE_ALIAS") or uuid.uuid4().hex[:12]
UTC = dt.timezone.utc
class ApiError(Exception):
def __init__(self, status, code, message, headers=None):
self.status, self.code, self.message, self.headers = status, code, message, headers
def bad_request(message):
return ApiError(400, "invalid_request", message)
def unauthorized(challenge, message="Требуется действительная аутентификация"):
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge})
def not_found():
return ApiError(404, "not_found", "Объект не найден")
def error_response(status, code, message, request_id, headers=None):
body = {"error": {"code": code, "message": message, "request_id": request_id}}
return JSONResponse(body, status_code=status, headers=headers)
class RequestContextMiddleware:
"""Add X-Request-Id (and X-Instance-Id) to every response, including errors and health."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
request_id = str(uuid.uuid4())
scope.setdefault("state", {})["request_id"] = request_id
started = False
async def send_with_id(message):
nonlocal started
if message["type"] == "http.response.start":
started = True
headers = MutableHeaders(scope=message)
headers["X-Request-Id"] = request_id
headers["X-Instance-Id"] = INSTANCE_ID
await send(message)
try:
await self.app(scope, receive, send_with_id)
except Exception:
log.exception("unhandled error request_id=%s", request_id)
if not started:
response = error_response(500, "internal_error", "Внутренняя ошибка сервера", request_id)
await response(scope, receive, send_with_id)
@asynccontextmanager
async def lifespan(app):
db.start()
try:
yield
finally:
db.stop()
app = FastAPI(title="Messenger lab2", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
app.add_middleware(RequestContextMiddleware)
@app.exception_handler(ApiError)
async def handle_api_error(request: Request, exc: ApiError):
return error_response(exc.status, exc.code, exc.message, request.state.request_id, exc.headers)
@app.exception_handler(StarletteHTTPException)
async def handle_http_exception(request: Request, exc: StarletteHTTPException):
if exc.status_code == 404:
code, message = "not_found", "Объект не найден"
elif exc.status_code < 500:
code, message = "invalid_request", "Некорректный запрос"
else:
code, message = "internal_error", "Внутренняя ошибка сервера"
return error_response(exc.status_code, code, message, request.state.request_id, exc.headers)
@app.exception_handler(RequestValidationError)
async def handle_validation_error(request: Request, exc: RequestValidationError):
return error_response(400, "invalid_request", "Некорректный запрос", request.state.request_id)
# ---------- validation helpers ----------
def clean_string(data, field, max_len):
value = data.get(field)
if not isinstance(value, str):
raise bad_request("Поле %s должно быть строкой" % field)
if not value.strip() or len(value) > max_len:
raise bad_request("Поле %s должно содержать от 1 до %d символов" % (field, max_len))
return value
def parse_uuid(value, what):
if not isinstance(value, str) or not UUID_RE.fullmatch(value):
raise bad_request("Некорректный UUID: %s" % what)
return value.lower()
async def read_json_object(request, allowed):
declared = request.headers.get("content-length", "")
if declared.isdigit() and int(declared) > MAX_BODY_BYTES:
raise ApiError(413, "payload_too_large", "Тело запроса слишком большое")
content_type = request.headers.get("content-type", "").split(";")[0].strip().lower()
if content_type and content_type != "application/json":
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
body = bytearray()
async for chunk in request.stream():
body += chunk
if len(body) > MAX_BODY_BYTES:
raise ApiError(413, "payload_too_large", "Тело запроса слишком большое")
try:
data = json.loads(bytes(body).decode("utf-8"))
except (UnicodeDecodeError, ValueError):
raise bad_request("Тело запроса не является корректным JSON") from None
if not isinstance(data, dict):
raise bad_request("Тело запроса должно быть JSON-объектом")
if set(data) != set(allowed):
raise bad_request("Ожидаемые поля: " + ", ".join(sorted(allowed)))
return data
def page_params(request):
query = request.query_params
raw_limit = query.getlist("limit")
if len(raw_limit) > 1 or len(query.getlist("cursor")) > 1:
raise bad_request("Параметры limit и cursor можно указать только один раз")
limit = DEFAULT_LIMIT
if raw_limit:
text = raw_limit[0]
if not (text.isascii() and text.isdigit()) or not 1 <= int(text) <= MAX_LIMIT:
raise bad_request("limit должен быть целым числом от 1 до %d" % MAX_LIMIT)
limit = int(text)
return limit, query.get("cursor") or None
def encode_cursor(kind, scope, created_at, item_id):
raw = json.dumps(
{"k": kind, "s": scope,
"t": int(created_at.timestamp() * 1_000_000),
"i": uuid.UUID(str(item_id)).int},
separators=(",", ":"),
)
return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
def decode_cursor(text, kind, scope):
try:
data = json.loads(base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)))
t, i = data["t"], data["i"]
valid = (data["k"] == kind and data["s"] == scope
and type(t) is int and type(i) is int and t >= 0 and i >= 0)
if not valid:
raise ValueError
return dt.datetime.fromtimestamp(t / 1_000_000, tz=UTC), uuid.UUID(int=i)
except (ValueError, KeyError, TypeError, binascii.Error, OverflowError):
raise bad_request("Некорректный cursor") from None
def page_response(items, limit, kind, scope, rows):
"""items are public JSON dicts; rows are the raw DB rows used for the opaque cursor."""
more = len(items) > limit
window = items[:limit]
last = rows[limit - 1] if more and len(rows) >= limit else None
cursor = (encode_cursor(kind, scope, last["created_at"], last["id"])
if last is not None else None)
return JSONResponse({"items": window, "next_cursor": cursor})
# ---------- authentication and resource access ----------
def current_user(request):
"""Lab2: only an opaque Bearer session identifies the caller; X-User-Id is ignored."""
token = bearer_token(request.headers.get("authorization"))
if not token:
raise unauthorized(BEARER_CHALLENGE)
with db.connection() as conn:
row = conn.execute(
"SELECT u.id, u.username, u.display_name, u.created_at "
"FROM sessions s JOIN users u ON u.id = s.user_id "
"WHERE s.token_hash = %s AND s.expires_at > clock_timestamp()",
(token_hash(token),),
).fetchone()
if row is None:
raise unauthorized(BEARER_CHALLENGE)
return user_public(row)
def authenticated_chat(request, chat_id):
user = current_user(request)
chat_uuid = parse_uuid(chat_id, "chat_id")
with db.connection() as conn:
row = conn.execute(
"SELECT c.id, c.title, c.created_at, "
"array_agg(m.user_id ORDER BY m.user_id) AS member_ids "
"FROM chats c JOIN chat_members m ON m.chat_id = c.id "
"WHERE c.id = %s AND m.user_id = %s GROUP BY c.id",
(chat_uuid, uuid.UUID(user["id"])),
).fetchone()
if row is None:
raise not_found() # unknown and foreign chats look identical
return user, chat_public(row)
# ---------- health ----------
@app.get("/health/live")
async def live():
return {"status": "ok"}
@app.get("/health/ready")
async def ready():
if not db.ready():
raise ApiError(503, "unavailable", "Хранилище данных недоступно")
return {"status": "ok"}
# ---------- users and sessions ----------
@app.post("/api/v1/users")
async def register_user(request: Request):
data = await read_json_object(request, ("username", "display_name", "password"))
username = data["username"]
if not isinstance(username, str) or not USERNAME_RE.fullmatch(username):
raise bad_request("username должен соответствовать [a-z0-9_]{3,32}")
display_name = clean_string(data, "display_name", 100)
password = data["password"]
if not isinstance(password, str) or not 12 <= len(password) <= 128:
raise bad_request("password должен содержать от 12 до 128 символов")
user_id = uuid.uuid4()
try:
with db.transaction() as conn:
conn.execute(
"INSERT INTO users(id, username, display_name, password_hash) VALUES (%s,%s,%s,%s)",
(user_id, username, display_name, hash_password(password)),
)
row = conn.execute("SELECT * FROM users WHERE id = %s", (user_id,)).fetchone()
except psycopg.errors.UniqueViolation:
raise ApiError(409, "conflict", "Имя пользователя уже занято") from None
return JSONResponse(user_public(row), status_code=201)
@app.post("/api/v1/auth/sessions")
async def create_session(request: Request):
credential = parse_basic(request.headers.get("authorization"))
if credential is None:
raise unauthorized(BASIC_CHALLENGE, "Неверные учетные данные")
username, password = credential
with db.connection() as conn:
row = conn.execute("SELECT * FROM users WHERE username = %s", (username,)).fetchone()
if row is None or not verify_password(password, row["password_hash"]):
raise unauthorized(BASIC_CHALLENGE, "Неверные учетные данные")
token = base64.urlsafe_b64encode(os.urandom(32)).decode().rstrip("=")
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
expires_at = dt.datetime.now(UTC) + dt.timedelta(seconds=ttl)
with db.transaction() as conn:
conn.execute(
"INSERT INTO sessions(token_hash, user_id, expires_at) VALUES (%s,%s,%s)",
(token_hash(token), row["id"], expires_at),
)
return JSONResponse({
"token": token,
"token_type": "Bearer",
"expires_at": utc_text(expires_at),
"user": user_public(row),
}, status_code=201)
@app.delete("/api/v1/auth/sessions/current")
async def revoke_session(request: Request):
token = bearer_token(request.headers.get("authorization"))
if not token:
raise unauthorized(BEARER_CHALLENGE)
with db.transaction() as conn:
result = conn.execute(
"DELETE FROM sessions WHERE token_hash = %s AND expires_at > clock_timestamp()",
(token_hash(token),),
)
if result.rowcount == 0:
raise unauthorized(BEARER_CHALLENGE)
return Response(status_code=204)
@app.get("/api/v1/users/me")
async def get_me(request: Request):
return current_user(request)
# ---------- chats ----------
@app.post("/api/v1/chats")
async def create_chat(request: Request):
user = current_user(request)
data = await read_json_object(request, ("title", "member_ids"))
title = clean_string(data, "title", 100)
raw_members = data["member_ids"]
if not isinstance(raw_members, list) or not 1 <= len(raw_members) <= 100:
raise bad_request("member_ids должен быть списком из 1–100 UUID")
members = [parse_uuid(m, "member_ids") for m in raw_members]
if len(set(members)) != len(members):
raise bad_request("member_ids содержит дубликаты")
if user["id"] not in members:
raise bad_request("member_ids должен содержать вызывающего пользователя")
chat_id = uuid.uuid4()
member_uuids = [uuid.UUID(x) for x in members]
try:
with db.transaction() as conn:
found = conn.execute(
"SELECT id FROM users WHERE id = ANY(%s::uuid[])", (member_uuids,)
).fetchall()
if len(found) != len(member_uuids):
raise bad_request("member_ids содержит неизвестного пользователя")
conn.execute("INSERT INTO chats(id, title) VALUES (%s,%s)", (chat_id, title))
for member in member_uuids:
conn.execute(
"INSERT INTO chat_members(chat_id, user_id) VALUES (%s,%s)",
(chat_id, member),
)
row = conn.execute(
"SELECT c.id, c.title, c.created_at, array_agg(m.user_id ORDER BY m.user_id) AS member_ids "
"FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE c.id = %s GROUP BY c.id",
(chat_id,),
).fetchone()
except psycopg.errors.ForeignKeyViolation:
raise bad_request("member_ids содержит неизвестного пользователя") from None
return JSONResponse(chat_public(row), status_code=201)
@app.get("/api/v1/chats")
async def list_chats(request: Request):
user = current_user(request)
limit, cursor = page_params(request)
after = decode_cursor(cursor, "chats", user["id"]) if cursor else None
sql = (
"SELECT c.id, c.title, c.created_at, array_agg(m.user_id ORDER BY m.user_id) AS member_ids "
"FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = %s"
)
params = [uuid.UUID(user["id"])]
if after:
sql += " AND (c.created_at, c.id) > (%s, %s::uuid)"
params.extend([after[0], after[1]])
sql += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT %s"
params.append(limit + 1)
with db.connection() as conn:
rows = conn.execute(sql, params).fetchall()
items = [chat_public(r) for r in rows]
return page_response(items, limit, "chats", user["id"], rows)
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, request: Request):
_, chat = authenticated_chat(request, chat_id)
return chat
# ---------- messages ----------
@app.post("/api/v1/chats/{chat_id}/messages")
async def create_message(chat_id: str, request: Request):
user, chat = authenticated_chat(request, chat_id)
data = await read_json_object(request, ("text",))
text = clean_string(data, "text", 4000)
message_id = uuid.uuid4()
with db.transaction() as conn:
conn.execute(
"INSERT INTO messages(id, chat_id, sender_id, text) VALUES (%s,%s,%s,%s)",
(message_id, uuid.UUID(chat["id"]), uuid.UUID(user["id"]), text),
)
row = conn.execute("SELECT * FROM messages WHERE id = %s", (message_id,)).fetchone()
return JSONResponse(message_public(row), status_code=201)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, request: Request):
_, chat = authenticated_chat(request, chat_id)
limit, cursor = page_params(request)
after = decode_cursor(cursor, "messages", chat["id"]) if cursor else None
sql = "SELECT * FROM messages WHERE chat_id = %s"
params = [uuid.UUID(chat["id"])]
if after:
sql += " AND (created_at, id) > (%s, %s::uuid)"
params.extend([after[0], after[1]])
sql += " ORDER BY created_at, id LIMIT %s"
params.append(limit + 1)
with db.connection() as conn:
rows = conn.execute(sql, params).fetchall()
items = [message_public(r) for r in rows]
return page_response(items, limit, "messages", chat["id"], rows)