import base64 import binascii import json import socket import psycopg from psycopg_pool import PoolTimeout, TooManyRequests import logging import re import time import urllib.parse import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Any, Dict, Optional, Tuple from app.errors import ( APIError, BadRequestError, InternalError, NotFoundError, UnauthorizedError, UnavailableError, ) from app.models import ( parse_limit, validate_create_chat, validate_create_message, validate_create_user, validate_uuid, ) from app.storage import PostgresStorage logger = logging.getLogger("messenger") CHAT_MESSAGES_PATTERN = re.compile(r"^/api/v1/chats/([^/]+)/messages$") CHAT_DETAIL_PATTERN = re.compile(r"^/api/v1/chats/([^/]+)$") class MessengerHandler(BaseHTTPRequestHandler): server_version = "MTUSI-Messenger/1.0" @property def storage(self) -> PostgresStorage: return self.server.storage # type: ignore @property def is_shutting_down(self) -> bool: return getattr(self.server, "is_shutting_down", False) def log_message(self, format: str, *args: Any): # Suppress default BaseHTTPRequestHandler noisy log pass def _get_request_id(self) -> str: return str(uuid.uuid4()) def setup(self): super().setup() self.connection.settimeout(10) def _send_json(self, status_code: int, data: Optional[Dict[str, Any]], request_id: str): body = b"" if data is not None and status_code != 204: body = json.dumps(data, ensure_ascii=False).encode("utf-8") self.send_response(status_code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.send_header("X-Request-Id", request_id) if status_code == 401: challenge = ('Basic realm="messenger", charset="UTF-8"' if urllib.parse.urlparse(self.path).path == '/api/v1/auth/sessions' else 'Bearer realm="messenger"') self.send_header('WWW-Authenticate', challenge) self.end_headers() if body: self.wfile.write(body) def _send_error(self, err: APIError, request_id: str): payload = err.to_dict(request_id) self._send_json(err.status_code, payload, request_id) def _read_json_body(self) -> Any: if self.headers.get('Transfer-Encoding'): raise BadRequestError('Transfer-Encoding is not supported') if self.headers.get_content_type() != 'application/json': raise APIError('unsupported_media_type', 'Expected application/json', 415) content_length_header = self.headers.get("Content-Length") if not content_length_header: raise BadRequestError("Missing request body") try: content_length = int(content_length_header) except (ValueError, TypeError): raise BadRequestError("Invalid Content-Length header") if content_length < 0 or content_length > 10 * 1024 * 1024: raise BadRequestError("Payload size invalid") raw_data = self.rfile.read(content_length) if not raw_data: raise BadRequestError("Empty request body") try: body = json.loads(raw_data.decode("utf-8")) # Reject unpaired surrogates before a driver/KDF tries to encode them. json.dumps(body, ensure_ascii=False).encode('utf-8') return body except (ValueError, UnicodeError): raise BadRequestError("Malformed JSON in request body") def _bearer(self): parts = self.headers.get('Authorization', '').split() if len(parts) != 2 or parts[0].lower() != 'bearer' or len(parts[1]) > 512: raise UnauthorizedError() return parts[1] def _authenticate_user(self): return self.storage.authenticate(self._bearer()) def _login(self): parts = self.headers.get('Authorization', '').split() if len(parts) != 2 or parts[0].lower() != 'basic' or len(parts[1]) > 2048: raise UnauthorizedError('Invalid credentials') try: credential = base64.b64decode(parts[1], validate=True).decode('utf-8') username, password = credential.split(':', 1) if not re.fullmatch(r'[a-z0-9_]{3,32}', username) or not 12 <= len(password) <= 128: raise ValueError except (ValueError, UnicodeError, binascii.Error): raise UnauthorizedError('Invalid credentials') from None if self.headers.get('Transfer-Encoding') or self.headers.get('Content-Length', '0') != '0': raise BadRequestError('Session creation has no body') return self.storage.login(username, password) def do_PUT(self): self._handle_request("PUT") def do_PATCH(self): self._handle_request("PATCH") def do_OPTIONS(self): self._handle_request("OPTIONS") def do_DELETE(self): self._handle_request("DELETE") def do_GET(self): self._handle_request("GET") def do_POST(self): self._handle_request("POST") def _handle_request(self, method: str): start_time = time.monotonic() request_id = self._get_request_id() parsed_url = urllib.parse.urlparse(self.path) path = parsed_url.path query = urllib.parse.parse_qs(parsed_url.query, keep_blank_values=True) status_code = 200 try: if self.is_shutting_down and not path.startswith("/health/"): raise UnavailableError("Server is shutting down") # Route dispatcher if method == "GET" and path == "/health/live": self._send_json(200, {"status": "ok"}, request_id) status_code = 200 elif method == "GET" and path == "/health/ready": if self.is_shutting_down: raise UnavailableError("Server is shutting down") self.storage.ready() self._send_json(200, {"status": "ok"}, request_id) status_code = 200 elif method == "POST" and path == "/api/v1/users": body = self._read_json_body() validated = validate_create_user(body) user = self.storage.create_user(**validated) self._send_json(201, user, request_id) status_code = 201 elif method == 'POST' and path == '/api/v1/auth/sessions': self._send_json(201, self._login(), request_id) status_code = 201 elif method == 'DELETE' and path == '/api/v1/auth/sessions/current': self.storage.logout(self._bearer()) self._send_json(204, None, request_id) status_code = 204 elif method == "GET" and path == "/api/v1/users/me": actor = self._authenticate_user() self._send_json(200, actor, request_id) status_code = 200 elif method == "POST" and path == "/api/v1/chats": actor = self._authenticate_user() body = self._read_json_body() validated = validate_create_chat(body) chat = self.storage.create_chat( creator_id=actor["id"], title=validated["title"], member_ids=validated["member_ids"], ) self._send_json(201, chat, request_id) status_code = 201 elif method == "GET" and path == "/api/v1/chats": actor = self._authenticate_user() limit_val = query.get("limit", [None])[0] cursor_val = query.get("cursor", [None])[0] limit = parse_limit(limit_val) result = self.storage.list_chats(actor["id"], limit=limit, cursor=cursor_val) self._send_json(200, result, request_id) status_code = 200 else: # Check regex routes match_messages = CHAT_MESSAGES_PATTERN.match(path) match_chat = CHAT_DETAIL_PATTERN.match(path) if match_messages: raw_chat_id = match_messages.group(1) actor = self._authenticate_user() chat_id = validate_uuid(raw_chat_id, "chat_id") if method == "POST": body = self._read_json_body() validated = validate_create_message(body) msg = self.storage.create_message( chat_id=chat_id, sender_id=actor["id"], text=validated["text"], ) self._send_json(201, msg, request_id) status_code = 201 elif method == "GET": limit_val = query.get("limit", [None])[0] cursor_val = query.get("cursor", [None])[0] limit = parse_limit(limit_val) result = self.storage.list_messages( user_id=actor["id"], chat_id=chat_id, limit=limit, cursor=cursor_val, ) self._send_json(200, result, request_id) status_code = 200 else: raise NotFoundError("Endpoint not found") elif match_chat: raw_chat_id = match_chat.group(1) actor = self._authenticate_user() chat_id = validate_uuid(raw_chat_id, "chat_id") if method == "GET": chat = self.storage.get_chat(user_id=actor["id"], chat_id=chat_id) self._send_json(200, chat, request_id) status_code = 200 else: raise NotFoundError("Endpoint not found") else: raise NotFoundError(f"Route not found: {method} {path}") except APIError as err: status_code = err.status_code self._send_error(err, request_id) except (psycopg.OperationalError, psycopg.InterfaceError, psycopg.errors.QueryCanceled, psycopg.errors.LockNotAvailable, PoolTimeout, TooManyRequests): status_code = 503 self._send_error(UnavailableError(), request_id) except (socket.timeout, ConnectionError): status_code = 408 self.close_connection = True except Exception as exc: status_code = 500 logger.error("Unhandled exception type: %s", type(exc).__name__) self._send_error(InternalError("Internal server error"), request_id) finally: elapsed_ms = (time.monotonic() - start_time) * 1000 # Safe structured log without payload content logger.info( "%s %s %d %.2fms req_id=%s", method, path, status_code, elapsed_ms, request_id, ) class MessengerServer(ThreadingHTTPServer): daemon_threads = True def __init__(self, server_address: Tuple[str, int], storage: Optional[PostgresStorage] = None): super().__init__(server_address, MessengerHandler) self.storage = storage or PostgresStorage() self.is_shutting_down = False