#!/usr/bin/env python3 """PostgreSQL-backed API for the asynchronous image-processing lab.""" import base64 import binascii from datetime import datetime, timedelta, timezone import hashlib import io import json import logging import os import re import secrets import signal import socket import sys import threading import unicodedata import warnings from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import parse_qs, urlsplit import uuid import time import ssl from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError import boto3 from botocore.config import Config from botocore.exceptions import BotoCoreError, ClientError from PIL import Image, UnidentifiedImageError from psycopg.conninfo import make_conninfo from psycopg.errors import UniqueViolation from psycopg.rows import dict_row from psycopg.types.json import Jsonb import psycopg from psycopg_pool import ConnectionPool, PoolTimeout from queueing import BrokerUnavailable, check_broker, publish_pending_job import observability as telemetry from opentelemetry import trace from opentelemetry.context import attach, detach from service_secrets import load_service_secrets LOG = logging.getLogger("messenger") USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$") MAX_BODY_BYTES = 1024 * 1024 MAX_UPLOAD_BYTES = 10 * 1024 * 1024 MAX_IMAGE_PIXELS = 40_000_000 IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") IDEMPOTENCY_TTL = timedelta(hours=24) IMAGE_CONTENT_TYPES = {"image/png": "PNG", "image/jpeg": "JPEG"} MIGRATIONS = Path(__file__).resolve().parent / "migrations" PASSWORD_HASHER = PasswordHasher( memory_cost=int(os.environ.get("ARGON2_MEMORY_KIB", "19456")), time_cost=int(os.environ.get("ARGON2_ITERATIONS", "2")), parallelism=int(os.environ.get("ARGON2_PARALLELISM", "1")), hash_len=32, salt_len=16, ) POOL = None S3_CLIENT = None S3_BUCKET = None SESSION_TTL_SECONDS = 3600 INSTANCE_ID = os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname() or str(uuid.uuid4()) OUTBOX_STOP = threading.Event() LOGIN_LIMIT = int(os.environ.get("LOGIN_LIMIT_PER_MINUTE", "5")) LOGIN_WINDOW_SECONDS = int(os.environ.get("LOGIN_WINDOW_SECONDS", "60")) class BinaryResponse: def __init__(self, data, content_type): self.data = data self.content_type = content_type class ApiError(Exception): def __init__(self, status, code, message, headers=None): super().__init__(message) self.status = status self.code = code self.message = message self.headers = headers or {} def invalid(message="Некорректный запрос"): return ApiError(400, "invalid_request", message) def unauthorized(scheme): challenge = ('Basic realm="messenger", charset="UTF-8"' if scheme == "Basic" else 'Bearer realm="messenger"') return ApiError(401, "unauthorized", "Требуется действительная аутентификация", {"WWW-Authenticate": challenge}) def utc_now(): return datetime.now(timezone.utc) def timestamp(value): return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") def user_json(row): return { "id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], "created_at": timestamp(row["created_at"]), } def chat_json(conn, row): members = conn.execute( "SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY member_position", (row["id"],), ).fetchall() return { "id": str(row["id"]), "title": row["title"], "member_ids": [str(member["user_id"]) for member in members], "created_at": timestamp(row["created_at"]), } def message_json(row, attachment_ids=None): if attachment_ids is None: attachment_ids = row.get("attachment_ids", []) return { "id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": timestamp(row["created_at"]), "attachment_ids": [str(item) for item in attachment_ids], } def attachment_json(row): return { "id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]), "filename": row["filename"], "content_type": row["content_type"], "size_bytes": row["size_bytes"], "sha256": row["sha256"], "status": row["status"], "variants": row["variants"], "error_code": row["error_code"], "created_at": timestamp(row["created_at"]), "updated_at": timestamp(row["updated_at"]), } def encode_cursor(kind, scope, created_at, object_id): payload = json.dumps( {"kind": kind, "scope": str(scope), "created_at": timestamp(created_at), "id": str(object_id)}, separators=(",", ":"), ).encode("utf-8") return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=") def decode_cursor(value, kind, scope): try: padded = value + "=" * (-len(value) % 4) raw = base64.b64decode(padded.encode("ascii"), altchars=b"-_", validate=True) data = json.loads(raw.decode("utf-8")) if (not isinstance(data, dict) or set(data) != {"kind", "scope", "created_at", "id"} or data["kind"] != kind or data["scope"] != str(scope) or not isinstance(data["created_at"], str)): raise ValueError("invalid cursor fields") created_at = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00")) if created_at.tzinfo is None: raise ValueError("cursor timestamp has no timezone") return created_at.astimezone(timezone.utc), uuid.UUID(data["id"]) except (ValueError, TypeError, KeyError, UnicodeError, binascii.Error): raise invalid("Некорректный cursor") def parse_uuid(value, label): if not isinstance(value, str): raise invalid("Некорректный " + label) try: return uuid.UUID(value) except (ValueError, AttributeError): raise invalid("Некорректный " + label) def parse_limit(query): values = query.get("limit") if values is None: return 50 if len(values) != 1 or not re.fullmatch(r"[0-9]+", values[0]): raise invalid("Некорректный limit") value = int(values[0]) if not 1 <= value <= 100: raise invalid("Некорректный limit") return value def publish_outbox(pool, stop_event): while not stop_event.wait(1): try: with pool.connection() as conn: pending = conn.execute( """SELECT id FROM image_jobs WHERE status = 'queued' AND published_attempt < attempt ORDER BY created_at, id LIMIT 20""" ).fetchall() for row in pending: try: publish_pending_job(pool, row["id"]) except BrokerUnavailable: LOG.warning("outbox publish deferred job_id=%s", row["id"]) break except (psycopg.Error, PoolTimeout) as error: LOG.warning("outbox scan failed error_type=%s", type(error).__name__) def database_conninfo(): ca_cert = os.environ.get("INTERNAL_CA_CERT", "") options = {} if ca_cert: options = { "sslmode": "verify-full", "sslrootcert": ca_cert, } return make_conninfo( host=os.environ.get("PGHOST", "localhost"), port=os.environ.get("PGPORT", "5432"), dbname=os.environ.get("PGDATABASE", "messenger"), user=os.environ.get("PGUSER", "messenger"), password=os.environ.get("PGPASSWORD", ""), connect_timeout=3, application_name="mtusi-messenger-lab3", **options, ) def migrate(pool): with pool.connection() as conn: conn.execute("SELECT pg_advisory_xact_lock(24012026, 2)") conn.execute( """CREATE TABLE IF NOT EXISTS schema_migrations ( version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now() )""" ) applied = {row["version"] for row in conn.execute( "SELECT version FROM schema_migrations" ).fetchall()} for path in sorted(MIGRATIONS.glob("[0-9]*.sql")): if path.name in applied: continue sql = path.read_text(encoding="utf-8").strip() if not sql: raise RuntimeError("empty database migration: " + path.name) conn.execute(sql, prepare=False) conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (path.name,)) LOG.info("database migration applied version=%s", path.name) def validate_runtime_config(): try: ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) if ttl < 1 or ttl > 31_536_000: raise ValueError() max_connections = int(os.environ.get("DB_POOL_MAX_SIZE", "10")) if max_connections < 1 or max_connections > 100: raise ValueError() port = int(os.environ.get("APP_PORT", "8080")) if not 1 <= port <= 65535: raise ValueError() except ValueError: raise SystemExit("Invalid APP_PORT, SESSION_TTL_SECONDS or DB_POOL_MAX_SIZE") return ttl, max_connections, port def configured_job_attempts(): try: attempts = int(os.environ.get("JOB_MAX_ATTEMPTS", "5")) except ValueError: raise SystemExit("JOB_MAX_ATTEMPTS must be an integer") if not 1 <= attempts <= 20: raise SystemExit("JOB_MAX_ATTEMPTS must be between 1 and 20") return attempts def create_s3_client(): endpoint = os.environ.get("S3_ENDPOINT", "").strip() region = os.environ.get("S3_REGION", "us-east-1").strip() bucket = os.environ.get("S3_BUCKET", "").strip() access_key = os.environ.get("S3_ACCESS_KEY_ID", "").strip() secret_key = os.environ.get("S3_SECRET_ACCESS_KEY", "") ca_cert = os.environ.get("INTERNAL_CA_CERT", "").strip() if not endpoint or not region or not bucket or not access_key or not secret_key: raise SystemExit("S3_ENDPOINT, S3_REGION, S3_BUCKET and S3 credentials are required") if not endpoint.startswith(("http://", "https://")): raise SystemExit("S3_ENDPOINT must use http:// or https://") client = boto3.client( "s3", endpoint_url=endpoint, region_name=region, aws_access_key_id=access_key, aws_secret_access_key=secret_key, verify=ca_cert or True, config=Config( signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=1, read_timeout=2, retries={"total_max_attempts": 1, "mode": "standard"}, ), ) return client, bucket def validate_image_payload(data, content_type): expected_format = IMAGE_CONTENT_TYPES.get(content_type) if expected_format is None: raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG") try: with warnings.catch_warnings(): warnings.simplefilter("error", Image.DecompressionBombWarning) with Image.open(io.BytesIO(data)) as image: if image.width * image.height > MAX_IMAGE_PIXELS: raise ApiError(413, "payload_too_large", "Изображение слишком велико") if image.format != expected_format: raise ApiError(415, "unsupported_media_type", "Тип содержимого не совпадает с изображением") image.verify() except ApiError: raise except (Image.DecompressionBombError, Image.DecompressionBombWarning): raise ApiError(413, "payload_too_large", "Изображение слишком велико") except (OSError, SyntaxError, UnidentifiedImageError, ValueError): raise ApiError(415, "unsupported_media_type", "Повреждённое или неподдерживаемое изображение") class MessengerHandler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def _require_lb_certificate(self): tls_cert = os.environ.get("API_SERVER_CERT", "").strip() if not tls_cert: return connection = getattr(self, "connection", None) if connection is None or not hasattr(connection, "getpeercert"): raise ApiError(401, "unauthorized", "Требуется сертификат балансировщика") certificate = connection.getpeercert() if not certificate: raise ApiError(401, "unauthorized", "Требуется сертификат балансировщика") identities = [] for name, value in certificate.get("subjectAltName", []): if name == "DNS": identities.append(value) for _, values in certificate.items(): pass if "lb" not in identities and "messenger-lb" not in identities: raise ApiError(401, "unauthorized", "Недопустимый сертификат балансировщика") def do_GET(self): self._dispatch() def do_POST(self): self._dispatch() def do_DELETE(self): self._dispatch() def do_PUT(self): self._dispatch() def do_PATCH(self): self._dispatch() def do_OPTIONS(self): self._dispatch() def _dispatch(self): self.request_id = str(uuid.uuid4()) self.response_status = 500 self._pending_object_key = None self._after_commit = [] path = urlsplit(self.path).path if os.environ.get("API_SERVER_CERT", "").strip(): try: self._require_lb_certificate() except ApiError as error: self._send_error(error.status, error.code, error.message, error.headers) return started = time.monotonic() template = telemetry.route_template(path) span = None context_token = None if telemetry.TRACER is not None: span = telemetry.TRACER.start_span( "HTTP " + self.command, kind=trace.SpanKind.SERVER, attributes={ "http.request.method": self.command, "http.route": template, }, ) context = trace.set_span_in_context(span) context_token = attach(context) try: if self.command == "GET" and path == "/health/live": status, payload = 200, {"status": "ok"} else: with POOL.connection() as conn: status, payload = self._route(conn) self._pending_object_key = None for callback in self._after_commit: callback() if isinstance(payload, BinaryResponse): self._send_bytes(status, payload.data, payload.content_type) else: self._send_json(status, payload) except ApiError as error: self._cleanup_pending_object() self._send_error(error.status, error.code, error.message, error.headers) except BrokerUnavailable: self._cleanup_pending_object() LOG.warning("broker unavailable request_id=%s", self.request_id) self._send_error(503, "unavailable", "Очередь обработки временно недоступна") except (psycopg.Error, PoolTimeout): self._cleanup_pending_object() LOG.warning("database unavailable request_id=%s", self.request_id) self._send_error(503, "unavailable", "Хранилище временно недоступно") except (BotoCoreError, ClientError): self._cleanup_pending_object() LOG.warning("object storage unavailable request_id=%s", self.request_id) self._send_error(503, "unavailable", "Файловое хранилище временно недоступно") except Exception as error: self._cleanup_pending_object() LOG.error("unhandled request error request_id=%s error_type=%s error=%r", self.request_id, type(error).__name__, error) self._send_error(500, "internal_error", "Внутренняя ошибка сервера") finally: duration = time.monotonic() - started status_class = str(self.response_status // 100) + "xx" if telemetry.HTTP_REQUESTS is not None: telemetry.HTTP_REQUESTS.add( 1, { "method": self.command, "route": template, "status_class": status_class, }, ) if telemetry.HTTP_DURATION is not None: telemetry.HTTP_DURATION.record( duration, { "method": self.command, "route": template, "status_class": status_class, }, ) if span is not None: span.set_attribute("http.response.status_code", self.response_status) span.set_status( trace.Status( trace.StatusCode.ERROR if self.response_status >= 500 else trace.StatusCode.OK, ) ) detach(context_token) span.end() LOG.info("request method=%s path=%s status=%s request_id=%s", self.command, urlsplit(self.path).path, self.response_status, self.request_id) def _cleanup_pending_object(self): key = self._pending_object_key self._pending_object_key = None if key is None or S3_CLIENT is None: return try: S3_CLIENT.delete_object(Bucket=S3_BUCKET, Key=key) except (BotoCoreError, ClientError) as error: LOG.error("failed to compensate object upload request_id=%s error_type=%s", self.request_id, type(error).__name__) def _send_json(self, status, payload): data = b"" if status == 204 else json.dumps( payload, ensure_ascii=False, separators=(",", ":") ).encode("utf-8") self.response_status = status self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.send_header("X-Request-Id", self.request_id) self.send_header("X-Instance-Id", INSTANCE_ID) self.send_header("Connection", "close") self.end_headers() if data: self.wfile.write(data) self.close_connection = True def _send_bytes(self, status, data, content_type): self.response_status = status self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "private, no-store") self.send_header("X-Request-Id", self.request_id) self.send_header("X-Instance-Id", INSTANCE_ID) self.send_header("Connection", "close") self.end_headers() if data: self.wfile.write(data) self.close_connection = True def _send_error(self, status, code, message, headers=None): data = json.dumps( {"error": {"code": code, "message": message, "request_id": self.request_id}}, ensure_ascii=False, separators=(",", ":"), ).encode("utf-8") self.response_status = status self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.send_header("X-Request-Id", self.request_id) self.send_header("X-Instance-Id", INSTANCE_ID) self.send_header("Connection", "close") for name, value in (headers or {}).items(): self.send_header(name, value) self.end_headers() self.wfile.write(data) self.close_connection = True def _read_json(self): content_type = self.headers.get("Content-Type", "") media_type = content_type.split(";", 1)[0].strip().lower() if media_type != "application/json": raise ApiError(415, "unsupported_media_type", "Ожидается application/json") length = self.headers.get("Content-Length") if length is None or not re.fullmatch(r"[0-9]+", length): raise invalid("Некорректный Content-Length") size = int(length) if size > MAX_BODY_BYTES: raise ApiError(413, "payload_too_large", "Тело запроса слишком велико") try: raw = self.rfile.read(size) if len(raw) != size: raise ValueError("incomplete body") def object_without_duplicates(pairs): result = {} for key, value in pairs: if key in result: raise ValueError("duplicate JSON key") result[key] = value return result value = json.loads( raw.decode("utf-8"), object_pairs_hook=object_without_duplicates, parse_constant=lambda value: (_ for _ in ()).throw(ValueError(value)), ) except (ValueError, UnicodeError): raise invalid("Некорректный JSON") if not isinstance(value, dict): raise invalid("JSON body должен быть объектом") return value def _read_binary(self): lengths = self.headers.get_all("Content-Length", []) if (self.headers.get("Transfer-Encoding") is not None or len(lengths) != 1 or len(lengths[0]) > 20 or not re.fullmatch(r"[0-9]+", lengths[0])): raise invalid("Некорректный Content-Length") size = int(lengths[0]) if size > MAX_UPLOAD_BYTES: raise ApiError(413, "payload_too_large", "Файл превышает 10 MiB") content_type = self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() if content_type not in IMAGE_CONTENT_TYPES: raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG") data = self.rfile.read(size) if len(data) != size: raise invalid("Неполное тело запроса") validate_image_payload(data, content_type) return data, content_type def _attachment_filename(self): query = self._query() values = query.get("filename") if set(query) != {"filename"} or values is None or len(values) != 1: raise invalid("Требуется ровно один параметр filename") filename = values[0] if (not 1 <= len(filename) <= 255 or any(char in "/\\\x00" or unicodedata.category(char) == "Cc" for char in filename)): raise invalid("Некорректный filename") return filename def _parse_attachment_ids(self, body): values = body.get("attachment_ids", []) if not isinstance(values, list) or len(values) > 10: raise invalid("Некорректный attachment_ids") attachment_ids = [parse_uuid(value, "attachment_id") for value in values] if len(set(attachment_ids)) != len(attachment_ids): raise invalid("attachment_ids содержит дубликаты") return attachment_ids def _validate_message_attachments(self, conn, chat_id, attachment_ids): if not attachment_ids: return rows = conn.execute( """SELECT id, status FROM attachments WHERE chat_id = %s AND id = ANY(%s::uuid[])""", (chat_id, attachment_ids), ).fetchall() if len(rows) != len(attachment_ids): raise ApiError(404, "not_found", "Объект не найден") if any(row["status"] == "failed" for row in rows): raise ApiError(409, "conflict", "Обработка вложения завершилась ошибкой") def _upload_attachment(self, conn, user_id, chat_id): filename = self._attachment_filename() chat = conn.execute( """SELECT c.id FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE c.id = %s AND m.user_id = %s""", (chat_id, user_id), ).fetchone() if chat is None: raise ApiError(404, "not_found", "Объект не найден") data, content_type = self._read_binary() attachment_id = uuid.uuid4() object_key = "attachments/" + str(attachment_id) + "/original" staging_key = "staging/" + str(attachment_id) + "/original" checksum = hashlib.sha256(data).hexdigest() self._pending_object_key = staging_key S3_CLIENT.put_object( Bucket=S3_BUCKET, Key=staging_key, Body=data, ContentType=content_type, Metadata={"sha256": checksum}, ) row = conn.execute( """INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, staging_key, status) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 'queued') RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, variants, error_code, created_at, updated_at""", (attachment_id, chat_id, user_id, filename, content_type, len(data), checksum, object_key, staging_key), ).fetchone() job_id = uuid.uuid4() conn.execute( """INSERT INTO image_jobs (id, attachment_id, max_attempts) VALUES (%s, %s, %s)""", (job_id, attachment_id, configured_job_attempts()), ) self._after_commit.append(lambda: publish_pending_job(POOL, job_id)) return 202, attachment_json(row) def _get_attachment(self, conn, user_id, attachment_id): row = conn.execute( """SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.status, a.variants, a.error_code, a.created_at, a.updated_at, a.object_key FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id WHERE a.id = %s AND m.user_id = %s""", (attachment_id, user_id), ).fetchone() if row is None: raise ApiError(404, "not_found", "Объект не найден") return row def _download_attachment(self, conn, user_id, attachment_id): query = self._query() if set(query) - {"variant"} or len(query.get("variant", [])) > 1: raise invalid("Некорректный variant") variant = query.get("variant", ["original"])[0] if variant not in ("original", "thumbnail", "crop", "optimized"): raise invalid("Некорректный variant") row = self._get_attachment(conn, user_id, attachment_id) if row["status"] != "ready": raise ApiError(409, "conflict", "Вложение ещё не готово") if variant == "original": object_key = row["object_key"] expected_size = row["size_bytes"] expected_checksum = row["sha256"] content_type = row["content_type"] else: metadata = next((item for item in row["variants"] if item["name"] == variant), None) if metadata is None: raise ApiError(404, "not_found", "Объект не найден") object_key = "attachments/" + str(attachment_id) + "/variants/" + variant + ".jpg" expected_size = metadata["size_bytes"] expected_checksum = metadata["sha256"] content_type = metadata["content_type"] response = S3_CLIENT.get_object(Bucket=S3_BUCKET, Key=object_key) with response["Body"] as body: data = body.read(MAX_UPLOAD_BYTES + 1) if (len(data) != expected_size or len(data) > MAX_UPLOAD_BYTES or hashlib.sha256(data).hexdigest() != expected_checksum): LOG.error("stored object integrity check failed attachment_id=%s", attachment_id) raise ApiError(503, "unavailable", "Файловое хранилище временно недоступно") return 200, BinaryResponse(data, content_type) def _require_fields(self, data, required): if set(data) != set(required): raise invalid("Неверный набор полей") def _query(self): try: return parse_qs(urlsplit(self.path).query, keep_blank_values=True, strict_parsing=True) except ValueError: raise invalid("Некорректная строка запроса") def _current_identity(self, conn): authorization = self.headers.get("Authorization", "") if not authorization.startswith("Bearer "): raise unauthorized("Bearer") token = authorization[len("Bearer "):] if not token or len(token) > 512: raise unauthorized("Bearer") digest = hashlib.sha256(token.encode("utf-8")).hexdigest() row = conn.execute( """SELECT u.id FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = %s AND s.expires_at > now()""", (digest,), ).fetchone() if row is None: raise unauthorized("Bearer") return row["id"], digest def _idempotency_key(self): values = self.headers.get_all("Idempotency-Key", []) if len(values) != 1 or not IDEMPOTENCY_KEY_RE.fullmatch(values[0]): raise invalid("Некорректный Idempotency-Key") return values[0] def _create_idempotent_message(self, conn, user_id, chat_id, request_path, body, key, attachment_ids): canonical_body = dict(body) canonical_body["attachment_ids"] = [str(item) for item in attachment_ids] canonical_body = json.dumps( canonical_body, ensure_ascii=False, sort_keys=True, separators=(",", ":") ).encode("utf-8") request_hash = hashlib.sha256(canonical_body).hexdigest() conn.execute("DELETE FROM idempotency_records WHERE expires_at <= now()") claimed = conn.execute( """INSERT INTO idempotency_records (user_id, http_method, request_path, idempotency_key, request_hash, expires_at) VALUES (%s, 'POST', %s, %s, %s, now() + %s) ON CONFLICT (user_id, http_method, request_path, idempotency_key) DO UPDATE SET request_hash = EXCLUDED.request_hash, response_status = NULL, response_body = NULL, created_at = now(), expires_at = EXCLUDED.expires_at WHERE idempotency_records.expires_at <= now() RETURNING idempotency_key""", (user_id, request_path, key, request_hash, IDEMPOTENCY_TTL), ).fetchone() if claimed is None: existing = conn.execute( """SELECT request_hash, response_status, response_body FROM idempotency_records WHERE user_id = %s AND http_method = 'POST' AND request_path = %s AND idempotency_key = %s""", (user_id, request_path, key), ).fetchone() if existing is None: raise ApiError(503, "unavailable", "Повтор запроса временно недоступен") if existing["request_hash"] != request_hash: legacy_body = dict(body) legacy_body.pop("attachment_ids", None) legacy_hash = hashlib.sha256(json.dumps( legacy_body, ensure_ascii=False, sort_keys=True, separators=(",", ":") ).encode("utf-8")).hexdigest() if attachment_ids or existing["request_hash"] != legacy_hash: raise ApiError(409, "conflict", "Idempotency-Key уже использован с другим телом") if existing["response_status"] is None or existing["response_body"] is None: raise ApiError(503, "unavailable", "Результат запроса временно недоступен") replay_body = dict(existing["response_body"]) replay_body.setdefault("attachment_ids", []) return existing["response_status"], replay_body row = conn.execute( """INSERT INTO messages (chat_id, sender_id, text) VALUES (%s, %s, %s) RETURNING id, chat_id, sender_id, text, created_at""", (chat_id, user_id, body["text"]), ).fetchone() for position, attachment_id in enumerate(attachment_ids): conn.execute( """INSERT INTO message_attachments (chat_id, message_id, attachment_id, position) VALUES (%s, %s, %s, %s)""", (chat_id, row["id"], attachment_id, position), ) payload = message_json(row, attachment_ids) conn.execute( """UPDATE idempotency_records SET response_status = 201, response_body = %s WHERE user_id = %s AND http_method = 'POST' AND request_path = %s AND idempotency_key = %s""", (Jsonb(payload), user_id, request_path, key), ) return 201, payload def _create_session(self, conn): forwarded = self.headers.get("X-Forwarded-For", "") ip = forwarded.split(",", 1)[0].strip() if forwarded else ( self.client_address[0] if getattr(self, "client_address", None) else "unknown" ) ip_hash = hashlib.sha256(ip.encode("utf-8")).hexdigest() conn.execute( "DELETE FROM login_attempts WHERE attempted_at < now() - make_interval(secs => %s)", (LOGIN_WINDOW_SECONDS,), ) count = conn.execute( """SELECT count(*) AS attempts FROM login_attempts WHERE ip_hash = %s AND attempted_at >= now() - make_interval(secs => %s)""", (ip_hash, LOGIN_WINDOW_SECONDS), ).fetchone()["attempts"] if count >= LOGIN_LIMIT: raise ApiError( 429, "rate_limited", "Слишком много попыток входа", {"Retry-After": str(LOGIN_WINDOW_SECONDS)}, ) conn.execute( "INSERT INTO login_attempts (ip_hash) VALUES (%s)", (ip_hash,), ) authorization = self.headers.get("Authorization", "") if not authorization.startswith("Basic "): raise unauthorized("Basic") length = self.headers.get("Content-Length", "0") if not re.fullmatch(r"[0-9]+", length) or int(length) != 0: raise invalid("Создание сессии не принимает тело запроса") try: encoded = authorization[len("Basic "):] decoded = base64.b64decode(encoded.encode("ascii"), validate=True).decode("utf-8") username, password = decoded.split(":", 1) except (ValueError, UnicodeError, binascii.Error): raise unauthorized("Basic") if not USERNAME_RE.fullmatch(username): raise unauthorized("Basic") row = conn.execute( "SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s", (username,), ).fetchone() valid = False if row is not None: try: valid = PASSWORD_HASHER.verify(row["password_hash"], password) if valid and PASSWORD_HASHER.check_needs_rehash(row["password_hash"]): conn.execute( "UPDATE users SET password_hash = %s WHERE id = %s", (PASSWORD_HASHER.hash(password), row["id"]), ) except (VerifyMismatchError, VerificationError, InvalidHashError): valid = False if not valid: raise unauthorized("Basic") token = secrets.token_urlsafe(32) expires_at = utc_now() + timedelta(seconds=SESSION_TTL_SECONDS) conn.execute( "INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s)", (hashlib.sha256(token.encode("utf-8")).hexdigest(), row["id"], expires_at), ) return 201, { "token": token, "token_type": "Bearer", "expires_at": timestamp(expires_at), "user": user_json(row), } def _route(self, conn): parsed = urlsplit(self.path) path = parsed.path if self.command == "GET" and path == "/health/ready": conn.execute("SELECT 1") S3_CLIENT.head_bucket(Bucket=S3_BUCKET) check_broker() return 200, {"status": "ok"} if self.command == "POST" and path == "/api/v1/users": body = self._read_json() self._require_fields(body, {"username", "display_name", "password"}) username, display_name, password = body["username"], body["display_name"], body["password"] if not isinstance(username, str) or not USERNAME_RE.fullmatch(username): raise invalid("Некорректный username") if not isinstance(display_name, str) or not display_name.strip() or len(display_name) > 100: raise invalid("Некорректный display_name") if not isinstance(password, str) or not 12 <= len(password) <= 128: raise invalid("Некорректный password") password_hash = PASSWORD_HASHER.hash(password) try: row = 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 UniqueViolation: raise ApiError(409, "conflict", "Username уже занят") return 201, user_json(row) if self.command == "POST" and path == "/api/v1/auth/sessions": return self._create_session(conn) if self.command == "DELETE" and path == "/api/v1/auth/sessions/current": _, digest = self._current_identity(conn) conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,)) return 204, None user_id, _ = self._current_identity(conn) if self.command == "GET" and path == "/api/v1/users/me": row = conn.execute( "SELECT id, username, display_name, created_at FROM users WHERE id = %s", (user_id,), ).fetchone() return 200, user_json(row) upload_match = re.fullmatch(r"/api/v1/chats/([^/]+)/attachments", path) if upload_match and self.command == "POST": chat_id = parse_uuid(upload_match.group(1), "chat_id") return self._upload_attachment(conn, user_id, chat_id) attachment_match = re.fullmatch( r"/api/v1/attachments/([^/]+)(/content)?", path ) if attachment_match and self.command == "GET": attachment_id = parse_uuid(attachment_match.group(1), "attachment_id") if attachment_match.group(2): return self._download_attachment(conn, user_id, attachment_id) query = self._query() if query: raise invalid("Параметры запроса не поддерживаются") return 200, attachment_json(self._get_attachment(conn, user_id, attachment_id)) if self.command == "POST" and path == "/api/v1/chats": body = self._read_json() self._require_fields(body, {"title", "member_ids"}) title, member_ids = body["title"], body["member_ids"] if not isinstance(title, str) or not title.strip() or len(title) > 100: raise invalid("Некорректный title") if not isinstance(member_ids, list) or not 1 <= len(member_ids) <= 100: raise invalid("Некорректный member_ids") normalized = [parse_uuid(item, "member_id") for item in member_ids] if len(set(normalized)) != len(normalized): raise invalid("member_ids содержит дубликаты") if user_id not in normalized: raise invalid("Создатель должен входить в чат") found = conn.execute( "SELECT id FROM users WHERE id = ANY(%s::uuid[])", (normalized,), ).fetchall() if len(found) != len(normalized): raise invalid("Неизвестный участник чата") chat = conn.execute( "INSERT INTO chats (title) VALUES (%s) RETURNING id, title, created_at", (title,), ).fetchone() for position, member_id in enumerate(normalized): conn.execute( "INSERT INTO chat_members (chat_id, user_id, member_position) VALUES (%s, %s, %s)", (chat["id"], member_id, position), ) return 201, chat_json(conn, chat) if self.command == "GET" and path == "/api/v1/chats": query = self._query() limit = parse_limit(query) cursors = query.get("cursor") if cursors is not None and (len(cursors) != 1 or not cursors[0]): raise invalid("Некорректный cursor") after = decode_cursor(cursors[0], "chats", user_id) if cursors else None sql = """SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = %s""" params = [user_id] if after is not None: sql += " AND (c.created_at, c.id) > (%s, %s)" params.extend(after) sql += " ORDER BY c.created_at, c.id LIMIT %s" params.append(limit + 1) rows = conn.execute(sql, params).fetchall() has_more = len(rows) > limit selected = rows[:limit] items = [chat_json(conn, row) for row in selected] next_cursor = None if has_more: last = selected[-1] next_cursor = encode_cursor("chats", user_id, last["created_at"], last["id"]) return 200, {"items": items, "next_cursor": next_cursor} chat_match = re.fullmatch(r"/api/v1/chats/([^/]+)(?:/messages)?", path) if chat_match: chat_id = parse_uuid(chat_match.group(1), "chat_id") chat = conn.execute( """SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE c.id = %s AND m.user_id = %s""", (chat_id, user_id), ).fetchone() if chat is None: raise ApiError(404, "not_found", "Объект не найден") is_messages_path = path.endswith("/messages") if not is_messages_path and self.command == "GET": return 200, chat_json(conn, chat) if is_messages_path and self.command == "POST": key = self._idempotency_key() body = self._read_json() if set(body) - {"text", "attachment_ids"} or "text" not in body: raise invalid("Неверный набор полей") text = body["text"] attachment_ids = self._parse_attachment_ids(body) if (not isinstance(text, str) or len(text) > 4000 or (text == "" and not attachment_ids) or (text != "" and not text.strip())): raise invalid("Некорректный text") self._validate_message_attachments(conn, chat_id, attachment_ids) return self._create_idempotent_message( conn, user_id, chat_id, path, body, key, attachment_ids ) if is_messages_path and self.command == "GET": query = self._query() limit = parse_limit(query) cursors = query.get("cursor") if cursors is not None and (len(cursors) != 1 or not cursors[0]): raise invalid("Некорректный cursor") after = decode_cursor(cursors[0], "messages", chat_id) if cursors else None sql = """SELECT id, chat_id, sender_id, text, created_at, ARRAY(SELECT ma.attachment_id FROM message_attachments ma WHERE ma.chat_id = messages.chat_id AND ma.message_id = messages.id ORDER BY ma.position) AS attachment_ids FROM messages WHERE chat_id = %s""" params = [chat_id] if after is not None: sql += " AND (created_at, id) > (%s, %s)" params.extend(after) sql += " ORDER BY created_at, id LIMIT %s" params.append(limit + 1) rows = conn.execute(sql, params).fetchall() has_more = len(rows) > limit selected = rows[:limit] items = [message_json(row) for row in selected] next_cursor = None if has_more: last = selected[-1] next_cursor = encode_cursor("messages", chat_id, last["created_at"], last["id"]) return 200, {"items": items, "next_cursor": next_cursor} raise ApiError(404, "not_found", "Объект не найден") def log_message(self, format_string, *args): return class MessengerServer(ThreadingHTTPServer): daemon_threads = False allow_reuse_address = True def main(): global POOL, S3_CLIENT, S3_BUCKET, SESSION_TTL_SECONDS logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") mode = sys.argv[1] if len(sys.argv) > 1 else "serve" if mode not in ("serve", "migrate") or len(sys.argv) > 2: raise SystemExit("Usage: app.py [serve|migrate]") if mode == "serve": try: load_service_secrets("api") except Exception as error: raise SystemExit("OpenBao service authentication failed: " + str(error)) from error telemetry.setup_observability( os.environ.get("OTEL_SERVICE_NAME", "messenger-api") ) SESSION_TTL_SECONDS, max_connections, port = validate_runtime_config() if mode == "serve": S3_CLIENT, S3_BUCKET = create_s3_client() configured_job_attempts() try: from queueing import broker_url broker_url() except RuntimeError as error: raise SystemExit(str(error)) host = os.environ.get("APP_HOST", "0.0.0.0") POOL = ConnectionPool( conninfo=database_conninfo(), min_size=1, max_size=max_connections, timeout=5, kwargs={"row_factory": dict_row}, open=False, ) try: POOL.open(wait=True, timeout=15) if mode == "migrate": migrate(POOL) POOL.close() LOG.info("database migrations complete") return with POOL.connection() as conn: conn.execute("SELECT 1") except Exception as error: POOL.close() LOG.error("database initialization failed error_type=%s", type(error).__name__) raise SystemExit("Database unavailable or migrations failed") server = MessengerServer((host, port), MessengerHandler) server_cert = os.environ.get("API_SERVER_CERT", "").strip() server_key = os.environ.get("API_SERVER_KEY", "").strip() internal_ca = os.environ.get("INTERNAL_CA_CERT", "").strip() if server_cert or server_key or internal_ca: if not all((server_cert, server_key, internal_ca)): raise SystemExit("API_SERVER_CERT, API_SERVER_KEY and INTERNAL_CA_CERT are required together") tls_context = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH, cafile=internal_ca, ) tls_context.load_cert_chain(server_cert, server_key) tls_context.verify_mode = ssl.CERT_REQUIRED tls_context.check_hostname = False server.socket = tls_context.wrap_socket(server.socket, server_side=True) outbox_thread = threading.Thread( target=publish_outbox, args=(POOL, OUTBOX_STOP), name="job-outbox", daemon=True, ) outbox_thread.start() LOG.info( "messenger starting host=%s port=%s storage=postgresql broker=rabbitmq instance_id=%s", host, port, INSTANCE_ID, ) def request_shutdown(_signum, _frame): threading.Thread(target=server.shutdown, daemon=True).start() signal.signal(signal.SIGTERM, request_shutdown) signal.signal(signal.SIGINT, request_shutdown) try: server.serve_forever() finally: server.server_close() OUTBOX_STOP.set() outbox_thread.join(timeout=3) POOL.close() LOG.info("messenger stopped") if __name__ == "__main__": main()