ЛР2: PostgreSQL, сессии, Redis-кэш, трек 5.2
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
"""MTUSI messenger API, lab2."""
|
||||
__version__ = "2.0.0"
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Точка входа: python -m messenger [serve|migrate|healthcheck]."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
_STD = set(vars(logging.LogRecord("", 0, "", 0, "", (), None))) | {"message", "asctime"}
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
"""Структурированный лог в stdout. Токены, пароли, Authorization и тела запросов не логируются."""
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
data = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created)) + "Z",
|
||||
"level": record.levelname.lower(), "logger": record.name, "msg": record.getMessage()}
|
||||
data.update({k: v for k, v in vars(record).items() if k not in _STD and not k.startswith("_")})
|
||||
if record.exc_info:
|
||||
data["exc"] = self.formatException(record.exc_info).splitlines()[-1]
|
||||
return json.dumps(data, ensure_ascii=False, default=str)
|
||||
|
||||
|
||||
def setup_logging() -> None:
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(JsonFormatter())
|
||||
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO").upper(), handlers=[handler], force=True)
|
||||
logging.getLogger("uvicorn.access").disabled = True # свой access-log без query-строк
|
||||
|
||||
|
||||
def serve() -> int:
|
||||
import uvicorn
|
||||
|
||||
from .app import build_app
|
||||
from .config import load
|
||||
|
||||
settings = load()
|
||||
app = build_app(settings)
|
||||
config = uvicorn.Config(app, host=settings.host, port=settings.port, log_config=None,
|
||||
access_log=False, server_header=False, proxy_headers=False,
|
||||
timeout_keep_alive=5, timeout_graceful_shutdown=10, lifespan="on")
|
||||
server = uvicorn.Server(config)
|
||||
server.run()
|
||||
return 0 if server.started else 1
|
||||
|
||||
|
||||
def migrate() -> int:
|
||||
from .config import load
|
||||
from .db import migrate_with_wait
|
||||
|
||||
applied = asyncio.run(migrate_with_wait(load()))
|
||||
print(json.dumps({"applied": applied}))
|
||||
return 0
|
||||
|
||||
|
||||
def healthcheck() -> int:
|
||||
port = os.environ.get("APP_PORT", "8080")
|
||||
path = sys.argv[2] if len(sys.argv) > 2 else "/health/ready"
|
||||
try:
|
||||
with urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=2) as resp:
|
||||
return 0 if resp.status == 200 else 1
|
||||
except Exception: # noqa: BLE001
|
||||
return 1
|
||||
|
||||
|
||||
def main() -> int:
|
||||
setup_logging()
|
||||
command = sys.argv[1] if len(sys.argv) > 1 else "serve"
|
||||
commands = {"serve": serve, "migrate": migrate, "healthcheck": healthcheck}
|
||||
if command not in commands:
|
||||
print("usage: python -m messenger [serve|migrate|healthcheck]", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
return commands[command]()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
from .config import ConfigError
|
||||
if isinstance(exc, ConfigError):
|
||||
logging.getLogger("messenger").error("configuration error: %s", exc)
|
||||
return 2
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,510 @@
|
||||
"""HTTP API мессенджера (lab2): Starlette + psycopg 3 (async pool) + Redis/Valkey-кэш сессий."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import contextlib
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from psycopg import errors as pg_errors
|
||||
from starlette.applications import Starlette
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse, Response
|
||||
from starlette.routing import Route
|
||||
|
||||
from . import db
|
||||
from .config import Settings
|
||||
from .errors import ApiError, invalid, not_found, unauthorized_basic, unauthorized_bearer, unavailable
|
||||
from .security import PasswordHasher, looks_like_token, new_token, token_hash
|
||||
from .sessions import Principal, SessionCache
|
||||
from .validation import (USERNAME_RE, decode_cursor, encode_cursor, parse_json_object, parse_limit,
|
||||
parse_uuid, single_param, text_field)
|
||||
|
||||
log = logging.getLogger("messenger.http")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# Ответы и обвязка
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
def request_id(request: Request) -> str:
|
||||
rid = getattr(request.state, "request_id", None)
|
||||
if not rid:
|
||||
rid = uuid.uuid4().hex
|
||||
request.state.request_id = rid
|
||||
return rid
|
||||
|
||||
|
||||
def json_response(request: Request, payload, status: int = 200, headers: dict | None = None) -> JSONResponse:
|
||||
h = {"X-Request-Id": request_id(request), "Cache-Control": "no-store"}
|
||||
h.update(headers or {})
|
||||
return JSONResponse(payload, status_code=status, headers=h)
|
||||
|
||||
|
||||
def error_response(request: Request, err: ApiError) -> JSONResponse:
|
||||
rid = request_id(request)
|
||||
body = {"error": {"code": err.public_code, "message": err.message, "request_id": rid}}
|
||||
return json_response(request, body, err.status, err.headers)
|
||||
|
||||
|
||||
class RequestContextMiddleware:
|
||||
"""Чистый ASGI middleware: X-Request-Id в каждом ответе (включая 404/405 роутера) и access-log
|
||||
без query-строки, заголовков и тела."""
|
||||
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
return await self.app(scope, receive, send)
|
||||
rid = uuid.uuid4().hex
|
||||
scope.setdefault("state", {})["request_id"] = rid
|
||||
started = time.monotonic()
|
||||
status_holder = {}
|
||||
|
||||
async def send_wrapper(message):
|
||||
if message["type"] == "http.response.start":
|
||||
status_holder["status"] = message["status"]
|
||||
headers = list(message.get("headers", []))
|
||||
if not any(k.lower() == b"x-request-id" for k, _ in headers):
|
||||
headers.append((b"x-request-id", rid.encode()))
|
||||
message["headers"] = headers
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, send_wrapper)
|
||||
finally:
|
||||
log.info("request", extra={"request_id": rid, "method": scope.get("method"),
|
||||
"path": scope.get("path"), "status": status_holder.get("status"),
|
||||
"duration_ms": round((time.monotonic() - started) * 1000, 2)})
|
||||
|
||||
|
||||
def endpoint(handler):
|
||||
"""Единая обработка ошибок и общий таймаут запроса."""
|
||||
async def wrapper(request: Request):
|
||||
state: AppState = request.app.state.messenger
|
||||
try:
|
||||
async with asyncio.timeout(state.settings.request_timeout_seconds):
|
||||
return await handler(request, state)
|
||||
except ApiError as err:
|
||||
return error_response(request, err)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if db.is_unavailable(exc) or isinstance(exc, TimeoutError):
|
||||
log.warning("dependency unavailable", extra={"request_id": request_id(request),
|
||||
"error": type(exc).__name__})
|
||||
return error_response(request, unavailable())
|
||||
log.exception("unhandled error", extra={"request_id": request_id(request)})
|
||||
return error_response(request, ApiError("internal_error"))
|
||||
wrapper.__name__ = handler.__name__
|
||||
return wrapper
|
||||
|
||||
|
||||
async def read_body(request: Request, limit: int) -> bytes:
|
||||
declared = request.headers.get("content-length")
|
||||
if declared is not None:
|
||||
if not declared.isdigit():
|
||||
raise invalid("Некорректный Content-Length")
|
||||
if int(declared) > limit:
|
||||
raise ApiError("payload_too_large")
|
||||
chunks, size = [], 0
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > limit:
|
||||
raise ApiError("payload_too_large")
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
async def read_json(request: Request, state: "AppState", allowed: set[str], required: set[str]) -> dict:
|
||||
ctype = request.headers.get("content-type", "").split(";")[0].strip().lower()
|
||||
body = await read_body(request, state.settings.max_body_bytes)
|
||||
if ctype != "application/json":
|
||||
raise invalid("Ожидается Content-Type: application/json")
|
||||
return parse_json_object(body, allowed, required)
|
||||
|
||||
|
||||
def user_json(row) -> dict:
|
||||
return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"],
|
||||
"created_at": db.iso(row["created_at"])}
|
||||
|
||||
|
||||
def chat_json(row) -> dict:
|
||||
return {"id": str(row["id"]), "title": row["title"],
|
||||
"member_ids": [str(m) for m in row["member_ids"]], "created_at": db.iso(row["created_at"])}
|
||||
|
||||
|
||||
def message_json(row) -> dict:
|
||||
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]),
|
||||
"text": row["text"], "created_at": db.iso(row["created_at"])}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# Состояние приложения и аутентификация
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
class AppState:
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
self.pool = db.make_pool(settings)
|
||||
self.cache = SessionCache(settings)
|
||||
self.hasher = PasswordHasher(settings.scrypt_log2_n, settings.scrypt_r, settings.scrypt_p,
|
||||
settings.kdf_concurrency)
|
||||
self.ready = False
|
||||
self.stop = asyncio.Event()
|
||||
self.tasks: list[asyncio.Task] = []
|
||||
|
||||
|
||||
async def authenticate(request: Request, state: AppState) -> Principal:
|
||||
"""Только Authorization: Bearer <opaque>. X-User-Id и Basic игнорируются/отклоняются."""
|
||||
header = request.headers.get("authorization", "")
|
||||
scheme, _, token = header.partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or not looks_like_token(token):
|
||||
raise unauthorized_bearer()
|
||||
th = token_hash(token)
|
||||
principal = await state.cache.get(th)
|
||||
if principal is not None:
|
||||
return principal
|
||||
async with state.pool.connection() as conn:
|
||||
row = await (await conn.execute(
|
||||
"SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at"
|
||||
" FROM sessions s JOIN users u ON u.id = s.user_id"
|
||||
" WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > clock_timestamp()",
|
||||
(th,))).fetchone()
|
||||
if row is None:
|
||||
raise unauthorized_bearer()
|
||||
principal = Principal(user=user_json(row), expires_at=row["expires_at"].timestamp(), token_hash=th)
|
||||
await state.cache.put(principal)
|
||||
return principal
|
||||
|
||||
|
||||
def parse_basic(header: str) -> tuple[str, str]:
|
||||
scheme, _, value = header.partition(" ")
|
||||
if scheme.lower() != "basic" or not value.strip():
|
||||
raise unauthorized_basic()
|
||||
try:
|
||||
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, ValueError, UnicodeDecodeError):
|
||||
raise unauthorized_basic() from None
|
||||
username, sep, password = decoded.partition(":") # двоеточие допустимо только в пароле
|
||||
if not sep or not username.isascii() or not USERNAME_RE.fullmatch(username) or not 12 <= len(password) <= 128:
|
||||
raise unauthorized_basic()
|
||||
return username, password
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# Handlers
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
@endpoint
|
||||
async def live(request: Request, state: AppState):
|
||||
return json_response(request, {"status": "ok"})
|
||||
|
||||
|
||||
@endpoint
|
||||
async def ready(request: Request, state: AppState):
|
||||
# Критичная зависимость синхронного пути — только PostgreSQL. Redis — кэш: при его потере
|
||||
# API продолжает работу через источник истины, поэтому readiness от него не зависит.
|
||||
if not state.ready:
|
||||
raise unavailable()
|
||||
try:
|
||||
async with asyncio.timeout(1.5):
|
||||
async with state.pool.connection() as conn:
|
||||
await conn.execute("SELECT 1")
|
||||
except Exception: # noqa: BLE001
|
||||
raise unavailable() from None
|
||||
return json_response(request, {"status": "ok"})
|
||||
|
||||
|
||||
@endpoint
|
||||
async def create_user(request: Request, state: AppState):
|
||||
data = await read_json(request, state, {"username", "display_name", "password"},
|
||||
{"username", "display_name", "password"})
|
||||
username = data["username"]
|
||||
if not isinstance(username, str) or not USERNAME_RE.fullmatch(username):
|
||||
raise invalid("username должен соответствовать [a-z0-9_]{3,32}")
|
||||
display_name = text_field(data, "display_name", 1, 100)
|
||||
password = text_field(data, "password", 12, 128)
|
||||
async with state.pool.connection() as conn:
|
||||
taken = await (await conn.execute("SELECT 1 FROM users WHERE username = %s", (username,))).fetchone()
|
||||
if taken:
|
||||
raise ApiError("conflict", "username уже занят")
|
||||
password_hash = await state.hasher.hash(password)
|
||||
try:
|
||||
async with state.pool.connection() as conn:
|
||||
row = await (await conn.execute(
|
||||
"INSERT INTO users (username, display_name, password_hash) VALUES (%s, %s, %s)"
|
||||
" RETURNING id, username, display_name, created_at",
|
||||
(username, display_name, password_hash))).fetchone()
|
||||
except pg_errors.UniqueViolation:
|
||||
# Гонка регистрации: проверку выше прошли оба запроса, уникальный индекс пропустил один.
|
||||
log.info("registration race resolved by unique constraint", extra={"request_id": request_id(request)})
|
||||
raise ApiError("conflict", "username уже занят") from None
|
||||
return json_response(request, user_json(row), 201)
|
||||
|
||||
|
||||
@endpoint
|
||||
async def me(request: Request, state: AppState):
|
||||
principal = await authenticate(request, state)
|
||||
return json_response(request, principal.user)
|
||||
|
||||
|
||||
@endpoint
|
||||
async def create_session(request: Request, state: AppState):
|
||||
username, password = parse_basic(request.headers.get("authorization", ""))
|
||||
body = await read_body(request, 1024)
|
||||
if body:
|
||||
raise invalid("POST /auth/sessions не принимает тело")
|
||||
async with state.pool.connection() as conn:
|
||||
row = await (await conn.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
|
||||
(username,))).fetchone()
|
||||
ok = await state.hasher.verify(password, row["password_hash"] if row else None)
|
||||
if not ok:
|
||||
raise unauthorized_basic()
|
||||
token = new_token()
|
||||
th = token_hash(token)
|
||||
async with state.pool.connection() as conn:
|
||||
srow = await (await conn.execute(
|
||||
"INSERT INTO sessions (token_hash, user_id, expires_at)"
|
||||
" VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s)) RETURNING expires_at",
|
||||
(th, row["id"], state.settings.session_ttl_seconds))).fetchone()
|
||||
user = user_json(row)
|
||||
await state.cache.put(Principal(user=user, expires_at=srow["expires_at"].timestamp(), token_hash=th))
|
||||
return json_response(request, {"token": token, "token_type": "Bearer",
|
||||
"expires_at": db.iso(srow["expires_at"]), "user": user}, 201)
|
||||
|
||||
|
||||
@endpoint
|
||||
async def delete_session(request: Request, state: AppState):
|
||||
principal = await authenticate(request, state)
|
||||
th = principal.token_hash
|
||||
async with state.pool.connection() as conn:
|
||||
async with conn.transaction():
|
||||
revoked = await (await conn.execute(
|
||||
"UPDATE sessions SET revoked_at = clock_timestamp()"
|
||||
" WHERE token_hash = %s AND revoked_at IS NULL RETURNING 1", (th,))).fetchone()
|
||||
if revoked is None:
|
||||
raise unauthorized_bearer()
|
||||
if state.cache.enabled:
|
||||
await conn.execute(
|
||||
"INSERT INTO session_cache_invalidations (token_hash) VALUES (%s) ON CONFLICT DO NOTHING",
|
||||
(th,))
|
||||
# COMMIT в PostgreSQL уже сделал отзыв окончательным; Redis лишь догоняет источник истины.
|
||||
if state.cache.enabled and await state.cache.invalidate(th):
|
||||
with contextlib.suppress(Exception):
|
||||
async with state.pool.connection() as conn:
|
||||
await conn.execute("DELETE FROM session_cache_invalidations WHERE token_hash = %s", (th,))
|
||||
return Response(status_code=204, headers={"X-Request-Id": request_id(request)})
|
||||
|
||||
|
||||
@endpoint
|
||||
async def create_chat(request: Request, state: AppState):
|
||||
principal = await authenticate(request, state)
|
||||
data = await read_json(request, state, {"title", "member_ids"}, {"title", "member_ids"})
|
||||
title = text_field(data, "title", 1, 100)
|
||||
raw_members = data["member_ids"]
|
||||
if not isinstance(raw_members, list) or not 1 <= len(raw_members) <= 100:
|
||||
raise invalid("member_ids: массив из 1–100 UUID")
|
||||
members = [parse_uuid(m, "member_id") for m in raw_members]
|
||||
if len(set(members)) != len(members):
|
||||
raise invalid("member_ids содержит дубликаты")
|
||||
caller = uuid.UUID(principal.user["id"])
|
||||
if caller not in members:
|
||||
raise invalid("member_ids должен содержать создателя чата")
|
||||
async with state.pool.connection() as conn:
|
||||
try:
|
||||
async with conn.transaction(): # атомарно: чат и весь состав или ничего
|
||||
chat = await (await conn.execute(
|
||||
"INSERT INTO chats (title, created_by) VALUES (%s, %s) RETURNING id, title, created_at",
|
||||
(title, caller))).fetchone()
|
||||
await conn.execute(
|
||||
"INSERT INTO chat_members (chat_id, user_id, position)"
|
||||
" SELECT %s, m.user_id, m.ord - 1 FROM unnest(%s::uuid[]) WITH ORDINALITY AS m(user_id, ord)",
|
||||
(chat["id"], members))
|
||||
except pg_errors.ForeignKeyViolation:
|
||||
raise invalid("member_ids содержит неизвестного пользователя") from None
|
||||
chat["member_ids"] = members
|
||||
return json_response(request, chat_json(chat), 201)
|
||||
|
||||
|
||||
_CHAT_LIST_SQL = (
|
||||
"SELECT c.id, c.title, c.created_at,"
|
||||
" (SELECT array_agg(x.user_id ORDER BY x.position) FROM chat_members x WHERE x.chat_id = c.id) AS member_ids"
|
||||
" FROM chat_members m JOIN chats c ON c.id = m.chat_id"
|
||||
" WHERE m.user_id = %s {after}"
|
||||
" ORDER BY c.created_at, c.id LIMIT %s")
|
||||
|
||||
|
||||
@endpoint
|
||||
async def list_chats(request: Request, state: AppState):
|
||||
principal = await authenticate(request, state)
|
||||
caller = uuid.UUID(principal.user["id"])
|
||||
limit = parse_limit(request.query_params)
|
||||
cursor = single_param(request.query_params, "cursor")
|
||||
async with state.pool.connection() as conn:
|
||||
if cursor is not None:
|
||||
ts, last_id = decode_cursor(cursor, "chats", caller)
|
||||
rows = await (await conn.execute(_CHAT_LIST_SQL.format(after="AND (c.created_at, c.id) > (%s, %s)"),
|
||||
(caller, ts, last_id, limit + 1))).fetchall()
|
||||
else:
|
||||
rows = await (await conn.execute(_CHAT_LIST_SQL.format(after=""), (caller, limit + 1))).fetchall()
|
||||
items = rows[:limit]
|
||||
next_cursor = (encode_cursor("chats", caller, items[-1]["created_at"], items[-1]["id"])
|
||||
if len(rows) > limit else None)
|
||||
return json_response(request, {"items": [chat_json(r) for r in items], "next_cursor": next_cursor})
|
||||
|
||||
|
||||
@endpoint
|
||||
async def get_chat(request: Request, state: AppState):
|
||||
principal = await authenticate(request, state)
|
||||
chat_id = parse_uuid(request.path_params["chat_id"], "chat_id")
|
||||
async with state.pool.connection() as conn:
|
||||
row = await (await conn.execute(
|
||||
"SELECT c.id, c.title, c.created_at, array_agg(m.user_id ORDER BY m.position) AS member_ids"
|
||||
" FROM chats c JOIN chat_members m ON m.chat_id = c.id"
|
||||
" WHERE c.id = %s AND EXISTS (SELECT 1 FROM chat_members a WHERE a.chat_id = c.id AND a.user_id = %s)"
|
||||
" GROUP BY c.id", (chat_id, uuid.UUID(principal.user["id"])))).fetchone()
|
||||
if row is None:
|
||||
raise not_found() # нет или чужой — одинаковый ответ
|
||||
return json_response(request, chat_json(row))
|
||||
|
||||
|
||||
async def _is_member(conn, chat_id: uuid.UUID, user_id: uuid.UUID) -> bool:
|
||||
row = await (await conn.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id))).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
@endpoint
|
||||
async def create_message(request: Request, state: AppState):
|
||||
principal = await authenticate(request, state)
|
||||
chat_id = parse_uuid(request.path_params["chat_id"], "chat_id")
|
||||
sender = uuid.UUID(principal.user["id"])
|
||||
try:
|
||||
data = await read_json(request, state, {"text"}, {"text"})
|
||||
text = text_field(data, "text", 1, 4000)
|
||||
except ApiError as err:
|
||||
if err.status == 400:
|
||||
# Посторонний не должен по 400/404 узнавать о существовании чата.
|
||||
async with state.pool.connection() as conn:
|
||||
if not await _is_member(conn, chat_id, sender):
|
||||
raise not_found() from None
|
||||
raise
|
||||
async with state.pool.connection() as conn:
|
||||
row = await (await conn.execute(
|
||||
"INSERT INTO messages (chat_id, sender_id, text)"
|
||||
" SELECT %(c)s, %(u)s, %(t)s"
|
||||
" WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = %(c)s AND user_id = %(u)s)"
|
||||
" RETURNING id, chat_id, sender_id, text, created_at",
|
||||
{"c": chat_id, "u": sender, "t": text})).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
return json_response(request, message_json(row), 201)
|
||||
|
||||
|
||||
_HISTORY_SQL = (
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s {after} ORDER BY created_at, id LIMIT %s")
|
||||
|
||||
|
||||
@endpoint
|
||||
async def list_messages(request: Request, state: AppState):
|
||||
principal = await authenticate(request, state)
|
||||
chat_id = parse_uuid(request.path_params["chat_id"], "chat_id")
|
||||
async with state.pool.connection() as conn:
|
||||
if not await _is_member(conn, chat_id, uuid.UUID(principal.user["id"])):
|
||||
raise not_found()
|
||||
limit = parse_limit(request.query_params)
|
||||
cursor = single_param(request.query_params, "cursor")
|
||||
if cursor is not None:
|
||||
ts, last_id = decode_cursor(cursor, "messages", chat_id)
|
||||
rows = await (await conn.execute(_HISTORY_SQL.format(after="AND (created_at, id) > (%s, %s)"),
|
||||
(chat_id, ts, last_id, limit + 1))).fetchall()
|
||||
else:
|
||||
rows = await (await conn.execute(_HISTORY_SQL.format(after=""), (chat_id, limit + 1))).fetchall()
|
||||
items = rows[:limit]
|
||||
next_cursor = (encode_cursor("messages", chat_id, items[-1]["created_at"], items[-1]["id"])
|
||||
if len(rows) > limit else None)
|
||||
return json_response(request, {"items": [message_json(r) for r in items], "next_cursor": next_cursor})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# Фоновые задачи и сборка приложения
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
async def expired_sessions_cleanup(state: AppState) -> None:
|
||||
"""Удаляет сессии, истёкшие более суток назад, пачками (не держит долгих блокировок)."""
|
||||
while not state.stop.is_set():
|
||||
with contextlib.suppress(Exception):
|
||||
async with state.pool.connection() as conn:
|
||||
await conn.execute(
|
||||
"DELETE FROM sessions WHERE token_hash IN (SELECT token_hash FROM sessions"
|
||||
" WHERE expires_at < clock_timestamp() - interval '1 day' LIMIT 1000)")
|
||||
with contextlib.suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(state.stop.wait(), timeout=600)
|
||||
|
||||
|
||||
def build_app(settings: Settings) -> Starlette:
|
||||
state = AppState(settings)
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(app: Starlette):
|
||||
if settings.migrate_on_start:
|
||||
applied = await db.migrate_with_wait(settings)
|
||||
log.info("migrations checked", extra={"applied": applied})
|
||||
await state.pool.open(wait=False)
|
||||
state.ready = True
|
||||
if state.cache.enabled:
|
||||
state.tasks.append(asyncio.create_task(state.cache.maintenance_loop(state.pool, state.stop)))
|
||||
state.tasks.append(asyncio.create_task(expired_sessions_cleanup(state)))
|
||||
log.info("api started", extra={"cache": state.cache.enabled,
|
||||
"session_ttl_seconds": settings.session_ttl_seconds})
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
state.ready = False
|
||||
state.stop.set()
|
||||
for task in state.tasks:
|
||||
task.cancel()
|
||||
await asyncio.gather(*state.tasks, return_exceptions=True)
|
||||
await state.cache.close()
|
||||
await state.pool.close()
|
||||
|
||||
async def http_exception(request: Request, exc: HTTPException):
|
||||
if exc.status_code == 405:
|
||||
err = ApiError("method_not_allowed", "Метод не поддерживается", headers=dict(exc.headers or {}))
|
||||
elif exc.status_code == 404:
|
||||
err = ApiError("not_found")
|
||||
else:
|
||||
err = ApiError("invalid_request")
|
||||
return error_response(request, err)
|
||||
|
||||
async def server_error(request: Request, exc: Exception):
|
||||
return error_response(request, ApiError("internal_error"))
|
||||
|
||||
routes = [
|
||||
Route("/health/live", live, methods=["GET"]),
|
||||
Route("/health/ready", ready, methods=["GET"]),
|
||||
Route("/api/v1/users", create_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", delete_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"]),
|
||||
Route("/api/v1/chats/{chat_id}/messages", create_message, methods=["POST"]),
|
||||
Route("/api/v1/chats/{chat_id}/messages", list_messages, methods=["GET"]),
|
||||
]
|
||||
app = Starlette(routes=routes, lifespan=lifespan,
|
||||
exception_handlers={HTTPException: http_exception, Exception: server_error})
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
app.state.messenger = state
|
||||
return app
|
||||
|
||||
|
||||
__all__ = ["build_app"]
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Конфигурация из окружения. Секреты читаются из *_FILE (Docker/Compose secrets)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class ConfigError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _secret(name: str, required: bool) -> str | None:
|
||||
"""Значение NAME или содержимое файла NAME_FILE (приоритет у файла)."""
|
||||
path = os.environ.get(name + "_FILE")
|
||||
if path:
|
||||
try:
|
||||
value = Path(path).read_text(encoding="utf-8").strip()
|
||||
except OSError as exc:
|
||||
raise ConfigError(f"cannot read {name}_FILE") from exc
|
||||
if not value:
|
||||
raise ConfigError(f"{name}_FILE is empty")
|
||||
return value
|
||||
value = os.environ.get(name, "").strip()
|
||||
if value:
|
||||
return value
|
||||
if required:
|
||||
raise ConfigError(f"{name} or {name}_FILE is required")
|
||||
return None
|
||||
|
||||
|
||||
def _int(name: str, default: int, lo: int, hi: int) -> int:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or raw == "":
|
||||
return default
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError as exc:
|
||||
raise ConfigError(f"{name} must be an integer") from exc
|
||||
if not lo <= value <= hi:
|
||||
raise ConfigError(f"{name} must be in [{lo}, {hi}]")
|
||||
return value
|
||||
|
||||
|
||||
def _float(name: str, default: float, lo: float, hi: float) -> float:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or raw == "":
|
||||
return default
|
||||
try:
|
||||
value = float(raw)
|
||||
except ValueError as exc:
|
||||
raise ConfigError(f"{name} must be a number") from exc
|
||||
if not lo <= value <= hi:
|
||||
raise ConfigError(f"{name} must be in [{lo}, {hi}]")
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
host: str
|
||||
port: int
|
||||
env: str
|
||||
database_url: str
|
||||
cache_url: str | None
|
||||
session_ttl_seconds: int
|
||||
session_cache_ttl_seconds: int
|
||||
cache_timeout_seconds: float
|
||||
cache_retry_seconds: float
|
||||
db_pool_min: int
|
||||
db_pool_max: int
|
||||
db_pool_timeout_seconds: float
|
||||
db_connect_timeout_seconds: int
|
||||
db_statement_timeout_ms: int
|
||||
request_timeout_seconds: float
|
||||
max_body_bytes: int
|
||||
kdf_concurrency: int
|
||||
scrypt_log2_n: int
|
||||
scrypt_r: int
|
||||
scrypt_p: int
|
||||
migrate_on_start: bool
|
||||
migrate_wait_seconds: int
|
||||
|
||||
@property
|
||||
def cache_enabled(self) -> bool:
|
||||
return self.cache_url is not None
|
||||
|
||||
|
||||
def load() -> Settings:
|
||||
store = os.environ.get("SESSION_STORE", "postgres").strip()
|
||||
if store != "postgres":
|
||||
# Источник истины сессий — всегда PostgreSQL; Redis/Valkey — только кэш (см. REPORT.md).
|
||||
raise ConfigError("SESSION_STORE must be 'postgres' (Redis/Valkey is a cache via CACHE_URL)")
|
||||
cache_mode = os.environ.get("SESSION_CACHE", "auto").strip()
|
||||
if cache_mode not in {"auto", "redis", "off"}:
|
||||
raise ConfigError("SESSION_CACHE must be auto, redis or off")
|
||||
cache_url = None if cache_mode == "off" else _secret("CACHE_URL", required=cache_mode == "redis")
|
||||
pool_max = _int("DB_POOL_MAX", 10, 1, 100)
|
||||
return Settings(
|
||||
host=os.environ.get("APP_HOST", "0.0.0.0"),
|
||||
port=_int("APP_PORT", 8080, 1, 65535),
|
||||
env=os.environ.get("APP_ENV", "lab"),
|
||||
database_url=_secret("DATABASE_URL", required=True) or "",
|
||||
cache_url=cache_url,
|
||||
session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600, 1, 30 * 24 * 3600),
|
||||
session_cache_ttl_seconds=_int("SESSION_CACHE_TTL_SECONDS", 60, 1, 3600),
|
||||
cache_timeout_seconds=_float("CACHE_TIMEOUT_SECONDS", 0.2, 0.01, 5),
|
||||
cache_retry_seconds=_float("CACHE_RETRY_SECONDS", 2.0, 0.1, 60),
|
||||
db_pool_min=min(_int("DB_POOL_MIN", 1, 0, 100), pool_max),
|
||||
db_pool_max=pool_max,
|
||||
db_pool_timeout_seconds=_float("DB_POOL_TIMEOUT_SECONDS", 2.0, 0.1, 60),
|
||||
db_connect_timeout_seconds=_int("DB_CONNECT_TIMEOUT_SECONDS", 3, 1, 60),
|
||||
db_statement_timeout_ms=_int("DB_STATEMENT_TIMEOUT_MS", 5000, 100, 600000),
|
||||
request_timeout_seconds=_float("REQUEST_TIMEOUT_SECONDS", 10.0, 1, 120),
|
||||
max_body_bytes=_int("MAX_BODY_BYTES", 65536, 1024, 1048576),
|
||||
kdf_concurrency=_int("KDF_CONCURRENCY", 4, 1, 64),
|
||||
scrypt_log2_n=_int("SCRYPT_LOG2_N", 15, 14, 20),
|
||||
scrypt_r=_int("SCRYPT_R", 8, 1, 32),
|
||||
scrypt_p=_int("SCRYPT_P", 3, 1, 16),
|
||||
migrate_on_start=os.environ.get("MIGRATE_ON_START", "true").lower() in {"1", "true", "yes"},
|
||||
migrate_wait_seconds=_int("MIGRATE_WAIT_SECONDS", 60, 0, 600),
|
||||
)
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Пул соединений PostgreSQL, версионируемые миграции и классификация ошибок БД."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg import errors as pg_errors
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import AsyncConnectionPool, PoolTimeout
|
||||
|
||||
from .config import Settings
|
||||
|
||||
log = logging.getLogger("messenger.db")
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[2] / "migrations"
|
||||
MIGRATION_LOCK_ID = 2026_0202 # pg_advisory_lock: параллельные реплики не применяют миграции дважды
|
||||
|
||||
|
||||
def connection_kwargs(settings: Settings) -> dict:
|
||||
options = (
|
||||
f"-c statement_timeout={settings.db_statement_timeout_ms} "
|
||||
"-c lock_timeout=2000 "
|
||||
"-c idle_in_transaction_session_timeout=10000 "
|
||||
"-c TimeZone=UTC"
|
||||
)
|
||||
return {
|
||||
"connect_timeout": settings.db_connect_timeout_seconds,
|
||||
"application_name": "messenger-api",
|
||||
"options": options,
|
||||
"row_factory": dict_row,
|
||||
}
|
||||
|
||||
|
||||
def make_pool(settings: Settings) -> AsyncConnectionPool:
|
||||
return AsyncConnectionPool(
|
||||
conninfo=settings.database_url,
|
||||
kwargs=connection_kwargs(settings),
|
||||
min_size=settings.db_pool_min,
|
||||
max_size=settings.db_pool_max,
|
||||
timeout=settings.db_pool_timeout_seconds, # ожидание свободного соединения
|
||||
max_waiting=200, # очередь ожидания ограничена
|
||||
max_idle=300,
|
||||
reconnect_timeout=30,
|
||||
check=AsyncConnectionPool.check_connection, # после рестарта PG битые соединения отбрасываются
|
||||
open=False,
|
||||
name="messenger",
|
||||
)
|
||||
|
||||
|
||||
def is_unavailable(exc: BaseException) -> bool:
|
||||
"""Ошибки, означающие «зависимость недоступна/перегружена», а не баг приложения."""
|
||||
if isinstance(exc, (PoolTimeout, psycopg.OperationalError, asyncio.TimeoutError, ConnectionError)):
|
||||
return True
|
||||
return isinstance(exc, (pg_errors.QueryCanceled, pg_errors.LockNotAvailable,
|
||||
pg_errors.AdminShutdown, pg_errors.CannotConnectNow))
|
||||
|
||||
|
||||
def iso(ts: datetime) -> str:
|
||||
"""RFC 3339 UTC с микросекундами и суффиксом Z (точность timestamptz в PostgreSQL)."""
|
||||
return ts.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def _migration_files() -> list[tuple[str, str, str]]:
|
||||
result = []
|
||||
for path in sorted(MIGRATIONS_DIR.glob("[0-9][0-9][0-9][0-9]_*.sql")):
|
||||
sql = path.read_text(encoding="utf-8")
|
||||
result.append((path.stem, sql, hashlib.sha256(sql.encode()).hexdigest()))
|
||||
return result
|
||||
|
||||
|
||||
async def migrate(settings: Settings) -> list[str]:
|
||||
"""Применяет недостающие миграции. Повторный запуск — no-op; изменённая применённая миграция —
|
||||
ошибка (миграции неизменяемы, исправления — новой версией)."""
|
||||
applied_now: list[str] = []
|
||||
async with await psycopg.AsyncConnection.connect(
|
||||
settings.database_url, autocommit=True, **connection_kwargs(settings)) as conn:
|
||||
await conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATION_LOCK_ID,))
|
||||
try:
|
||||
await conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||
" version text PRIMARY KEY, checksum text NOT NULL,"
|
||||
" applied_at timestamptz NOT NULL DEFAULT clock_timestamp())")
|
||||
rows = await (await conn.execute("SELECT version, checksum FROM schema_migrations")).fetchall()
|
||||
done = {r["version"]: r["checksum"] for r in rows}
|
||||
for version, sql, checksum in _migration_files():
|
||||
if version in done:
|
||||
if done[version] != checksum:
|
||||
raise RuntimeError(f"applied migration {version} was modified")
|
||||
continue
|
||||
async with conn.transaction():
|
||||
await conn.execute(sql)
|
||||
await conn.execute(
|
||||
"INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)",
|
||||
(version, checksum))
|
||||
applied_now.append(version)
|
||||
log.info("migration applied", extra={"version": version})
|
||||
finally:
|
||||
await conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATION_LOCK_ID,))
|
||||
return applied_now
|
||||
|
||||
|
||||
async def migrate_with_wait(settings: Settings) -> list[str]:
|
||||
deadline = time.monotonic() + settings.migrate_wait_seconds
|
||||
delay = 0.5
|
||||
while True:
|
||||
try:
|
||||
return await migrate(settings)
|
||||
except psycopg.OperationalError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
log.warning("database not reachable yet; retrying migrations")
|
||||
await asyncio.sleep(delay)
|
||||
delay = min(delay * 2, 5)
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Единый формат ошибок API: {"error":{"code","message","request_id"}}."""
|
||||
from __future__ import annotations
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
_STATUS = {
|
||||
"invalid_request": 400,
|
||||
"unauthorized": 401,
|
||||
"not_found": 404,
|
||||
"method_not_allowed": 405,
|
||||
"conflict": 409,
|
||||
"payload_too_large": 413,
|
||||
"unsupported_media_type": 415,
|
||||
"rate_limited": 429,
|
||||
"internal_error": 500,
|
||||
"unavailable": 503,
|
||||
}
|
||||
|
||||
_DEFAULT_MESSAGE = {
|
||||
"invalid_request": "Некорректный запрос",
|
||||
"unauthorized": "Требуется действительная аутентификация",
|
||||
"not_found": "Объект не найден",
|
||||
"conflict": "Конфликт состояния",
|
||||
"payload_too_large": "Слишком большой запрос",
|
||||
"unsupported_media_type": "Неподдерживаемый тип содержимого",
|
||||
"rate_limited": "Слишком много запросов",
|
||||
"internal_error": "Внутренняя ошибка",
|
||||
"unavailable": "Сервис временно недоступен",
|
||||
}
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, code: str, message: str | None = None, *, challenge: str | None = None,
|
||||
headers: dict[str, str] | None = None):
|
||||
super().__init__(code)
|
||||
self.code = code
|
||||
self.status = _STATUS[code]
|
||||
self.message = message or _DEFAULT_MESSAGE.get(code, "Ошибка")
|
||||
self.headers = dict(headers or {})
|
||||
if challenge:
|
||||
self.headers["WWW-Authenticate"] = challenge
|
||||
|
||||
@property
|
||||
def public_code(self) -> str:
|
||||
# 405 не входит в enum контракта: отдаём invalid_request с корректным HTTP-статусом.
|
||||
return "invalid_request" if self.code == "method_not_allowed" else self.code
|
||||
|
||||
|
||||
def invalid(message: str) -> ApiError:
|
||||
return ApiError("invalid_request", message)
|
||||
|
||||
|
||||
def unauthorized_bearer() -> ApiError:
|
||||
return ApiError("unauthorized", challenge=BEARER_CHALLENGE)
|
||||
|
||||
|
||||
def unauthorized_basic() -> ApiError:
|
||||
return ApiError("unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE)
|
||||
|
||||
|
||||
def not_found() -> ApiError:
|
||||
return ApiError("not_found")
|
||||
|
||||
|
||||
def unavailable() -> ApiError:
|
||||
return ApiError("unavailable", headers={"Retry-After": "1"})
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Password KDF (scrypt из OpenSSL через hashlib) и opaque-токены сессий.
|
||||
|
||||
Пароль хешируется медленным memory-hard KDF с солью: цель — сделать перебор украденных
|
||||
hash дорогим. Токен сессии уже содержит 256 бит случайности, перебирать его бессмысленно,
|
||||
поэтому для индекса в БД/кэше достаточно быстрого SHA-256 — это разные задачи.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
|
||||
_PREFIX = "$scrypt$"
|
||||
|
||||
|
||||
def _b64(data: bytes) -> str:
|
||||
return base64.b64encode(data).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _unb64(text: str) -> bytes:
|
||||
return base64.b64decode(text + "=" * (-len(text) % 4), validate=True)
|
||||
|
||||
|
||||
class PasswordHasher:
|
||||
"""Формат PHC-подобный: $scrypt$ln=15,r=8,p=3$<salt>$<hash>. Параметры хранятся в строке,
|
||||
поэтому их можно усилить позднее без потери старых hash."""
|
||||
|
||||
def __init__(self, log2_n: int, r: int, p: int, concurrency: int):
|
||||
self.log2_n, self.r, self.p = log2_n, r, p
|
||||
# Ограничиваем одновременные KDF: каждый вызов занимает 128*r*N байт RAM (32 MiB при ln=15).
|
||||
self._slots = asyncio.Semaphore(concurrency)
|
||||
self._dummy: str | None = None
|
||||
|
||||
def _maxmem(self, log2_n: int, r: int, p: int) -> int:
|
||||
return 128 * r * (2 ** log2_n) * 2 + 1024 * 1024 * p
|
||||
|
||||
def _derive(self, password: str, salt: bytes, log2_n: int, r: int, p: int) -> bytes:
|
||||
return hashlib.scrypt(password.encode("utf-8"), salt=salt, n=2 ** log2_n, r=r, p=p,
|
||||
maxmem=self._maxmem(log2_n, r, p), dklen=32)
|
||||
|
||||
def hash_sync(self, password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
digest = self._derive(password, salt, self.log2_n, self.r, self.p)
|
||||
return f"{_PREFIX}ln={self.log2_n},r={self.r},p={self.p}${_b64(salt)}${_b64(digest)}"
|
||||
|
||||
def verify_sync(self, password: str, encoded: str) -> bool:
|
||||
try:
|
||||
if not encoded.startswith(_PREFIX):
|
||||
return False
|
||||
params, salt_b64, hash_b64 = encoded[len(_PREFIX):].split("$")
|
||||
fields = dict(item.split("=", 1) for item in params.split(","))
|
||||
log2_n, r, p = int(fields["ln"]), int(fields["r"]), int(fields["p"])
|
||||
if not (10 <= log2_n <= 22 and 1 <= r <= 32 and 1 <= p <= 16):
|
||||
return False
|
||||
expected = _unb64(hash_b64)
|
||||
actual = self._derive(password, _unb64(salt_b64), log2_n, r, p)
|
||||
except (ValueError, KeyError):
|
||||
return False
|
||||
return hmac.compare_digest(actual, expected)
|
||||
|
||||
async def hash(self, password: str) -> str:
|
||||
async with self._slots:
|
||||
return await asyncio.to_thread(self.hash_sync, password)
|
||||
|
||||
async def verify(self, password: str, encoded: str | None) -> bool:
|
||||
"""Для неизвестного пользователя проверяем фиктивный hash: время ответа не выдаёт,
|
||||
существует ли username."""
|
||||
if encoded is None:
|
||||
if self._dummy is None:
|
||||
self._dummy = await self.hash("dummy-password-for-timing")
|
||||
encoded, password = self._dummy, password + "\x00never"
|
||||
async with self._slots:
|
||||
await asyncio.to_thread(self.verify_sync, password, encoded)
|
||||
return False
|
||||
async with self._slots:
|
||||
return await asyncio.to_thread(self.verify_sync, password, encoded)
|
||||
|
||||
|
||||
TOKEN_BYTES = 32 # 256 бит энтропии
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return secrets.token_urlsafe(TOKEN_BYTES) # 43 символа base64url
|
||||
|
||||
|
||||
def token_hash(token: str) -> bytes:
|
||||
return hashlib.sha256(token.encode("ascii")).digest()
|
||||
|
||||
|
||||
def looks_like_token(token: str) -> bool:
|
||||
return len(token) == 43 and all(c.isascii() and (c.isalnum() or c in "-_") for c in token)
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Сессии: PostgreSQL — источник истины, Redis/Valkey — read-through кэш с TTL.
|
||||
|
||||
Политика (подробно — REPORT.md):
|
||||
* ключ sess:v1:<sha256(token)> хранит {user, expires_at}; TTL = min(SESSION_CACHE_TTL_SECONDS,
|
||||
остаток жизни сессии) — кэш никогда не переживает срок сессии;
|
||||
* logout: revoked_at + строка outbox в одной транзакции PostgreSQL, затем в Redis атомарно
|
||||
«надгробие» sess:v1:revoked:<hash> и DEL ключа. Заполнение кэша — Lua SET … только если
|
||||
надгробия нет, поэтому конкурентный read-through не вернёт отозванную сессию в кэш;
|
||||
* Redis недоступен → аутентификация идёт в PostgreSQL (fail-open только к источнику истины,
|
||||
не к анонимному доступу); после ошибки кэш не читается, пока фоновый цикл не проверит Redis
|
||||
и не дообработает outbox инвалидаций;
|
||||
* flush/restart Redis = холодный кэш: сессии остаются в PostgreSQL.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
from redis import asyncio as aioredis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from .config import Settings
|
||||
|
||||
log = logging.getLogger("messenger.sessions")
|
||||
|
||||
KEY = "sess:v1:"
|
||||
TOMBSTONE = "sess:v1:revoked:"
|
||||
|
||||
# KEYS[1]=session key, KEYS[2]=tombstone; ARGV[1]=value, ARGV[2]=ttl ms
|
||||
_SET_IF_NOT_REVOKED = """
|
||||
if redis.call('EXISTS', KEYS[2]) == 1 then return 0 end
|
||||
redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2])
|
||||
return 1
|
||||
"""
|
||||
# KEYS[1]=session key, KEYS[2]=tombstone; ARGV[1]=tombstone ttl ms
|
||||
_INVALIDATE = """
|
||||
redis.call('SET', KEYS[2], '1', 'PX', ARGV[1])
|
||||
redis.call('DEL', KEYS[1])
|
||||
return 1
|
||||
"""
|
||||
|
||||
|
||||
@dataclass
|
||||
class Principal:
|
||||
user: dict
|
||||
expires_at: float # epoch seconds
|
||||
token_hash: bytes
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
self.client: aioredis.Redis | None = None
|
||||
self._set_script = None
|
||||
self._invalidate_script = None
|
||||
# degraded=True: кэш не читаем (было исключение Redis или есть недообработанный outbox).
|
||||
self.degraded = True
|
||||
self._next_probe = 0.0
|
||||
self.stats = {"hits": 0, "misses": 0, "errors": 0}
|
||||
if settings.cache_url:
|
||||
t = settings.cache_timeout_seconds
|
||||
self.client = aioredis.from_url(
|
||||
settings.cache_url, socket_timeout=t, socket_connect_timeout=t,
|
||||
retry_on_timeout=False, health_check_interval=0, max_connections=50,
|
||||
decode_responses=False)
|
||||
self._set_script = self.client.register_script(_SET_IF_NOT_REVOKED)
|
||||
self._invalidate_script = self.client.register_script(_INVALIDATE)
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self.client is not None
|
||||
|
||||
def _tombstone_ms(self) -> int:
|
||||
# Надгробие живёт дольше любой записи кэша и любого запроса в полёте.
|
||||
return int((self.settings.session_cache_ttl_seconds + self.settings.request_timeout_seconds + 5) * 1000)
|
||||
|
||||
def _fail(self, op: str, exc: Exception) -> None:
|
||||
self.stats["errors"] += 1
|
||||
if not self.degraded:
|
||||
log.warning("cache unavailable; falling back to PostgreSQL",
|
||||
extra={"op": op, "error": type(exc).__name__})
|
||||
self.degraded = True
|
||||
self._next_probe = time.monotonic() + self.settings.cache_retry_seconds
|
||||
|
||||
async def get(self, th: bytes) -> Principal | None:
|
||||
if not self.client or self.degraded:
|
||||
return None
|
||||
try:
|
||||
raw = await self.client.get(KEY + th.hex())
|
||||
except (RedisError, OSError, asyncio.TimeoutError) as exc:
|
||||
self._fail("get", exc)
|
||||
return None
|
||||
if raw is None:
|
||||
self.stats["misses"] += 1
|
||||
return None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
principal = Principal(user=data["user"], expires_at=float(data["exp"]), token_hash=th)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return None
|
||||
if principal.expires_at <= time.time():
|
||||
return None
|
||||
self.stats["hits"] += 1
|
||||
return principal
|
||||
|
||||
async def put(self, p: Principal) -> None:
|
||||
if not self.client or self.degraded:
|
||||
return
|
||||
ttl_ms = int(min(self.settings.session_cache_ttl_seconds, p.expires_at - time.time()) * 1000)
|
||||
if ttl_ms < 1:
|
||||
return
|
||||
value = json.dumps({"user": p.user, "exp": p.expires_at}, separators=(",", ":"))
|
||||
try:
|
||||
await self._set_script(keys=[KEY + p.token_hash.hex(), TOMBSTONE + p.token_hash.hex()],
|
||||
args=[value, ttl_ms])
|
||||
except (RedisError, OSError, asyncio.TimeoutError) as exc:
|
||||
self._fail("put", exc)
|
||||
|
||||
async def invalidate(self, th: bytes) -> bool:
|
||||
if not self.client:
|
||||
return True
|
||||
try:
|
||||
await self._invalidate_script(keys=[KEY + th.hex(), TOMBSTONE + th.hex()],
|
||||
args=[self._tombstone_ms()])
|
||||
return True
|
||||
except (RedisError, OSError, asyncio.TimeoutError) as exc:
|
||||
self._fail("invalidate", exc)
|
||||
return False
|
||||
|
||||
async def ping(self) -> bool:
|
||||
if not self.client:
|
||||
return False
|
||||
try:
|
||||
return bool(await self.client.ping())
|
||||
except (RedisError, OSError, asyncio.TimeoutError):
|
||||
return False
|
||||
|
||||
async def drain_outbox(self, pool: AsyncConnectionPool) -> int:
|
||||
"""Повторяет инвалидации из session_cache_invalidations. True-результат: outbox пуст."""
|
||||
drained = 0
|
||||
while True:
|
||||
async with pool.connection() as conn:
|
||||
rows = await (await conn.execute(
|
||||
"SELECT token_hash FROM session_cache_invalidations ORDER BY created_at LIMIT 500"
|
||||
)).fetchall()
|
||||
if not rows:
|
||||
return drained
|
||||
done = []
|
||||
for row in rows:
|
||||
th = bytes(row["token_hash"])
|
||||
if not await self.invalidate(th):
|
||||
raise ConnectionError("cache still unavailable")
|
||||
done.append(th)
|
||||
async with pool.connection() as conn:
|
||||
await conn.execute("DELETE FROM session_cache_invalidations WHERE token_hash = ANY(%s)", (done,))
|
||||
drained += len(done)
|
||||
|
||||
async def maintenance_loop(self, pool: AsyncConnectionPool, stop: asyncio.Event) -> None:
|
||||
"""Возвращает кэш в работу только после успешного PING и пустого outbox."""
|
||||
while not stop.is_set():
|
||||
if self.client and time.monotonic() >= self._next_probe:
|
||||
try:
|
||||
if await self.ping():
|
||||
drained = await self.drain_outbox(pool)
|
||||
if self.degraded:
|
||||
log.info("cache available again", extra={"replayed_invalidations": drained})
|
||||
self.degraded = False
|
||||
else:
|
||||
self._fail("probe", ConnectionError("ping failed"))
|
||||
except ConnectionError as exc:
|
||||
self._fail("drain", exc)
|
||||
except Exception as exc: # noqa: BLE001 — БД недоступна: состояние кэша не меняем
|
||||
log.warning("outbox drain skipped", extra={"error": type(exc).__name__})
|
||||
try:
|
||||
await asyncio.wait_for(stop.wait(), timeout=1.0)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.client:
|
||||
await self.client.aclose()
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Строгая валидация входа: лишние поля, неверные типы и malformed JSON — 400."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from .errors import ApiError, invalid
|
||||
|
||||
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}")
|
||||
|
||||
|
||||
def _no_duplicates(pairs):
|
||||
obj = {}
|
||||
for key, value in pairs:
|
||||
if key in obj:
|
||||
raise ValueError("duplicate key")
|
||||
obj[key] = value
|
||||
return obj
|
||||
|
||||
|
||||
def _reject_constant(name):
|
||||
raise ValueError("non-standard JSON constant " + name)
|
||||
|
||||
|
||||
def parse_json_object(raw: bytes, allowed: set[str], required: set[str]) -> dict:
|
||||
if not raw:
|
||||
raise invalid("Ожидается JSON-объект")
|
||||
try:
|
||||
data = json.loads(raw.decode("utf-8"), object_pairs_hook=_no_duplicates,
|
||||
parse_constant=_reject_constant)
|
||||
except (UnicodeDecodeError, ValueError, RecursionError):
|
||||
raise invalid("Некорректный JSON") from None
|
||||
if not isinstance(data, dict):
|
||||
raise invalid("Ожидается JSON-объект")
|
||||
extra = set(data) - allowed
|
||||
if extra:
|
||||
raise invalid("Лишние поля: " + ", ".join(sorted(extra))[:200])
|
||||
missing = required - set(data)
|
||||
if missing:
|
||||
raise invalid("Отсутствуют поля: " + ", ".join(sorted(missing)))
|
||||
return data
|
||||
|
||||
|
||||
def text_field(data: dict, name: str, lo: int, hi: int) -> str:
|
||||
value = data.get(name)
|
||||
if not isinstance(value, str):
|
||||
raise invalid(f"Поле {name} должно быть строкой")
|
||||
if not lo <= len(value) <= hi: # len() в Python — число Unicode code points
|
||||
raise invalid(f"Поле {name}: длина {lo}–{hi} символов")
|
||||
if lo > 0 and not value.strip():
|
||||
raise invalid(f"Поле {name} не может состоять только из пробелов")
|
||||
if "\x00" in value:
|
||||
raise invalid(f"Поле {name} содержит недопустимый символ")
|
||||
try:
|
||||
value.encode("utf-8")
|
||||
except UnicodeEncodeError: # одиночные суррогаты из \uD800-escape
|
||||
raise invalid(f"Поле {name} содержит некорректный Unicode") from None
|
||||
return value
|
||||
|
||||
|
||||
def parse_uuid(value, what: str = "UUID") -> uuid.UUID:
|
||||
if not isinstance(value, str):
|
||||
raise invalid(f"Некорректный {what}")
|
||||
try:
|
||||
parsed = uuid.UUID(value)
|
||||
except ValueError:
|
||||
raise invalid(f"Некорректный {what}") from None
|
||||
# Принимаем только каноническую 36-символьную запись (без {} и urn:).
|
||||
if len(value) != 36:
|
||||
raise invalid(f"Некорректный {what}")
|
||||
return parsed
|
||||
|
||||
|
||||
def parse_limit(params) -> int:
|
||||
values = params.getlist("limit")
|
||||
if not values:
|
||||
return 50
|
||||
if len(values) > 1 or not values[0].isascii() or not values[0].isdigit() or len(values[0]) > 3:
|
||||
raise invalid("limit должен быть целым 1–100")
|
||||
limit = int(values[0])
|
||||
if not 1 <= limit <= 100:
|
||||
raise invalid("limit должен быть целым 1–100")
|
||||
return limit
|
||||
|
||||
|
||||
def single_param(params, name: str) -> str | None:
|
||||
values = params.getlist(name)
|
||||
if len(values) > 1:
|
||||
raise invalid(f"Параметр {name} указан несколько раз")
|
||||
return values[0] if values else None
|
||||
|
||||
|
||||
# --- keyset cursor -------------------------------------------------------------------------
|
||||
# Курсор непрозрачен для клиента: base64url(JSON) с видом списка и областью (чат/пользователь).
|
||||
# Подделка курсора не даёт доступа: область всё равно проверяется, а позиция лишь фильтр.
|
||||
|
||||
def encode_cursor(kind: str, scope: uuid.UUID, created_at: datetime, item_id: uuid.UUID) -> str:
|
||||
payload = json.dumps({"v": 1, "k": kind, "s": str(scope), "t": created_at.isoformat(), "i": str(item_id)},
|
||||
separators=(",", ":")).encode()
|
||||
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor: str, kind: str, scope: uuid.UUID) -> tuple[datetime, uuid.UUID]:
|
||||
try:
|
||||
if not cursor or len(cursor) > 512 or not cursor.isascii():
|
||||
raise ValueError
|
||||
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
|
||||
data = json.loads(raw)
|
||||
if data.get("v") != 1 or data.get("k") != kind or data.get("s") != str(scope):
|
||||
raise ValueError
|
||||
ts = datetime.fromisoformat(data["t"])
|
||||
if ts.tzinfo is None:
|
||||
raise ValueError
|
||||
return ts, uuid.UUID(data["i"])
|
||||
except (ValueError, KeyError, TypeError, AttributeError, UnicodeError):
|
||||
raise ApiError("invalid_request", "Некорректный cursor") from None
|
||||
Reference in New Issue
Block a user