ЛР 7: TLS/mTLS, Argon2id, OpenBao и negative tests (оценка 3)
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Яковлев Матвей Дмитриевич
2026-11-28 12:29:50 +01:00
parent 20afc2c790
commit 8c75b7266f
53 changed files with 3114 additions and 89 deletions
+1
View File
@@ -0,0 +1 @@
"""Messenger lab2: PostgreSQL-backed API."""
+26
View File
@@ -0,0 +1,26 @@
"""Local entry point: python -m app (HTTPS with required client cert inside the mesh)."""
import os
import ssl
import uvicorn
if __name__ == "__main__":
cert = os.environ.get("TLS_CERTFILE")
key = os.environ.get("TLS_KEYFILE")
options = {}
if cert and key:
options = dict(
ssl_certfile=cert,
ssl_keyfile=key,
ssl_ca_certs=os.environ.get("TLS_CLIENT_CA", "/certs/ca.crt"),
ssl_cert_reqs=ssl.CERT_REQUIRED if os.environ.get("TLS_REQUIRE_CLIENT", "1") == "1"
else ssl.CERT_NONE,
)
uvicorn.run(
"app.main:app",
host=os.environ.get("APP_HOST", "0.0.0.0"),
port=int(os.environ.get("APP_PORT", "8443")),
workers=1,
log_level=os.environ.get("LOG_LEVEL", "info"),
**options,
)
+47
View File
@@ -0,0 +1,47 @@
"""Fetch runtime secrets from OpenBao using a scoped AppRole (never root token)."""
import json
import logging
import os
import ssl
import urllib.request
from pathlib import Path
log = logging.getLogger("messenger.bao")
def load_secrets():
"""Populate environment variables from secret/messenger/app via AppRole login."""
if os.environ.get("BAO_ENABLED", "1") == "0":
log.info("OpenBao integration disabled for local offline work")
return {}
creds_path = Path(os.environ.get("BAO_APPROLE_FILE", "/certs/private/bao-approle.json"))
if not creds_path.exists():
raise RuntimeError("AppRole credentials are missing: run scripts/bootstrap_bao.py")
creds = json.loads(creds_path.read_text())
ca = os.environ.get("TLS_CA_FILE", "/certs/ca.crt")
address = os.environ.get("BAO_ADDR", "https://openbao:8200").rstrip("/")
context = ssl.create_default_context(cafile=ca)
def post(path, body, token=None):
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
request = urllib.request.Request(
address + path, data=json.dumps(body).encode(), headers=headers, method="POST")
with urllib.request.urlopen(request, context=context, timeout=8) as response:
return json.loads(response.read())
login = post("/v1/auth/approle/login", {
"role_id": creds["role_id"], "secret_id": creds["secret_id"],
})
token = login["auth"]["client_token"]
request = urllib.request.Request(address + "/v1/secret/data/messenger/app",
headers={"X-Vault-Token": token})
with urllib.request.urlopen(request, context=context, timeout=8) as response:
secret = json.loads(response.read())["data"]["data"]
for key in ("DATABASE_URL", "S3_ACCESS_KEY", "S3_SECRET_KEY", "REDIS_PASSWORD"):
if key in secret:
os.environ[key] = str(secret[key])
log.info("loaded scoped secrets from OpenBao (token TTL=%s)", login["auth"].get("lease_duration"))
return secret
+49
View File
@@ -0,0 +1,49 @@
"""Redis Streams durable job broker (at-least-once, consumer group, no bytes in messages)."""
import json
import logging
import os
log = logging.getLogger("messenger.broker")
client = None
STREAM = "attachment.jobs"
GROUP = "attachment-workers"
def start():
global client
import redis
import ssl
client = redis.Redis(
host=os.environ.get("BROKER_HOST", "redis"),
port=int(os.environ.get("BROKER_PORT", "6379")),
db=0,
decode_responses=True,
socket_connect_timeout=3,
socket_timeout=5,
password=os.environ.get("REDIS_PASSWORD"),
ssl=True,
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs=os.environ.get("TLS_CA_FILE", "/certs/ca.crt"),
)
client.ping()
try:
client.xgroup_create(STREAM, GROUP, id="0", mkstream=True)
except redis.ResponseError as exc:
if "BUSYGROUP" not in str(exc):
raise
log.info("broker ready: stream=%s group=%s", STREAM, GROUP)
def publish(job):
"""Publisher confirm = the XADD reply id. The job carries IDs, never bytes or secrets."""
return client.xadd(STREAM, {"job": json.dumps(job, ensure_ascii=False)})
def ready():
try:
client.ping()
return True
except Exception:
log.exception("broker readiness check failed")
return False
+172
View File
@@ -0,0 +1,172 @@
"""PostgreSQL access: small bounded connection pool, versioned migrations, row helpers."""
import logging
import os
import queue
from contextlib import contextmanager
from datetime import timezone
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
log = logging.getLogger("messenger.db")
ROOT = Path(__file__).resolve().parents[1]
MIGRATIONS = ROOT / "migrations"
def _read_secret(path):
if not path:
return None
value = Path(path).read_text(encoding="utf-8").strip()
if not value:
raise RuntimeError("secret file is empty: " + path)
return value
def database_url():
"""Prefer a mounted secret file; fall back to an environment variable for local runs."""
url = _read_secret(os.environ.get("DATABASE_URL_FILE"))
if url:
return url
url = os.environ.get("DATABASE_URL")
if not url:
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
if os.environ.get("DB_TLS", "1") != "0":
separator = "&" if "?" in url else "?"
url += separator + "sslmode=verify-full&sslrootcert=" + os.environ.get(
"TLS_CA_FILE", "/certs/ca.crt")
return url
class Database:
"""A tiny FIFO pool. Each request borrows one connection and returns it."""
def __init__(self):
self._pool = None
self.dsn = None
def start(self):
self.dsn = database_url()
size = int(os.environ.get("DB_POOL_MAX", "8"))
self._pool = queue.Queue(maxsize=size)
for _ in range(size):
self._pool.put(self._connect())
self.migrate()
def _connect(self):
return psycopg.connect(self.dsn, connect_timeout=3, row_factory=dict_row, autocommit=True)
def stop(self):
if self._pool is None:
return
while not self._pool.empty():
try:
self._pool.get_nowait().close()
except queue.Empty:
break
self._pool = None
@contextmanager
def connection(self):
conn = self._pool.get(timeout=5)
try:
yield conn
finally:
self._pool.put(conn)
@contextmanager
def transaction(self):
with self.connection() as conn:
# Explicit BEGIN/COMMIT; rollback on any exception.
conn.execute("BEGIN")
try:
yield conn
except BaseException:
conn.execute("ROLLBACK")
raise
else:
conn.execute("COMMIT")
def ready(self):
try:
with self.connection() as conn:
conn.execute("SELECT 1").fetchone()
return True
except Exception:
log.exception("readiness check failed")
return False
def migrate(self):
"""Apply *.sql in name order, at most once each; restart-safe with the same volume."""
with self.transaction() as conn:
# All API replicas start against the same database. A transaction-scoped
# advisory lock makes the migration step strictly single-runner:
# the second replica waits, then sees schema_migrations already filled.
conn.execute("SELECT pg_advisory_xact_lock(20261116)")
conn.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations ("
"name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp())"
)
applied = {r["name"] for r in conn.execute("SELECT name FROM schema_migrations").fetchall()}
for path in sorted(MIGRATIONS.glob("*.sql")):
if path.name in applied:
continue
conn.execute(path.read_text(encoding="utf-8"))
conn.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (path.name,))
log.info("applied migration %s", path.name)
db = Database()
def utc_text(value):
"""RFC 3339 UTC with an explicit Z and microsecond precision."""
value = value.astimezone(timezone.utc)
return value.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def user_public(row):
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": utc_text(row["created_at"]),
}
def chat_public(row):
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(x) for x in (row["member_ids"] or [])],
"created_at": utc_text(row["created_at"]),
}
def message_public(row):
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"attachment_ids": [str(x) for x in (row["attachment_ids"] or [])],
"created_at": utc_text(row["created_at"]),
}
def attachment_public(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"] or [],
"error_code": row["error_code"],
"created_at": utc_text(row["created_at"]),
"updated_at": utc_text(row["updated_at"]),
}
+49
View File
@@ -0,0 +1,49 @@
"""Cheap header-only PNG/JPEG probing: magic, declared MIME and pixel limit."""
import struct
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
JPEG_MAGIC = b"\xff\xd8\xff"
SOF_MARKERS = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
class InvalidImage(ValueError):
pass
def probe(data):
"""Return (content_type, width, height) without decoding the whole image."""
if data.startswith(PNG_MAGIC):
if len(data) < 24 or data[12:16] != b"IHDR":
raise InvalidImage("truncated PNG")
width, height = struct.unpack(">II", data[16:24])
if width == 0 or height == 0:
raise InvalidImage("invalid PNG dimensions")
return "image/png", width, height
if data[:3] == JPEG_MAGIC:
i = 2
while i + 9 < len(data):
if data[i] != 0xFF:
i += 1
continue
marker = data[i + 1]
if marker == 0xFF:
i += 1
continue
if marker == 0xD8 or 0xD0 <= marker <= 0xD7 or marker == 0x01:
i += 2
continue
if marker == 0xD9:
break
length = struct.unpack(">H", data[i + 2:i + 4])[0]
if length < 2 or i + 2 + length > len(data):
raise InvalidImage("truncated JPEG segment")
if marker in SOF_MARKERS:
height, width = struct.unpack(">HH", data[i + 5:i + 9])
if width == 0 or height == 0:
raise InvalidImage("invalid JPEG dimensions")
return "image/jpeg", width, height
i += 2 + length
raise InvalidImage("JPEG has no SOF marker")
raise InvalidImage("not a PNG or JPEG")
+682
View File
@@ -0,0 +1,682 @@
"""Lab2 messenger HTTP layer. Contract: contracts/openapi.json.
State lives in PostgreSQL: users, chats, memberships, messages and sessions.
Basic is accepted only on POST /auth/sessions; every other protected route needs Bearer.
"""
import base64
import binascii
import datetime as dt
import hashlib
import json
import logging
import os
import collections
import re
import threading
import time
import uuid
from contextlib import asynccontextmanager
import psycopg
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from starlette.datastructures import MutableHeaders
from starlette.exceptions import HTTPException as StarletteHTTPException
from . import broker, s3, telemetry
from .db import attachment_public, chat_public, db, message_public, user_public, utc_text
from .images import InvalidImage, probe
from .security import bearer_token, hash_password, parse_basic, token_hash, verify_password
log = logging.getLogger("messenger")
MAX_BODY_BYTES = 1 << 20
MAX_UPLOAD_BYTES = 10 * 1024 * 1024 # 10 MiB
MAX_IMAGE_PIXELS = 40_000_000
DEFAULT_LIMIT, MAX_LIMIT = 50, 100
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}\Z")
UUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\Z")
IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}\Z")
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
INSTANCE_ID = os.environ.get("INSTANCE_ALIAS") or uuid.uuid4().hex[:12]
UTC = dt.timezone.utc
# Local login rate limit (per process; shared across replicas is level 4).
LOGIN_MAX_ATTEMPTS = 5
LOGIN_WINDOW_SECONDS = 60
_login_attempts = collections.defaultdict(collections.deque)
_login_lock = threading.Lock()
def limit_login(username):
"""Shared across API replicas via the broker; local fallback before startup."""
key = "rate:login:" + username
try:
if broker.client is not None:
count = broker.client.incr(key)
if count == 1:
broker.client.expire(key, LOGIN_WINDOW_SECONDS)
limited = count > LOGIN_MAX_ATTEMPTS
else:
raise RuntimeError("broker not ready")
except Exception:
now = time.monotonic()
with _login_lock:
window = _login_attempts[username]
while window and now - window[0] > LOGIN_WINDOW_SECONDS:
window.popleft()
if len(window) >= LOGIN_MAX_ATTEMPTS:
limited = True
else:
window.append(now)
limited = False
if limited:
raise ApiError(429, "rate_limited", "Слишком много попыток входа",
{"Retry-After": str(LOGIN_WINDOW_SECONDS)})
class ApiError(Exception):
def __init__(self, status, code, message, headers=None):
self.status, self.code, self.message, self.headers = status, code, message, headers
def bad_request(message):
return ApiError(400, "invalid_request", message)
def unauthorized(challenge, message="Требуется действительная аутентификация"):
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge})
def not_found():
return ApiError(404, "not_found", "Объект не найден")
def error_response(status, code, message, request_id, headers=None):
body = {"error": {"code": code, "message": message, "request_id": request_id}}
return JSONResponse(body, status_code=status, headers=headers)
class RequestContextMiddleware:
"""Request IDs, server spans and low-cardinality HTTP metrics for every response."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
request_id = str(uuid.uuid4())
scope.setdefault("state", {})["request_id"] = request_id
started = False
status = [None]
begun = time.monotonic()
async def send_with_id(message):
nonlocal started
if message["type"] == "http.response.start":
started = True
status[0] = message["status"]
headers = MutableHeaders(scope=message)
headers["X-Request-Id"] = request_id
headers["X-Instance-Id"] = INSTANCE_ID
await send(message)
with telemetry.http_span(scope["method"], "unmatched") as span:
try:
await self.app(scope, receive, send_with_id)
except Exception:
log.exception("unhandled error request_id=%s", request_id)
if not started:
response = error_response(500, "internal_error", "Внутренняя ошибка сервера", request_id)
await response(scope, receive, send_with_id)
finally:
route = scope.get("route")
# Use the route TEMPLATE, never the raw path with UUIDs.
template = route.path if route is not None else "unmatched"
code = status[0] or 500
status_class = "%dxx" % (code // 100)
telemetry.record_http(scope["method"], template, status_class, time.monotonic() - begun)
if span is not None and span.is_recording():
span.set_attribute("http.response.status_code", code)
span.set_attribute("messenger.request_id", request_id)
@asynccontextmanager
async def lifespan(app):
from .bao import load_secrets
load_secrets()
telemetry.init("messenger-api", INSTANCE_ID)
db.start()
s3.start()
broker.start()
try:
yield
finally:
db.stop()
app = FastAPI(title="Messenger lab2", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
app.add_middleware(RequestContextMiddleware)
@app.exception_handler(ApiError)
async def handle_api_error(request: Request, exc: ApiError):
return error_response(exc.status, exc.code, exc.message, request.state.request_id, exc.headers)
@app.exception_handler(StarletteHTTPException)
async def handle_http_exception(request: Request, exc: StarletteHTTPException):
if exc.status_code == 404:
code, message = "not_found", "Объект не найден"
elif exc.status_code < 500:
code, message = "invalid_request", "Некорректный запрос"
else:
code, message = "internal_error", "Внутренняя ошибка сервера"
return error_response(exc.status_code, code, message, request.state.request_id, exc.headers)
@app.exception_handler(RequestValidationError)
async def handle_validation_error(request: Request, exc: RequestValidationError):
return error_response(400, "invalid_request", "Некорректный запрос", request.state.request_id)
# ---------- validation helpers ----------
def clean_string(data, field, max_len):
value = data.get(field)
if not isinstance(value, str):
raise bad_request("Поле %s должно быть строкой" % field)
if not value.strip() or len(value) > max_len:
raise bad_request("Поле %s должно содержать от 1 до %d символов" % (field, max_len))
return value
def idempotency_key(request):
value = request.headers.get("idempotency-key")
if not value or not IDEMPOTENCY_KEY_RE.fullmatch(value):
raise bad_request("Idempotency-Key обязателен и должен соответствовать [A-Za-z0-9._:-]{1,128}")
return value
async def read_raw(request, limit):
"""Read a binary body with a hard byte limit applied before buffering everything."""
declared = request.headers.get("content-length", "")
if declared.isdigit() and int(declared) > limit:
raise ApiError(413, "payload_too_large", "Файл слишком большой")
body = bytearray()
async for chunk in request.stream():
body += chunk
if len(body) > limit:
raise ApiError(413, "payload_too_large", "Файл слишком большой")
return bytes(body)
def validate_filename(value):
if not isinstance(value, str) or not 1 <= len(value) <= 255:
raise bad_request("filename должен содержать от 1 до 255 символов")
if any(ch in value for ch in ("/", "\\", "\x00")) or any(ord(ch) < 32 or ord(ch) == 127 for ch in value):
raise bad_request("filename содержит недопустимые символы")
return value
def parse_uuid(value, what):
if not isinstance(value, str) or not UUID_RE.fullmatch(value):
raise bad_request("Некорректный UUID: %s" % what)
return value.lower()
async def read_json_object(request, required, optional=()):
declared = request.headers.get("content-length", "")
if declared.isdigit() and int(declared) > MAX_BODY_BYTES:
raise ApiError(413, "payload_too_large", "Тело запроса слишком большое")
content_type = request.headers.get("content-type", "").split(";")[0].strip().lower()
if content_type and content_type != "application/json":
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
body = bytearray()
async for chunk in request.stream():
body += chunk
if len(body) > MAX_BODY_BYTES:
raise ApiError(413, "payload_too_large", "Тело запроса слишком большое")
try:
data = json.loads(bytes(body).decode("utf-8"))
except (UnicodeDecodeError, ValueError):
raise bad_request("Тело запроса не является корректным JSON") from None
if not isinstance(data, dict):
raise bad_request("Тело запроса должно быть JSON-объектом")
expected = set(required) | set(optional)
if not set(required).issubset(data) or not set(data).issubset(expected):
raise bad_request("Ожидаемые поля: " + ", ".join(sorted(expected)))
return data
def page_params(request):
query = request.query_params
raw_limit = query.getlist("limit")
if len(raw_limit) > 1 or len(query.getlist("cursor")) > 1:
raise bad_request("Параметры limit и cursor можно указать только один раз")
limit = DEFAULT_LIMIT
if raw_limit:
text = raw_limit[0]
if not (text.isascii() and text.isdigit()) or not 1 <= int(text) <= MAX_LIMIT:
raise bad_request("limit должен быть целым числом от 1 до %d" % MAX_LIMIT)
limit = int(text)
return limit, query.get("cursor") or None
def encode_cursor(kind, scope, created_at, item_id):
raw = json.dumps(
{"k": kind, "s": scope,
"t": int(created_at.timestamp() * 1_000_000),
"i": uuid.UUID(str(item_id)).int},
separators=(",", ":"),
)
return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
def decode_cursor(text, kind, scope):
try:
data = json.loads(base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)))
t, i = data["t"], data["i"]
valid = (data["k"] == kind and data["s"] == scope
and type(t) is int and type(i) is int and t >= 0 and i >= 0)
if not valid:
raise ValueError
return dt.datetime.fromtimestamp(t / 1_000_000, tz=UTC), uuid.UUID(int=i)
except (ValueError, KeyError, TypeError, binascii.Error, OverflowError):
raise bad_request("Некорректный cursor") from None
def page_response(items, limit, kind, scope, rows):
"""items are public JSON dicts; rows are the raw DB rows used for the opaque cursor."""
more = len(items) > limit
window = items[:limit]
last = rows[limit - 1] if more and len(rows) >= limit else None
cursor = (encode_cursor(kind, scope, last["created_at"], last["id"])
if last is not None else None)
return JSONResponse({"items": window, "next_cursor": cursor})
# ---------- authentication and resource access ----------
def current_user(request):
"""Lab2: only an opaque Bearer session identifies the caller; X-User-Id is ignored."""
token = bearer_token(request.headers.get("authorization"))
if not token:
raise unauthorized(BEARER_CHALLENGE)
with db.connection() as conn:
row = conn.execute(
"SELECT u.id, u.username, u.display_name, u.created_at "
"FROM sessions s JOIN users u ON u.id = s.user_id "
"WHERE s.token_hash = %s AND s.expires_at > clock_timestamp()",
(token_hash(token),),
).fetchone()
if row is None:
raise unauthorized(BEARER_CHALLENGE)
return user_public(row)
def authenticated_chat(request, chat_id):
user = current_user(request)
chat_uuid = parse_uuid(chat_id, "chat_id")
with db.connection() as conn:
row = conn.execute(
"SELECT c.id, c.title, c.created_at, "
"array_agg(m.user_id ORDER BY m.user_id) AS member_ids "
"FROM chats c JOIN chat_members m ON m.chat_id = c.id "
"WHERE c.id = %s AND m.user_id = %s GROUP BY c.id",
(chat_uuid, uuid.UUID(user["id"])),
).fetchone()
if row is None:
raise not_found() # unknown and foreign chats look identical
return user, chat_public(row)
# ---------- health ----------
@app.get("/health/live")
async def live():
return {"status": "ok"}
@app.get("/health/ready")
async def ready():
if not db.ready():
raise ApiError(503, "unavailable", "Хранилище данных недоступно")
if not s3.ready():
raise ApiError(503, "unavailable", "Хранилище вложений недоступно")
if not broker.ready():
raise ApiError(503, "unavailable", "Брокер заданий недоступен")
return {"status": "ok"}
# ---------- users and sessions ----------
@app.post("/api/v1/users")
async def register_user(request: Request):
data = await read_json_object(request, ("username", "display_name", "password"))
username = data["username"]
if not isinstance(username, str) or not USERNAME_RE.fullmatch(username):
raise bad_request("username должен соответствовать [a-z0-9_]{3,32}")
display_name = clean_string(data, "display_name", 100)
password = data["password"]
if not isinstance(password, str) or not 12 <= len(password) <= 128:
raise bad_request("password должен содержать от 12 до 128 символов")
user_id = uuid.uuid4()
try:
with db.transaction() as conn:
conn.execute(
"INSERT INTO users(id, username, display_name, password_hash) VALUES (%s,%s,%s,%s)",
(user_id, username, display_name, hash_password(password)),
)
row = conn.execute("SELECT * FROM users WHERE id = %s", (user_id,)).fetchone()
except psycopg.errors.UniqueViolation:
raise ApiError(409, "conflict", "Имя пользователя уже занято") from None
return JSONResponse(user_public(row), status_code=201)
@app.post("/api/v1/auth/sessions")
async def create_session(request: Request):
credential = parse_basic(request.headers.get("authorization"))
if credential is None:
raise unauthorized(BASIC_CHALLENGE, "Неверные учетные данные")
username, password = credential
limit_login(username)
with db.connection() as conn:
row = conn.execute("SELECT * FROM users WHERE username = %s", (username,)).fetchone()
if row is None or not verify_password(password, row["password_hash"]):
raise unauthorized(BASIC_CHALLENGE, "Неверные учетные данные")
token = base64.urlsafe_b64encode(os.urandom(32)).decode().rstrip("=")
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
expires_at = dt.datetime.now(UTC) + dt.timedelta(seconds=ttl)
with db.transaction() as conn:
conn.execute(
"INSERT INTO sessions(token_hash, user_id, expires_at) VALUES (%s,%s,%s)",
(token_hash(token), row["id"], expires_at),
)
return JSONResponse({
"token": token,
"token_type": "Bearer",
"expires_at": utc_text(expires_at),
"user": user_public(row),
}, status_code=201)
@app.delete("/api/v1/auth/sessions/current")
async def revoke_session(request: Request):
token = bearer_token(request.headers.get("authorization"))
if not token:
raise unauthorized(BEARER_CHALLENGE)
with db.transaction() as conn:
result = conn.execute(
"DELETE FROM sessions WHERE token_hash = %s AND expires_at > clock_timestamp()",
(token_hash(token),),
)
if result.rowcount == 0:
raise unauthorized(BEARER_CHALLENGE)
return Response(status_code=204)
@app.get("/api/v1/users/me")
async def get_me(request: Request):
return current_user(request)
# ---------- chats ----------
@app.post("/api/v1/chats")
async def create_chat(request: Request):
user = current_user(request)
data = await read_json_object(request, ("title", "member_ids"))
title = clean_string(data, "title", 100)
raw_members = data["member_ids"]
if not isinstance(raw_members, list) or not 1 <= len(raw_members) <= 100:
raise bad_request("member_ids должен быть списком из 1–100 UUID")
members = [parse_uuid(m, "member_ids") for m in raw_members]
if len(set(members)) != len(members):
raise bad_request("member_ids содержит дубликаты")
if user["id"] not in members:
raise bad_request("member_ids должен содержать вызывающего пользователя")
chat_id = uuid.uuid4()
member_uuids = [uuid.UUID(x) for x in members]
try:
with db.transaction() as conn:
found = conn.execute(
"SELECT id FROM users WHERE id = ANY(%s::uuid[])", (member_uuids,)
).fetchall()
if len(found) != len(member_uuids):
raise bad_request("member_ids содержит неизвестного пользователя")
conn.execute("INSERT INTO chats(id, title) VALUES (%s,%s)", (chat_id, title))
for member in member_uuids:
conn.execute(
"INSERT INTO chat_members(chat_id, user_id) VALUES (%s,%s)",
(chat_id, member),
)
row = conn.execute(
"SELECT c.id, c.title, c.created_at, array_agg(m.user_id ORDER BY m.user_id) AS member_ids "
"FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE c.id = %s GROUP BY c.id",
(chat_id,),
).fetchone()
except psycopg.errors.ForeignKeyViolation:
raise bad_request("member_ids содержит неизвестного пользователя") from None
return JSONResponse(chat_public(row), status_code=201)
@app.get("/api/v1/chats")
async def list_chats(request: Request):
user = current_user(request)
limit, cursor = page_params(request)
after = decode_cursor(cursor, "chats", user["id"]) if cursor else None
sql = (
"SELECT c.id, c.title, c.created_at, array_agg(m.user_id ORDER BY m.user_id) AS member_ids "
"FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = %s"
)
params = [uuid.UUID(user["id"])]
if after:
sql += " AND (c.created_at, c.id) > (%s, %s::uuid)"
params.extend([after[0], after[1]])
sql += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT %s"
params.append(limit + 1)
with db.connection() as conn:
rows = conn.execute(sql, params).fetchall()
items = [chat_public(r) for r in rows]
return page_response(items, limit, "chats", user["id"], rows)
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, request: Request):
_, chat = authenticated_chat(request, chat_id)
return chat
# ---------- messages ----------
@app.post("/api/v1/chats/{chat_id}/messages")
async def create_message(chat_id: str, request: Request):
"""Idempotent POST: the ledger row and the message are committed atomically."""
user, chat = authenticated_chat(request, chat_id) # replay re-checks session and access
data = await read_json_object(request, ("text",), optional=("attachment_ids",))
text = data.get("text", "")
if not isinstance(text, str) or len(text) > 4000:
raise bad_request("text должен быть строкой до 4000 символов")
raw_attachments = data.get("attachment_ids", [])
if not isinstance(raw_attachments, list) or len(raw_attachments) > 10:
raise bad_request("attachment_ids должен быть списком до 10 UUID")
attachment_ids = [parse_uuid(x, "attachment_ids") for x in raw_attachments]
if len(set(attachment_ids)) != len(attachment_ids):
raise bad_request("attachment_ids содержит дубликаты")
if not text.strip() and not attachment_ids:
raise bad_request("Нужен непустой текст или хотя бы одно вложение")
key = idempotency_key(request)
# Canonical body hash: key order does not matter; omitted attachment_ids == [].
canonical = json.dumps(
{"text": text, "attachment_ids": sorted(attachment_ids)},
sort_keys=True, separators=(",", ":"),
)
request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
scope_path = request.url.path
actor_id = uuid.UUID(user["id"])
for _attempt in range(5):
try:
with db.transaction() as conn:
previous = conn.execute(
"SELECT request_hash, status_code, response_body FROM idempotency_records "
"WHERE user_id=%s AND method=%s AND path=%s AND key=%s FOR UPDATE",
(actor_id, "POST", scope_path, key),
).fetchone()
if previous is not None:
if previous["request_hash"] != request_hash:
raise ApiError(409, "conflict", "Тот же Idempotency-Key использован с другим телом")
return JSONResponse(previous["response_body"], status_code=previous["status_code"])
if attachment_ids:
found = conn.execute(
"SELECT id FROM attachments WHERE id = ANY(%s::uuid[]) AND chat_id = %s",
([uuid.UUID(x) for x in attachment_ids], uuid.UUID(chat["id"])),
).fetchall()
if len(found) != len(attachment_ids):
raise ApiError(404, "not_found", "Вложение не найдено в этом чате")
message_id = uuid.uuid4()
conn.execute(
"INSERT INTO messages(id, chat_id, sender_id, text, attachment_ids) "
"VALUES (%s,%s,%s,%s,%s::uuid[])",
(message_id, uuid.UUID(chat["id"]), actor_id, text,
[uuid.UUID(x) for x in attachment_ids]),
)
row = conn.execute("SELECT * FROM messages WHERE id = %s", (message_id,)).fetchone()
body = message_public(row)
conn.execute(
"INSERT INTO idempotency_records"
"(user_id, method, path, key, request_hash, status_code, response_body) "
"VALUES (%s,%s,%s,%s,%s,%s,%s::jsonb)",
(actor_id, "POST", scope_path, key, request_hash, 201,
json.dumps(body, ensure_ascii=False)),
)
log.info("message accepted", extra={"event": "message.created"})
return JSONResponse(body, status_code=201)
except psycopg.errors.UniqueViolation:
# Another replica won the race for this key. Roll back and read its
# committed response on the next attempt instead of creating a duplicate.
continue
raise ApiError(409, "conflict", "Не удалось зафиксировать Idempotency-Key")
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, request: Request):
_, chat = authenticated_chat(request, chat_id)
limit, cursor = page_params(request)
after = decode_cursor(cursor, "messages", chat["id"]) if cursor else None
sql = "SELECT * FROM messages WHERE chat_id = %s"
params = [uuid.UUID(chat["id"])]
if after:
sql += " AND (created_at, id) > (%s, %s::uuid)"
params.extend([after[0], after[1]])
sql += " ORDER BY created_at, id LIMIT %s"
params.append(limit + 1)
with db.connection() as conn:
rows = conn.execute(sql, params).fetchall()
items = [message_public(r) for r in rows]
return page_response(items, limit, "messages", chat["id"], rows)
# ---------- attachments (lab4) ----------
def attachment_for(request, attachment_id):
"""An attachment is visible only to members of its chat; outsiders get a plain 404."""
user = current_user(request)
row = None
try:
aid = uuid.UUID(attachment_id)
except (ValueError, TypeError, AttributeError):
raise bad_request("Некорректный UUID вложения") from None
with db.connection() as conn:
row = conn.execute(
"SELECT a.* FROM attachments a "
"JOIN chat_members m ON m.chat_id = a.chat_id "
"WHERE a.id = %s AND m.user_id = %s",
(aid, uuid.UUID(user["id"])),
).fetchone()
if row is None:
raise not_found()
return row
@app.post("/api/v1/chats/{chat_id}/attachments")
async def upload_attachment(chat_id: str, request: Request):
user, chat = authenticated_chat(request, chat_id)
filename = validate_filename(request.query_params.get("filename"))
declared = request.headers.get("content-type", "").split(";")[0].strip().lower()
if declared not in ("image/png", "image/jpeg"):
raise ApiError(415, "unsupported_media_type", "Ожидается image/png или image/jpeg")
data = await read_raw(request, MAX_UPLOAD_BYTES)
try:
content_type, width, height = probe(data)
except InvalidImage:
raise ApiError(415, "unsupported_media_type", "Содержимое не является PNG или JPEG") from None
if declared != content_type:
raise ApiError(415, "unsupported_media_type", "MIME не соответствует содержимому")
if width * height > MAX_IMAGE_PIXELS:
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
digest = hashlib.sha256(data).hexdigest()
# Durable staging first: the worker reads this object, not client-supplied paths.
object_key = "staging/" + uuid.uuid4().hex
attachment_id = uuid.uuid4()
job_id = uuid.uuid4()
s3.put_object(object_key, data, content_type)
try:
with db.transaction() as conn:
conn.execute(
"INSERT INTO attachments(id, chat_id, owner_id, filename, content_type, "
"size_bytes, sha256, object_key, status, variants, error_code) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued','[]'::jsonb,NULL)",
(attachment_id, uuid.UUID(chat["id"]), uuid.UUID(user["id"]),
filename, content_type, len(data), digest, object_key),
)
row = conn.execute("SELECT * FROM attachments WHERE id = %s", (attachment_id,)).fetchone()
# 202 is returned only after a durable handoff: staging + metadata + broker XADD.
job = {
"schema_version": 1,
"job_id": str(job_id),
"type": "attachment.process.v1",
"attachment_id": str(attachment_id),
"pipeline_version": 1,
"attempt": 1,
"created_at": utc_text(dt.datetime.now(UTC)),
}
traceparent = telemetry.carrier().get("traceparent")
if traceparent:
job["traceparent"] = traceparent # W3C context only, never bytes or credentials
broker.publish(job)
except Exception:
s3.delete_object(object_key)
raise
log.info("attachment accepted (queued)", extra={"event": "attachment.queued"})
return JSONResponse(attachment_public(row), status_code=202)
@app.get("/api/v1/attachments/{attachment_id}")
async def get_attachment(attachment_id: str, request: Request):
return attachment_public(attachment_for(request, attachment_id))
@app.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment(attachment_id: str, request: Request):
row = attachment_for(request, attachment_id)
variant = request.query_params.get("variant", "original")
if row["status"] != "ready":
raise ApiError(409, "conflict", "Вложение ещё не готово")
object_key = row["object_key"]
content_type = row["content_type"]
if variant != "original":
matches = [v for v in (row["variants"] or []) if v.get("name") == variant]
if not matches:
raise not_found()
object_key += "." + variant + ".jpg" if variant == "thumbnail" else "." + variant
content_type = matches[0]["content_type"]
body, stored_type = s3.get_object(object_key)
return Response(content=body, media_type=content_type or stored_type)
+70
View File
@@ -0,0 +1,70 @@
"""MinIO/S3 client shared by all API replicas. Bucket bootstrap is idempotent."""
import logging
import os
log = logging.getLogger("messenger.s3")
client = None
bucket = None
def start():
global client, bucket
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
endpoint = os.environ.get("S3_ENDPOINT", "https://minio:9000")
bucket = os.environ.get("S3_BUCKET", "messenger")
client = boto3.client(
"s3",
endpoint_url=endpoint,
aws_access_key_id=os.environ.get("S3_ACCESS_KEY", "messenger"),
aws_secret_access_key=os.environ.get("S3_SECRET_KEY", "local-only-synthetic-secret"),
region_name="us-east-1",
verify=os.environ.get("TLS_CA_FILE", "/certs/ca.crt"),
config=Config(signature_version="s3v4", connect_timeout=3, read_timeout=10,
retries={"max_attempts": 2, "mode": "standard"}),
)
_bootstrap_bucket()
def _bootstrap_bucket():
from botocore.exceptions import ClientError
try:
client.head_bucket(Bucket=bucket)
return
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code not in ("404", "NoSuchBucket", "NotFound"):
raise
try:
client.create_bucket(Bucket=bucket)
log.info("created bucket %s", bucket)
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code not in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
raise
def put_object(key, body, content_type):
client.put_object(Bucket=bucket, Key=key, Body=body, ContentType=content_type)
def get_object(key):
response = client.get_object(Bucket=bucket, Key=key)
return response["Body"].read(), response.get("ContentType", "application/octet-stream")
def delete_object(key):
client.delete_object(Bucket=bucket, Key=key)
def ready():
if client is None:
return False
try:
client.head_bucket(Bucket=bucket)
return True
except Exception:
log.exception("S3 readiness check failed")
return False
+66
View File
@@ -0,0 +1,66 @@
"""Password KDF (Argon2id) and HTTP credential parsing (Basic / Bearer)."""
import base64
import binascii
import hashlib
import hmac
import os
import re
from argon2.exceptions import VerificationError
from argon2.low_level import Type, hash_secret, verify_secret
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}\Z")
ARGON2_TIME = 2
ARGON2_MEMORY = 19 * 1024 # 19 MiB minimum required by lab7
ARGON2_PARALLELISM = 1
ARGON2_HASH_LEN = 32
def hash_password(password):
salt = os.urandom(16)
derived = hash_secret(
password.encode("utf-8"), salt,
time_cost=ARGON2_TIME, memory_cost=ARGON2_MEMORY,
parallelism=ARGON2_PARALLELISM, hash_len=ARGON2_HASH_LEN, type=Type.ID,
)
return "argon2id$%d$%d$%d$%s$%s" % (
ARGON2_TIME, ARGON2_MEMORY, ARGON2_PARALLELISM, salt.hex(), derived.hex()
)
def verify_password(password, stored):
try:
scheme, t, m, p, salt_hex, digest_hex = stored.split("$")
if scheme != "argon2id":
return False
encoded = bytes.fromhex(digest_hex) # full Argon2id encoded hash
return verify_secret(encoded, password.encode("utf-8"), Type.ID)
except (ValueError, TypeError, VerificationError):
return False
def token_hash(token):
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def parse_basic(header):
if not header or not header.lower().startswith("basic "):
return None
encoded = header[6:].strip()
try:
raw = base64.b64decode(encoded, validate=True).decode("utf-8")
except (ValueError, UnicodeDecodeError, binascii.Error):
return None
if ":" not in raw:
return None
username, password = raw.split(":", 1)
if not USERNAME_RE.fullmatch(username) or not 12 <= len(password) <= 128:
return None
return username, password
def bearer_token(header):
if not header or not header.lower().startswith("bearer "):
return None
token = header[7:].strip()
return token or None
+138
View File
@@ -0,0 +1,138 @@
"""OpenTelemetry bootstrap: OTLP traces, metrics and logs via the Collector.
The module degrades to no-op when the SDK is absent (offline unit tests).
All attributes are low-cardinality: method, route template, status class, job type/outcome.
No message bodies, tokens, filenames or user/chat/message IDs are exported.
"""
import logging
import os
from contextlib import nullcontext
AVAILABLE = True
try:
from opentelemetry import metrics, trace
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
except ImportError:
AVAILABLE = False
log = logging.getLogger("messenger.telemetry")
tracer = None
meter = None
propagator = None
http_requests = None
http_duration = None
jobs_total = None
job_duration = None
_enabled = False
def init(service_name, instance_id):
global tracer, meter, propagator, http_requests, http_duration, jobs_total, job_duration, _enabled
if not AVAILABLE or os.environ.get("OTEL_SDK_DISABLED", "").lower() in ("1", "true"):
log.info("telemetry disabled or SDK unavailable")
return False
endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "https://otel-collector:4318").rstrip("/")
ca_file = os.environ.get("TLS_CA_FILE", "/certs/ca.crt")
resource = Resource.create({
"service.name": service_name,
"service.version": "1.0.0",
"service.instance.id": instance_id,
"deployment.environment.name": "lab",
})
provider = TracerProvider(resource=resource)
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint + "/v1/traces", certificate_file=ca_file)))
trace.set_tracer_provider(provider)
tracer = provider.get_tracer(service_name)
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint=endpoint + "/v1/metrics", certificate_file=ca_file),
export_interval_millis=int(os.environ.get("OTEL_METRIC_EXPORT_INTERVAL", "5000")),
)
meter_provider = MeterProvider(resource=resource, metric_readers=[reader])
metrics.set_meter_provider(meter_provider)
meter = meter_provider.get_meter(service_name)
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(
BatchLogRecordProcessor(OTLPLogExporter(endpoint=endpoint + "/v1/logs", certificate_file=ca_file))
)
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
root = logging.getLogger()
root.addHandler(handler)
root.setLevel(logging.INFO)
http_requests = meter.create_counter(
"http.server.requests", unit="{request}", description="HTTP requests by method, route and status class"
)
http_duration = meter.create_histogram(
"http.server.duration", unit="s", description="HTTP server request duration"
)
jobs_total = meter.create_counter(
"messenger.jobs", unit="{job}", description="Processed jobs by type and outcome"
)
job_duration = meter.create_histogram(
"messenger.job.duration", unit="s", description="Worker job processing duration"
)
propagator = TraceContextTextMapPropagator()
_enabled = True
log.info("telemetry enabled: service=%s endpoint=%s", service_name, endpoint)
return True
def http_span(method, route):
if tracer is None:
return nullcontext()
span = tracer.start_as_current_span(
"HTTP " + method,
attributes={"http.request.method": method, "http.route": route},
)
return span
def record_http(method, route, status_class, elapsed_seconds):
if http_requests is not None:
attrs = {"http.request.method": method, "http.route": route,
"http.response.status_class": status_class}
http_requests.add(1, attrs)
http_duration.record(elapsed_seconds, attrs)
def record_job(job_type, outcome, elapsed_seconds):
if jobs_total is not None:
attrs = {"job.type": job_type, "job.outcome": outcome}
jobs_total.add(1, attrs)
job_duration.record(elapsed_seconds, attrs)
def carrier():
"""W3C trace context to carry through the broker (no bytes or secrets)."""
out = {}
if propagator is not None and tracer is not None:
propagator.inject(out)
return out
def extract(carrier_map):
if propagator is None:
return None
return propagator.extract(carrier_map)
def worker_span(job_type, context=None):
if tracer is None:
return nullcontext()
return tracer.start_as_current_span("PROCESS " + job_type, context=context,
attributes={"job.type": job_type})