feat: PostgreSQL, Bearer-сессии (Valkey/PostgreSQL), Argon2id, миграции, compose
- схема и миграции (migrations/0001_init.sql, python -m messenger.migrate); - регистрация с паролем (Argon2id), вход по Basic, opaque Bearer, logout, expiry; - сессии: SESSION_STORE=valkey (AOF, appendfsync always) или postgres; - пул соединений, statement/lock timeout и клиентский дедлайн: отказ БД = 503; - keyset-пагинация по индексу (chat_id, created_at, id), два запроса без OR; - compose.yaml с закреплёнными образами, secrets, restart.sh. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
893beaa79a
commit
01524165dd
+101
-40
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
@@ -11,14 +12,16 @@ from typing import Any
|
||||
from starlette.applications import Starlette
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
from starlette.responses import JSONResponse, Response
|
||||
from starlette.routing import Route
|
||||
from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Send
|
||||
|
||||
from . import cursor, docs, validation
|
||||
from . import authhdr, cursor, docs, passwords, repo, validation
|
||||
from .config import Settings
|
||||
from .errors import ApiError, InvalidRequest, PayloadTooLarge, Unauthorized, Unavailable
|
||||
from .store import Store, User
|
||||
from .db import Database
|
||||
from .errors import BASIC_CHALLENGE, ApiError, InvalidRequest, PayloadTooLarge, Unauthorized, Unavailable
|
||||
from .sessions import SessionStore, build_store
|
||||
from .timefmt import rfc3339
|
||||
|
||||
log = logging.getLogger("messenger")
|
||||
access_log = logging.getLogger("messenger.access")
|
||||
@@ -36,7 +39,7 @@ def error_response(request_id: str, status: int, code: str, message: str, header
|
||||
|
||||
async def api_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
assert isinstance(exc, ApiError)
|
||||
return error_response(request.state.request_id, exc.status, exc.code, exc.message)
|
||||
return error_response(request.state.request_id, exc.status, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
async def http_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
@@ -108,19 +111,24 @@ class RequestContextMiddleware:
|
||||
# --------------------------------------------------------------------------
|
||||
# Request helpers
|
||||
# --------------------------------------------------------------------------
|
||||
def store_of(request: Request) -> Store:
|
||||
return request.app.state.store
|
||||
def db_of(request: Request) -> Database:
|
||||
return request.app.state.db
|
||||
|
||||
|
||||
def current_user(request: Request) -> User:
|
||||
"""Lab 1 identification: X-User-Id must be the UUID of an existing user, otherwise 401."""
|
||||
raw = request.headers.get("x-user-id")
|
||||
if raw is None or validation.UUID_RE.fullmatch(raw) is None:
|
||||
raise Unauthorized()
|
||||
user = store_of(request).get_user(raw.lower())
|
||||
if user is None:
|
||||
raise Unauthorized()
|
||||
return user
|
||||
def sessions_of(request: Request) -> SessionStore:
|
||||
return request.app.state.sessions
|
||||
|
||||
|
||||
async def authenticate(request: Request) -> str:
|
||||
"""User id of a valid Bearer session, otherwise 401. X-User-Id is ignored since lab 2.
|
||||
|
||||
Store failures are 503 (Unavailable), never 401 and never anonymous access.
|
||||
"""
|
||||
token = authhdr.parse_bearer(request.headers.get("authorization"))
|
||||
user_id = await sessions_of(request).user_id_for(token)
|
||||
if user_id is None:
|
||||
raise Unauthorized("Сессия недействительна, истекла или отозвана")
|
||||
return user_id
|
||||
|
||||
|
||||
def path_uuid(request: Request, name: str) -> str:
|
||||
@@ -170,85 +178,136 @@ async def live(request: Request) -> JSONResponse:
|
||||
|
||||
|
||||
async def ready(request: Request) -> JSONResponse:
|
||||
# The only critical dependency is process memory; while draining after
|
||||
# SIGTERM the instance reports 503 so no new traffic is routed to it.
|
||||
"""200 only if the mandatory synchronous path can be served: PostgreSQL and,
|
||||
with SESSION_STORE=valkey, Valkey answer. 503 while draining after SIGTERM."""
|
||||
if request.app.state.draining:
|
||||
raise Unavailable("Сервер завершает работу")
|
||||
db_ok, store_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping())
|
||||
if not db_ok:
|
||||
raise Unavailable("PostgreSQL недоступен")
|
||||
if not store_ok:
|
||||
raise Unavailable("Хранилище сессий недоступно")
|
||||
return ok({"status": "ok"})
|
||||
|
||||
|
||||
async def register_user(request: Request) -> JSONResponse:
|
||||
data = await read_json(request)
|
||||
validation.check_fields(data, {"username", "display_name"})
|
||||
validation.check_fields(data, {"username", "display_name", "password"})
|
||||
username = validation.username_field(data)
|
||||
display_name = validation.text_field(data, "display_name", 100)
|
||||
user = store_of(request).create_user(username, display_name)
|
||||
password = validation.password_field(data)
|
||||
password_hash = await passwords.hash_password(password)
|
||||
user = await repo.create_user(db_of(request), username, display_name, password_hash)
|
||||
log.info("user_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}})
|
||||
return ok(user.to_json(), 201)
|
||||
|
||||
|
||||
async def create_session(request: Request) -> JSONResponse:
|
||||
"""Login: only `Authorization: Basic`; wrong user and wrong password give the same 401."""
|
||||
username, password = authhdr.parse_basic(request.headers.get("authorization"))
|
||||
found = await repo.get_credentials(db_of(request), username)
|
||||
user, stored_hash = found if found else (None, None)
|
||||
if not await passwords.verify_password(stored_hash, password) or user is None:
|
||||
log.info("login_failed", extra={"fields": {"request_id": request.state.request_id}})
|
||||
raise Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE)
|
||||
ttl = request.app.state.settings.session_ttl_seconds
|
||||
token, expires_at = await sessions_of(request).create(user.id, ttl)
|
||||
log.info("session_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}})
|
||||
return ok({"token": token, "token_type": "Bearer", "expires_at": rfc3339(expires_at), "user": user.to_json()}, 201)
|
||||
|
||||
|
||||
async def revoke_session(request: Request) -> Response:
|
||||
token = authhdr.parse_bearer(request.headers.get("authorization"))
|
||||
if not await sessions_of(request).revoke(token):
|
||||
raise Unauthorized("Сессия недействительна, истекла или отозвана")
|
||||
log.info("session_revoked", extra={"fields": {"request_id": request.state.request_id}})
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
async def me(request: Request) -> JSONResponse:
|
||||
return ok(current_user(request).to_json())
|
||||
user_id = await authenticate(request)
|
||||
user = await repo.get_user(db_of(request), user_id)
|
||||
if user is None:
|
||||
raise Unauthorized("Сессия недействительна, истекла или отозвана")
|
||||
return ok(user.to_json())
|
||||
|
||||
|
||||
async def create_chat(request: Request) -> JSONResponse:
|
||||
user = current_user(request)
|
||||
user_id = await authenticate(request)
|
||||
data = await read_json(request)
|
||||
validation.check_fields(data, {"title", "member_ids"})
|
||||
title = validation.text_field(data, "title", 100)
|
||||
member_ids = validation.member_ids_field(data)
|
||||
chat = store_of(request).create_chat(user.id, title, member_ids)
|
||||
chat = await repo.create_chat(db_of(request), user_id, title, member_ids)
|
||||
log.info("chat_created", extra={"fields": {"request_id": request.state.request_id, "chat_id": chat.id, "members": len(member_ids)}})
|
||||
return ok(chat.to_json(), 201)
|
||||
|
||||
|
||||
async def list_chats(request: Request) -> JSONResponse:
|
||||
user = current_user(request)
|
||||
user_id = await authenticate(request)
|
||||
limit, raw_cursor = page_params(request)
|
||||
after = cursor.decode(raw_cursor, cursor.CHATS, user.id) if raw_cursor else None
|
||||
items, has_more = store_of(request).list_chats(user.id, after, limit)
|
||||
next_cursor = cursor.encode(cursor.CHATS, user.id, items[-1].key) if has_more else None
|
||||
after = cursor.decode(raw_cursor, cursor.CHATS, user_id) if raw_cursor else None
|
||||
items, has_more = await repo.list_chats(db_of(request), user_id, after, limit)
|
||||
next_cursor = cursor.encode(cursor.CHATS, user_id, items[-1].key) if has_more else None
|
||||
return ok({"items": [c.to_json() for c in items], "next_cursor": next_cursor})
|
||||
|
||||
|
||||
async def get_chat(request: Request) -> JSONResponse:
|
||||
user = current_user(request)
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
return ok(store_of(request).get_chat(user.id, chat_id).to_json())
|
||||
return ok((await repo.get_chat(db_of(request), user_id, chat_id)).to_json())
|
||||
|
||||
|
||||
async def create_message(request: Request) -> JSONResponse:
|
||||
user = current_user(request)
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
store = store_of(request)
|
||||
store.get_chat(user.id, chat_id) # access check before reading the body: outsiders get 404
|
||||
db = db_of(request)
|
||||
await repo.ensure_member(db, user_id, chat_id) # outsiders get 404 before the body is read
|
||||
data = await read_json(request)
|
||||
validation.check_fields(data, {"text"})
|
||||
text = validation.text_field(data, "text", 4000)
|
||||
# sender_id is derived from the identification, never taken from the body.
|
||||
message = store.add_message(user.id, chat_id, text)
|
||||
# sender_id is derived from the session, never taken from the body.
|
||||
message = await repo.add_message(db, user_id, chat_id, text)
|
||||
return ok(message.to_json(), 201)
|
||||
|
||||
|
||||
async def list_messages(request: Request) -> JSONResponse:
|
||||
user = current_user(request)
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
store = store_of(request)
|
||||
store.get_chat(user.id, chat_id) # 404 for outsiders before any cursor details leak
|
||||
db = db_of(request)
|
||||
await repo.ensure_member(db, user_id, chat_id) # 404 for outsiders before cursor details leak
|
||||
limit, raw_cursor = page_params(request)
|
||||
after = cursor.decode(raw_cursor, cursor.MESSAGES, chat_id) if raw_cursor else None
|
||||
items, has_more = store.list_messages(user.id, chat_id, after, limit)
|
||||
items, has_more = await repo.list_messages(db, chat_id, after, limit)
|
||||
next_cursor = cursor.encode(cursor.MESSAGES, chat_id, items[-1].key) if has_more else None
|
||||
return ok({"items": [m.to_json() for m in items], "next_cursor": next_cursor})
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None, store: Store | None = None) -> Starlette:
|
||||
def create_app(settings: Settings | None = None) -> Starlette:
|
||||
settings = settings or Settings.from_env()
|
||||
db = Database(settings)
|
||||
sessions = build_store(settings, db)
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(app: Starlette):
|
||||
passwords.configure(settings.hash_concurrency)
|
||||
await db.open()
|
||||
log.info("dependencies_configured", extra={"fields": {
|
||||
"session_store": sessions.name, "session_ttl_s": settings.session_ttl_seconds,
|
||||
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds}})
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await sessions.close()
|
||||
await db.close()
|
||||
|
||||
routes = [
|
||||
Route("/health/live", live, methods=["GET"]),
|
||||
Route("/health/ready", ready, methods=["GET"]),
|
||||
Route("/api/v1/users", register_user, methods=["POST"]),
|
||||
Route("/api/v1/users/me", me, methods=["GET"]),
|
||||
Route("/api/v1/auth/sessions", create_session, methods=["POST"]),
|
||||
Route("/api/v1/auth/sessions/current", revoke_session, methods=["DELETE"]),
|
||||
Route("/api/v1/chats", create_chat, methods=["POST"]),
|
||||
Route("/api/v1/chats", list_chats, methods=["GET"]),
|
||||
Route("/api/v1/chats/{chat_id}", get_chat, methods=["GET"]),
|
||||
@@ -263,9 +322,11 @@ def create_app(settings: Settings | None = None, store: Store | None = None) ->
|
||||
app = Starlette(
|
||||
routes=routes,
|
||||
exception_handlers={ApiError: api_error_handler, HTTPException: http_exception_handler},
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
app.state.settings = settings
|
||||
app.state.store = store or Store()
|
||||
app.state.db = db
|
||||
app.state.sessions = sessions
|
||||
app.state.draining = False
|
||||
return app
|
||||
|
||||
Reference in New Issue
Block a user