"""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 import unicodedata from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlsplit from uuid import UUID, uuid4 import psycopg from psycopg.types.json import Jsonb from psycopg_pool import PoolTimeout from redis.exceptions import RedisError from botocore.exceptions import BotoCoreError, ClientError from attachments import BadImage, MAX_UPLOAD, Objects, PixelLimit, spool, verify_image from auth import Sessions, USERNAME, parse_basic, parse_bearer, password_hash, valid_password, verify_password from db import KeyConflict, MissingAttachment, Store, UnusableAttachment, setting import telemetry as tm 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",), ("attachment_ids",)) items = body.get("attachment_ids", []) if not isinstance(items, list) or len(items) > 10: raise bad("attachment_ids: от 0 до 10 элементов") attachment_ids = [parse_uuid(value) for value in items] if len(set(attachment_ids)) != len(attachment_ids): raise bad("attachment_ids: дубликаты") raw_text = body["text"] if raw_text == "" and attachment_ids: text = "" else: text = clean_text(raw_text, 1, 4000, "text") key = ctx.header("Idempotency-Key") if not IDEMPOTENCY_KEY.fullmatch(key): raise bad("Некорректный или отсутствующий Idempotency-Key") try: with tm.span("db.message.write", tm.SpanKind.CLIENT): return 201, ctx.store.message(ctx.user["id"], chat["id"], text, key, attachment_ids) except KeyConflict: raise ApiError(409, "conflict", "Ключ уже использован для другого сообщения") except MissingAttachment: raise not_found() except UnusableAttachment: 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 upload_attachment(ctx, chat_id): chat = visible_chat(ctx, chat_id) filename = clean_text(ctx.param("filename"), 1, 255, "filename") if any(char in "/\\" or unicodedata.category(char) == "Cc" for char in filename): raise bad("Некорректное имя файла") mime = ctx.header("Content-Type").split(";")[0].strip().lower() if mime not in ("image/jpeg", "image/png"): raise ApiError(415, "unsupported_media_type", "Поддерживаются PNG и JPEG") with ctx.server.image_slot, spool() as file: length = ctx.stream_body(file) try: verify_image(file, mime) except BadImage: raise ApiError(415, "unsupported_media_type", "Повреждённое или неподдерживаемое изображение") except PixelLimit: raise ApiError(413, "payload_too_large", "Изображение превышает лимит пикселей") objects = ctx.server.objects row = ctx.store.save_attachment( chat["id"], ctx.user["id"], filename, mime, length, lambda item: objects.put(objects.key(item, "staging"), file, mime, length), Jsonb(tm.carrier()), ) return 202, public_attachment(row) def public_attachment(row): return {key: value for key, value in row.items() if key != "pipeline_version"} def get_metadata(ctx, attachment_id): row = ctx.store.attachment(ctx.user["id"], parse_uuid(attachment_id)) if row is None: raise not_found() return 200, public_attachment(row) def download_attachment(ctx, attachment_id): row = ctx.store.attachment(ctx.user["id"], parse_uuid(attachment_id)) if row is None: raise not_found() if row["status"] != "ready": raise ApiError(409, "conflict", "Вложение ещё недоступно") variant = ctx.param("variant", "original") variants = {item["name"]: item["content_type"] for item in row["variants"]} if variant != "original" and variant not in variants: raise not_found() objects = ctx.server.objects ctx.content_type = row["content_type"] if variant == "original" else variants[variant] key = objects.result_key(row["id"], row["pipeline_version"], variant) return 200, objects.get(key) def live(ctx): return 200, {"status": "ok"} def ready(ctx): if ctx.server.stopping.is_set(): raise ApiError(503, "unavailable", "Сервер завершает работу") with tm.span("db.readiness", tm.SpanKind.CLIENT): ctx.store.ready() with tm.span("redis.readiness", tm.SpanKind.CLIENT): ctx.server.sessions.redis.ping() with tm.span("s3.readiness", tm.SpanKind.CLIENT): ctx.server.objects.ready() 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), ("POST", r"/api/v1/chats/([^/]+)/attachments", upload_attachment, True), ("GET", r"/api/v1/attachments/([^/]+)", get_metadata, True), ("GET", r"/api/v1/attachments/([^/]+)/content", download_attachment, 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" self.content_type = None 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 stream_body(self, file): length = self.content_length() if length > MAX_UPLOAD: raise ApiError(413, "payload_too_large", "Слишком большой файл") remaining = length deadline = time.monotonic() + 10 while remaining: timeout = deadline - time.monotonic() if timeout <= 0: raise bad("Таймаут загрузки") self.handler.connection.settimeout(timeout) try: chunk = self.handler.rfile.read1(min(remaining, 64 * 1024)) except TimeoutError: raise bad("Таймаут загрузки") if not chunk: raise bad("Тело запроса получено не полностью") file.write(chunk) remaining -= len(chunk) self.body_read = True file.seek(0) return length 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)): resource = "{attachment_id}" if pattern.pattern.startswith("/api/v1/attachments/") else "{chat_id}" ctx.route = pattern.pattern.replace("([^/]+)", resource) 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): incoming = {name: self.headers.get(name, "") for name in ("traceparent", "tracestate")} with tm.span("HTTP", tm.SpanKind.SERVER, incoming) as active: self.respond(active) def respond(self, active): 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, BotoCoreError, ClientError, PoolTimeout, psycopg.OperationalError, psycopg.errors.QueryCanceled, psycopg.errors.LockNotAvailable): error = ApiError(503, "unavailable", "Хранилище временно недоступно") except Exception as exc: tm.record("http_exception", request_id=request_id, exception_type=type(exc).__name__) 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. if isinstance(payload, bytes): data, content_type = payload, ctx.content_type else: content_type = "application/json; charset=utf-8" 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", content_type) self.send_header("X-Content-Type-Options", "nosniff") 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 duration = time.monotonic() - started tm.observe_http(active, self.command, ctx.route, status, duration) tm.observe_process(ctx.store.pool) tm.record("http_request", method=self.command, route=ctx.route, status=status, duration_ms=round(duration * 1000, 2), request_id=request_id) 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() self.objects = Objects() self.image_slot = threading.BoundedSemaphore(1) 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: tm.setup("api", server.instance_id) 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()