ЛР 3: реализация мессенджера и сценарии проверки

This commit is contained in:
Russiankryt
2026-12-03 17:20:50 +03:00
parent 0ab3a341aa
commit 0ae5bfb167
21 changed files with 1191 additions and 37 deletions
+417
View File
@@ -0,0 +1,417 @@
"""HTTP entry point for the persistent messenger (based on lab 1)."""
import base64
import datetime as dt
import hmac
import json
import os
import re
import signal
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
from uuid import UUID, uuid4
import psycopg
from psycopg_pool import PoolTimeout
from redis.exceptions import RedisError
from auth import Sessions, USERNAME, parse_basic, parse_bearer, password_hash, valid_password, verify_password
from db import KeyConflict, Store, setting
MAX_BODY = 64 * 1024
QUERY_LIMIT = re.compile(r"[0-9]{1,6}")
LENGTH = re.compile(r"[0-9]{1,12}")
IDEMPOTENCY_KEY = re.compile(r"[A-Za-z0-9._:-]{1,128}")
FIRST = (dt.datetime.min.replace(tzinfo=dt.timezone.utc), UUID(int=0))
class ApiError(Exception):
def __init__(self, status, code, message, headers=None):
super().__init__(message)
self.status, self.code, self.message = status, code, message
self.headers = headers or {}
def bad(message="Некорректный запрос"):
return ApiError(400, "invalid_request", message)
def not_found():
return ApiError(404, "not_found", "Объект не найден")
def unauthorized(scheme):
challenge = f'{scheme} realm="messenger"'
if scheme == "Basic":
challenge += ', charset="UTF-8"'
return ApiError(401, "unauthorized", "Нужна аутентификация", {"WWW-Authenticate": challenge})
def clean_text(value, min_len, max_len, field):
if not isinstance(value, str) or not min_len <= len(value) <= max_len or not value.strip():
raise bad(f"Поле {field} имеет недопустимую длину или тип")
try:
value.encode("utf-8")
except UnicodeEncodeError:
raise bad(f"Поле {field} содержит недопустимые символы")
if "\x00" in value:
raise bad(f"Поле {field} содержит NUL")
return value
def parse_uuid(value):
if not isinstance(value, str):
raise bad("Некорректный UUID")
try:
return UUID(value)
except ValueError:
raise bad("Некорректный UUID")
def only_fields(body, required, optional=()):
if not isinstance(body, dict) or set(required) - body.keys() or body.keys() - set(required + optional):
raise bad("Неверный набор полей")
def json_value(value):
if isinstance(value, dt.datetime):
return value.astimezone(dt.timezone.utc).isoformat().replace("+00:00", "Z")
if isinstance(value, UUID):
return str(value)
raise TypeError("Unsupported JSON value")
def encode_cursor(scope, row, key):
raw = json.dumps([scope, row["created_at"], row["id"]], default=json_value).encode()
signature = hmac.digest(key, raw, "sha256")
return base64.urlsafe_b64encode(raw + signature).decode().rstrip("=")
def decode_cursor(cursor, scope, key):
try:
if len(cursor) > 512 or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
raise ValueError
envelope = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
raw, signature = envelope[:-32], envelope[-32:]
if not hmac.compare_digest(hmac.digest(key, raw, "sha256"), signature):
raise ValueError
actual_scope, timestamp, item_id = json.loads(raw)
if actual_scope != scope:
raise ValueError
return dt.datetime.fromisoformat(timestamp.replace("Z", "+00:00")), UUID(item_id)
except (ValueError, TypeError, AttributeError):
raise bad("Некорректный cursor")
def page(ctx, scope, read):
limit = ctx.param("limit", "50")
cursor = ctx.param("cursor")
if not QUERY_LIMIT.fullmatch(limit) or not 1 <= int(limit) <= 100:
raise bad("limit должен быть целым числом от 1 до 100")
count = int(limit)
key = ctx.server.cursor_key
rows = read(decode_cursor(cursor, scope, key) if cursor is not None else FIRST, count + 1)
return {"items": rows[:count],
"next_cursor": encode_cursor(scope, rows[count - 1], key) if len(rows) > count else None}
def create_user(ctx):
body = ctx.json_body()
only_fields(body, ("username", "display_name", "password"))
username = body["username"]
if not isinstance(username, str) or not USERNAME.fullmatch(username):
raise bad("Некорректный username")
name = clean_text(body["display_name"], 1, 100, "display_name")
if not valid_password(body["password"]):
raise bad("Некорректный password")
try:
return 201, ctx.store.register(username, name, password_hash(body["password"]))
except psycopg.errors.UniqueViolation:
raise ApiError(409, "conflict", "Username уже занят")
def login(ctx):
if ctx.content_length():
raise bad("Вход принимает только Basic Authorization")
credentials = parse_basic(ctx.header("Authorization"))
if not credentials:
raise unauthorized("Basic")
username, password = credentials
user, stored = ctx.store.credential(username)
if not verify_password(password, stored):
raise unauthorized("Basic")
token, expires = ctx.server.sessions.issue(user["id"])
return 201, {"token": token, "token_type": "Bearer", "expires_at": expires, "user": user}
def logout(ctx):
if not ctx.server.sessions.revoke(ctx.token):
raise unauthorized("Bearer")
return 204, None
def get_me(ctx):
return 200, ctx.user
def create_chat(ctx):
body = ctx.json_body()
only_fields(body, ("title", "member_ids"))
title = clean_text(body["title"], 1, 100, "title")
ids = body["member_ids"]
if not isinstance(ids, list) or not 1 <= len(ids) <= 100:
raise bad("member_ids: от 1 до 100 элементов")
members = [parse_uuid(value) for value in ids]
if len(set(members)) != len(members) or ctx.user["id"] not in members:
raise bad("member_ids: дубликаты или нет вызывающего")
try:
return 201, ctx.store.create_chat(title, members)
except psycopg.errors.ForeignKeyViolation:
raise bad("member_ids: неизвестный пользователь")
def list_chats(ctx):
user_id = ctx.user["id"]
return 200, page(ctx, f"chats:{user_id}", lambda cursor, n: ctx.store.chats(user_id, cursor, n))
def visible_chat(ctx, chat_id):
chat = ctx.store.chat(ctx.user["id"], parse_uuid(chat_id))
if chat is None:
raise not_found()
return chat
def get_chat(ctx, chat_id):
return 200, visible_chat(ctx, chat_id)
def create_message(ctx, chat_id):
chat = visible_chat(ctx, chat_id)
body = ctx.json_body()
only_fields(body, ("text",))
text = clean_text(body["text"], 1, 4000, "text")
key = ctx.header("Idempotency-Key")
if not IDEMPOTENCY_KEY.fullmatch(key):
raise bad("Некорректный или отсутствующий Idempotency-Key")
try:
return 201, ctx.store.message(ctx.user["id"], chat["id"], text, key)
except KeyConflict:
raise ApiError(409, "conflict", "Ключ уже использован для другого сообщения")
def list_messages(ctx, chat_id):
cid = visible_chat(ctx, chat_id)["id"]
return 200, page(ctx, f"messages:{cid}", lambda cursor, n: ctx.store.messages(cid, cursor, n))
def live(ctx):
return 200, {"status": "ok"}
def ready(ctx):
if ctx.server.stopping.is_set():
raise ApiError(503, "unavailable", "Сервер завершает работу")
ctx.store.ready()
ctx.server.sessions.redis.ping()
return live(ctx)
ROUTES = [(method, re.compile(path), action, authenticated) for method, path, action, authenticated in (
("GET", r"/health/live", live, False),
("GET", r"/health/ready", ready, False),
("POST", r"/api/v1/users", create_user, False),
("POST", r"/api/v1/auth/sessions", login, False),
("DELETE", r"/api/v1/auth/sessions/current", logout, True),
("GET", r"/api/v1/users/me", get_me, True),
("POST", r"/api/v1/chats", create_chat, True),
("GET", r"/api/v1/chats", list_chats, True),
("GET", r"/api/v1/chats/([^/]+)", get_chat, True),
("POST", r"/api/v1/chats/([^/]+)/messages", create_message, True),
("GET", r"/api/v1/chats/([^/]+)/messages", list_messages, True),
)]
class Context:
def __init__(self, handler):
self.handler = handler
self.server = handler.server
self.store = self.server.store
self.user = self.token = None
self.body_read = False
self.route = "unmatched"
def header(self, name):
values = self.handler.headers.get_all(name, [])
return values[0] if len(values) == 1 else ""
def param(self, name, default=None):
values = self.query.get(name, [])
if len(values) > 1:
raise bad(f"Повторяющийся параметр {name}")
return values[0] if values else default
def content_length(self):
if self.handler.headers.get_all("Transfer-Encoding"):
raise bad("Нужен запрос с Content-Length")
if not self.handler.headers.get_all("Content-Length"):
return 0
value = self.header("Content-Length")
if not LENGTH.fullmatch(value):
raise bad("Некорректный Content-Length")
return int(value)
def read_body(self, limit):
length = self.content_length()
if length > limit:
raise ApiError(413, "payload_too_large", "Слишком большое тело запроса")
try:
raw = self.handler.rfile.read(length)
except TimeoutError:
raise bad("Таймаут чтения тела")
self.body_read = True
if len(raw) != length:
raise bad("Тело запроса получено не полностью")
return raw
def json_body(self):
raw = self.read_body(MAX_BODY)
if self.header("Content-Type").split(";")[0].strip().lower() != "application/json":
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
try:
return json.loads(raw.decode("utf-8"))
except (ValueError, RecursionError):
raise bad("Некорректный JSON")
def authenticate(self):
self.token = parse_bearer(self.header("Authorization"))
if self.token:
user_id = self.server.sessions.get(self.token)
if user_id:
self.user = self.store.user(user_id)
if self.user:
return
raise unauthorized("Bearer")
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server_version = "messenger"
sys_version = ""
timeout = 8
def log_message(self, *args):
pass
def dispatch(self, ctx):
try:
parts = urlsplit(self.path)
ctx.query = parse_qs(parts.query, keep_blank_values=True, max_num_fields=32)
except ValueError:
raise bad("Некорректный URL")
for method, pattern, action, authenticated in ROUTES:
if method == self.command and (match := pattern.fullmatch(parts.path)):
ctx.route = action.__name__
if self.server.stopping.is_set() and action != live:
raise ApiError(503, "unavailable", "Сервер завершает работу")
if authenticated:
ctx.authenticate()
return action(ctx, *match.groups())
raise not_found()
def handle_any(self):
started = time.monotonic()
request_id = str(uuid4())
ctx = Context(self)
headers = {}
error = None
try:
status, payload = self.dispatch(ctx)
except ApiError as exc:
error = exc
except (RedisError, PoolTimeout, psycopg.OperationalError, psycopg.errors.QueryCanceled,
psycopg.errors.LockNotAvailable):
error = ApiError(503, "unavailable", "Хранилище временно недоступно")
except Exception as exc:
print(json.dumps({"request_id": request_id, "exception": type(exc).__name__}), flush=True)
error = ApiError(500, "internal_error", "Внутренняя ошибка")
if error:
status, headers = error.status, error.headers
payload = {"error": {"code": error.code, "message": error.message, "request_id": request_id}}
self.close_connection = True # Rejected bodies are never parsed as a next request.
data = b"" if status == 204 else json.dumps(payload, default=json_value, ensure_ascii=False).encode()
try:
self.send_response(status)
if status != 204:
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.send_header("X-Request-Id", request_id)
self.send_header("X-Instance-Id", self.server.instance_id)
self.send_header("Connection", "close")
for name, value in headers.items():
self.send_header(name, value)
self.end_headers()
if data:
self.wfile.write(data)
except (OSError, TimeoutError):
pass
print(json.dumps({"method": self.command, "route": ctx.route, "status": status,
"duration_ms": round((time.monotonic() - started) * 1000, 2),
"request_id": request_id}), flush=True)
do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = handle_any
class Server(ThreadingHTTPServer):
request_queue_size = 64
daemon_threads = False
def __init__(self, address):
super().__init__(address, Handler)
self.stopping = threading.Event()
self.instance_id = uuid4().hex
self.workers = threading.BoundedSemaphore(16)
self.cursor_key = setting("CURSOR_KEY").encode()
self.store = Store()
self.sessions = Sessions()
def process_request(self, request, address):
if not self.workers.acquire(blocking=False):
self.shutdown_request(request)
return
try:
super().process_request(request, address)
except BaseException:
self.workers.release()
raise
def process_request_thread(self, request, address):
try:
super().process_request_thread(request, address)
finally:
self.workers.release()
def main():
address = os.environ.get("APP_HOST", "0.0.0.0"), int(os.environ.get("APP_PORT", "8080"))
with Server(address) as server:
def stop(signum, frame):
if not server.stopping.is_set():
server.stopping.set()
threading.Thread(target=server.shutdown, daemon=True).start()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
try:
server.serve_forever()
finally:
server.server_close()
server.store.pool.close()
server.sessions.redis.close()
if __name__ == "__main__":
main()
+91
View File
@@ -0,0 +1,91 @@
"""Password verification and revocable Redis-backed sessions."""
import base64
import hashlib
import hmac
import os
import re
import secrets
from datetime import datetime, timezone
from redis import Redis
from db import setting
USERNAME = re.compile(r"[a-z0-9_]{3,32}")
TOKEN = re.compile(r"[A-Za-z0-9_-]{43}")
def valid_password(password):
if not isinstance(password, str) or not 12 <= len(password) <= 128:
return False
try:
password.encode("utf-8")
except UnicodeEncodeError:
return False
return True
def password_hash(password, salt=None):
if salt is None:
salt = secrets.token_bytes(16)
digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=16384, r=8, p=3)
return f"scrypt:{salt.hex()}:{digest.hex()}"
DUMMY_HASH = password_hash("dummy unknown account")
def verify_password(password, stored):
_, salt, _ = (stored or DUMMY_HASH).split(":")
actual = password_hash(password, bytes.fromhex(salt))
return hmac.compare_digest(actual, stored or DUMMY_HASH) and stored is not None
def parse_basic(value):
scheme, _, data = value.partition(" ")
if scheme.lower() != "basic" or not 1 <= len(data) <= 1024:
return None
try:
username, sep, password = base64.b64decode(data, validate=True).decode("utf-8").partition(":")
except (ValueError, UnicodeError):
return None
if sep and USERNAME.fullmatch(username) and valid_password(password):
return username, password
return None
def parse_bearer(value):
scheme, _, token = value.partition(" ")
if scheme.lower() == "bearer" and TOKEN.fullmatch(token):
return token
return None
class Sessions:
def __init__(self):
self.redis = Redis.from_url(
setting("CACHE_URL"), socket_timeout=2, socket_connect_timeout=2,
max_connections=24, decode_responses=True,
)
self.ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
if self.ttl < 1:
raise ValueError("SESSION_TTL_SECONDS must be positive")
@staticmethod
def key(token):
return "messenger:session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
def issue(self, user_id):
token = secrets.token_urlsafe(32)
seconds, micros = self.redis.time()
expires_ms = seconds * 1000 + micros // 1000 + self.ttl * 1000
self.redis.set(self.key(token), str(user_id), pxat=expires_ms)
return token, datetime.fromtimestamp(expires_ms / 1000, timezone.utc)
def get(self, token):
return self.redis.get(self.key(token))
def revoke(self, token):
return bool(self.redis.delete(self.key(token)))
+166
View File
@@ -0,0 +1,166 @@
"""PostgreSQL migrations, transactional writes and keyset reads."""
import hashlib
import json
import os
from pathlib import Path
from uuid import uuid4
import psycopg
from psycopg.conninfo import make_conninfo
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
def setting(name):
path = os.environ.get(name + "_FILE")
return Path(path).read_text(encoding="utf-8").strip() if path else os.environ[name]
def connection_string():
return make_conninfo(
setting("DATABASE_URL"),
connect_timeout=3,
options="-c statement_timeout=4000 -c lock_timeout=2500",
)
def migrate():
with psycopg.connect(connection_string(), autocommit=True) as connection:
migrations = Path(__file__).with_name("migrations")
with connection.transaction():
connection.execute("SELECT pg_advisory_xact_lock(17002026)")
connection.execute("""
CREATE TABLE IF NOT EXISTS schema_migrations (
name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now()
)
""")
for file in sorted(migrations.glob("*.sql")):
with connection.transaction():
connection.execute("SELECT pg_advisory_xact_lock(17002026)")
if connection.execute(
"SELECT 1 FROM schema_migrations WHERE name = %s", (file.name,)
).fetchone():
continue
connection.execute(file.read_text(encoding="utf-8"))
connection.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (file.name,))
class KeyConflict(Exception):
"""The same active idempotency key has a different canonical request."""
class Store:
def __init__(self):
self.pool = ConnectionPool(
connection_string(), min_size=1, max_size=8, timeout=2, open=False,
kwargs={"row_factory": dict_row},
)
self.pool.open()
def ready(self):
with self.pool.connection() as connection:
connection.execute("SELECT 1")
def register(self, username, display_name, password_hash):
with self.pool.connection() as connection:
return connection.execute("""
INSERT INTO users(id, username, display_name, password_hash)
VALUES (%s, %s, %s, %s)
RETURNING id, username, display_name, created_at
""", (uuid4(), username, display_name, password_hash)).fetchone()
def credential(self, username):
with self.pool.connection() as connection:
user = connection.execute("""
SELECT id, username, display_name, created_at, password_hash
FROM users WHERE username = %s
""", (username,)).fetchone()
if user:
return user, user.pop("password_hash")
return None, None
def user(self, user_id):
with self.pool.connection() as connection:
return connection.execute("""
SELECT id, username, display_name, created_at FROM users WHERE id = %s
""", (user_id,)).fetchone()
def create_chat(self, title, members):
with self.pool.connection() as connection:
chat = connection.execute("""
INSERT INTO chats(id, title) VALUES (%s, %s) RETURNING *
""", (uuid4(), title)).fetchone()
connection.execute("""
INSERT INTO chat_members(chat_id, user_id, position)
SELECT %s, member, ord FROM unnest(%s::uuid[]) WITH ORDINALITY AS m(member, ord)
""", (chat["id"], members))
return {**chat, "member_ids": members}
def chat(self, user_id, chat_id):
with self.pool.connection() as connection:
return connection.execute("""
SELECT c.*, ARRAY(SELECT user_id FROM chat_members m
WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids
FROM chats c JOIN chat_members membership ON membership.chat_id = c.id
WHERE membership.user_id = %s AND c.id = %s
""", (user_id, chat_id)).fetchone()
def chats(self, user_id, cursor, count):
with self.pool.connection() as connection:
return connection.execute("""
SELECT c.*, ARRAY(SELECT m.user_id FROM chat_members m
WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids
FROM chats c JOIN chat_members membership ON membership.chat_id = c.id
WHERE membership.user_id = %s
AND (c.created_at, c.id) > (%s::timestamptz, %s::uuid)
ORDER BY c.created_at, c.id LIMIT %s
""", (user_id, *cursor, count)).fetchall()
def message(self, user_id, chat_id, text, key):
scope = (user_id, chat_id, key)
fingerprint = hashlib.sha256(json.dumps({"text": text}, separators=(",", ":")).encode()).digest()
with self.pool.connection() as connection:
accepted = connection.execute("""
INSERT INTO message_requests(user_id, chat_id, request_key, fingerprint)
VALUES (%s, %s, %s, %s)
ON CONFLICT (user_id, chat_id, request_key) DO UPDATE
SET fingerprint = EXCLUDED.fingerprint, message_id = NULL,
expires_at = clock_timestamp() + interval '24 hours'
WHERE message_requests.expires_at <= clock_timestamp()
RETURNING request_key
""", (*scope, fingerprint)).fetchone()
if accepted:
message = self.insert_message(connection, user_id, chat_id, text)
connection.execute("""
UPDATE message_requests SET message_id = %s
WHERE user_id = %s AND chat_id = %s AND request_key = %s
""", (message["id"], *scope))
return message
existing = connection.execute("""
SELECT m.*, r.fingerprint
FROM message_requests r JOIN messages m ON m.id = r.message_id
WHERE r.user_id = %s AND r.chat_id = %s AND r.request_key = %s
""", scope).fetchone()
if existing.pop("fingerprint") != fingerprint:
raise KeyConflict()
return existing
def insert_message(self, connection, user_id, chat_id, text):
return connection.execute("""
INSERT INTO messages(id, chat_id, sender_id, text)
VALUES (%s, %s, %s, %s)
RETURNING *
""", (uuid4(), chat_id, user_id, text)).fetchone()
def messages(self, chat_id, cursor, count):
with self.pool.connection() as connection:
return connection.execute("""
SELECT * FROM messages
WHERE chat_id = %s AND (created_at, id) > (%s::timestamptz, %s::uuid)
ORDER BY created_at, id LIMIT %s
""", (chat_id, *cursor, count)).fetchall()
if __name__ == "__main__":
migrate()
+33
View File
@@ -0,0 +1,33 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX chats_page ON chats (created_at, id);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats(id),
user_id uuid NOT NULL REFERENCES users(id),
position integer NOT NULL CHECK (position > 0),
PRIMARY KEY (chat_id, user_id),
UNIQUE (chat_id, position)
);
CREATE INDEX chat_members_by_user ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
);
CREATE INDEX messages_page ON messages (chat_id, created_at, id);
+10
View File
@@ -0,0 +1,10 @@
CREATE TABLE message_requests (
user_id uuid NOT NULL,
chat_id uuid NOT NULL,
request_key text NOT NULL,
fingerprint bytea NOT NULL,
expires_at timestamptz NOT NULL DEFAULT (clock_timestamp() + interval '24 hours'),
message_id uuid REFERENCES messages(id),
PRIMARY KEY (user_id, chat_id, request_key),
FOREIGN KEY (chat_id, user_id) REFERENCES chat_members(chat_id, user_id)
);