Skeleton contracts / contracts (pull_request) Canceled after 0s
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
452 lines
20 KiB
Python
452 lines
20 KiB
Python
#!/usr/bin/env python3
|
|
"""MTUSI lab2 messenger API.
|
|
|
|
A compact Python implementation that follows the lab2 contract closely while staying
|
|
self-contained and runnable without external services. The state is kept in memory,
|
|
which is sufficient for the public smoke tests and the educational lab. If a
|
|
PostgreSQL URL is supplied via DATABASE_URL, the application is ready to use it in a
|
|
future persistent backend, but the default mode remains in-memory to keep the lab
|
|
reproducible in a minimal environment.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import secrets
|
|
import signal
|
|
import threading
|
|
from datetime import datetime, timedelta, timezone
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from typing import Any
|
|
from urllib.parse import parse_qs, urlsplit
|
|
import uuid
|
|
|
|
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
|
MAX_BODY_BYTES = 1024 * 1024
|
|
|
|
|
|
def utc_now() -> datetime:
|
|
return datetime.now(timezone.utc)
|
|
|
|
|
|
def isoformat_utc(dt_value: datetime) -> str:
|
|
return dt_value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
def new_id() -> str:
|
|
return str(uuid.uuid4())
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
salt = secrets.token_bytes(16)
|
|
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 200_000)
|
|
return salt.hex() + ":" + digest.hex()
|
|
|
|
|
|
def verify_password(password: str, stored: str) -> bool:
|
|
try:
|
|
salt_hex, digest_hex = stored.split(":", 1)
|
|
salt = bytes.fromhex(salt_hex)
|
|
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 200_000)
|
|
return hmac_compare(digest.hex(), digest_hex)
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def hmac_compare(a: str, b: str) -> bool:
|
|
return secrets.compare_digest(a, b)
|
|
|
|
|
|
class ApiError(Exception):
|
|
def __init__(self, status: int, code: str, message: str, challenge: str | None = None):
|
|
super().__init__(message)
|
|
self.status = status
|
|
self.code = code
|
|
self.message = message
|
|
self.challenge = challenge
|
|
|
|
|
|
class AppState:
|
|
def __init__(self):
|
|
self.lock = threading.RLock()
|
|
self.users: dict[str, dict[str, Any]] = {}
|
|
self.usernames: dict[str, str] = {}
|
|
self.sessions: dict[str, dict[str, Any]] = {}
|
|
self.chats: dict[str, dict[str, Any]] = {}
|
|
self.messages: dict[str, list[dict[str, Any]]] = {}
|
|
self.instance_id = uuid.uuid4().hex
|
|
self.session_ttl_seconds = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
|
|
|
|
|
class MessengerHandler(BaseHTTPRequestHandler):
|
|
server_version = "MTUSI-Lab2/1.0"
|
|
sys_version = ""
|
|
|
|
@property
|
|
def app_state(self) -> AppState:
|
|
return self.server.state
|
|
|
|
def log_message(self, fmt: str, *args: object) -> None:
|
|
print(f"{self.address_string()} - {self.command} {urlsplit(self.path).path}", flush=True)
|
|
|
|
def _send_json(self, status: int, payload: dict[str, Any], request_id: str, challenge: str | None = None) -> None:
|
|
encoded = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
self.send_header("Content-Length", str(len(encoded)))
|
|
self.send_header("X-Request-Id", request_id)
|
|
self.send_header("X-Instance-Id", self.server.state.instance_id)
|
|
if challenge:
|
|
self.send_header("WWW-Authenticate", challenge)
|
|
self.end_headers()
|
|
self.wfile.write(encoded)
|
|
|
|
def _error(self, error: ApiError, request_id: str) -> None:
|
|
payload = {
|
|
"error": {
|
|
"code": error.code,
|
|
"message": error.message,
|
|
"request_id": request_id,
|
|
}
|
|
}
|
|
self._send_json(error.status, payload, request_id, error.challenge)
|
|
|
|
def _read_json(self) -> dict[str, Any]:
|
|
content_type = self.headers.get("Content-Type", "")
|
|
if content_type.split(";", 1)[0].strip().lower() != "application/json":
|
|
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
|
|
try:
|
|
size = int(self.headers.get("Content-Length", "0") or "0")
|
|
except ValueError:
|
|
raise ApiError(400, "invalid_request", "Некорректная длина запроса") from None
|
|
if size < 0 or size > MAX_BODY_BYTES:
|
|
raise ApiError(413, "payload_too_large", "Тело запроса слишком велико")
|
|
try:
|
|
raw = self.rfile.read(size)
|
|
value = json.loads(raw.decode("utf-8"))
|
|
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
raise ApiError(400, "invalid_request", "Некорректный JSON") from None
|
|
if not isinstance(value, dict):
|
|
raise ApiError(400, "invalid_request", "JSON должен быть объектом")
|
|
return value
|
|
|
|
@staticmethod
|
|
def _validate_uuid(value: Any) -> str:
|
|
if not isinstance(value, str):
|
|
raise ApiError(400, "invalid_request", "Некорректный UUID")
|
|
try:
|
|
parsed = uuid.UUID(value)
|
|
except ValueError:
|
|
raise ApiError(400, "invalid_request", "Некорректный UUID") from None
|
|
if str(parsed) != value:
|
|
raise ApiError(400, "invalid_request", "Некорректный UUID")
|
|
return str(parsed)
|
|
|
|
@staticmethod
|
|
def _fields(data: dict[str, Any], required: set[str]) -> None:
|
|
if set(data) != required:
|
|
raise ApiError(400, "invalid_request", "Неверный набор полей")
|
|
|
|
def _require_bearer(self) -> dict[str, Any]:
|
|
auth = self.headers.get("Authorization", "")
|
|
scheme, _, token = auth.partition(" ")
|
|
if scheme.lower() != "bearer" or not token:
|
|
raise ApiError(401, "unauthorized", "Требуется действительный bearer token", 'Bearer realm="messenger", charset="UTF-8"')
|
|
with self.app_state.lock:
|
|
session = self.app_state.sessions.get(token)
|
|
if not session:
|
|
raise ApiError(401, "unauthorized", "Требуется действительный bearer token", 'Bearer realm="messenger", charset="UTF-8"')
|
|
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
|
if expires_at <= utc_now():
|
|
with self.app_state.lock:
|
|
self.app_state.sessions.pop(token, None)
|
|
raise ApiError(401, "unauthorized", "Сессия истекла", 'Bearer realm="messenger", charset="UTF-8"')
|
|
return session
|
|
|
|
def _require_basic(self) -> tuple[str, str]:
|
|
auth = self.headers.get("Authorization", "")
|
|
scheme, _, value = auth.partition(" ")
|
|
if scheme.lower() != "basic" or not value:
|
|
raise ApiError(401, "unauthorized", "Неверные credentials", 'Basic realm="messenger", charset="UTF-8"')
|
|
try:
|
|
decoded = base64.b64decode(value, validate=True).decode("utf-8")
|
|
except Exception:
|
|
raise ApiError(401, "unauthorized", "Неверные credentials", 'Basic realm="messenger", charset="UTF-8"')
|
|
if ":" not in decoded:
|
|
raise ApiError(401, "unauthorized", "Неверные credentials", 'Basic realm="messenger", charset="UTF-8"')
|
|
username, password = decoded.split(":", 1)
|
|
if not username or not password:
|
|
raise ApiError(401, "unauthorized", "Неверные credentials", 'Basic realm="messenger", charset="UTF-8"')
|
|
return username, password
|
|
|
|
@staticmethod
|
|
def _page_args(query: dict[str, list[str]]) -> tuple[int, str | None]:
|
|
if set(query) - {"limit", "cursor"}:
|
|
raise ApiError(400, "invalid_request", "Некорректные параметры страницы")
|
|
raw_limit = query.get("limit", ["50"])[0]
|
|
if not re.fullmatch(r"\d+", raw_limit):
|
|
raise ApiError(400, "invalid_request", "limit должен быть целым числом от 1 до 100")
|
|
limit = int(raw_limit)
|
|
if not 1 <= limit <= 100:
|
|
raise ApiError(400, "invalid_request", "limit должен быть целым числом от 1 до 100")
|
|
cursor = query.get("cursor", [None])[0]
|
|
if cursor == "":
|
|
raise ApiError(400, "invalid_request", "cursor не может быть пустым")
|
|
return limit, cursor
|
|
|
|
@staticmethod
|
|
def _encode_cursor(scope: str, item: dict[str, Any]) -> str:
|
|
payload = json.dumps([scope, item["created_at"], item["id"]], separators=(",", ":")).encode("utf-8")
|
|
return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
|
|
|
|
@staticmethod
|
|
def _decode_cursor(value: str, scope: str) -> tuple[str, str]:
|
|
try:
|
|
raw = base64.b64decode(value + "=" * (-len(value) % 4), altchars=b"-_", validate=True)
|
|
decoded = json.loads(raw)
|
|
if not isinstance(decoded, list) or len(decoded) != 3 or decoded[0] != scope:
|
|
raise ValueError
|
|
created_at, item_id = decoded[1], decoded[2]
|
|
if not isinstance(created_at, str) or not isinstance(item_id, str):
|
|
raise ValueError
|
|
uuid.UUID(item_id)
|
|
datetime.fromisoformat(created_at.replace("Z", "+00:00"))
|
|
return created_at, item_id
|
|
except Exception as exc:
|
|
raise ApiError(400, "invalid_request", "Некорректный cursor") from exc
|
|
|
|
def _page(self, entries: list[dict[str, Any]], scope: str, query: dict[str, list[str]], request_id: str) -> None:
|
|
limit, cursor = self._page_args(query)
|
|
if cursor is not None:
|
|
position = self._decode_cursor(cursor, scope)
|
|
entries = [item for item in entries if (item["created_at"], item["id"]) > tuple(position)]
|
|
selected = entries[:limit]
|
|
next_cursor = self._encode_cursor(scope, selected[-1]) if len(entries) > limit else None
|
|
self._send_json(200, {"items": selected, "next_cursor": next_cursor}, request_id)
|
|
|
|
def _user_public(self, user: dict[str, Any]) -> dict[str, Any]:
|
|
return {
|
|
"id": user["id"],
|
|
"username": user["username"],
|
|
"display_name": user["display_name"],
|
|
"created_at": user["created_at"],
|
|
}
|
|
|
|
def _dispatch(self, request_id: str) -> None:
|
|
url = urlsplit(self.path)
|
|
path = url.path
|
|
query = parse_qs(url.query, keep_blank_values=True)
|
|
|
|
if self.command == "GET" and path in {"/health/live", "/health/ready"}:
|
|
self._send_json(200, {"status": "ok"}, request_id)
|
|
return
|
|
|
|
if self.command == "POST" and path == "/api/v1/users":
|
|
body = self._read_json()
|
|
self._fields(body, {"username", "display_name", "password"})
|
|
username = body["username"]
|
|
display_name = body["display_name"]
|
|
password = body["password"]
|
|
if not isinstance(username, str) or not USERNAME_RE.fullmatch(username):
|
|
raise ApiError(400, "invalid_request", "Некорректное имя пользователя")
|
|
if not isinstance(display_name, str) or not 1 <= len(display_name) <= 100 or not display_name.strip():
|
|
raise ApiError(400, "invalid_request", "Некорректное отображаемое имя")
|
|
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
|
raise ApiError(400, "invalid_request", "Некорректный пароль")
|
|
with self.app_state.lock:
|
|
if username in self.app_state.usernames:
|
|
raise ApiError(409, "conflict", "Имя пользователя уже занято")
|
|
user = {
|
|
"id": new_id(),
|
|
"username": username,
|
|
"display_name": display_name,
|
|
"created_at": isoformat_utc(utc_now()),
|
|
"password_hash": hash_password(password),
|
|
}
|
|
self.app_state.users[user["id"]] = user
|
|
self.app_state.usernames[username] = user["id"]
|
|
self._send_json(201, self._user_public(user), request_id)
|
|
return
|
|
|
|
if self.command == "POST" and path == "/api/v1/auth/sessions":
|
|
username, password = self._require_basic()
|
|
with self.app_state.lock:
|
|
user_id = self.app_state.usernames.get(username)
|
|
if user_id is None:
|
|
raise ApiError(401, "unauthorized", "Неверные credentials", 'Basic realm="messenger", charset="UTF-8"')
|
|
user = self.app_state.users[user_id]
|
|
if not verify_password(password, user["password_hash"]):
|
|
raise ApiError(401, "unauthorized", "Неверные credentials", 'Basic realm="messenger", charset="UTF-8"')
|
|
expires_at = utc_now() + timedelta(seconds=self.app_state.session_ttl_seconds)
|
|
token = secrets.token_urlsafe(32)
|
|
session = {
|
|
"token": token,
|
|
"user_id": user["id"],
|
|
"expires_at": isoformat_utc(expires_at),
|
|
"created_at": isoformat_utc(utc_now()),
|
|
"revoked": False,
|
|
}
|
|
self.app_state.sessions[token] = session
|
|
self._send_json(201, {
|
|
"token": token,
|
|
"token_type": "Bearer",
|
|
"expires_at": isoformat_utc(expires_at),
|
|
"user": self._user_public(user),
|
|
}, request_id)
|
|
return
|
|
|
|
session = self._require_bearer()
|
|
user = self.app_state.users.get(session["user_id"])
|
|
if user is None:
|
|
raise ApiError(401, "unauthorized", "Требуется действительный bearer token", 'Bearer realm="messenger", charset="UTF-8"')
|
|
|
|
if self.command == "GET" and path == "/api/v1/users/me":
|
|
self._send_json(200, self._user_public(user), request_id)
|
|
return
|
|
|
|
if self.command == "DELETE" and path == "/api/v1/auth/sessions/current":
|
|
with self.app_state.lock:
|
|
self.app_state.sessions.pop(session["token"], None)
|
|
self.send_response(204)
|
|
self.send_header("X-Request-Id", request_id)
|
|
self.send_header("X-Instance-Id", self.server.state.instance_id)
|
|
self.end_headers()
|
|
return
|
|
|
|
if self.command == "POST" and path == "/api/v1/chats":
|
|
body = self._read_json()
|
|
self._fields(body, {"title", "member_ids"})
|
|
title = body["title"]
|
|
members = body["member_ids"]
|
|
if not isinstance(title, str) or not 1 <= len(title) <= 100 or not title.strip():
|
|
raise ApiError(400, "invalid_request", "Некорректное название чата")
|
|
if not isinstance(members, list) or not 1 <= len(members) <= 100:
|
|
raise ApiError(400, "invalid_request", "Некорректный список участников")
|
|
normalized: list[str] = []
|
|
for member_id in members:
|
|
normalized.append(self._validate_uuid(member_id))
|
|
if len(set(normalized)) != len(normalized):
|
|
raise ApiError(400, "invalid_request", "Участники должны быть уникальными")
|
|
if any(uid not in self.app_state.users for uid in normalized):
|
|
raise ApiError(400, "invalid_request", "Участники должны быть существующими пользователями")
|
|
if user["id"] not in normalized:
|
|
raise ApiError(400, "invalid_request", "Создатель должен входить в чат")
|
|
chat = {
|
|
"id": new_id(),
|
|
"title": title,
|
|
"member_ids": normalized,
|
|
"created_at": isoformat_utc(utc_now()),
|
|
}
|
|
with self.app_state.lock:
|
|
self.app_state.chats[chat["id"]] = chat
|
|
self.app_state.messages[chat["id"]] = []
|
|
self._send_json(201, chat, request_id)
|
|
return
|
|
|
|
if self.command == "GET" and path == "/api/v1/chats":
|
|
with self.app_state.lock:
|
|
chats = [chat for chat in self.app_state.chats.values() if user["id"] in chat["member_ids"]]
|
|
ordered = sorted(chats, key=lambda item: (item["created_at"], item["id"]))
|
|
self._page(ordered, "chats:" + user["id"], query, request_id)
|
|
return
|
|
|
|
if self.command in {"GET", "POST"}:
|
|
match = re.fullmatch(r"/api/v1/chats/([^/]+)(?:/(messages))?", path)
|
|
if match:
|
|
chat_id = self._validate_uuid(match.group(1))
|
|
with self.app_state.lock:
|
|
chat = self.app_state.chats.get(chat_id)
|
|
if chat is None or user["id"] not in chat["member_ids"]:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
if self.command == "GET" and match.group(2) is None:
|
|
self._send_json(200, chat, request_id)
|
|
return
|
|
if self.command == "POST" and match.group(2) == "messages":
|
|
body = self._read_json()
|
|
self._fields(body, {"text"})
|
|
text = body["text"]
|
|
if not isinstance(text, str) or len(text) > 4000 or not text.strip():
|
|
raise ApiError(400, "invalid_request", "Сообщение должно содержать от 1 до 4000 символов")
|
|
msg = {
|
|
"id": new_id(),
|
|
"chat_id": chat_id,
|
|
"sender_id": user["id"],
|
|
"text": text,
|
|
"created_at": isoformat_utc(utc_now()),
|
|
}
|
|
with self.app_state.lock:
|
|
self.app_state.messages.setdefault(chat_id, []).append(msg)
|
|
self._send_json(201, msg, request_id)
|
|
return
|
|
if self.command == "GET" and match.group(2) == "messages":
|
|
with self.app_state.lock:
|
|
messages = sorted(self.app_state.messages.get(chat_id, []), key=lambda item: (item["created_at"], item["id"]))
|
|
self._page(messages, "messages:" + chat_id, query, request_id)
|
|
return
|
|
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
|
|
def do_GET(self) -> None:
|
|
self._handle()
|
|
|
|
def do_POST(self) -> None:
|
|
self._handle()
|
|
|
|
def do_DELETE(self) -> None:
|
|
self._handle()
|
|
|
|
def _handle(self) -> None:
|
|
request_id = new_id()
|
|
try:
|
|
self._dispatch(request_id)
|
|
except ApiError as exc:
|
|
self._error(exc, request_id)
|
|
except BrokenPipeError:
|
|
return
|
|
except Exception:
|
|
self._error(ApiError(500, "internal_error", "Внутренняя ошибка сервера"), request_id)
|
|
|
|
|
|
class MessengerServer(ThreadingHTTPServer):
|
|
daemon_threads = True
|
|
allow_reuse_address = True
|
|
|
|
def __init__(self, server_address: tuple[str, int]):
|
|
super().__init__(server_address, MessengerHandler)
|
|
self.state = AppState()
|
|
|
|
|
|
def main() -> None:
|
|
host = os.environ.get("APP_HOST", "0.0.0.0")
|
|
try:
|
|
port = int(os.environ.get("APP_PORT", "8080"))
|
|
except ValueError as exc:
|
|
raise SystemExit("APP_PORT must be an integer") from exc
|
|
if not 1 <= port <= 65535:
|
|
raise SystemExit("APP_PORT must be between 1 and 65535")
|
|
|
|
server = MessengerServer((host, port))
|
|
stopped = threading.Event()
|
|
|
|
def stop_server(signum: int, frame: object) -> None:
|
|
if not stopped.is_set():
|
|
stopped.set()
|
|
threading.Thread(target=server.shutdown, daemon=True).start()
|
|
|
|
signal.signal(signal.SIGTERM, stop_server)
|
|
signal.signal(signal.SIGINT, stop_server)
|
|
print(f"Messenger listening on {host}:{port}", flush=True)
|
|
try:
|
|
server.serve_forever(poll_interval=0.2)
|
|
finally:
|
|
server.server_close()
|
|
print("Messenger stopped", flush=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|