ЛР 2 — БВТ-2302 — Сабитов — на 3

This commit is contained in:
2026-12-01 00:50:23 +03:00
parent 65003b6119
commit ff7296c240
17 changed files with 987 additions and 34 deletions
+1
View File
@@ -0,0 +1 @@
"""HTTP API of the MTUCI course messenger, lab 2."""
+460
View File
@@ -0,0 +1,460 @@
"""Lab 2: one FastAPI API, durable PostgreSQL state and opaque bearer sessions."""
from __future__ import annotations
import base64
import hashlib
import json
import logging
import os
import re
import secrets
import time
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Annotated
import psycopg
from psycopg.errors import UniqueViolation
from psycopg.rows import dict_row
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError
from fastapi import Depends, FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel, ConfigDict, Field, StrictStr
log = logging.getLogger('messenger')
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
app = FastAPI(title='MTUCI Messenger / lab 2', docs_url=None, redoc_url=None, openapi_url=None)
KDF = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
# Even for a nonexistent user, a failed login runs a password KDF check.
DUMMY_HASH = KDF.hash('Dummy-password-not-a-real-user-123')
TTL_SECONDS = int(os.environ.get('SESSION_TTL_SECONDS', '3600'))
NAME = re.compile(r'^[a-z0-9_]{3,32}$')
TOKEN = re.compile(r'[A-Za-z0-9_-]{64}')
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def timestamp(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
def db():
"""Open a connection whose context manager commits or rolls back."""
dsn = os.environ.get('DATABASE_URL', '')
if dsn:
return psycopg.connect(dsn, row_factory=dict_row, connect_timeout=3)
return psycopg.connect(
host=os.environ.get('POSTGRES_HOST', 'db'),
dbname=os.environ['POSTGRES_DB'],
user=os.environ['POSTGRES_USER'],
password=os.environ['POSTGRES_PASSWORD'],
row_factory=dict_row,
connect_timeout=3,
)
def migrate() -> None:
migration = (Path(__file__).resolve().parent.parent / 'migrations' / '001_initial.sql').read_text(encoding='utf-8')
with db() as conn:
conn.execute('SELECT pg_advisory_xact_lock(2026, 2)')
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations (
version integer PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
)""")
installed = conn.execute('SELECT 1 FROM schema_migrations WHERE version=1').fetchone()
if not installed:
conn.execute(migration)
conn.execute('INSERT INTO schema_migrations(version) VALUES (1)')
log.info('Migration 001 checked')
@app.on_event('startup')
def on_startup():
if TTL_SECONDS <= 0:
raise RuntimeError('SESSION_TTL_SECONDS must be a positive integer')
for attempt in range(20):
try:
migrate()
return
except psycopg.OperationalError:
if attempt == 19:
raise
time.sleep(1)
class Error(Exception):
def __init__(self, status: int, code: str, message: str, challenge: str | None = None):
self.status, self.code, self.message, self.challenge = status, code, message, challenge
def fail(status: int, code: str, message: str, challenge: str | None = None):
raise Error(status, code, message, challenge)
def error_response(request: Request, status: int, code: str, message: str, challenge: str | None = None):
rid = getattr(request.state, 'rid', str(uuid.uuid4()))
headers = {'WWW-Authenticate': challenge} if challenge else {}
return JSONResponse(status_code=status, headers=headers,
content={'error': {'code': code, 'message': message, 'request_id': rid}})
@app.middleware('http')
async def add_request_id(request: Request, call_next):
request.state.rid = str(uuid.uuid4())
try:
response = await call_next(request)
except (psycopg.OperationalError, psycopg.InterfaceError):
log.warning('Database unavailable, request_id=%s', request.state.rid)
response = error_response(request, 503, 'unavailable', 'Хранилище недоступно')
except Exception as exc:
log.error('Unexpected %s, request_id=%s', type(exc).__name__, request.state.rid)
response = error_response(request, 500, 'internal_error', 'Внутренняя ошибка сервера')
response.headers['X-Request-Id'] = request.state.rid
return response
@app.exception_handler(Error)
async def on_error(request: Request, exc: Error):
return error_response(request, exc.status, exc.code, exc.message, exc.challenge)
@app.exception_handler(RequestValidationError)
async def on_validation_error(request: Request, exc: RequestValidationError):
return error_response(request, 400, 'invalid_request', 'Неверные поля или типы запроса')
@app.exception_handler(404)
async def on_not_found(request: Request, exc):
return error_response(request, 404, 'not_found', 'Объект не найден')
@app.exception_handler(405)
async def on_method_not_allowed(request: Request, exc):
return error_response(request, 405, 'invalid_request', 'Метод не поддерживается')
class StrictModel(BaseModel):
model_config = ConfigDict(extra='forbid', strict=True)
class NewUser(StrictModel):
username: StrictStr = Field(min_length=3, max_length=32, pattern=r'^[a-z0-9_]{3,32}$')
display_name: StrictStr = Field(min_length=1, max_length=100)
password: StrictStr = Field(min_length=12, max_length=128)
class NewChat(StrictModel):
title: StrictStr = Field(min_length=1, max_length=100)
member_ids: list[StrictStr] = Field(min_length=1, max_length=100)
class NewMessage(StrictModel):
text: StrictStr = Field(min_length=1, max_length=4000)
async def json_body(request: Request, model):
media_type = request.headers.get('Content-Type', '').split(';', 1)[0].strip().lower()
if media_type != 'application/json':
fail(415, 'unsupported_media_type', 'Ожидается application/json')
body = bytearray()
async for chunk in request.stream():
if len(body) + len(chunk) > 1024 * 1024:
fail(413, 'payload_too_large', 'Слишком большой запрос')
body.extend(chunk)
try:
return model.model_validate(json.loads(body.decode('utf-8')))
except (ValueError, RecursionError):
fail(400, 'invalid_request', 'Неверный JSON, поля или типы запроса')
async def user_body(request: Request):
return await json_body(request, NewUser)
async def chat_body(request: Request):
return await json_body(request, NewChat)
async def message_body(request: Request):
return await json_body(request, NewMessage)
def validate_text(value: str, *, postgres: bool = True):
if not value.strip() or (postgres and '\x00' in value):
fail(400, 'invalid_request', 'Некорректная обязательная строка')
try:
value.encode('utf-8')
except UnicodeEncodeError:
fail(400, 'invalid_request', 'Некорректный Unicode')
def valid_uuid(value: str) -> uuid.UUID:
try:
parsed = uuid.UUID(value)
if str(parsed) != value.lower():
raise ValueError()
return parsed
except (TypeError, ValueError, AttributeError):
fail(400, 'invalid_request', 'Неверный UUID')
def view_user(row: dict) -> dict:
return {key: str(row[key]) if key == 'id' else timestamp(row[key]) if key == 'created_at' else row[key]
for key in ('id', 'username', 'display_name', 'created_at')}
def view_chat(row: dict, member_ids) -> dict:
return {'id': str(row['id']), 'title': row['title'],
'member_ids': [str(i) for i in member_ids], 'created_at': timestamp(row['created_at'])}
def view_message(row: dict) -> dict:
return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'sender_id': str(row['sender_id']),
'text': row['text'], 'created_at': timestamp(row['created_at'])}
def authorization(request: Request, scheme: str) -> str:
values = request.headers.getlist('Authorization')
if len(values) != 1:
return ''
prefix, _, credential = values[0].partition(' ')
return credential.lstrip(' ') if prefix.lower() == scheme else ''
def token_digest(token: str) -> str:
return hashlib.sha256(token.encode('ascii')).hexdigest()
def bearer_user(request: Request) -> dict:
token = authorization(request, 'bearer')
if TOKEN.fullmatch(token) is None:
fail(401, 'unauthorized', 'Нужен действительный Bearer-токен', BEARER_CHALLENGE)
digest = token_digest(token)
with db() 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 > %s''', (digest, utc_now())).fetchone()
if not row:
fail(401, 'unauthorized', 'Сессия отсутствует или истекла', BEARER_CHALLENGE)
return row
Actor = Annotated[dict, Depends(bearer_user)]
def parse_limit(raw: str) -> int:
if not re.fullmatch(r'[0-9]{1,3}', raw or ''):
fail(400, 'invalid_request', 'Неверный limit')
value = int(raw)
if not (1 <= value <= 100):
fail(400, 'invalid_request', 'limit должен быть от 1 до 100')
return value
def encode_cursor(scope: str, row: dict) -> str:
payload = {'scope': scope, 'created_at': timestamp(row['created_at']), 'id': str(row['id'])}
return base64.urlsafe_b64encode(json.dumps(payload, separators=(',', ':')).encode()).decode().rstrip('=')
def decode_cursor(raw: str | None, scope: str):
if raw is None:
return None
try:
if len(raw) > 1024 or re.fullmatch(r'[A-Za-z0-9_-]+', raw) is None:
raise ValueError()
data = base64.b64decode(raw + '=' * (-len(raw) % 4), altchars=b'-_', validate=True)
if base64.urlsafe_b64encode(data).decode('ascii').rstrip('=') != raw:
raise ValueError()
payload = json.loads(data.decode('utf-8'))
if not isinstance(payload, dict) or set(payload) != {'scope', 'created_at', 'id'} or payload['scope'] != scope:
raise ValueError()
at = datetime.fromisoformat(payload['created_at'].replace('Z', '+00:00'))
cursor_id = uuid.UUID(payload['id'])
if at.tzinfo is None or timestamp(at) != payload['created_at'] or str(cursor_id) != payload['id']:
raise ValueError()
return at, cursor_id
except (ValueError, TypeError, AttributeError, OverflowError, RecursionError):
fail(400, 'invalid_request', 'Неверный cursor')
def page_options(request: Request, scope: str):
query = request.query_params
if set(query) - {'limit', 'cursor'} or any(len(query.getlist(name)) > 1 for name in ('limit', 'cursor')):
fail(400, 'invalid_request', 'Некорректные параметры страницы')
return parse_limit(query.get('limit', '50')), decode_cursor(query.get('cursor'), scope)
@app.get('/health/live')
def live():
return {'status': 'ok'}
@app.get('/health/ready')
def ready():
try:
with db() as conn:
migrated = conn.execute('SELECT 1 FROM schema_migrations WHERE version = 1').fetchone()
except psycopg.Error:
fail(503, 'unavailable', 'PostgreSQL недоступен')
if not migrated:
fail(503, 'unavailable', 'Схема PostgreSQL не готова')
return {'status': 'ok'}
@app.post('/api/v1/users', status_code=201)
def create_user(data: Annotated[NewUser, Depends(user_body)]):
validate_text(data.display_name)
validate_text(data.password, postgres=False)
record = (uuid.uuid4(), data.username, data.display_name, KDF.hash(data.password), utc_now())
try:
with db() as conn:
row = conn.execute('''INSERT INTO users(id,username,display_name,password_hash,created_at)
VALUES (%s,%s,%s,%s,%s) RETURNING *''', record).fetchone()
except UniqueViolation:
fail(409, 'conflict', 'Имя пользователя занято')
return view_user(row)
async def basic_credentials(request: Request):
try:
decoded = base64.b64decode(authorization(request, 'basic'), validate=True).decode('utf-8')
username, password = decoded.split(':', 1)
if not NAME.fullmatch(username) or not (12 <= len(password) <= 128):
raise ValueError()
except ValueError:
fail(401, 'unauthorized', 'Неверные учётные данные', BASIC_CHALLENGE)
async for chunk in request.stream():
if chunk:
fail(400, 'invalid_request', 'Вход принимает только заголовок Authorization')
return username, password
@app.post('/api/v1/auth/sessions', status_code=201)
def login(credentials: Annotated[tuple[str, str], Depends(basic_credentials)]):
username, password = credentials
with db() as conn:
row = conn.execute('SELECT * FROM users WHERE username=%s', (username,)).fetchone()
try:
verified = KDF.verify(row['password_hash'] if row else DUMMY_HASH, password)
except VerificationError:
verified = False
if not row or not verified:
fail(401, 'unauthorized', 'Неверные учётные данные', BASIC_CHALLENGE)
token = secrets.token_urlsafe(48)
issued = utc_now()
expires = issued + timedelta(seconds=TTL_SECONDS)
with db() as conn:
conn.execute('''INSERT INTO sessions(token_hash,user_id,expires_at,created_at)
VALUES (%s,%s,%s,%s)''', (token_digest(token), row['id'], expires, issued))
return {'token': token, 'token_type': 'Bearer', 'expires_at': timestamp(expires), 'user': view_user(row)}
@app.delete('/api/v1/auth/sessions/current', status_code=204)
def logout(request: Request, actor: Actor):
token = authorization(request, 'bearer')
with db() as conn:
removed = conn.execute('DELETE FROM sessions WHERE token_hash=%s', (token_digest(token),)).rowcount
if not removed:
fail(401, 'unauthorized', 'Сессия отсутствует или истекла', BEARER_CHALLENGE)
return Response(status_code=204)
@app.get('/api/v1/users/me')
def me(actor: Actor):
return view_user(actor)
def get_members(conn, chat_id):
return [r['user_id'] for r in conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id', (chat_id,)).fetchall()]
def accessible_chat(conn, chat_id: str, user_id: uuid.UUID):
cid = valid_uuid(chat_id)
row = conn.execute('''SELECT c.id,c.title,c.created_at FROM chats c
JOIN chat_members m ON m.chat_id=c.id
WHERE c.id=%s AND m.user_id=%s''', (cid, user_id)).fetchone()
if not row:
fail(404, 'not_found', 'Чат не найден')
return row
@app.post('/api/v1/chats', status_code=201)
def create_chat(actor: Actor, data: Annotated[NewChat, Depends(chat_body)]):
validate_text(data.title)
ids = [valid_uuid(item) for item in data.member_ids]
if len(ids) != len(set(ids)) or actor['id'] not in ids:
fail(400, 'invalid_request', 'Некорректный список участников')
cid = uuid.uuid4()
created_at = utc_now()
with db() as conn:
n = conn.execute('SELECT COUNT(*) AS total FROM users WHERE id=ANY(%s::uuid[])', (ids,)).fetchone()['total']
if n != len(ids):
fail(400, 'invalid_request', 'Неизвестный участник')
row = conn.execute('INSERT INTO chats(id,title,created_at) VALUES (%s,%s,%s) RETURNING *',
(cid, data.title, created_at)).fetchone()
with conn.cursor() as cur:
cur.executemany('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)', [(cid, i) for i in ids])
return view_chat(row, sorted(ids))
@app.get('/api/v1/chats')
def list_chats(request: Request, actor: Actor):
scope = 'chats:' + str(actor['id'])
page_size, since = page_options(request, scope)
with db() as conn:
rows = conn.execute('''SELECT c.id,c.title,c.created_at FROM chats c
JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s
AND (%s::timestamptz IS NULL OR (c.created_at,c.id)>(%s::timestamptz,%s::uuid))
ORDER BY c.created_at,c.id LIMIT %s''',
(actor['id'], since[0] if since else None, since[0] if since else None,
since[1] if since else None, page_size + 1)).fetchall()
page = rows[:page_size]
items = [view_chat(r, get_members(conn, r['id'])) for r in page]
return {'items': items, 'next_cursor': encode_cursor(scope, page[-1]) if len(rows) > page_size else None}
@app.get('/api/v1/chats/{chat_id}')
def get_chat(chat_id: str, actor: Actor):
with db() as conn:
row = accessible_chat(conn, chat_id, actor['id'])
members = get_members(conn, row['id'])
return view_chat(row, members)
@app.post('/api/v1/chats/{chat_id}/messages', status_code=201)
def create_message(chat_id: str, actor: Actor, data: Annotated[NewMessage, Depends(message_body)]):
validate_text(data.text)
with db() as conn:
chat = accessible_chat(conn, chat_id, actor['id'])
row = conn.execute('''INSERT INTO messages(id,chat_id,sender_id,text,created_at)
VALUES (%s,%s,%s,%s,%s) RETURNING *''',
(uuid.uuid4(), chat['id'], actor['id'], data.text, utc_now())).fetchone()
return view_message(row)
@app.get('/api/v1/chats/{chat_id}/messages')
def list_messages(chat_id: str, request: Request, actor: Actor):
with db() as conn:
chat = accessible_chat(conn, chat_id, actor['id'])
scope = 'messages:' + str(chat['id'])
page_size, since = page_options(request, scope)
rows = conn.execute('''SELECT * FROM messages WHERE chat_id=%s
AND (%s::timestamptz IS NULL OR (created_at,id)>(%s::timestamptz,%s::uuid))
ORDER BY created_at,id LIMIT %s''',
(chat['id'], since[0] if since else None, since[0] if since else None,
since[1] if since else None, page_size + 1)).fetchall()
return {'items': [view_message(row) for row in rows[:page_size]],
'next_cursor': encode_cursor(scope, rows[page_size - 1]) if len(rows) > page_size else None}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host=os.environ.get('APP_HOST', '0.0.0.0'), port=int(os.environ.get('APP_PORT', '8080')),
access_log=False, workers=1)