From 6435b6a1c570d7a87f406f87d4ff790fb5c37acf Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:01:21 +0300 Subject: [PATCH 01/16] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=20=D1=80=D0=B5=D1=88=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=9B?= =?UTF-8?q?=D0=A0=206=20=D0=B1=D0=B5=D0=B7=20=D0=B8=D0=B7=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D0=B5=D0=BD=D0=B8=D0=B9=20(src,=20migrations,=20student-?= =?UTF-8?q?tests,=20bench,=20infra,=20scripts,=20compose,=20Dockerfile,=20?= =?UTF-8?q?docs)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitattributes | 5 + .github/workflows/app.yml | 42 + Dockerfile | 67 + Makefile | 109 + bench/failover_series.py | 141 ++ bench/incidents.py | 424 ++++ bench/loadgen.py | 212 ++ bench/pipeline_faults.py | 309 +++ bench/rolling_under_load.py | 75 + bench/track1.py | 361 ++++ bench/track1_summary.py | 146 ++ bench/upload_memory.py | 244 +++ compose.yaml | 683 ++++++ docs/DATA_MODEL.md | 57 + docs/OBSERVABILITY.md | 110 + docs/PIPELINE.md | 128 ++ docs/RUNBOOK.md | 54 + docs/SLO.md | 32 + docs/WINDOWS.md | 103 + infra/grafana/dashboards/messenger.json | 1881 +++++++++++++++++ .../provisioning/dashboards/dashboards.yaml | 16 + .../provisioning/datasources/datasources.yaml | 73 + infra/haproxy/haproxy.cfg | 116 + infra/loki/loki.yaml | 60 + infra/otel/collector.yaml | 93 + infra/otel/traces-all.yaml | 6 + infra/otel/traces-tail.yaml | 39 + infra/prometheus/prometheus.yml | 36 + infra/prometheus/rules/alerts.yml | 90 + infra/prometheus/rules/slo.yml | 38 + infra/rabbitmq/enabled_plugins | 1 + infra/rabbitmq/rabbitmq.conf | 24 + infra/rabbitmq/topology.json | 21 + infra/seaweedfs/start.sh | 52 + infra/tempo/tempo.yaml | 34 + infra/valkey/valkey.conf | 17 + migrations/0001_init.sql | 65 + migrations/0002_idempotency_keys.sql | 25 + migrations/0003_post_message_function.sql | 50 + migrations/0004_attachments.sql | 145 ++ migrations/0005_pipeline.sql | 260 +++ migrations/0006_observability.sql | 19 + requirements-test.txt | 6 + requirements.in | 30 + requirements.txt | 1709 +++++++++++++++ scripts/build_dashboard.py | 294 +++ scripts/check_dashboard.py | 79 + scripts/collect_evidence.py | 221 ++ scripts/collect_evidence_resume.py | 50 + scripts/demo_attachments.py | 138 ++ scripts/demo_pipeline.py | 132 ++ scripts/explain_history.py | 114 + scripts/init_secrets.py | 81 + scripts/lbctl.py | 125 ++ scripts/obs.py | 213 ++ scripts/restart.cmd | 6 + scripts/restart.sh | 21 + scripts/restore-api.sh | 8 + scripts/rolling-update.sh | 37 + scripts/stop-one.cmd | 7 + scripts/stop-one.sh | 35 + scripts/trace_demo.py | 138 ++ src/messenger/__init__.py | 3 + src/messenger/__main__.py | 92 + src/messenger/app.py | 682 ++++++ src/messenger/attachments.py | 339 +++ src/messenger/audit.py | 190 ++ src/messenger/authhdr.py | 48 + src/messenger/broker.py | 93 + src/messenger/config.py | 348 +++ src/messenger/cursor.py | 56 + src/messenger/db.py | 171 ++ src/messenger/docs.py | 57 + src/messenger/errors.py | 71 + src/messenger/healthcheck.py | 31 + src/messenger/images.py | 328 +++ src/messenger/imaging.py | 208 ++ src/messenger/jobctl.py | 220 ++ src/messenger/jobs.py | 428 ++++ src/messenger/logging_setup.py | 44 + src/messenger/migrate.py | 76 + src/messenger/passwords.py | 53 + src/messenger/pipeline.py | 63 + src/messenger/relay.py | 235 ++ src/messenger/repo.py | 373 ++++ src/messenger/s3_bootstrap.py | 182 ++ src/messenger/service.py | 76 + src/messenger/sessions.py | 160 ++ src/messenger/storage.py | 211 ++ src/messenger/telemetry.py | 364 ++++ src/messenger/timefmt.py | 22 + src/messenger/validation.py | 195 ++ src/messenger/worker.py | 403 ++++ student-tests/conftest.py | 439 ++++ student-tests/imagegen.py | 117 + student-tests/test_api.py | 344 +++ student-tests/test_attachments.py | 291 +++ student-tests/test_balancing.py | 354 ++++ student-tests/test_consistency.py | 125 ++ student-tests/test_db.py | 119 ++ student-tests/test_explain.py | 35 + student-tests/test_failures.py | 111 + student-tests/test_idempotency.py | 281 +++ student-tests/test_observability.py | 184 ++ student-tests/test_pipeline_flow.py | 504 +++++ student-tests/test_sessions.py | 66 + student-tests/test_storage_failures.py | 112 + student-tests/unit/test_images.py | 148 ++ student-tests/unit/test_pipeline.py | 224 ++ student-tests/unit/test_telemetry.py | 196 ++ student-tests/unit/test_unit.py | 225 ++ 111 files changed, 19604 insertions(+) create mode 100644 .gitattributes create mode 100644 .github/workflows/app.yml create mode 100644 Dockerfile create mode 100644 bench/failover_series.py create mode 100644 bench/incidents.py create mode 100644 bench/loadgen.py create mode 100644 bench/pipeline_faults.py create mode 100644 bench/rolling_under_load.py create mode 100644 bench/track1.py create mode 100644 bench/track1_summary.py create mode 100644 bench/upload_memory.py create mode 100644 compose.yaml create mode 100644 docs/DATA_MODEL.md create mode 100644 docs/OBSERVABILITY.md create mode 100644 docs/PIPELINE.md create mode 100644 docs/RUNBOOK.md create mode 100644 docs/SLO.md create mode 100644 docs/WINDOWS.md create mode 100644 infra/grafana/dashboards/messenger.json create mode 100644 infra/grafana/provisioning/dashboards/dashboards.yaml create mode 100644 infra/grafana/provisioning/datasources/datasources.yaml create mode 100644 infra/haproxy/haproxy.cfg create mode 100644 infra/loki/loki.yaml create mode 100644 infra/otel/collector.yaml create mode 100644 infra/otel/traces-all.yaml create mode 100644 infra/otel/traces-tail.yaml create mode 100644 infra/prometheus/prometheus.yml create mode 100644 infra/prometheus/rules/alerts.yml create mode 100644 infra/prometheus/rules/slo.yml create mode 100644 infra/rabbitmq/enabled_plugins create mode 100644 infra/rabbitmq/rabbitmq.conf create mode 100644 infra/rabbitmq/topology.json create mode 100644 infra/seaweedfs/start.sh create mode 100644 infra/tempo/tempo.yaml create mode 100644 infra/valkey/valkey.conf create mode 100644 migrations/0001_init.sql create mode 100644 migrations/0002_idempotency_keys.sql create mode 100644 migrations/0003_post_message_function.sql create mode 100644 migrations/0004_attachments.sql create mode 100644 migrations/0005_pipeline.sql create mode 100644 migrations/0006_observability.sql create mode 100644 requirements-test.txt create mode 100644 requirements.in create mode 100644 requirements.txt create mode 100644 scripts/build_dashboard.py create mode 100644 scripts/check_dashboard.py create mode 100644 scripts/collect_evidence.py create mode 100644 scripts/collect_evidence_resume.py create mode 100644 scripts/demo_attachments.py create mode 100644 scripts/demo_pipeline.py create mode 100644 scripts/explain_history.py create mode 100644 scripts/init_secrets.py create mode 100644 scripts/lbctl.py create mode 100644 scripts/obs.py create mode 100644 scripts/restart.cmd create mode 100644 scripts/restart.sh create mode 100644 scripts/restore-api.sh create mode 100644 scripts/rolling-update.sh create mode 100644 scripts/stop-one.cmd create mode 100644 scripts/stop-one.sh create mode 100644 scripts/trace_demo.py create mode 100644 src/messenger/__init__.py create mode 100644 src/messenger/__main__.py create mode 100644 src/messenger/app.py create mode 100644 src/messenger/attachments.py create mode 100644 src/messenger/audit.py create mode 100644 src/messenger/authhdr.py create mode 100644 src/messenger/broker.py create mode 100644 src/messenger/config.py create mode 100644 src/messenger/cursor.py create mode 100644 src/messenger/db.py create mode 100644 src/messenger/docs.py create mode 100644 src/messenger/errors.py create mode 100644 src/messenger/healthcheck.py create mode 100644 src/messenger/images.py create mode 100644 src/messenger/imaging.py create mode 100644 src/messenger/jobctl.py create mode 100644 src/messenger/jobs.py create mode 100644 src/messenger/logging_setup.py create mode 100644 src/messenger/migrate.py create mode 100644 src/messenger/passwords.py create mode 100644 src/messenger/pipeline.py create mode 100644 src/messenger/relay.py create mode 100644 src/messenger/repo.py create mode 100644 src/messenger/s3_bootstrap.py create mode 100644 src/messenger/service.py create mode 100644 src/messenger/sessions.py create mode 100644 src/messenger/storage.py create mode 100644 src/messenger/telemetry.py create mode 100644 src/messenger/timefmt.py create mode 100644 src/messenger/validation.py create mode 100644 src/messenger/worker.py create mode 100644 student-tests/conftest.py create mode 100644 student-tests/imagegen.py create mode 100644 student-tests/test_api.py create mode 100644 student-tests/test_attachments.py create mode 100644 student-tests/test_balancing.py create mode 100644 student-tests/test_consistency.py create mode 100644 student-tests/test_db.py create mode 100644 student-tests/test_explain.py create mode 100644 student-tests/test_failures.py create mode 100644 student-tests/test_idempotency.py create mode 100644 student-tests/test_observability.py create mode 100644 student-tests/test_pipeline_flow.py create mode 100644 student-tests/test_sessions.py create mode 100644 student-tests/test_storage_failures.py create mode 100644 student-tests/unit/test_images.py create mode 100644 student-tests/unit/test_pipeline.py create mode 100644 student-tests/unit/test_telemetry.py create mode 100644 student-tests/unit/test_unit.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3c10fe5 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# LF everywhere: identical files on Windows/Linux and inside `git archive | docker build -`. +* text=auto eol=lf +*.png binary +# cmd.exe expects CRLF in batch files. +*.cmd text eol=crlf diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml new file mode 100644 index 0000000..80b299d --- /dev/null +++ b/.github/workflows/app.yml @@ -0,0 +1,42 @@ +name: Application (lab6) +on: [push, pull_request] +permissions: + contents: read +jobs: + app: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.13' + - name: Synthetic secrets and env (CI only, never committed) + run: python scripts/init_secrets.py && cp .env.example .env + - name: Build, migrate once, bootstrap S3, start broker, 2 API replicas, LB, relay, worker, Collector, Prometheus, Loki, Tempo, Grafana + run: docker compose --env-file .env up -d --build --wait + - name: Contract and public smoke + run: make check test PYTHON=python + - name: Persistence across restart of LB, API replicas, relay, worker, PostgreSQL, Valkey, S3, RabbitMQ + run: make test-persistence ACTION_SCRIPT=scripts/restart.sh PYTHON=python + - name: Failover of the replica that served the test, then restore it + run: | + make test-failover ACTION_SCRIPT=scripts/stop-one.sh PYTHON=python + sh scripts/restore-api.sh && python scripts/lbctl.py wait-up 2 + - name: Defense scenario - worker stopped, 202, 409, restart API and broker, ready + run: python -m pip install -q pillow==12.3.0 && python scripts/demo_pipeline.py + - name: Own tests (unit + stand; every failure is restored in finally) + run: | + python -m pip install --require-hashes --no-deps -r requirements.txt + python -m pip install -r requirements-test.txt + make student-test PYTHON=python + - name: Lab 6 - controlled trace in Tempo + logs in Loki, every dashboard query through Grafana + run: python scripts/trace_demo.py && python scripts/check_dashboard.py + - name: Lab 5 invariants (read-only audit of PostgreSQL and both buckets) + run: docker compose run --rm --no-deps auditor --verify-checksums + - name: Logs + if: always() + run: docker compose logs --tail 100 api lb s3 s3-init broker relay worker otel-collector prometheus loki tempo grafana + - name: Remove CI stand and its synthetic data + if: always() + run: docker compose down -v diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..74f4f55 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,67 @@ +# syntax=docker/dockerfile:1 +# Messenger, lab 5 (API replicas behind HAProxy, PostgreSQL + Valkey + S3 + RabbitMQ). Built by +# compose.yaml (services api, migrate, s3-init, relay, worker, auditor, jobctl: one image, different +# commands; only the worker imports Pillow). +# +# Python is interpreted, so there is no separate compile stage; the image +# contains only the interpreter, locked dependencies and the source code. +# Base image is pinned by version AND digest (python 3.13.16, Debian 12 bookworm). +FROM python:3.13.16-slim-bookworm@sha256:a1165e272e578941b84abc79e4ab38a0305cd12803a5c4247979ac7655f4d641 + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 + +WORKDIR /app + +# 1. Dependencies first (layer cache survives source edits). Every package, +# including transitive ones, is pinned with sha256 hashes in requirements.txt; +# --no-deps guarantees nothing outside the lock file is installed. +COPY requirements.txt ./ +RUN pip install --root-user-action=ignore --require-hashes --no-deps -r requirements.txt + +# 2. JPEG integrity check: libjpeg-turbo's djpeg (strict mode, see src/messenger/images.py). +# Version pinned to the Debian 12 package; apt lists are removed in the same layer. +RUN apt-get update \ + && apt-get install -y --no-install-recommends libjpeg-turbo-progs=1:2.1.5-2 \ + && rm -rf /var/lib/apt/lists/* + +# 3. Unprivileged runtime user. Code stays owned by root, so the process +# cannot modify its own code. +RUN groupadd --system --gid 10001 app \ + && useradd --system --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app + +COPY src/ ./src/ +# Versioned SQL migrations, applied by `python -m messenger.migrate` (compose service migrate). +COPY migrations/ ./migrations/ +# Course contract, served read-only at /openapi.json for Swagger UI (/docs). +COPY contracts/openapi.json ./contracts/openapi.json + +# Non-secret defaults; compose.yaml passes the rest. Passwords come only as files +# (DATABASE_URL_FILE / CACHE_URL_FILE -> Docker secrets), never as ENV or COPY. +ENV PYTHONPATH=/app/src \ + APP_HOST=0.0.0.0 \ + APP_PORT=8080 \ + APP_ENV=lab \ + LOG_LEVEL=info \ + SHUTDOWN_TIMEOUT_SECONDS=8 \ + DOCS_ENABLED=true \ + SESSION_TTL_SECONDS=3600 \ + DATABASE_URL_FILE=/run/secrets/database_url + +# Build revision (scripts/rolling-update.sh passes git commit + time): makes every rolled-out +# image distinguishable in `docker inspect` and in the "starting" log line of each replica. +ARG BUILD_REVISION=dev +LABEL org.opencontainers.image.revision=$BUILD_REVISION +ENV APP_REVISION=$BUILD_REVISION + +USER app:app +EXPOSE 8080 +STOPSIGNAL SIGTERM + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD ["python", "-m", "messenger.healthcheck"] + +# Exec form: the Python server is PID 1 and receives SIGTERM directly (no shell in between). +CMD ["python", "-m", "messenger"] diff --git a/Makefile b/Makefile index 5ad43ad..5c940fb 100644 --- a/Makefile +++ b/Makefile @@ -31,3 +31,112 @@ test-failover: test-security: $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +# --------------------------------------------------------------------------- +# Student solution (lab 5, Python). On Windows: PowerShell/Git Bash with GNU make, public +# tests need PYTHONUTF8=1, and the hooks are started through scripts/*.cmd (Git Bash). +.PHONY: grafana alerts trace-demo dashboard dashboard-check incidents track1 obs-test secrets up down logs ps migrate student-test unit-test explain lb-status restore rolling-update failover-series bench-memory worker-stop worker-start jobs failed audit track2 + +secrets: + $(PYTHON) scripts/init_secrets.py + +# Build, apply migrations ONCE (service migrate), start broker, API replicas, LB, relay and worker. +up: secrets + docker compose up -d --build --wait + +# Safe stop: containers stop, named volumes (data, queue) stay. +down: + docker compose down + +logs: + docker compose logs --tail 50 api lb relay worker + +ps: + docker compose ps -a + +migrate: + docker compose run --rm migrate + +# HAProxy view of the replicas (UP/DOWN) mapped to containers and X-Instance-Id. +lb-status: + $(PYTHON) scripts/lbctl.py status + $(PYTHON) scripts/lbctl.py replicas + +# Start replicas stopped by scripts/stop-one.sh again and wait until the LB has them all UP. +restore: + sh scripts/restore-api.sh + $(PYTHON) scripts/lbctl.py wait-up $${API_REPLICAS:-2} + +# Replace every API replica one by one with a freshly built image (no downtime). +rolling-update: + sh scripts/rolling-update.sh + +# Lab 3: stop each replica in turn under load, measure RPS/errors/recovery (evidence/failover/). +failover-series: + $(PYTHON) bench/failover_series.py --output evidence/failover + +# Lab 5 demo: stop the worker (uploads still get 202, content answers 409), start it again. +worker-stop: + docker compose stop worker + +worker-start: + docker compose start worker + +# Lab 5 operator view: jobs by state + outbox backlog; failed registry (replay: see REPORT.md). +jobs: + docker compose run --rm --no-deps jobctl stats + +failed: + docker compose run --rm --no-deps jobctl list-failed + +# Track 2: read-only check of the pipeline invariants over PostgreSQL and both buckets. +audit: + docker compose run --rm --no-deps auditor + +# Track 2: automatic fault-injection matrix (duplicate, reorder, crashes, stale versions). +track2: + $(PYTHON) bench/pipeline_faults.py --output evidence/track2 + +# Own tests: unit + black-box against the running stand (needs requirements*.txt in a venv). +student-test: + $(PYTHON) -m pytest student-tests -v + +unit-test: + $(PYTHON) -m pytest student-tests -m "not stack" -q + +explain: + $(PYTHON) scripts/explain_history.py --output evidence/explain-history.txt + +# Lab 4: peak RAM of the replicas under 16 simultaneous uploads (evidence/memory/). +bench-memory: + $(PYTHON) bench/upload_memory.py --output evidence/memory + +# --------------------------------------------------------------------------- +# Lab 6: observability (docs/OBSERVABILITY.md, docs/SLO.md, docs/RUNBOOK.md, docs/TRACK1.md) +grafana: + @echo "Grafana: http://127.0.0.1:3000 user admin, password in secrets/grafana_admin_password" + +alerts: + $(PYTHON) scripts/obs.py alerts + +# Controlled request with our own traceparent -> its trace in Tempo + its logs in Loki. +trace-demo: + $(PYTHON) scripts/trace_demo.py --output evidence/trace-demo.txt + +# Regenerate the dashboard JSON / run every dashboard query through Grafana. +dashboard: + $(PYTHON) scripts/build_dashboard.py + +dashboard-check: + $(PYTHON) scripts/check_dashboard.py --output evidence/dashboard-check.txt + +# Level 4 incidents under load (worker stop, DB lock, slow handler, backend/collector down). +incidents: + $(PYTHON) bench/incidents.py all + +# Track 1: price of observability (off / full / head10 / tail), 3 runs each. +track1: + $(PYTHON) bench/track1.py --runs 3 --output evidence/track1 + +obs-test: + $(PYTHON) -m pytest student-tests/test_observability.py -v diff --git a/bench/failover_series.py b/bench/failover_series.py new file mode 100644 index 0000000..b4c5daf --- /dev/null +++ b/bench/failover_series.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Level 4: stop EACH API replica in turn under load (restoring the previous one first) and +measure RPS, errors and recovery. Modes: graceful `stop` (SIGTERM + drain), `kill` (SIGKILL) +and `pause` (frozen process: the kernel still accepts TCP, nothing answers - the worst case +for detection, only the active health check can find it). + + python bench/failover_series.py --output evidence/failover # ~5 min for 2 replicas x 3 modes + +Timeline of one round (all times from the moment the stop command is issued): + warm-up 6 s -> stop replica -> 12 s with it down -> start it again -> wait until HAProxy + has every replica UP (rejoin time) -> 6 s steady state. +Measured per round: requests/ok/failed and ok-RPS before / during / after, the last failed +request (+s), the first moment after which the stopped replica never answered again +(= removal from rotation), time until the restarted replica is UP in HAProxy and serves +traffic again, plus the history check (no confirmed message lost, no duplicate). +Output: /series.json (summary), /timeline--.csv (per second), +/series.md (table for REPORT.md). No tokens are written. +""" +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import json +import platform +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(ROOT / "bench")) +import lbctl # noqa: E402 +from loadgen import Load # noqa: E402 + + +def docker(*args: str) -> str: + return subprocess.run(["docker", *args], capture_output=True, text=True, check=True, timeout=120).stdout + + +def one_round(replica: dict, mode: str, replicas: int, workers: int, out: Path) -> dict: + load = Load(workers).start() + time.sleep(6) + t_stop = load.now() + if mode == "pause": + docker("pause", replica["id"]) + else: + docker("stop", "--time", "15" if mode == "stop" else "0", replica["id"]) + t_stopped = load.now() + time.sleep(12) + t_start = load.now() + docker("unpause" if mode == "pause" else "start", replica["id"]) + lbctl.wait_up(replicas, timeout=90) + t_up = load.now() + # The restarted container keeps its hostname: wait until it serves requests again. + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + if any(e[3] == replica["hostname"] and e[0] > t_up for e in load.events): + break + time.sleep(0.1) + t_serves = load.now() + time.sleep(6) + load.stop() + t_end = load.now() + + failed_after_stop = [e for e in load.events if e[0] >= t_stop and e[2] not in (200, 201)] + served_by_target = [e[0] for e in load.events if e[3] == replica["hostname"] and t_stop <= e[0] < t_start] + out_of_rotation = (max(served_by_target) - t_stop) if served_by_target else 0.0 + rows = load.per_second() + with (out / f"timeline-{mode}-{replica['name']}.csv").open("w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=["second", "ok", "failed", "instances"]) + writer.writeheader() + for row in rows: + row = dict(row) + row["instances"] = row["instances"].replace(replica["hostname"], "TARGET") + writer.writerow(row) + state = json.loads(docker("inspect", replica["id"]))[0]["State"] + return { + "mode": mode, "replica": replica["name"], "instance_id": replica["hostname"], + "stop_command_seconds": round(t_stopped - t_stop, 2), + "before": load.window(0.5, t_stop), "during": load.window(t_stop, t_start), "after": load.window(t_serves, t_end), + "failed_after_stop": len(failed_after_stop), + "failed_statuses": sorted({e[2] for e in failed_after_stop}), + "last_failure_after_stop_s": round(max((e[0] for e in failed_after_stop), default=t_stop) - t_stop, 3), + "target_last_served_after_stop_s": round(out_of_rotation, 3), + "rejoin_up_in_lb_s": round(t_up - t_start, 2), "rejoin_serving_s": round(t_serves - t_start, 2), + "client_retries_same_key": load.retries, + "history": load.verify_history(), + "restarted_state": f"{state['Status']} health={(state.get('Health') or {}).get('Status')}", + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--output", default="evidence/failover") + parser.add_argument("--modes", default="stop,kill,pause") + parser.add_argument("--workers", type=int, default=4) + args = parser.parse_args() + out = ROOT / args.output + out.mkdir(parents=True, exist_ok=True) + replicas = sorted((r for r in lbctl.replicas() if r["state"] == "running"), key=lambda r: r["name"]) + assert len(replicas) >= 2, "need at least two running replicas" + lbctl.wait_up(len(replicas)) + results = [] + for mode in args.modes.split(","): + for replica in replicas: # each replica in turn; the previous one is already restored + print(f"== {mode} {replica['name']} ...", flush=True) + result = one_round(replica, mode, len(replicas), args.workers, out) + results.append(result) + print(json.dumps({k: result[k] for k in ("failed_after_stop", "last_failure_after_stop_s", + "target_last_served_after_stop_s", "rejoin_serving_s")}), flush=True) + meta = {"date": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"), + "commit": subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True, + text=True).stdout.strip(), + "host": f"{platform.system()} {platform.release()}, docker {docker('version', '--format', '{{.Server.Version}}').strip()}", + "workload": f"{args.workers} closed-loop workers from the host via 127.0.0.1:8080: POST message " + "(Idempotency-Key, uncertain -> same key) + GET last page; client timeout 3 s", + "lb": "HAProxy: check GET /health/ready inter 1s fastinter 500ms fall 2 rise 2, timeout check 1s; " + "retry-on conn-failure + redispatch", + "api": "DRAIN_SECONDS=3, SHUTDOWN_TIMEOUT_SECONDS=8, stop_grace_period 15s"} + (out / "series.json").write_text(json.dumps({"meta": meta, "rounds": results}, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8") + lines = ["| Режим | Реплика | Запросов во время отказа | Ошибок после stop | ok-RPS до / во время / после | " + "Последняя ошибка, с | Цель ушла из ротации, с | Возврат в LB / обслуживает, с | Потери / дубли |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |"] + for r in results: + h = r["history"] + lines.append(f"| {r['mode']} | {r['replica']} | {r['during']['requests']} | {r['failed_after_stop']} " + f"{r['failed_statuses'] or ''} | {r['before']['ok_rps']} / {r['during']['ok_rps']} / {r['after']['ok_rps']} | " + f"{r['last_failure_after_stop_s']} | {r['target_last_served_after_stop_s']} | " + f"{r['rejoin_up_in_lb_s']} / {r['rejoin_serving_s']} | " + f"{h['lost_confirmed']} / {h['duplicate_ids'] + h['duplicate_texts']} |") + (out / "series.md").write_text("\n".join([f"Дата {meta['date']}, commit {meta['commit']}. {meta['workload']}.", "", + *lines, ""]), encoding="utf-8") + print("\n".join(lines)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/bench/incidents.py b/bench/incidents.py new file mode 100644 index 0000000..f8ae7be --- /dev/null +++ b/bench/incidents.py @@ -0,0 +1,424 @@ +#!/usr/bin/env python3 +"""Lab 6 level 4: controlled incidents under load, found and timed with the STORED observations. + + python bench/incidents.py worker-stop # (1) worker stopped -> queue lag alert -> resolved + python bench/incidents.py db-lock # (2a) slow/blocked database (table lock held 90 s) + python bench/incidents.py slow-handler # (2b) contrast: slow handler code, healthy database + python bench/incidents.py backend-down # (3a) Tempo + Loki stopped: API unaffected, Collector bounded + python bench/incidents.py collector-down # (3b) Collector stopped: SDK queues bounded, API unaffected + python bench/incidents.py all +Results: evidence/incidents/.json (timeline, alert times, metric snapshots, client counts) +and .txt (human-readable). Every incident restores the stand in `finally`. + +Load during every incident (own threads, fixed pacing): 4 writers posting messages +(~8 req/s in total) and 1 uploader (one PNG every 2 s). Client-side counts are kept separately +from the telemetry, so the effect of an incident on users is measured independently of it. +""" +from __future__ import annotations + +import argparse +import base64 +import json +import os +import secrets +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +import obs # noqa: E402 + +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") + "/api/v1" +OUT = ROOT / "evidence" / "incidents" +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() + + +# ----------------------------------------------------------------------------- HTTP + load +def http(method: str, path: str, body=None, headers=None, raw: bytes | None = None, timeout: float = 15): + h = dict(headers or {}) + data = raw + if body is not None: + data = json.dumps(body).encode() + h["Content-Type"] = "application/json" + request = urllib.request.Request(BASE + path, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(request, timeout=timeout) as r: + return r.status, r.headers, json.loads(r.read() or b"null") + except urllib.error.HTTPError as exc: + return exc.code, exc.headers, None + + +def new_actor() -> dict: + username = "inc_" + uuid.uuid4().hex[:12] + password = "Incident-" + secrets.token_hex(8) + _, _, user = http("POST", "/users", {"username": username, "display_name": "load", "password": password}) + auth = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode() + _, _, session = http("POST", "/auth/sessions", headers={"Authorization": auth}) + headers = {"Authorization": "Bearer " + session["token"]} + _, _, chat = http("POST", "/chats", {"title": "incident load", "member_ids": [user["id"]]}, headers) + return {"headers": headers, "chat": chat["id"]} + + +class Load: + """Background traffic; per-second client-side outcome counts (status classes, timeouts).""" + + def __init__(self, writers: int = 4, write_interval: float = 0.5, upload_interval: float = 2.0): + self.actors = [new_actor() for _ in range(writers + 1)] + self.write_interval, self.upload_interval = write_interval, upload_interval + self.stop = threading.Event() + self.lock = threading.Lock() + self.events: list[tuple[float, str, int, float]] = [] # (time, kind, status, latency) + self.uploads: list[tuple[float, str]] = [] # (accepted at, attachment id) + self.threads = [threading.Thread(target=self.writer, args=(a,), daemon=True) for a in self.actors[:-1]] + self.threads.append(threading.Thread(target=self.uploader, args=(self.actors[-1],), daemon=True)) + + def record(self, kind: str, status: int, began: float) -> None: + with self.lock: + self.events.append((time.time(), kind, status, time.perf_counter() - began)) + + def writer(self, actor: dict) -> None: + while not self.stop.is_set(): + began = time.perf_counter() + try: + status, _, _ = http("POST", f"/chats/{actor['chat']}/messages", {"text": "load"}, + {**actor["headers"], "Idempotency-Key": uuid.uuid4().hex}, timeout=10) + except Exception: # noqa: BLE001 - timeout / connection error + status = 0 + self.record("message", status, began) + self.stop.wait(max(0.0, self.write_interval - (time.perf_counter() - began))) + + def uploader(self, actor: dict) -> None: + while not self.stop.is_set(): + began = time.perf_counter() + try: + status, _, body = http("POST", f"/chats/{actor['chat']}/attachments?filename=load.png", raw=SAMPLE, + headers={**actor["headers"], "Content-Type": "image/png"}, timeout=15) + if status == 202: + with self.lock: + self.uploads.append((time.time(), body["id"])) + except Exception: # noqa: BLE001 + status = 0 + self.record("upload", status, began) + self.stop.wait(max(0.0, self.upload_interval - (time.perf_counter() - began))) + + def __enter__(self): + for t in self.threads: + t.start() + return self + + def __exit__(self, *exc): + self.stop.set() + for t in self.threads: + t.join(20) + + def summary(self, start: float, end: float) -> dict: + with self.lock: + ev = [e for e in self.events if start <= e[0] < end] + out = {} + for kind in ("message", "upload"): + rows = [e for e in ev if e[1] == kind] + lat = sorted(e[3] for e in rows if 200 <= e[2] < 300) + out[kind] = {"total": len(rows), + "2xx": sum(200 <= e[2] < 300 for e in rows), "4xx": sum(400 <= e[2] < 500 for e in rows), + "5xx": sum(e[2] >= 500 for e in rows), "no_response": sum(e[2] == 0 for e in rows), + "p50_ms": _pct(lat, 0.50), "p95_ms": _pct(lat, 0.95), "p99_ms": _pct(lat, 0.99)} + return out + + +def _pct(values: list[float], q: float): + if not values: + return None + return round(values[min(len(values) - 1, int(q * len(values)))] * 1000, 1) + + +# ----------------------------------------------------------------------------- stand control +def compose(*args: str, timeout: float = 180) -> str: + return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", + timeout=timeout, check=True).stdout + + +def docker_mem(service: str) -> float | None: + """Current memory (MiB) of a compose service's first container, from `docker stats`.""" + ids = compose("ps", "-q", service).split() + if not ids: + return None + raw = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", ids[0]], + capture_output=True, text=True).stdout.split("/")[0].strip() + num = float("".join(c for c in raw if c.isdigit() or c == ".")) + return round(num / 1024 if raw.endswith("KiB") else num * 1024 if raw.endswith("GiB") else num, 1) + + +class Timeline: + def __init__(self, name: str): + self.name = name + self.t0 = time.time() + self.rows: list[dict] = [] + self.lines: list[str] = [] + + def mark(self, what: str, **data) -> float: + now = time.time() + self.rows.append({"t": round(now - self.t0, 1), "event": what, **data}) + line = f"+{now - self.t0:7.1f} s {what}" + (f" {json.dumps(data, ensure_ascii=False)}" if data else "") + print(line, flush=True) + self.lines.append(line) + return now + + +def wait_alert(tl: Timeline, alert: str, state: str, since: float, timeout: float) -> float | None: + """Poll Prometheus every 2 s; returns seconds from `since` to the alert reaching `state`.""" + deadline = time.time() + timeout + last = None + while time.time() < deadline: + current = obs.alert_state(alert) + if current != last: + tl.mark(f"alert {alert}: {current}") + last = current + if (state == "resolved" and current == "inactive") or current == state: + return round(time.time() - since, 1) + time.sleep(2) + tl.mark(f"alert {alert}: still {last} after {timeout} s") + return None + + +def wait_quiet(tl: Timeline, timeout: float = 420) -> None: + """Start every incident from a calm stand: no alert pending/firing (a previous incident's alert + would otherwise make the detection time look like 0 s).""" + deadline = time.time() + timeout + while time.time() < deadline: + active = [a["name"] for a in obs.alerts()] + if not active: + tl.mark("stand quiet: no pending/firing alerts") + return + time.sleep(5) + raise SystemExit(f"alerts still active after {timeout} s: {active}") + + +def snapshot(queries: dict[str, str]) -> dict: + out = {} + for name, expr in queries.items(): + try: + value = obs.scalar(expr) + out[name] = None if value is None else round(value, 4) + except Exception as exc: # noqa: BLE001 + out[name] = f"error: {type(exc).__name__}" + return out + + +Q_API = { + "rps": "messenger:http_requests:rate1m", + "error_ratio_5xx": "messenger:http_error_ratio:rate1m", + "p99_s": "messenger:http_latency:p99_2m", + "db_p95_s_api": 'histogram_quantile(0.95, sum by (le) (rate(db_client_operation_duration_seconds_bucket{job="messenger-api"}[1m])))', + "db_pool_waiting_api": 'sum(db_client_connection_pending_requests{job="messenger-api"})', + "db_pool_used_api": 'sum(db_client_connection_count{job="messenger-api", db_client_connection_state="used"})', +} +Q_QUEUE = { + "queued": 'max(messenger_queue_depth{state="queued"})', + "oldest_age_s": "max(messenger_queue_oldest_age_seconds)", + "jobs_succeeded_per_s": 'sum(rate(messenger_jobs_processed_total{outcome="succeeded"}[1m]))', + "worker_busy": "sum(messenger_worker_busy)", + "time_to_ready_p95_s": 'histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[2m])))', +} +Q_COLLECTOR = { + "collector_rss_mib": "otelcol_process_memory_rss / 1048576", + "spans_accepted_per_s": "sum(rate(otelcol_receiver_accepted_spans[1m]))", + "spans_failed_total": "sum(otelcol_exporter_send_failed_spans) or vector(0)", + "logs_failed_total": "sum(otelcol_exporter_send_failed_log_records) or vector(0)", + "queue_size_tempo": 'max(otelcol_exporter_queue_size{exporter="otlp_http/tempo"})', + "queue_capacity_tempo": 'max(otelcol_exporter_queue_capacity{exporter="otlp_http/tempo"})', + "sdk_export_failures_total": 'sum(messenger_telemetry_spans_exported_total{result="failure"}) or vector(0)', +} + + +# ----------------------------------------------------------------------------- incidents +def worker_stop(tl: Timeline, load: Load) -> dict: + """(1) The worker is stopped: uploads still get 202, nothing is processed. Expected: queue + depth and the oldest job age grow -> MessengerQueueLagGrowing firing; after the start the + backlog drains -> resolved. HTTP SLIs stay green (the API does not depend on the worker).""" + time.sleep(30) + result = {"before": {**snapshot(Q_API), **snapshot(Q_QUEUE)}} + start = tl.mark("FAULT: docker compose stop worker") + compose("stop", "worker") + try: + result["detect_s"] = wait_alert(tl, "MessengerQueueLagGrowing", "firing", start, 240) + result["during"] = {**snapshot(Q_API), **snapshot(Q_QUEUE)} + result["during_client"] = load.summary(start, time.time()) + tl.mark("observed during", **result["during"]) + finally: + fixed = tl.mark("FIX: docker compose start worker") + compose("start", "worker") + result["resolve_s"] = wait_alert(tl, "MessengerQueueLagGrowing", "resolved", fixed, 300) + result["after"] = {**snapshot(Q_API), **snapshot(Q_QUEUE)} + tl.mark("observed after", **result["after"]) + result["client_total"] = load.summary(tl.t0, time.time()) + return result + + +def db_lock(tl: Timeline, load: Load) -> dict: + """(2a) A long transaction holds an EXCLUSIVE lock on `messages` for 150 s (an "ALTER TABLE"/ + migration-like incident). Message writes wait for the lock until lock_timeout and answer 503; + reads keep working. Expected: 5xx ratio and p99 grow, DB pool waits; the trace of a failed + POST shows the time inside the `db ...` span (error LockNotAvailable), not in handler code.""" + time.sleep(30) + result = {"before": snapshot(Q_API)} + sql = "BEGIN; LOCK TABLE messages IN EXCLUSIVE MODE; SELECT pg_sleep(150); COMMIT;" + start = tl.mark("FAULT: psql holds LOCK TABLE messages IN EXCLUSIVE MODE for 150 s") + locker = subprocess.Popen(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", + "-c", sql], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + result["detect_error_s"] = wait_alert(tl, "MessengerApiHighErrorRate", "firing", start, 140) + result["during"] = snapshot(Q_API) + tl.mark("observed during", **result["during"]) + result["during_client"] = load.summary(start, time.time()) + result["example_trace"] = example_trace('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && status = error }') + result["pg_locks"] = subprocess.run( + ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", + "SELECT state, wait_event_type, wait_event, count(*), max(now() - xact_start)::text " + "FROM pg_stat_activity WHERE datname = 'messenger' AND state <> 'idle' GROUP BY 1, 2, 3"], + cwd=ROOT, capture_output=True, text=True, encoding="utf-8").stdout.strip().splitlines() + tl.mark("pg_stat_activity lock waits", waits=result["pg_locks"]) + finally: + locker.wait(200) + fixed = tl.mark("FIX: lock released (transaction ended)") + result["resolve_s"] = wait_alert(tl, "MessengerApiHighErrorRate", "resolved", fixed, 240) + result["after"] = snapshot(Q_API) + result["client_total"] = load.summary(tl.t0, time.time()) + return result + + +def slow_handler(tl: Timeline, load: Load) -> dict: + """(2b) Contrast to (2a): API_FAULT_POINTS=slow_handler=1500 - 1.5 s of handler code before the + database call in POST messages, database healthy. Expected: p99 > 1 s -> MessengerApiLatencyHigh, + NO 5xx, DB p95 unchanged; the trace shows a 1.5 s server span whose `db` child is a few ms.""" + time.sleep(30) + result = {"before": snapshot(Q_API)} + env = {**os.environ, "API_FAULT_POINTS": "slow_handler=1500"} + start = tl.mark("FAULT: api recreated with API_FAULT_POINTS=slow_handler=1500") + subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--wait", "api"], cwd=ROOT, env=env, + capture_output=True, check=True, timeout=180) + try: + result["detect_s"] = wait_alert(tl, "MessengerApiLatencyHigh", "firing", start, 300) + result["during"] = snapshot(Q_API) + tl.mark("observed during", **result["during"]) + result["during_client"] = load.summary(start, time.time()) + result["example_trace"] = example_trace('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && duration > 1s }') + finally: + fixed = tl.mark("FIX: api recreated without fault points") + clean = {k: v for k, v in os.environ.items() if k != "API_FAULT_POINTS"} + subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--wait", "api"], cwd=ROOT, env=clean, + capture_output=True, check=True, timeout=180) + result["resolve_s"] = wait_alert(tl, "MessengerApiLatencyHigh", "resolved", fixed, 300) + result["after"] = snapshot(Q_API) + result["client_total"] = load.summary(tl.t0, time.time()) + return result + + +def backend_down(tl: Timeline, load: Load) -> dict: + """(3a) Tempo and Loki stopped for ~4 min. Expected: API/worker unaffected (client counts), the + Collector retries into a BOUNDED queue (size <= capacity), then drops and counts + (send_failed), its RSS stays under the memory_limiter; TelemetryExportFailing fires.""" + time.sleep(20) + result = {"before": {**snapshot(Q_API), **snapshot(Q_COLLECTOR)}, "collector_mem_mib": []} + start = tl.mark("FAULT: docker compose stop tempo loki") + compose("stop", "tempo", "loki") + try: + # failures appear only after the exporter gave up (retry max_elapsed_time 60 s), then the + # 2 min rate window and `for: 30s`: 120-190 s were measured, so wait up to 240 s. + result["detect_s"] = wait_alert(tl, "TelemetryExportFailing", "firing", start, 240) + while time.time() - start < 250: + result["collector_mem_mib"].append(docker_mem("otel-collector")) + time.sleep(10) + result["during"] = {**snapshot(Q_API), **snapshot(Q_COLLECTOR)} + tl.mark("observed during", **result["during"], collector_mem_mib=result["collector_mem_mib"]) + result["during_client"] = load.summary(start, time.time()) + finally: + fixed = tl.mark("FIX: docker compose start tempo loki") + compose("start", "tempo", "loki") + result["resolve_s"] = wait_alert(tl, "TelemetryExportFailing", "resolved", fixed, 300) + result["after"] = {**snapshot(Q_API), **snapshot(Q_COLLECTOR)} + result["client_total"] = load.summary(tl.t0, time.time()) + return result + + +def collector_down(tl: Timeline, load: Load) -> dict: + """(3b) The Collector itself stopped for 2 min. Expected: API unaffected; the SDK exporters fail + fast (3 s timeout) in their background threads, BatchSpanProcessor drops beyond 2048 queued + spans, API memory flat. Counted afterwards: messenger_telemetry_spans_exported_total{result=failure} + (cumulative, delivered once the Collector is back). Metrics of the outage window are missing: + a gap in the graphs, not a lie.""" + time.sleep(20) + api_mem = [] + result = {"before": {**snapshot(Q_API), **snapshot(Q_COLLECTOR)}} + start = tl.mark("FAULT: docker compose stop otel-collector") + compose("stop", "otel-collector") + try: + while time.time() - start < 120: + api_mem.append(docker_mem("api")) + time.sleep(10) + result["api_mem_mib"] = api_mem + result["during_client"] = load.summary(start, time.time()) + tl.mark("client during outage", **result["during_client"]["message"], api_mem_mib=api_mem) + finally: + tl.mark("FIX: docker compose start otel-collector") + compose("start", "otel-collector") + time.sleep(45) + result["after"] = {**snapshot(Q_API), **snapshot(Q_COLLECTOR)} + tl.mark("observed after", **result["after"]) + result["client_total"] = load.summary(tl.t0, time.time()) + return result + + +def example_trace(traceql: str) -> dict | None: + """First matching trace: its span tree as text (the diagnosis evidence).""" + time.sleep(8) + found = obs.search(traceql, minutes=5, limit=5) + if not found: + return None + trace_id = found[0]["traceID"] + return {"traceql": traceql, "trace_id": trace_id, "tree": obs.tree(obs.trace_spans(trace_id)).splitlines()} + + +INCIDENTS = {"worker-stop": worker_stop, "db-lock": db_lock, "slow-handler": slow_handler, + "backend-down": backend_down, "collector-down": collector_down} + + +def run(name: str) -> dict: + print(f"\n=== incident {name}") + tl = Timeline(name) + wait_quiet(tl) + with Load() as load: + tl.mark("load started (4 writers x 2 req/s, 1 upload / 2 s)") + result = INCIDENTS[name](tl, load) + result.update({"incident": name, "timeline": tl.rows, "doc": INCIDENTS[name].__doc__.strip()}) + OUT.mkdir(parents=True, exist_ok=True) + (OUT / f"{name}.json").write_text(json.dumps(result, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") + text = [f"incident {name}: {time.strftime('%Y-%m-%d %H:%M:%S')}", INCIDENTS[name].__doc__.strip(), "", *tl.lines, ""] + for key in ("detect_s", "detect_error_s", "resolve_s"): + if key in result: + text.append(f"{key}: {result[key]}") + for key in ("before", "during", "after", "during_client", "client_total"): + if key in result: + text.append(f"{key}: {json.dumps(result[key], ensure_ascii=False)}") + if result.get("example_trace"): + text += ["", f"example trace ({result['example_trace']['traceql']}):", *result["example_trace"]["tree"]] + (OUT / f"{name}.txt").write_text("\n".join(text) + "\n", encoding="utf-8", newline="\n") + return result + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("incident", choices=[*INCIDENTS, "all"]) + args = parser.parse_args() + for name in (INCIDENTS if args.incident == "all" else [args.incident]): + run(name) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bench/loadgen.py b/bench/loadgen.py new file mode 100644 index 0000000..97a94de --- /dev/null +++ b/bench/loadgen.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Background HTTP traffic through the LB for failover / rolling-update experiments (level 4). + +Closed loop, N worker threads, each: POST a message (Idempotency-Key) + GET the last page. +An uncertain POST (timeout, connection error, 5xx) is retried with the SAME key and body, +exactly as a correct client must do; the history is checked afterwards for losses and +duplicates. Every request is recorded as (t, kind, status, instance, latency). +This is a correctness/availability probe, not a capacity benchmark (see bench/track1 for that). + + python bench/loadgen.py --duration 30 --workers 4 # prints a summary JSON +""" +from __future__ import annotations + +import argparse +import base64 +import json +import math +import os +import threading +import time +import uuid +from collections import Counter, defaultdict + +import urllib.error +import urllib.request + +BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") + + +class Http: + """Minimal stdlib client with keep-alive per thread (http.client under urllib is not).""" + + def __init__(self, base_url: str, timeout: float): + import http.client + from urllib.parse import urlsplit + parts = urlsplit(base_url) + self.host, self.port = parts.hostname, parts.port or 80 + self.timeout = timeout + self.factory = lambda: http.client.HTTPConnection(self.host, self.port, timeout=self.timeout) + self.conn = self.factory() + + def request(self, method: str, path: str, body: bytes | None = None, headers: dict | None = None): + try: + self.conn.request(method, path, body=body, headers=headers or {}) + response = self.conn.getresponse() + data = response.read() + if response.getheader("connection", "").lower() == "close": + self.conn.close() + self.conn = self.factory() + return response.status, dict(response.getheaders()), data + except Exception: + self.conn.close() + self.conn = self.factory() + raise + + +def call(method: str, path: str, body=None, headers=None, timeout=10.0): + data = json.dumps(body).encode() if body is not None else None + h = {"Content-Type": "application/json", **(headers or {})} + req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return r.status, json.loads(r.read() or b"null") + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read() or b"null") + + +def make_user(label: str) -> dict: + username = f"{label}_{uuid.uuid4().hex[:12]}" + password = "Load-password-" + uuid.uuid4().hex + status, user = call("POST", "/api/v1/users", {"username": username, "display_name": label, "password": password}) + assert status == 201, (status, user) + cred = base64.b64encode(f"{username}:{password}".encode()).decode() + status, session = call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}) + assert status == 201, (status, session) + return {"id": user["id"], "token": session["token"]} + + +class Load: + def __init__(self, workers: int = 4, timeout: float = 3.0, pause: float = 0.0): + self.workers = workers + self.timeout = timeout + self.pause = pause + self.alice, self.bob = make_user("load"), make_user("load") + status, chat = call("POST", "/api/v1/chats", {"title": "load", "member_ids": [self.alice["id"], self.bob["id"]]}, + headers={"Authorization": "Bearer " + self.alice["token"]}) + assert status == 201, chat + self.chat = chat + self.stop_event = threading.Event() + self.lock = threading.Lock() + self.events: list[tuple[float, str, int, str, float]] = [] + self.confirmed: dict[str, dict] = {} + self.retries = 0 + self.t0 = time.monotonic() + self.threads = [threading.Thread(target=self._worker, args=(i,), daemon=True) for i in range(workers)] + + def now(self) -> float: + return time.monotonic() - self.t0 + + def _record(self, kind: str, status: int, instance: str, latency: float) -> None: + with self.lock: + self.events.append((round(self.now(), 4), kind, status, instance, round(latency * 1000, 2))) + + def _worker(self, index: int) -> None: + http = Http(BASE_URL, self.timeout) + auth = {"Authorization": "Bearer " + self.alice["token"]} + path = f"/api/v1/chats/{self.chat['id']}/messages" + n, key = 0, uuid.uuid4().hex + text = f"w{index}-0-{key[:6]}" + while not self.stop_event.is_set(): + started = time.monotonic() + try: + status, headers, data = http.request("POST", path, json.dumps({"text": text}).encode(), + {**auth, "Idempotency-Key": key, "Content-Type": "application/json"}) + instance = headers.get("x-instance-id") or headers.get("X-Instance-Id") or "-" + except Exception: + status, instance, data = 0, "-", b"" + self._record("POST", status, instance, time.monotonic() - started) + if status == 201: + msg = json.loads(data) + with self.lock: + self.confirmed[msg["id"]] = msg + n += 1 + key = uuid.uuid4().hex + text = f"w{index}-{n}-{key[:6]}" + elif status in (0, 502, 503, 504, 500): + with self.lock: + self.retries += 1 # same key + same text on the next iteration + started = time.monotonic() + try: + status, headers, _ = http.request("GET", path + "?limit=5", None, auth) + instance = headers.get("x-instance-id") or headers.get("X-Instance-Id") or "-" + except Exception: + status, instance = 0, "-" + self._record("GET", status, instance, time.monotonic() - started) + if self.pause: + time.sleep(self.pause) + + def start(self) -> "Load": + self.t0 = time.monotonic() + for t in self.threads: + t.start() + return self + + def stop(self) -> None: + self.stop_event.set() + for t in self.threads: + t.join(timeout=15) + + def verify_history(self) -> dict: + """Walk the whole history with the second user: no confirmed message lost, no duplicate.""" + items, cursor = [], None + while True: + q = "?limit=100" + (f"&cursor={cursor}" if cursor else "") + status, page = call("GET", f"/api/v1/chats/{self.chat['id']}/messages{q}", + headers={"Authorization": "Bearer " + self.bob["token"]}, timeout=30) + assert status == 200, page + items += page["items"] + cursor = page["next_cursor"] + if not cursor: + break + ids = [m["id"] for m in items] + texts = [m["text"] for m in items] + lost = [i for i in self.confirmed if i not in set(ids)] + changed = [m for m in items if m["id"] in self.confirmed and self.confirmed[m["id"]] != m] + return {"history_messages": len(items), "confirmed_messages": len(self.confirmed), + "lost_confirmed": len(lost), "altered_confirmed": len(changed), + "duplicate_ids": len(ids) - len(set(ids)), "duplicate_texts": len(texts) - len(set(texts)), + "unconfirmed_but_stored": len(set(ids) - set(self.confirmed))} + + # ------------------------------------------------------------------ summaries + def window(self, start: float, end: float) -> dict: + ev = [e for e in self.events if start <= e[0] < end] + ok = [e for e in ev if e[2] in (200, 201)] + lat = sorted(e[4] for e in ok) + + def pct(p: float): + return lat[max(0, math.ceil(p * len(lat)) - 1)] if lat else None + span = max(end - start, 1e-9) + return {"seconds": round(span, 2), "requests": len(ev), "ok": len(ok), "failed": len(ev) - len(ok), + "ok_rps": round(len(ok) / span, 1), "error_ratio": round((len(ev) - len(ok)) / len(ev), 5) if ev else None, + "statuses": dict(Counter(e[2] for e in ev)), "instances": dict(Counter(e[3] for e in ok)), + "p50_ms": pct(.5), "p95_ms": pct(.95), "p99_ms": pct(.99)} + + def per_second(self) -> list[dict]: + buckets: dict[int, list] = defaultdict(list) + for e in self.events: + buckets[int(e[0])].append(e) + rows = [] + for second in sorted(buckets): + ev = buckets[second] + rows.append({"second": second, "ok": sum(1 for e in ev if e[2] in (200, 201)), + "failed": sum(1 for e in ev if e[2] not in (200, 201)), + "instances": "|".join(f"{k}:{v}" for k, v in sorted(Counter(e[3] for e in ev).items()))}) + return rows + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--duration", type=float, default=20) + parser.add_argument("--workers", type=int, default=4) + args = parser.parse_args() + load = Load(args.workers).start() + time.sleep(args.duration) + load.stop() + print(json.dumps({"total": load.window(0, load.now()), "history": load.verify_history(), + "client_retries_same_key": load.retries}, ensure_ascii=False, indent=2)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/bench/pipeline_faults.py b/bench/pipeline_faults.py new file mode 100644 index 0000000..ea225a7 --- /dev/null +++ b/bench/pipeline_faults.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 +"""Track 2 experiment: proven idempotency of the versioned pipeline under injected faults. + +Hypothesis. With at-least-once delivery, duplicated and reordered messages, crashes of the worker +before/after its side effects and stale jobs of an older pipeline version: + H1 no accepted (202) work is lost - every upload ends ready (or failed with a code, never stuck); + H2 every effect (attachment, pipeline_version, variant) is published exactly once - one set of + variant rows written by ONE successful attempt, one set of objects in the bucket; + H3 the published version only grows - an older job never overwrites a newer result, `ready` + never goes back to queued/processing; + H4 objects of interrupted attempts are garbage that the cleanup removes; nothing published is + ever deleted. + +Method. For every scenario the affected service (relay/worker) is recreated with FAULT_POINTS of +the scenario (the real code paths, real crashes = os._exit of the process, real `docker pause`), +N uploads go through the LB, then the scenario-specific facts are read from PostgreSQL and S3 and +the read-only invariant audit (messenger.audit, I1-I7, with SHA-256 of every published object) +runs over the WHOLE stand. The normal configuration is restored after each scenario. + + python bench/pipeline_faults.py --output evidence/track2 [--uploads 5] +""" +from __future__ import annotations + +import argparse +import datetime as dt +import json +import platform +import statistics +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "student-tests")) +import imagegen # noqa: E402 +from conftest import (Api, attachment_row, compose, events_of, jobctl, psql, s3_keys, service_with_env, # noqa: E402 + wait_healthy) + +FAST = {"JOB_LEASE_SECONDS": "6", "ORPHAN_GRACE_SECONDS": "3", "CLEANUP_INTERVAL_SECONDS": "1"} + + +def now() -> str: + return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def wait(condition, timeout: float, what: str): + deadline = time.monotonic() + timeout + while True: + value = condition() + if value: + return value + if time.monotonic() > deadline: + raise AssertionError(what) + time.sleep(0.5) + + +def facts(attachment_id: str, objects: set[str]) -> dict: + row = attachment_row(attachment_id) + out = psql("SELECT json_build_object(" + "'claims', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id WHERE j.attachment_id = '{0}'), " + "'succeeded_attempts', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id " + " WHERE j.attachment_id = '{0}' AND a.outcome = 'succeeded'), " + "'variant_rows', (SELECT count(*) FROM attachment_variants WHERE attachment_id = '{0}'), " + "'versions', (SELECT coalesce(json_agg(DISTINCT pipeline_version), '[]') FROM attachment_variants " + " WHERE attachment_id = '{0}'), " + "'job_states', (SELECT coalesce(json_agg(state || ':v' || pipeline_version ORDER BY created_at), '[]') " + " FROM jobs WHERE attachment_id = '{0}'), " + "'uncleaned_failed_attempts', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id " + " WHERE j.attachment_id = '{0}' AND a.outcome <> 'succeeded' AND a.objects_cleaned_at IS NULL))" + .format(attachment_id)) + f = json.loads(out) + f.update(status=row["status"], published_version=row["published_version"], staging_state=row["staging_state"], + objects=len([k for k in objects if k.startswith(f"a/{attachment_id}/")])) + f["events"] = [e["event"] for e in events_of(attachment_id)] + return f + + +def audit() -> dict: + r = compose("run", "--rm", "--no-deps", "-T", "auditor", "--verify-checksums", check=False, timeout=600) + report = json.loads(r.stdout) + return {"ok": report["ok"], "violations": report["violations"], "notes": len(report["notes"]), + "objects": report["objects"]} + + +class Run: + def __init__(self, api: Api, uploads: int): + self.api = api + self.n = uploads + self.alice, self.bob = api.user("t2a"), api.user("t2b") + self.chat = api.chat(self.alice, self.bob) + + def upload_many(self, n: int | None = None) -> list[dict]: + return [self.api.upload(self.alice, self.chat, imagegen.png(60 + i, 40, noise=True)).json() + for i in range(n or self.n)] + + def finish(self, atts: list[dict], timeout: float = 180) -> tuple[list[dict], list[float]]: + started = time.monotonic() + took = [] + for a in atts: + self.api.wait_status(self.bob, a["id"], timeout=timeout) + took.append(round(time.monotonic() - started, 2)) + return atts, took + + +def expect_one_effect(f: dict, version: int = 1) -> list[str]: + """H1 + H2 for a plain upload of pipeline `version`.""" + problems = [] + if f["status"] != "ready": + problems.append(f"status {f['status']}") + if f["succeeded_attempts"] != 1 or f["variant_rows"] != 3 or f["published_version"] != version: + problems.append(f"effect {f['succeeded_attempts']} attempts/{f['variant_rows']} rows/v{f['published_version']}") + if f["objects"] != 4: # original + thumbnail + crop + optimized, cleanup done + problems.append(f"{f['objects']} objects in the bucket") + return problems + + +def plain_scenario(run: Run, name: str, service: str, env: dict, *, scale: int | None = None, + cleanup_wait: bool = True) -> dict: + with service_with_env(service, scale=scale, **env): + atts, took = run.finish(run.upload_many()) + if cleanup_wait: # garbage of interrupted attempts: cleaned after ORPHAN_GRACE_SECONDS + try: + wait(lambda: all(json.loads(psql( + "SELECT json_build_object('n', count(*)) FROM job_attempts a JOIN jobs j ON j.id = a.job_id " + f"WHERE j.attachment_id = '{a['id']}' AND a.outcome <> 'succeeded' " + "AND a.objects_cleaned_at IS NULL"))["n"] == 0 for a in atts), 60, "cleanup") + except AssertionError: + pass # reported below as uncleaned attempts + objects = s3_keys("a/") + per = [facts(a["id"], objects) for a in atts] + problems = {a["id"]: p for a, f in zip(atts, per) if (p := expect_one_effect(f))} + return {"scenario": name, "faults": {service: env}, "uploads": len(atts), + "ready": sum(f["status"] == "ready" for f in per), "claims_total": sum(f["claims"] for f in per), + "max_claims": max(f["claims"] for f in per), "time_to_ready_s": {"p50": statistics.median(took), + "max": max(took)}, + "event_sequences": sorted({" > ".join(f["events"]) for f in per}), "problems": problems} + + +def versions_scenario(run: Run) -> dict: + """Stale job after a newer version: v2 (slow) and v3 run at the same time; v3 publishes first, + v2 finishes later and must end superseded without touching the published v3 result.""" + att = run.upload_many(1)[0] + run.api.wait_status(run.bob, att["id"], "ready") + observed = set() + with service_with_env("worker", WORKER_FAULT_POINTS="slow=10,slow_pipeline=2"): + jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "track2", "--reason", "new encoder") + wait(lambda: "processing:v2" in facts(att["id"], set())["job_states"], 60, "v2 not claimed") + jobctl("reprocess", att["id"], "--pipeline", "3", "--operator", "track2", "--reason", "newer encoder") + deadline = time.monotonic() + 120 + while time.monotonic() < deadline: + meta = run.api.attachment(run.bob, att["id"]) + observed.add(meta["status"]) + states = facts(att["id"], set())["job_states"] + if not any(s.startswith(("queued", "processing")) for s in states): + break + time.sleep(0.3) + final = run.api.attachment(run.bob, att["id"]) + f = facts(att["id"], s3_keys("a/")) + thumb_v3 = psql(f"SELECT encode(sha256, 'hex') FROM attachment_variants WHERE attachment_id = '{att['id']}' " + "AND pipeline_version = 3 AND name = 'thumbnail'") + problems = [] + if f["job_states"] != ["succeeded:v1", "superseded:v2", "succeeded:v3"]: + problems.append(f"job states {f['job_states']}") + if f["published_version"] != 3 or observed != {"ready"}: + problems.append(f"published v{f['published_version']}, statuses seen {sorted(observed)}") + if next(v["sha256"] for v in final["variants"] if v["name"] == "thumbnail") != thumb_v3: + problems.append("published thumbnail is not the v3 one") + # Stale duplicate of the FIRST job, published by hand with the relay's broker user: a no-op. + job_v1 = psql(f"SELECT id FROM jobs WHERE attachment_id = '{att['id']}' AND pipeline_version = 1") + script = ("import asyncio, aio_pika, datetime as d\n" + "from messenger import broker\n" + "async def m():\n" + " c = await aio_pika.connect(open('/run/secrets/broker_url').read().strip())\n" + " ch = await c.channel(publisher_confirms=True)\n" + " ex = await ch.get_exchange(broker.EXCHANGE, ensure=False)\n" + f" body = broker.encode('{job_v1}', '{att['id']}', 1, 1, d.datetime.now(d.timezone.utc))\n" + " await ex.publish(aio_pika.Message(body), routing_key=broker.ROUTING_KEY)\n" + " await c.close()\n" + "asyncio.run(m())\n") + compose("exec", "-T", "relay", "python", "-c", script) + time.sleep(3) + after = run.api.attachment(run.bob, att["id"]) + if after != final: + problems.append("stale v1 message changed the attachment") + return {"scenario": "stale_version_and_reorder", "uploads": 1, "statuses_seen_during_reprocess": sorted(observed), + "job_states": f["job_states"], "published_version": f["published_version"], + "variant_rows_by_version": f["variant_rows"], "objects": f["objects"], + "events": f["events"], "problems": problems} + + +def queued_reorder_scenario(run: Run) -> dict: + """Both newer versions wait in the outbox; the relay publishes them in REVERSE order and one worker + takes them one by one: v3 is published first, v2 is then superseded at its claim (no work).""" + att = run.upload_many(1)[0] + run.api.wait_status(run.bob, att["id"], "ready") + # The worker stays stopped until it is recreated with concurrency 1 (no normal start in between). + # Worker and relay stay stopped until each is recreated with the scenario's settings: no normal + # start in between that would consume/publish the jobs in the ordinary order. + compose("stop", "worker", "relay") + try: + jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "track2", "--reason", "v2") + jobctl("reprocess", att["id"], "--pipeline", "3", "--operator", "track2", "--reason", "v3") + with service_with_env("relay", RELAY_FAULT_POINTS="reverse_order"): + wait(lambda: psql("SELECT count(*) FROM outbox o JOIN jobs j ON j.id = o.job_id WHERE j.attachment_id = " + f"'{att['id']}' AND j.pipeline_version > 1 AND o.published_at IS NOT NULL") == "2", + 30, "both reprocess jobs not published") # in one relay batch: v3 first, then v2 + with service_with_env("worker", WORKER_CONCURRENCY="1"): + wait(lambda: not any(s.startswith(("queued", "processing")) + for s in facts(att["id"], set())["job_states"]), 120, "reprocess jobs did not finish") + finally: + compose("start", "worker", "relay") + wait_healthy("worker", "relay") + f = facts(att["id"], s3_keys("a/")) + problems = [] + if f["job_states"] != ["succeeded:v1", "superseded:v2", "succeeded:v3"] or f["published_version"] != 3: + problems.append(f"{f['job_states']} published v{f['published_version']}") + if f["claims"] != 2: # v1 and v3 only: v2 was superseded before any work + problems.append(f"{f['claims']} claims") + return {"scenario": "reordered_versions_in_queue", "job_states": f["job_states"], "claims": f["claims"], + "published_version": f["published_version"], "events": f["events"], "problems": problems} + + +def hung_worker_scenario(run: Run) -> dict: + with service_with_env("worker", scale=2, WORKER_FAULT_POINTS="slow=8", **FAST): + att = run.upload_many(1)[0] + owner = wait(lambda: psql(f"SELECT lease_owner FROM jobs WHERE attachment_id = '{att['id']}' " + "AND state = 'processing'"), 30, "not claimed") + ids = compose("ps", "-q", "worker").stdout.split() + names = dict(line.split() for line in subprocess.run( + ["docker", "inspect", "-f", "{{.Config.Hostname}} {{.Id}}", *ids], capture_output=True, text=True, + check=True).stdout.splitlines()) + subprocess.run(["docker", "pause", names[owner]], check=True) + try: + run.api.wait_status(run.bob, att["id"], "ready", timeout=150) + published = psql(f"SELECT string_agg(object_key, ',' ORDER BY object_key) FROM attachment_variants " + f"WHERE attachment_id = '{att['id']}'") + finally: + subprocess.run(["docker", "unpause", names[owner]], check=True) + time.sleep(15) + again = psql(f"SELECT string_agg(object_key, ',' ORDER BY object_key) FROM attachment_variants " + f"WHERE attachment_id = '{att['id']}'") + wait(lambda: json.loads(psql("SELECT json_build_object('n', count(*)) FROM job_attempts a JOIN jobs j " + f"ON j.id = a.job_id WHERE j.attachment_id = '{att['id']}' AND a.outcome <> " + "'succeeded' AND a.objects_cleaned_at IS NULL"))["n"] == 0, 60, "cleanup") + f = facts(att["id"], s3_keys("a/")) + problems = expect_one_effect(f) + if published != again: + problems.append("the resumed (fenced) attempt changed the published result") + return {"scenario": "hung_worker_docker_pause", "frozen": owner, "claims": f["claims"], "events": f["events"], + "problems": problems} + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("--output", default="evidence/track2") + p.add_argument("--uploads", type=int, default=5) + args = p.parse_args() + out = ROOT / args.output + out.mkdir(parents=True, exist_ok=True) + api = Api() + run = Run(api, args.uploads) + started = now() + results = [] + plan = [ + ("baseline_no_faults", "worker", {}), + ("duplicate_publish", "relay", {"RELAY_FAULT_POINTS": "duplicate_publish"}), + ("duplicate_and_reverse_order", "relay", {"RELAY_FAULT_POINTS": "duplicate_publish,reverse_order"}), + ("relay_crash_after_confirm_before_mark", "relay", {"RELAY_FAULT_POINTS": "crash_after_publish"}), + ("worker_crash_before_side_effect", "worker", {"WORKER_FAULT_POINTS": "crash_after_claim", **FAST}), + ("worker_crash_after_s3_before_commit", "worker", {"WORKER_FAULT_POINTS": "crash_after_s3_write", **FAST}), + ("worker_crash_after_commit_before_ack", "worker", {"WORKER_FAULT_POINTS": "crash_after_commit", **FAST}), + ("transient_errors_then_success", "worker", {"WORKER_FAULT_POINTS": "transient_error=2", + "JOB_RETRY_BASE_SECONDS": "0.5", **FAST}), + ] + for name, service, env in plan: + print(f"[{now()}] {name}", flush=True) + results.append(plain_scenario(run, name, service, env)) + print(f"[{now()}] two_workers_duplicate_publish", flush=True) + with service_with_env("relay", RELAY_FAULT_POINTS="duplicate_publish"): + results.append(plain_scenario(run, "two_workers_duplicate_publish", "worker", {}, scale=2)) + for scenario in (versions_scenario, queued_reorder_scenario, hung_worker_scenario): + print(f"[{now()}] {scenario.__name__}", flush=True) + results.append(scenario(run)) + wait_healthy("worker", "relay") + report = audit() + summary = { + "experiment": "track 2: idempotency of the versioned pipeline under injected faults", + "started": started, "finished": now(), + "host": {"os": platform.platform(), "python": platform.python_version()}, + "uploads_per_plain_scenario": args.uploads, + "scenarios": results, + "audit_after_all": report, + "violations": sum(len(r["problems"]) for r in results) + len(report["violations"]), + } + (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1), encoding="utf-8") + lines = [f"{'scenario':45} {'uploads':>7} {'ready':>5} {'claims':>6} problems"] + for r in results: + lines.append(f"{r['scenario']:45} {r.get('uploads', 1):>7} {r.get('ready', '-'):>5} " + f"{r.get('claims_total', r.get('claims', '-')):>6} {len(r['problems'])}") + lines.append(f"audit after all scenarios: ok={report['ok']} violations={len(report['violations'])} " + f"objects={report['objects']}") + (out / "summary.txt").write_text("\n".join(lines) + "\n", encoding="utf-8") + print("\n".join(lines)) + return 0 if summary["violations"] == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bench/rolling_under_load.py b/bench/rolling_under_load.py new file mode 100644 index 0000000..c4fd9ba --- /dev/null +++ b/bench/rolling_under_load.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Level 4: scripts/rolling-update.sh while bench/loadgen.py traffic runs through the LB. + + python bench/rolling_under_load.py --output evidence/rolling-update + +Writes /summary.json (errors, RPS, history check, revisions before/after), +/timeline.csv (per second ok/failed/instances) and /script-output.txt. +""" +from __future__ import annotations + +import argparse +import csv +import json +import os +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(ROOT / "bench")) +import lbctl # noqa: E402 +from loadgen import Load # noqa: E402 + + +def revisions() -> dict[str, str]: + result = {} + for r in lbctl.replicas(): + if r["state"] == "running": + label = subprocess.run(["docker", "inspect", "-f", '{{index .Config.Labels "org.opencontainers.image.revision"}}', + r["id"]], capture_output=True, text=True).stdout.strip() + result[r["name"]] = f"{r['hostname']} revision={label}" + return result + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--output", default="evidence/rolling-update") + parser.add_argument("--workers", type=int, default=4) + args = parser.parse_args() + out = ROOT / args.output + out.mkdir(parents=True, exist_ok=True) + before = revisions() + load = Load(args.workers).start() + time.sleep(5) + t_begin = load.now() + bash = (os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe") + if os.name == "nt" else "sh") + env = {**os.environ, "PYTHON": sys.executable} + script = subprocess.run([bash, str(ROOT / "scripts" / "rolling-update.sh")], cwd=ROOT, env=env, + capture_output=True, text=True, encoding="utf-8", timeout=900) + t_end = load.now() + time.sleep(5) + load.stop() + (out / "script-output.txt").write_text(f"$ sh scripts/rolling-update.sh (exit {script.returncode})\n" + + script.stdout + script.stderr, encoding="utf-8") + with (out / "timeline.csv").open("w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=["second", "ok", "failed", "instances"]) + writer.writeheader() + writer.writerows(load.per_second()) + summary = {"script_exit_code": script.returncode, "update_seconds": round(t_end - t_begin, 1), + "before": before, "after": revisions(), + "during_update": load.window(t_begin, t_end), "whole_run": load.window(0, load.now()), + "client_retries_same_key": load.retries, "history": load.verify_history(), + "workload": f"{args.workers} closed-loop workers: POST (Idempotency-Key) + GET page via 127.0.0.1:8080"} + (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps({k: summary[k] for k in ("script_exit_code", "update_seconds", "before", "after", "history")}, + ensure_ascii=False, indent=2)) + print(json.dumps(summary["during_update"], ensure_ascii=False)) + return 0 if script.returncode == 0 else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/bench/track1.py b/bench/track1.py new file mode 100644 index 0000000..81db3f9 --- /dev/null +++ b/bench/track1.py @@ -0,0 +1,361 @@ +#!/usr/bin/env python3 +"""Track 1 "the price of observability": the same load under four telemetry configurations. + + python bench/track1.py --runs 3 --rate 40 --duration 90 --output evidence/track1 + python bench/track1.py --configs full,tail --runs 1 # subset, quick check + +Configurations (only the telemetry differs; image, limits, load and data are the same): + off OTEL_SDK_DISABLED=true in api/relay/worker (stdout JSON logs only) - baseline + full SDK on, every trace kept (parentbased_always_on, Collector traces-all) + head10 SDK head sampling 10 % (parentbased_traceidratio 0.1), Collector traces-all + tail SDK on 100 %, Collector TAIL sampling: all errors + all traces >= 250 ms + 10 % of the + rest (infra/otel/traces-tail.yaml) - proposed balance +Metrics and logs are NOT sampled in any configuration: the dashboards/alerts stay exact. + +Load (open loop, fixed arrival rate, latency measured from the SCHEDULED start of each request, +so a slow server cannot slow down the generator - no coordinated omission): `rate` req/s, +70 % POST message / 30 % GET history page, + 1 upload/s for the worker. Rare events on purpose: +API_FAULT_POINTS=random_5xx=10,random_slow=10 -> ~1 % of POSTs answer 503, ~1 % take +500 ms. +The client counts them exactly; then Tempo is asked how many of them are still findable. + +Per run: recreate the services for the configuration, warm up `warmup` s, measure `duration` s, +wait for ingestion, read: client RPS/latency/errors; CPU of api/worker/relay/postgres EXACTLY from +the cgroup counter (`/sys/fs/cgroup/cpu.stat` usage_usec at the start and the end of the window), +CPU of the telemetry stack from its own counters (increase of process_cpu_seconds_total), RAM from +docker stats (sampled every 5 s); GET latency (no faults injected there) as the clean overhead; +Collector counters (accepted / sent / dropped spans, log records, metric points); Tempo/Loki bytes +received; SDK spans recorded/exported; error and slow traces found in Tempo vs injected. +Order of runs: off, full, head10, tail repeated `runs` times (drift spreads over all configs). +""" +from __future__ import annotations + +import argparse +import base64 +import json +import os +import random +import secrets +import statistics +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request +import uuid +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +import obs # noqa: E402 + +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") + "/api/v1" +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() +FAULTS = "random_5xx=10,random_slow=10" + +CONFIGS = { + "off": {"OTEL_SDK_DISABLED": "true", "OTEL_COLLECTOR_TRACES": "traces-all"}, + "full": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_always_on", + "OTEL_COLLECTOR_TRACES": "traces-all"}, + "head10": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_traceidratio", + "OTEL_TRACES_SAMPLER_ARG": "0.1", "OTEL_COLLECTOR_TRACES": "traces-all"}, + "tail": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_always_on", + "OTEL_COLLECTOR_TRACES": "traces-tail"}, +} +WATCHED = ["api", "worker", "relay", "otel-collector", "tempo", "loki", "prometheus", "postgres"] + + +# ----------------------------------------------------------------------------- stand +def compose_up(env: dict) -> None: + """`docker compose up` of the telemetry-dependent services; retried: on Windows the CLI itself + sometimes fails to start (exit 0xC0000142) when the desktop session is busy.""" + for attempt in range(3): + result = subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--wait", "otel-collector", "api", + "relay", "worker"], cwd=ROOT, env=env, capture_output=True, timeout=300) + if result.returncode == 0: + return + print(f" compose up failed (exit {result.returncode}), retry {attempt + 1}", flush=True) + time.sleep(10) + raise RuntimeError("docker compose up failed 3 times") + + +def apply_config(name: str) -> None: + env = {k: v for k, v in os.environ.items() if not k.startswith("OTEL_")} + env.update(CONFIGS[name]) + env["API_FAULT_POINTS"] = FAULTS + compose_up(env) + deadline = time.time() + 90 + while time.time() < deadline: # LB sees both replicas again + try: + with urllib.request.urlopen(BASE.rsplit("/api/v1", 1)[0] + "/health/ready", timeout=2) as r: + if r.status == 200: + break + except Exception: # noqa: BLE001 + pass + time.sleep(1) + time.sleep(5) + + +def restore() -> None: + env = {k: v for k, v in os.environ.items() if not k.startswith("OTEL_") and k != "API_FAULT_POINTS"} + compose_up(env) + + +def container_ids() -> dict[str, str]: + out = {} + for service in WATCHED: + ids = subprocess.run(["docker", "compose", "ps", "-q", service], cwd=ROOT, capture_output=True, + text=True).stdout.split() + for i, cid in enumerate(ids): + out[f"{service}-{i + 1}" if len(ids) > 1 else service] = cid + return out + + +CGROUP_SERVICES = ("api", "worker", "relay", "postgres") # images with a shell (`cat`) + + +def cgroup_cpu(ids: dict[str, str]) -> dict[str, float]: + """usage_usec of every application container's cgroup, read in parallel (seconds).""" + out: dict[str, float] = {} + + def one(name: str, cid: str) -> None: + raw = subprocess.run(["docker", "exec", cid, "cat", "/sys/fs/cgroup/cpu.stat"], capture_output=True, + text=True, timeout=30).stdout + for line in raw.splitlines(): + if line.startswith("usage_usec "): + out[name] = int(line.split()[1]) / 1e6 + + threads = [threading.Thread(target=one, args=(n, c)) for n, c in ids.items() if n.split("-")[0] in CGROUP_SERVICES] + for t in threads: + t.start() + for t in threads: + t.join(40) + return out + + +class Stats(threading.Thread): + """docker stats every 5 s: CPU % (100 = one core) and memory (MiB) per container.""" + + def __init__(self, ids: dict[str, str]): + super().__init__(daemon=True) + self.ids = ids + self.samples: dict[str, list[tuple[float, float]]] = {k: [] for k in ids} + self.stop = threading.Event() + + def run(self) -> None: + names = {v[:12]: k for k, v in self.ids.items()} + while not self.stop.is_set(): + raw = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.ID}};{{.CPUPerc}};{{.MemUsage}}", + *self.ids.values()], capture_output=True, text=True).stdout + for line in raw.splitlines(): + cid, cpu, mem = line.split(";") + if cid[:12] in names: + self.samples[names[cid[:12]]].append((float(cpu.rstrip("%")), _mib(mem.split("/")[0].strip()))) + self.stop.wait(5) + + def summary(self) -> dict: + out = {} + for name, rows in self.samples.items(): + if rows: + out[name] = {"cpu_pct_avg": round(statistics.mean(r[0] for r in rows), 1), + "mem_mib_avg": round(statistics.mean(r[1] for r in rows), 1), + "mem_mib_max": round(max(r[1] for r in rows), 1)} + return out + + +def _mib(text: str) -> float: + num = float("".join(c for c in text if c.isdigit() or c == ".")) + return num / 1024 if text.endswith("KiB") else num * 1024 if text.endswith("GiB") else num + + +# ----------------------------------------------------------------------------- load +def http(method, path, body=None, headers=None, raw=None, timeout=10.0): + h = dict(headers or {}) + data = raw + if body is not None: + data = json.dumps(body).encode() + h["Content-Type"] = "application/json" + request = urllib.request.Request(BASE + path, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(request, timeout=timeout) as r: + return r.status, json.loads(r.read() or b"null") + except urllib.error.HTTPError as exc: + exc.read() + return exc.code, None + except Exception: # noqa: BLE001 + return 0, None + + +def actor() -> dict: + username = "t1_" + uuid.uuid4().hex[:12] + password = "Track1-" + secrets.token_hex(8) + _, user = http("POST", "/users", {"username": username, "display_name": "track1", "password": password}) + _, session = http("POST", "/auth/sessions", + headers={"Authorization": "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()}) + headers = {"Authorization": "Bearer " + session["token"]} + _, chat = http("POST", "/chats", {"title": "track1", "member_ids": [user["id"]]}, headers) + return {"headers": headers, "chat": chat["id"]} + + +def load(rate: float, seconds: float, warmup: float, ids: dict[str, str]) -> dict: + actors = [actor() for _ in range(8)] + for a in actors: # same history size in every run + for _ in range(20): + http("POST", f"/chats/{a['chat']}/messages", {"text": "seed"}, {**a["headers"], "Idempotency-Key": uuid.uuid4().hex}) + results: list[tuple[float, str, int, float]] = [] + lock = threading.Lock() + rnd = random.Random(42) # the same request mix in every run + + def one(scheduled: float, kind: str, a: dict) -> None: + if kind == "post": + status, _ = http("POST", f"/chats/{a['chat']}/messages", {"text": "load"}, + {**a["headers"], "Idempotency-Key": uuid.uuid4().hex}) + elif kind == "get": + status, _ = http("GET", f"/chats/{a['chat']}/messages?limit=20", headers=a["headers"]) + else: + status, _ = http("POST", f"/chats/{a['chat']}/attachments?filename=t1.png", raw=SAMPLE, + headers={**a["headers"], "Content-Type": "image/png"}, timeout=20) + with lock: + results.append((scheduled, kind, status, time.perf_counter() - scheduled)) + + total = warmup + seconds + plan = [] + for i in range(int(total * rate)): + plan.append((i / rate, "post" if rnd.random() < 0.7 else "get", rnd.randrange(len(actors)))) + for i in range(int(total)): + plan.append((i + 0.5, "upload", rnd.randrange(len(actors)))) + plan.sort() + start = time.perf_counter() + snap: dict = {} + + def snapshot_start() -> None: + snap["t0"], snap["cpu0"] = time.time(), cgroup_cpu(ids) + + starter = None + with ThreadPoolExecutor(max_workers=96) as pool: + for offset, kind, idx in plan: + if starter is None and offset >= warmup: + starter = threading.Thread(target=snapshot_start) + starter.start() + delay = start + offset - time.perf_counter() + if delay > 0: + time.sleep(delay) + pool.submit(one, start + offset, kind, actors[idx]) + t1, cpu1 = time.time(), cgroup_cpu(ids) + starter.join(60) + measured = [r for r in results if r[0] - start >= warmup] + window_s = t1 - snap["t0"] + out = {"window": [snap["t0"], t1], + "cpu_pct": {name: round(100 * (cpu1[name] - snap["cpu0"][name]) / window_s, 1) + for name in cpu1 if name in snap["cpu0"]}} + for kind in ("post", "get", "upload"): + rows = [r for r in measured if r[1] == kind] + ok = sorted(r[3] for r in rows if 200 <= r[2] < 300) + out[kind] = {"sent": len(rows), "ok": len(ok), "5xx": sum(r[2] >= 500 for r in rows), + "no_response": sum(r[2] == 0 for r in rows), + "ok_rps": round(len(ok) / seconds, 2), + "p50_ms": _pct(ok, .5), "p95_ms": _pct(ok, .95), "p99_ms": _pct(ok, .99), + "slow_over_450ms": sum(1 for r in rows if 200 <= r[2] < 300 and r[3] > 0.45)} + return out + + +def _pct(values, q): + return round(values[min(len(values) - 1, int(q * len(values)))] * 1000, 1) if values else None + + +# ----------------------------------------------------------------------------- telemetry side +def increase(expr: str, start: float, end: float) -> float | None: + """Counter growth inside [start, end]: sum(increase(expr[window])) evaluated at `end`. increase() + handles counter resets (services are recreated for every configuration) and series of old + processes (they do not grow); subtracting two raw sums did not, and gave negative numbers.""" + window = max(15, int(round(end - start))) + try: + result = obs.promql(f"sum(increase({expr}[{window}s]))", at=end) + except Exception: # noqa: BLE001 + return None + return round(float(result[0]["value"][1]), 1) if result else 0.0 + + +def tempo_count(traceql: str, start: float, end: float) -> int: + end_i, start_i = int(end) + 1, int(start) + try: + found = obs.get("tempo", "api/search", {"q": traceql, "start": start_i, "end": end_i, "limit": 5000}, + timeout=60).get("traces", []) + except Exception: # noqa: BLE001 + return -1 + return len(found) + + +def telemetry_side(window: list[float], config: str) -> dict: + start, end = window + end_q = end + 25 # counters pushed every 5 s, batch 2 s + return { + "sdk_spans_recorded": increase("messenger_telemetry_spans_ended_total", start, end_q), + "sdk_spans_export_failed": increase('messenger_telemetry_spans_exported_total{result="failure"}', start, end_q), + "collector_spans_accepted": increase("otelcol_receiver_accepted_spans", start, end_q), + "collector_spans_refused": increase("otelcol_receiver_refused_spans", start, end_q), + "collector_spans_sent": increase('otelcol_exporter_sent_spans{exporter="otlp_http/tempo"}', start, end_q), + "collector_spans_send_failed": increase("otelcol_exporter_send_failed_spans", start, end_q), + "collector_logs_accepted": increase("otelcol_receiver_accepted_log_records", start, end_q), + "collector_metric_points_accepted": increase("otelcol_receiver_accepted_metric_points", start, end_q), + "tempo_bytes_received": increase("tempo_distributor_bytes_received_total", start, end_q), + "loki_bytes_received": increase("loki_distributor_bytes_received_total", start, end_q), + # the Collector names its own CPU counter otelcol_process_cpu_seconds (no _total suffix) + "telemetry_cpu_s": {"otel-collector": increase('otelcol_process_cpu_seconds{job="otel-collector"}', start, end_q), + **{job: increase(f'process_cpu_seconds_total{{job="{job}"}}', start, end_q) + for job in ("tempo", "loki", "prometheus")}}, + "error_traces_in_tempo": tempo_count('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && span.http.response.status_code = 503 }', + start, end), + "slow_traces_in_tempo": tempo_count('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && kind = server && duration > 450ms }', + start, end), + "server_traces_in_tempo": tempo_count('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && kind = server }', start, end), + } + + +# ----------------------------------------------------------------------------- main +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--configs", default="off,full,head10,tail") + parser.add_argument("--runs", type=int, default=3) + parser.add_argument("--first-run", type=int, default=1, help="continue an interrupted series (keeps earlier files)") + parser.add_argument("--rate", type=float, default=40) + parser.add_argument("--duration", type=float, default=90) + parser.add_argument("--warmup", type=float, default=20) + parser.add_argument("--output", default="evidence/track1") + args = parser.parse_args() + out_dir = ROOT / args.output + out_dir.mkdir(parents=True, exist_ok=True) + configs = args.configs.split(",") + meta = {"started": time.strftime("%Y-%m-%d %H:%M:%S"), "rate": args.rate, "duration": args.duration, + "warmup": args.warmup, "faults": FAULTS, "configs": {c: CONFIGS[c] for c in configs}} + if args.first_run == 1 or not (out_dir / "meta.json").exists(): + (out_dir / "meta.json").write_text(json.dumps(meta, indent=1) + "\n", encoding="utf-8") + try: + for run in range(args.first_run, args.runs + 1): + for config in configs: + print(f"--- run {run} config {config}", flush=True) + apply_config(config) + ids = container_ids() + stats = Stats(ids) + stats.start() + client = load(args.rate, args.duration, args.warmup, ids) + stats.stop.set() + stats.join(15) + time.sleep(30) # ingestion + tail decision_wait + metric push + result = {"config": config, "run": run, "client": client, "resources": stats.summary(), + "telemetry": telemetry_side(client["window"], config)} + (out_dir / f"run{run}-{config}.json").write_text(json.dumps(result, indent=1) + "\n", encoding="utf-8") + c, t = client["post"], result["telemetry"] + print(f" post ok_rps={c['ok_rps']} p50={c['p50_ms']} p95={c['p95_ms']} p99={c['p99_ms']} " + f"5xx={c['5xx']} slow={c['slow_over_450ms']} | get p99={client['get']['p99_ms']} | cpu " + f"{client['cpu_pct']} | " + f"errors in tempo={t.get('error_traces_in_tempo')} slow in tempo={t.get('slow_traces_in_tempo')}", + flush=True) + finally: + restore() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bench/track1_summary.py b/bench/track1_summary.py new file mode 100644 index 0000000..686acf0 --- /dev/null +++ b/bench/track1_summary.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Summarise evidence/track1/run*-.json into evidence/track1/summary.md (+ summary.json). + + python bench/track1_summary.py [evidence/track1] + +Per configuration: median over the runs (in brackets min..max), so one noisy run cannot decide. +CPU: application containers from cgroup usage_usec (exact, per window), the telemetry stack from +its own process CPU counters; RAM: docker stats average. Kept rare events = traces found in Tempo / +events the client saw (5xx answers, POSTs > 450 ms). +""" +from __future__ import annotations + +import json +import statistics +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +ORDER = ["off", "full", "head10", "tail"] + + +def med(values): + values = [v for v in values if v is not None] + if not values: + return None, None, None + return statistics.median(values), min(values), max(values) + + +def fmt(triple, digits=1, unit=""): + m, lo, hi = triple + if m is None: + return "—" + if lo == hi: + return f"{m:.{digits}f}{unit}" + return f"{m:.{digits}f}{unit} ({lo:.{digits}f}–{hi:.{digits}f})" + + +def kept(found, seen): + if found is None or found < 0 or not seen: + return None + return 100.0 * found / seen + + +def summarise(rs: list[dict]) -> dict: + post = [r["client"]["post"] for r in rs] + get = [r["client"]["get"] for r in rs] + cpu = [r["client"].get("cpu_pct", {}) for r in rs] + res = [r["resources"] for r in rs] + tel = [r["telemetry"] for r in rs] + windows = [r["client"]["window"][1] - r["client"]["window"][0] + 25 for r in rs] + + def tele_cpu(t, w): + values = (t.get("telemetry_cpu_s") or {}).values() + return None if not values or any(v is None for v in values) else 100 * sum(values) / w + + return { + "runs": len(rs), + "post_ok_rps": med([p["ok_rps"] for p in post]), + "post_p50_ms": med([p["p50_ms"] for p in post]), "post_p95_ms": med([p["p95_ms"] for p in post]), + "post_p99_ms": med([p["p99_ms"] for p in post]), + "get_p50_ms": med([g["p50_ms"] for g in get]), "get_p95_ms": med([g["p95_ms"] for g in get]), + "get_p99_ms": med([g["p99_ms"] for g in get]), + "api_cpu_pct": med([sum(v for k, v in c.items() if k.startswith("api")) or None for c in cpu]), + "worker_cpu_pct": med([c.get("worker") for c in cpu]), + "relay_cpu_pct": med([c.get("relay") for c in cpu]), + "postgres_cpu_pct": med([c.get("postgres") for c in cpu]), + "api_mem_mib": med([sum(v["mem_mib_avg"] for k, v in x.items() if k.startswith("api")) or None for x in res]), + "telemetry_cpu_pct": med([tele_cpu(t, w) for t, w in zip(tel, windows)]), + "telemetry_mem_mib": med([sum(x.get(k, {}).get("mem_mib_avg", 0) for k in ("otel-collector", "tempo", "loki", + "prometheus")) for x in res]), + "collector_mem_mib": med([x.get("otel-collector", {}).get("mem_mib_avg") for x in res]), + "spans_recorded": med([t.get("sdk_spans_recorded") for t in tel]), + "spans_accepted": med([t.get("collector_spans_accepted") for t in tel]), + "spans_to_tempo": med([t.get("collector_spans_sent") for t in tel]), + "spans_refused_or_failed": med([None if t.get("collector_spans_refused") is None else + t["collector_spans_refused"] + (t.get("collector_spans_send_failed") or 0) + + (t.get("sdk_spans_export_failed") or 0) for t in tel]), + "tempo_kib": med([None if t.get("tempo_bytes_received") is None else t["tempo_bytes_received"] / 1024 for t in tel]), + "loki_kib": med([None if t.get("loki_bytes_received") is None else t["loki_bytes_received"] / 1024 for t in tel]), + "logs": med([t.get("collector_logs_accepted") for t in tel]), + "metric_points": med([t.get("collector_metric_points_accepted") for t in tel]), + "errors_injected": med([p["5xx"] for p in post]), + "errors_in_tempo": med([t.get("error_traces_in_tempo") for t in tel]), + "errors_kept_pct": med([kept(t.get("error_traces_in_tempo"), p["5xx"]) for t, p in zip(tel, post)]), + "slow_seen": med([p["slow_over_450ms"] for p in post]), + "slow_in_tempo": med([t.get("slow_traces_in_tempo") for t in tel]), + "slow_kept_pct": med([kept(t.get("slow_traces_in_tempo"), p["slow_over_450ms"]) for t, p in zip(tel, post)]), + "post_traces_in_tempo": med([t.get("server_traces_in_tempo") for t in tel]), + } + + +def main() -> int: + folder = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / "evidence" / "track1" + runs: dict[str, list[dict]] = {} + for f in sorted(folder.glob("run*-*.json")): + data = json.loads(f.read_text(encoding="utf-8")) + runs.setdefault(data["config"], []).append(data) + meta = json.loads((folder / "meta.json").read_text(encoding="utf-8")) + summary = {c: summarise(runs[c]) for c in ORDER if c in runs} + rows = list(summary.items()) + L = [f"# Трек 1: цена наблюдаемости — сводка (серия от {meta['started']})", "", + f"Нагрузка: open loop {meta['rate']:.0f} req/s (70 % POST message, 30 % GET history) + 1 upload/s, " + f"прогрев {meta['warmup']:.0f} с, замер {meta['duration']:.0f} с; редкие события `{meta['faults']}` " + "(~1 % POST → 503, ~1 % POST +500 мс). Медиана по повторам, в скобках min–max.", "", + "## Задержка (клиент, от запланированного момента запроса)", "", + "| Конфигурация | POST ok RPS | POST p50, мс | POST p95, мс | POST p99, мс* | GET p50, мс | GET p95, мс | GET p99, мс |", + "| --- | --- | --- | --- | --- | --- | --- | --- |"] + for c, s in rows: + L.append(f"| {c} ({s['runs']}) | {fmt(s['post_ok_rps'], 2)} | {fmt(s['post_p50_ms'])} | {fmt(s['post_p95_ms'])} | " + f"{fmt(s['post_p99_ms'])} | {fmt(s['get_p50_ms'])} | {fmt(s['get_p95_ms'])} | {fmt(s['get_p99_ms'])} |") + L += ["", "\\* p99 POST определяется внедрёнными медленными запросами (1 % × +500 мс), поэтому ≈ 500 мс во всех " + "конфигурациях; чистая цена телеметрии видна по GET (там отказы не внедряются) и по p50/p95.", "", + "## Ресурсы", "", + "| Конфигурация | CPU api×2, % | CPU worker, % | CPU relay, % | CPU postgres, % | CPU телеметрии**, % | RAM api×2, MiB | RAM телеметрии**, MiB | RAM Collector, MiB |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |"] + for c, s in rows: + L.append(f"| {c} | {fmt(s['api_cpu_pct'])} | {fmt(s['worker_cpu_pct'])} | {fmt(s['relay_cpu_pct'])} | " + f"{fmt(s['postgres_cpu_pct'])} | {fmt(s['telemetry_cpu_pct'])} | {fmt(s['api_mem_mib'])} | " + f"{fmt(s['telemetry_mem_mib'])} | {fmt(s['collector_mem_mib'])} |") + L += ["", "100 % = одно ядро. CPU приложения — точный счётчик cgroup (`cpu.stat usage_usec`) за окно замера; " + "\\*\\* телеметрия = Collector + Tempo + Loki + Prometheus (их собственные счётчики CPU; RAM — docker stats).", "", + "## Объём телеметрии и потери (окно замера + 25 с на доставку)", "", + "| Конфигурация | spans записано SDK | принято Collector | ушло в Tempo | отказ/сбой отправки | Tempo, KiB | Loki, KiB | log records | metric points |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |"] + for c, s in rows: + L.append(f"| {c} | {fmt(s['spans_recorded'], 0)} | {fmt(s['spans_accepted'], 0)} | {fmt(s['spans_to_tempo'], 0)} | " + f"{fmt(s['spans_refused_or_failed'], 0)} | {fmt(s['tempo_kib'], 0)} | {fmt(s['loki_kib'], 0)} | " + f"{fmt(s['logs'], 0)} | {fmt(s['metric_points'], 0)} |") + L += ["", "«Отказ/сбой» = отказано memory_limiter-ом + не отправлено Collector-ом + не отправлено SDK. " + "Отброшенное политикой sampling (head в SDK, tail в Collector) потерей не считается: это решение.", "", + "## Что осталось найти: редкие ошибки и медленные запросы", "", + "| Конфигурация | 5xx у клиента | 5xx-трасс в Tempo | найдено ошибок | медленных (> 450 мс) у клиента | медленных трасс в Tempo | найдено медленных | трасс POST в Tempo |", + "| --- | --- | --- | --- | --- | --- | --- | --- |"] + for c, s in rows: + L.append(f"| {c} | {fmt(s['errors_injected'], 0)} | {fmt(s['errors_in_tempo'], 0)} | {fmt(s['errors_kept_pct'], 0, ' %')} | " + f"{fmt(s['slow_seen'], 0)} | {fmt(s['slow_in_tempo'], 0)} | {fmt(s['slow_kept_pct'], 0, ' %')} | " + f"{fmt(s['post_traces_in_tempo'], 0)} |") + out = "\n".join(L) + "\n" + (folder / "summary.md").write_text(out, encoding="utf-8", newline="\n") + (folder / "summary.json").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8", newline="\n") + print(out) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bench/upload_memory.py b/bench/upload_memory.py new file mode 100644 index 0000000..e2c6f35 --- /dev/null +++ b/bench/upload_memory.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Level 4 experiment: peak memory of the API replicas under >= 10 simultaneous uploads. + +Hypothesis: the memory of one replica is bounded by UPLOAD_CONCURRENCY x MAX_UPLOAD_BYTES (bodies +waiting for a slot stay in TCP buffers, not in the process) + one image check at a time +(IMAGE_VERIFY_CONCURRENCY), independent of how many clients upload at once. + +Method (repeatable, the stand must be up): +* for every scenario the api replicas are RECREATED with the scenario's settings, so the cgroup + counter memory.peak starts from an idle process (it never decreases during a container's life); +* idle memory.current of each replica is read; then N clients upload at the same moment through + the LB (a barrier releases them together), each a different file; +* during the run memory.current of every replica is sampled every 50 ms inside the container; + afterwards memory.peak (cgroup v2: all processes of the container incl. djpeg) and VmHWM of + PID 1 (the Python server alone) are read; +* the normal configuration is restored at the end. + + python bench/upload_memory.py --output evidence/memory +""" +from __future__ import annotations + +import argparse +import io +import json +import os +import platform +import statistics +import subprocess +import sys +import threading +import time +import uuid +from pathlib import Path + +import httpx2 as httpx +from PIL import Image + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "student-tests")) +import imagegen # noqa: E402 + +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080") +PASSWORD = "Bench-password-Ω-12345" +MiB = 1024 * 1024 + + +def sh(*args: str, env: dict | None = None, timeout: float = 300) -> str: + return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, check=True, timeout=timeout, + env={**os.environ, **(env or {})}).stdout + + +def replicas() -> list[str]: + return sh("docker", "compose", "ps", "-q", "api").split() + + +def cg(cid: str, name: str) -> int: + return int(sh("docker", "exec", cid, "cat", f"/sys/fs/cgroup/{name}").split()[0]) + + +def memory_stat(cid: str, key: str) -> int: + for line in sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.stat").splitlines(): + name, value = line.split() + if name == key: + return int(value) + return 0 + + +def vmhwm(cid: str) -> int: + for line in sh("docker", "exec", cid, "cat", "/proc/1/status").splitlines(): + if line.startswith("VmHWM:"): + return int(line.split()[1]) * 1024 + return 0 + + +def container_events() -> dict[str, str]: + """restart count + OOM-kill events per container (cgroup memory.events oom_kill counter).""" + out = {} + for cid in sh("docker", "compose", "ps", "-q").split(): + name, restarts = sh("docker", "inspect", "-f", "{{.Name}} {{.RestartCount}}", cid).split() + events = dict(line.split() for line in sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.events").splitlines()) + out[name.lstrip("/")] = f"restarts={restarts} oom_kill={events.get('oom_kill', '?')}" + return out + + +def recreate(env: dict) -> None: + sh("docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "--wait", "api", env=env, timeout=300) + sh(sys.executable, "scripts/lbctl.py", "wait-up", str(len(replicas())), "--timeout", "90") # LB sees them UP + time.sleep(3) + + +class Sampler(threading.Thread): + """memory.current of one container every 50 ms, read by a shell loop inside it.""" + + def __init__(self, cid: str): + super().__init__(daemon=True) + self.cid = cid + self.values: list[int] = [] + self.proc = subprocess.Popen(["docker", "exec", cid, "sh", "-c", + "while :; do cat /sys/fs/cgroup/memory.current; sleep 0.05; done"], + stdout=subprocess.PIPE, text=True) + + def run(self) -> None: + for line in self.proc.stdout: + if line.strip().isdigit(): + self.values.append(int(line)) + + def stop(self) -> None: + self.proc.kill() + + +def actor(client: httpx.Client) -> tuple[str, str]: + name = "mem_" + uuid.uuid4().hex[:10] + client.post("/api/v1/users", json={"username": name, "display_name": "bench", "password": PASSWORD}).raise_for_status() + import base64 + basic = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode() + token = client.post("/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}).json()["token"] + me = client.get("/api/v1/users/me", headers={"Authorization": "Bearer " + token}).json() + chat = client.post("/api/v1/chats", headers={"Authorization": "Bearer " + token}, + json={"title": "mem", "member_ids": [me["id"]]}).json() + return token, chat["id"] + + +def big_jpeg(width: int, height: int, seed: int) -> bytes: + """Large progressive JPEG (smooth content keeps it < 10 MiB): the costliest file to check.""" + image = Image.linear_gradient("L").resize((width, height)).convert("RGB") + image.putpixel((seed % width, 0), (seed % 255, 0, 0)) + out = io.BytesIO() + image.save(out, "JPEG", quality=90, progressive=True, subsampling=0) + return out.getvalue() + + +def run_scenario(name: str, env: dict, files: list[tuple[bytes, str]]) -> dict: + recreate(env) + ids = replicas() + idle = {cid: cg(cid, "memory.current") for cid in ids} + client = httpx.Client(base_url=BASE, timeout=120) + token, chat_id = actor(client) + barrier = threading.Barrier(len(files)) + results: list[tuple[int, float, str]] = [None] * len(files) # type: ignore[list-item] + + def upload(i: int, data: bytes, ctype: str) -> None: + c = httpx.Client(base_url=BASE, timeout=120) + barrier.wait() + started = time.perf_counter() + r = c.post(f"/api/v1/chats/{chat_id}/attachments?filename=f{i}", content=data, + headers={"Authorization": "Bearer " + token, "Content-Type": ctype}) + reason = r.json()["error"]["message"] if r.status_code != 201 else "" + results[i] = (r.status_code, time.perf_counter() - started, r.headers.get("x-instance-id", "-"), reason) + c.close() + + s3_id = sh("docker", "compose", "ps", "-q", "s3").strip() + restarts_before = container_events() + samplers = [Sampler(cid) for cid in ids] + [Sampler(s3_id)] + for s in samplers: + s.start() + time.sleep(0.5) + threads = [threading.Thread(target=upload, args=(i, d, t)) for i, (d, t) in enumerate(files)] + wall = time.perf_counter() + for t in threads: + t.start() + for t in threads: + t.join() + wall = time.perf_counter() - wall + time.sleep(0.5) + for s in samplers: + s.stop() + per_replica = {} + for cid, s in zip(ids, samplers[:-1]): + hostname = sh("docker", "inspect", "-f", "{{.Config.Hostname}}", cid).strip() + per_replica[hostname] = { + "idle_mib": round(idle[cid] / MiB, 1), + "peak_mib": round(cg(cid, "memory.peak") / MiB, 1), + "sampled_max_mib": round(max(s.values or [0]) / MiB, 1), + "python_vmhwm_mib": round(vmhwm(cid) / MiB, 1), + "uploads_served": sum(1 for r in results if r[2] == hostname), + "limit_mib": round(cg(cid, "memory.max") / MiB, 1), + } + per_replica[hostname]["peak_minus_idle_mib"] = round(per_replica[hostname]["peak_mib"] + - per_replica[hostname]["idle_mib"], 1) + lat = sorted(r[1] for r in results if r[0] == 201) + codes: dict[str, int] = {} + reasons: dict[str, int] = {} + for r in results: + codes[str(r[0])] = codes.get(str(r[0]), 0) + 1 + if r[3]: + reasons[r[3]] = reasons.get(r[3], 0) + 1 + summary = { + "scenario": name, "settings": env, "clients": len(files), + "s3_sampled_max_mib": round(max(samplers[-1].values or [0]) / MiB, 1), + "s3_anon_after_mib": round(memory_stat(s3_id, "anon") / MiB, 1), + "s3_limit_mib": round(cg(s3_id, "memory.max") / MiB, 1), + # OOM kills / restarts DURING the scenario (any container of the stand): must be empty + "incidents": {k: v for k, v in container_events().items() if v != restarts_before.get(k)}, + "file_mib_each": round(statistics.mean(len(d) for d, _ in files) / MiB, 2), + "types": sorted({t for _, t in files}), "status_codes": codes, "error_reasons": reasons, "wall_seconds": round(wall, 2), + "latency_s": {"p50": round(lat[len(lat) // 2], 2), "max": round(lat[-1], 2)} if lat else None, + "replicas": per_replica, + } + print(json.dumps(summary, ensure_ascii=False), flush=True) + return summary + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("--clients", type=int, default=16) + p.add_argument("--output", default="evidence/memory") + args = p.parse_args() + out = ROOT / args.output + out.mkdir(parents=True, exist_ok=True) + print("generating files ...", flush=True) + pngs = [(imagegen.png_of_size(int(9.5 * MiB)), "image/png") for _ in range(2 * args.clients)] + jpegs = [(big_jpeg(8000, 5000, i), "image/jpeg") for i in range(args.clients)] + base = {"UPLOAD_CONCURRENCY": "4", "IMAGE_VERIFY_CONCURRENCY": "1"} + n, n2 = args.clients, 2 * args.clients + scenarios = [ + (f"png-9.4MiB x{n}, slots=4 (default)", base, pngs[:n]), + (f"png-9.4MiB x{n2}, slots=4 (default)", base, pngs), + (f"png-9.4MiB x{n2}, slots=16 (bound raised)", {"UPLOAD_CONCURRENCY": "16", "IMAGE_VERIFY_CONCURRENCY": "1"}, pngs), + (f"jpeg-40Mpx-progressive-4:4:4 x{n}, verify=1 (default)", base, jpegs), + (f"jpeg-40Mpx-progressive-4:4:4 x{n}, verify=4", {"UPLOAD_CONCURRENCY": "4", "IMAGE_VERIFY_CONCURRENCY": "4"}, jpegs), + ] + results = [] + sh("docker", "compose", "restart", "s3") # S3 memory counters start from an idle process + sh("docker", "compose", "up", "-d", "--wait", "s3") + try: + for name, env, files in scenarios: + results.append(run_scenario(name, env, files)) + finally: + recreate({}) # back to the compose defaults + meta = { + "date": time.strftime("%Y-%m-%d %H:%M:%S"), "host": platform.platform(), "cpus": os.cpu_count(), + "commit": sh("git", "rev-parse", "--short", "HEAD").strip(), + "api_limits": sh("docker", "inspect", "-f", "{{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}", + replicas()[0]).strip(), + "jpeg_file_mib": round(len(jpegs[0][0]) / MiB, 2), "png_file_mib": round(len(pngs[0][0]) / MiB, 2), + } + (out / "summary.json").write_text(json.dumps({"meta": meta, "scenarios": results}, ensure_ascii=False, indent=1), + encoding="utf-8") + print(json.dumps(meta, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..f1e254b --- /dev/null +++ b/compose.yaml @@ -0,0 +1,683 @@ +# Lab 6 stand = lab 5 + observability (docs/OBSERVABILITY.md): +# api x2 / relay / worker --OTLP/HTTP--> otel-collector --> prometheus (metrics, + alert rules) +# --> loki (logs) --> tempo (traces) +# grafana (127.0.0.1:3000): provisioned datasources + dashboard + Prometheus alert view. +# The application never waits for telemetry: no depends_on on it, bounded SDK queues. +# Network `telemetry` (internal) joins only the apps and these five services. +# +# Lab 5 part: client -> HAProxy (lb) -> API x N (scalable service `api`) +# -> PostgreSQL (metadata, jobs, outbox: source of truth) + Valkey (sessions) +# + SeaweedFS S3 (staging bucket and final bucket, both private) +# relay : outbox in PostgreSQL -> RabbitMQ (publisher confirms) [service `relay`] +# broker : RabbitMQ 4.3, durable quorum queue + dead-letter queue [service `broker`] +# worker : RabbitMQ -> variants -> final bucket + PostgreSQL, then ack [service `worker`] +# From a clean clone (details and Windows notes: REPORT.md, docs/WINDOWS.md): +# python scripts/init_secrets.py # once: random local credentials into ./secrets (git-ignored) +# cp .env.example .env # optional overrides (API_REPLICAS, limits, ...) +# docker compose --env-file .env up -d --build --wait +# Order: postgres/valkey/s3/broker healthy -> migrate + s3-init (ONE run each, exit 0) +# -> api healthy -> lb; relay and worker start after migrate/s3-init. +# Images are pinned by version AND digest. Passwords/keys are passed only as secret files, and +# every service gets only the secrets it needs. Only the LB publishes ports (loopback only). +# Networks: `edge` (lb <-> api); internal (no route outside): `data` (postgres/valkey), +# `storage` (s3), `queue` (broker). The API is NOT on `queue`: it never talks to the broker. +name: mtusi-lab6 + +x-api-env: &api-env + APP_ENV: ${APP_ENV:-lab} + LOG_LEVEL: ${LOG_LEVEL:-info} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_STORE: ${SESSION_STORE:-valkey} + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + DB_POOL_MIN: ${DB_POOL_MIN:-1} + DB_POOL_MAX: ${DB_POOL_MAX:-10} + DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3} + CACHE_TIMEOUT_SECONDS: ${CACHE_TIMEOUT_SECONDS:-0.5} + PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-2} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + # Graceful stop: 3 s drain (readiness 503, still serving) + up to 8 s for in-flight requests. + DRAIN_SECONDS: ${DRAIN_SECONDS:-3} + SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-8} + DOCS_ENABLED: ${DOCS_ENABLED:-true} + MESSAGE_WRITE_PATH: ${MESSAGE_WRITE_PATH:-function} + # S3: the API's own key pair (Write staging + Read final, see infra/seaweedfs/start.sh). + S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-3} + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + UPLOAD_CONCURRENCY: ${UPLOAD_CONCURRENCY:-4} + UPLOAD_QUEUE_TIMEOUT_SECONDS: ${UPLOAD_QUEUE_TIMEOUT_SECONDS:-5} + UPLOAD_READ_TIMEOUT_SECONDS: ${UPLOAD_READ_TIMEOUT_SECONDS:-30} + IMAGE_VERIFY_TIMEOUT_SECONDS: ${IMAGE_VERIFY_TIMEOUT_SECONDS:-10} + IMAGE_VERIFY_CONCURRENCY: ${IMAGE_VERIFY_CONCURRENCY:-1} + JPEG_MAX_MEMORY_MB: ${JPEG_MAX_MEMORY_MB:-256} + PENDING_GRACE_SECONDS: ${PENDING_GRACE_SECONDS:-900} + JANITOR_INTERVAL_SECONDS: ${JANITOR_INTERVAL_SECONDS:-60} + # Lab 5: pipeline version and attempt budget of the jobs created by uploads. + PIPELINE_VERSION: ${PIPELINE_VERSION:-1} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + # Failure experiments only (student-tests, bench/); empty = no injected failures. + FAULT_POINTS: ${API_FAULT_POINTS:-} + +# Lab 6: OpenTelemetry SDK settings shared by api, relay and worker (src/messenger/telemetry.py). +# OTEL_SDK_DISABLED=true = telemetry off (track 1 baseline). Sampler: head sampling in the SDK +# (parentbased_always_on | parentbased_traceidratio + OTEL_TRACES_SAMPLER_ARG). Exporter timeout +# 3 s and bounded batch queues (2048 spans / log records): a dead Collector costs dropped telemetry, +# not memory or request latency. +x-otel-env: &otel-env + OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false} + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TIMEOUT: ${OTEL_EXPORTER_OTLP_TIMEOUT:-3} + OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} + OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-parentbased_always_on} + OTEL_TRACES_SAMPLER_ARG: ${OTEL_TRACES_SAMPLER_ARG:-1.0} + OTEL_METRIC_EXPORT_INTERVAL: ${OTEL_METRIC_EXPORT_INTERVAL:-5000} + OTEL_BSP_MAX_QUEUE_SIZE: ${OTEL_BSP_MAX_QUEUE_SIZE:-2048} + OTEL_BSP_SCHEDULE_DELAY: ${OTEL_BSP_SCHEDULE_DELAY:-1000} + OTEL_BLRP_MAX_QUEUE_SIZE: ${OTEL_BLRP_MAX_QUEUE_SIZE:-2048} + OTEL_BLRP_SCHEDULE_DELAY: ${OTEL_BLRP_SCHEDULE_DELAY:-1000} + +# Settings of the pipeline shared by relay and worker (docs/PIPELINE.md). +x-pipeline-env: &pipeline-env + APP_ENV: ${APP_ENV:-lab} + LOG_LEVEL: ${LOG_LEVEL:-info} + DATABASE_URL_FILE: /run/secrets/database_url + BROKER_URL_FILE: /run/secrets/broker_url + DB_POOL_MAX: ${PIPELINE_DB_POOL_MAX:-6} + DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3} + S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} + S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-3} + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-30} + JOB_RETRY_BASE_SECONDS: ${JOB_RETRY_BASE_SECONDS:-2} + JOB_RETRY_MAX_SECONDS: ${JOB_RETRY_MAX_SECONDS:-60} + QUEUED_REPUBLISH_SECONDS: ${QUEUED_REPUBLISH_SECONDS:-300} + +services: + postgres: + image: postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + # pg_stat_statements: per-statement counters for the experiments. + command: ["postgres", "-c", "shared_preload_libraries=pg_stat_statements", "-c", "max_connections=${PG_MAX_CONNECTIONS:-100}"] + secrets: [postgres_password] + volumes: + - pgdata:/var/lib/postgresql # PostgreSQL 18 image keeps PGDATA under this path + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger -q"] + interval: 2s + timeout: 3s + retries: 30 + start_period: 10s + stop_grace_period: 30s # clean shutdown checkpoint instead of crash recovery + restart: unless-stopped + networks: [data] + deploy: + resources: + limits: {cpus: "${PG_CPUS:-2.0}", memory: "${PG_MEMORY:-1g}"} + + valkey: + image: valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 + # The password goes into a config include readable only by the valkey user, + # so it never appears in the process arguments. docker-entrypoint.sh drops root. + command: + - sh + - -c + - >- + umask 077 && + printf 'requirepass %s\n' "$$(cat /run/secrets/valkey_password)" > /tmp/requirepass.conf && + chown valkey /tmp/requirepass.conf && + exec docker-entrypoint.sh valkey-server /etc/valkey/valkey.conf + secrets: [valkey_password] + volumes: + - ./infra/valkey/valkey.conf:/etc/valkey/valkey.conf:ro + - valkeydata:/data + healthcheck: + test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/valkey_password)\" valkey-cli ping | grep -q PONG"] + interval: 2s + timeout: 3s + retries: 30 + start_period: 5s + restart: unless-stopped + networks: [data] + deploy: + resources: + limits: {cpus: "${VALKEY_CPUS:-0.5}", memory: 256m} + + # S3-compatible object storage (SeaweedFS: master + volume + filer + S3 gateway in one process). + # Bytes live ONLY here, on the named volume s3data: staging bucket (originals accepted before + # 202) and final bucket (published originals and variants). Identities: infra/seaweedfs/start.sh. + s3: + image: chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62 + entrypoint: ["/bin/sh", "/etc/seaweedfs/start.sh"] + environment: + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} + # Go heap target below the container limit: the GC returns memory before the cgroup OOM. + GOMEMLIMIT: ${S3_GOMEMLIMIT:-600MiB} + secrets: + - s3_admin_access_key_id + - s3_admin_secret_access_key + - s3_api_access_key_id + - s3_api_secret_access_key + - s3_worker_access_key_id + - s3_worker_secret_access_key + - s3_auditor_access_key_id + - s3_auditor_secret_access_key + volumes: + - ./infra/seaweedfs/start.sh:/etc/seaweedfs/start.sh:ro + - s3data:/data + healthcheck: + # Unauthenticated health endpoint of the S3 gateway (200 once it serves requests). + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8333/healthz"] + interval: 2s + timeout: 3s + retries: 30 + start_period: 10s + stop_grace_period: 30s + restart: unless-stopped + networks: [storage] + deploy: + resources: + limits: {cpus: "${S3_CPUS:-1.0}", memory: "${S3_MEMORY:-1g}"} + + # Lab 5: RabbitMQ. Topology (exchange, quorum queue, DLX/DLQ) and users come from definition + # files imported at boot (infra/rabbitmq, secrets/rabbitmq_users.json). Messages of the quorum + # queue live on the named volume rabbitmqdata. No management UI, no host port. + broker: + image: rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5 + hostname: broker # node name rabbit@broker: stable across container re-creation + secrets: + - source: rabbitmq_users + target: /etc/rabbitmq/definitions.d/users.json + volumes: + - ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/conf.d/20-lab5.conf:ro + - ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro + - ./infra/rabbitmq/topology.json:/etc/rabbitmq/definitions.d/topology.json:ro + - rabbitmqdata:/var/lib/rabbitmq + healthcheck: + # The node runs and the AMQP listener accepts connections. + test: ["CMD-SHELL", "rabbitmq-diagnostics -q ping && rabbitmq-diagnostics -q check_port_connectivity"] + interval: 5s + timeout: 10s + retries: 30 + start_period: 20s + stop_grace_period: 30s + restart: unless-stopped + networks: [queue] + deploy: + resources: + limits: {cpus: "${BROKER_CPUS:-1.0}", memory: "${BROKER_MEMORY:-512m}"} + + # One-shot schema migration: runs ONCE per `up`, before any API replica starts + # (api depends_on service_completed_successfully). Replicas never migrate themselves. + migrate: + build: + context: . + args: + BUILD_REVISION: ${BUILD_REVISION:-dev} + image: ${API_IMAGE:-mtusi-messenger:lab6} + command: ["python", "-m", "messenger.migrate"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + secrets: [database_url] + depends_on: + postgres: + condition: service_healthy + healthcheck: + disable: true + restart: "no" + networks: [data] + deploy: + resources: + limits: {cpus: "0.5", memory: 256m} + + # One-shot, idempotent S3 bootstrap: both buckets, sentinel object, verification of the access + # model (private buckets, least-privilege keys). The ONLY holder of the admin key pair besides s3. + s3-init: + image: ${API_IMAGE:-mtusi-messenger:lab6} + command: ["python", "-m", "messenger.s3_bootstrap"] + environment: + S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} + S3_ADMIN_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key_id + S3_ADMIN_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_access_key + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_api_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_api_secret_access_key + S3_WORKER_ACCESS_KEY_ID_FILE: /run/secrets/s3_worker_access_key_id + S3_WORKER_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_worker_secret_access_key + S3_AUDITOR_ACCESS_KEY_ID_FILE: /run/secrets/s3_auditor_access_key_id + S3_AUDITOR_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_auditor_secret_access_key + secrets: + - s3_admin_access_key_id + - s3_admin_secret_access_key + - s3_api_access_key_id + - s3_api_secret_access_key + - s3_worker_access_key_id + - s3_worker_secret_access_key + - s3_auditor_access_key_id + - s3_auditor_secret_access_key + depends_on: + s3: + condition: service_healthy + migrate: + condition: service_completed_successfully # same image: built once by `migrate` + healthcheck: + disable: true + restart: "no" + networks: [storage] + deploy: + resources: + limits: {cpus: "0.5", memory: 256m} + + api: + build: + context: . + args: + BUILD_REVISION: ${BUILD_REVISION:-dev} + image: ${API_IMAGE:-mtusi-messenger:lab6} + environment: + <<: [*api-env, *otel-env] + OTEL_SERVICE_NAME: messenger-api + secrets: + - database_url + - cache_url + - source: s3_api_access_key_id + target: s3_access_key_id + - source: s3_api_secret_access_key + target: s3_secret_access_key + # No `ports` and no container_name: replicas are reachable only through `lb`, + # and `--scale api=N` / deploy.replicas works. X-Instance-Id = container hostname. + expose: ["8080"] + healthcheck: + test: ["CMD", "python", "-m", "messenger.healthcheck"] + interval: 2s + timeout: 2s + retries: 3 + start_period: 5s + depends_on: + postgres: + condition: service_healthy + valkey: + condition: service_healthy + s3: + condition: service_healthy + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + stop_grace_period: 15s # > DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS (11 s) + restart: unless-stopped + networks: [edge, data, storage, telemetry] + deploy: + replicas: ${API_REPLICAS:-2} + resources: + # 512m: UPLOAD_CONCURRENCY (4) x 10 MiB bodies + one djpeg (<= JPEG_MAX_MEMORY_MB) + runtime; + # measured in lab 4 (bench/upload_memory.py). No resizing happens in the API. + limits: {cpus: "${API_CPUS:-1.0}", memory: "${API_MEMORY:-512m}"} + # No swap on top of the limit (Docker's default would allow as much swap again): the RAM bound + # of the experiments is a real bound, and running out of it is visible, not hidden in swap. + memswap_limit: ${API_MEMORY:-512m} + + lb: + image: haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + ports: + # The ONLY public entry point, on the loopback interfaces only. Both IPv4 and IPv6: + # on Windows `localhost` resolves to ::1 first, and a refused ::1 connection costs ~2 s + # per request before the fallback to 127.0.0.1 (measured in lab 3: 2.0 s vs 0.007 s). + - "127.0.0.1:${APP_PUBLISH_PORT:-8080}:8080" + - "[::1]:${APP_PUBLISH_PORT:-8080}:8080" + - "127.0.0.1:${LB_STATS_PORT:-8404}:8404" # local status page (UP/DOWN of replicas) + healthcheck: + # Config is valid and the process answers; whether any API is ready is the LB's own job. + test: ["CMD-SHELL", "haproxy -c -q -f /usr/local/etc/haproxy/haproxy.cfg && wget -q -O /dev/null http://127.0.0.1:8404/"] + interval: 5s + timeout: 3s + retries: 3 + depends_on: + api: + condition: service_healthy + restart: unless-stopped + networks: [edge] + deploy: + resources: + limits: {cpus: "${LB_CPUS:-1.0}", memory: 128m} + + # Lab 5: outbox relay + lease reaper (src/messenger/relay.py). One process; a second one would + # be safe (SKIP LOCKED) but is not needed. Database + broker only, no S3 keys. + relay: + image: ${API_IMAGE:-mtusi-messenger:lab6} + command: ["python", "-m", "messenger.relay"] + environment: + <<: [*pipeline-env, *otel-env] + OTEL_SERVICE_NAME: messenger-relay + RELAY_POLL_SECONDS: ${RELAY_POLL_SECONDS:-0.5} + FAULT_POINTS: ${RELAY_FAULT_POINTS:-} + secrets: + - database_url + - source: broker_url_relay + target: broker_url + healthcheck: + test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"] + interval: 5s + timeout: 3s + retries: 3 + start_period: 10s + depends_on: + postgres: + condition: service_healthy + broker: + condition: service_healthy + migrate: + condition: service_completed_successfully + stop_grace_period: 10s + restart: unless-stopped + networks: [data, queue, telemetry] + deploy: + resources: + limits: {cpus: "${RELAY_CPUS:-0.5}", memory: 256m} + + # Lab 5: image worker (src/messenger/worker.py). Scalable (`--scale worker=2`): competing + # consumers of one queue; the database lease decides who works on a job. + worker: + image: ${API_IMAGE:-mtusi-messenger:lab6} + command: ["python", "-m", "messenger.worker"] + environment: + <<: [*pipeline-env, *otel-env] + OTEL_SERVICE_NAME: messenger-worker + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + WORKER_SHUTDOWN_SECONDS: ${WORKER_SHUTDOWN_SECONDS:-20} + IMAGE_MAX_MEMORY_MB: ${IMAGE_MAX_MEMORY_MB:-768} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} + ORPHAN_GRACE_SECONDS: ${ORPHAN_GRACE_SECONDS:-600} + CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30} + FAULT_POINTS: ${WORKER_FAULT_POINTS:-} + secrets: + - database_url + - source: broker_url_worker + target: broker_url + - source: s3_worker_access_key_id + target: s3_access_key_id + - source: s3_worker_secret_access_key + target: s3_secret_access_key + healthcheck: + test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"] + interval: 5s + timeout: 3s + retries: 3 + start_period: 10s + depends_on: + postgres: + condition: service_healthy + broker: + condition: service_healthy + s3: + condition: service_healthy + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + stop_grace_period: 30s # > WORKER_SHUTDOWN_SECONDS (20 s) + release + restart: unless-stopped + networks: [data, storage, queue, telemetry] + deploy: + replicas: ${WORKER_REPLICAS:-1} + resources: + # WORKER_CONCURRENCY (2) child processes x IMAGE_MAX_MEMORY_MB (768) address space + worker. + limits: {cpus: "${WORKER_CPUS:-2.0}", memory: "${WORKER_MEMORY:-1536m}"} + memswap_limit: ${WORKER_MEMORY:-1536m} + + # Track 2: read-only checker of the pipeline invariants (database in read-only transactions, + # S3 auditor key: Read + List, no Write). On demand: docker compose run --rm auditor + auditor: + profiles: ["tools"] + image: ${API_IMAGE:-mtusi-messenger:lab6} + entrypoint: ["python", "-m", "messenger.audit"] + command: [] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + DB_TIMEOUT_SECONDS: ${AUDIT_DB_TIMEOUT_SECONDS:-30} + S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-3} + secrets: + - database_url + - source: s3_auditor_access_key_id + target: s3_access_key_id + - source: s3_auditor_secret_access_key + target: s3_secret_access_key + depends_on: + postgres: + condition: service_healthy + s3: + condition: service_healthy + restart: "no" + networks: [data, storage] + deploy: + resources: + limits: {cpus: "1.0", memory: 256m} + + # Operator CLI (replay of failed jobs, reprocess with a newer pipeline, failed registry): + # docker compose run --rm jobctl list-failed + # docker compose run --rm jobctl replay --operator alice --reason "..." + jobctl: + profiles: ["tools"] + image: ${API_IMAGE:-mtusi-messenger:lab6} + entrypoint: ["python", "-m", "messenger.jobctl"] + command: [] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + secrets: [database_url] + depends_on: + postgres: + condition: service_healthy + restart: "no" + networks: [data] + deploy: + resources: + limits: {cpus: "0.5", memory: 128m} + + # ------------------------------------------------------------------ lab 6: observability + # Receives OTLP from api/relay/worker, limits memory, batches, forwards to the three stores. + # Distroless image (no shell): its health is the `up{job="otel-collector"}` scrape of :8888. + otel-collector: + image: otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea + command: + - --config=/etc/otelcol/collector.yaml + # traces-all (keep every span) | traces-tail (tail sampling, track 1) + - --config=/etc/otelcol/${OTEL_COLLECTOR_TRACES:-traces-all}.yaml + environment: + GOMEMLIMIT: 360MiB # Go heap target under the 512 MiB container limit + volumes: + - ./infra/otel:/etc/otelcol:ro + restart: unless-stopped + networks: [telemetry] + deploy: + resources: + limits: {cpus: "${COLLECTOR_CPUS:-1.0}", memory: 512m} + memswap_limit: 512m + + # Metrics store + alert rules (OTLP receiver for the Collector's pushes; scrapes otelcol_*). + prometheus: + image: prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06 + command: + - --config.file=/etc/prometheus/prometheus.yml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=15d + - --storage.tsdb.retention.size=2GB + - --web.enable-otlp-receiver + - --web.listen-address=:9090 + volumes: + - ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - ./infra/prometheus/rules:/etc/prometheus/rules:ro + - promdata:/prometheus + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9090/-/ready"] + interval: 5s + timeout: 3s + retries: 30 + start_period: 10s + stop_grace_period: 30s + restart: unless-stopped + networks: [telemetry] + deploy: + resources: + limits: {cpus: "${PROMETHEUS_CPUS:-1.0}", memory: 512m} + memswap_limit: 512m + + # Logs store (OTLP endpoint /otlp). Distroless: health = up{job="loki"} + /ready via Grafana. + loki: + image: grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7 + command: ["-config.file=/etc/loki/lab6.yaml"] + volumes: + - ./infra/loki/loki.yaml:/etc/loki/lab6.yaml:ro + - lokidata:/loki + stop_grace_period: 30s + restart: unless-stopped + networks: [telemetry] + deploy: + resources: + limits: {cpus: "${LOKI_CPUS:-1.0}", memory: 512m} + memswap_limit: 512m + + # Traces store (OTLP/HTTP :4318, query API :3200). Distroless: health = up{job="tempo"}. + tempo: + image: grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38 + command: ["-config.file=/etc/tempo/lab6.yaml"] + volumes: + - ./infra/tempo/tempo.yaml:/etc/tempo/lab6.yaml:ro + - tempodata:/var/tempo + stop_grace_period: 30s + restart: unless-stopped + networks: [telemetry] + deploy: + resources: + limits: {cpus: "${TEMPO_CPUS:-1.0}", memory: 512m} + memswap_limit: 512m + + # UI: datasources (fixed UIDs) and the dashboard are provisioned from Git; only this port and the + # LB are published, on loopback. Admin password = secrets/grafana_admin_password (init_secrets.py). + grafana: + image: grafana/grafana:13.2.6@sha256:b21409d7951ddcfd63a4b49083e4ef2cc35bc1437d071813bf82bfb238b00bca + environment: + GF_SECURITY_ADMIN_USER: admin + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + GF_USERS_ALLOW_SIGN_UP: "false" + GF_AUTH_ANONYMOUS_ENABLED: "false" + GF_ANALYTICS_REPORTING_ENABLED: "false" + GF_ANALYTICS_CHECK_FOR_UPDATES: "false" + GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES: "false" + GF_NEWS_NEWS_FEED_ENABLED: "false" + GF_PLUGINS_PREINSTALL_DISABLED: "true" # no plugin downloads at start: works offline + GF_DASHBOARDS_DEFAULT_HOME_DASHBOARD_PATH: /var/lib/grafana/dashboards/messenger.json + GF_LOG_LEVEL: warn + GOMEMLIMIT: 700MiB # Go heap target under the 1 GiB limit (512 MiB was not enough: GC thrashing) + secrets: [grafana_admin_password] + volumes: + - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + - grafanadata:/var/lib/grafana + ports: + - "127.0.0.1:${GRAFANA_PORT:-3000}:3000" + - "[::1]:${GRAFANA_PORT:-3000}:3000" + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:3000/api/health"] + interval: 5s + timeout: 3s + retries: 30 + start_period: 20s + depends_on: + prometheus: + condition: service_healthy + loki: + condition: service_started + tempo: + condition: service_started + restart: unless-stopped + networks: [telemetry, ui] + deploy: + resources: + limits: {cpus: "${GRAFANA_CPUS:-1.0}", memory: 1g} + memswap_limit: 1g + +networks: + edge: + data: + internal: true # no route outside: stores talk only to the services above + storage: + internal: true # S3 API reachable only by api, s3-init, worker, auditor + queue: + internal: true # broker reachable only by relay and worker + telemetry: + internal: true # OTLP + stores: apps, collector, prometheus, loki, tempo, grafana + ui: # only Grafana: publishes 127.0.0.1:3000 + +volumes: + pgdata: + valkeydata: + s3data: + rabbitmqdata: + promdata: + lokidata: + tempodata: + grafanadata: + +secrets: + postgres_password: + file: ./secrets/postgres_password + valkey_password: + file: ./secrets/valkey_password + database_url: + file: ./secrets/database_url + cache_url: + file: ./secrets/cache_url + s3_admin_access_key_id: + file: ./secrets/s3_admin_access_key_id + s3_admin_secret_access_key: + file: ./secrets/s3_admin_secret_access_key + s3_api_access_key_id: + file: ./secrets/s3_api_access_key_id + s3_api_secret_access_key: + file: ./secrets/s3_api_secret_access_key + s3_worker_access_key_id: + file: ./secrets/s3_worker_access_key_id + s3_worker_secret_access_key: + file: ./secrets/s3_worker_secret_access_key + s3_auditor_access_key_id: + file: ./secrets/s3_auditor_access_key_id + s3_auditor_secret_access_key: + file: ./secrets/s3_auditor_secret_access_key + rabbitmq_users: + file: ./secrets/rabbitmq_users.json + broker_url_relay: + file: ./secrets/broker_url_relay + broker_url_worker: + file: ./secrets/broker_url_worker + grafana_admin_password: + file: ./secrets/grafana_admin_password diff --git a/docs/DATA_MODEL.md b/docs/DATA_MODEL.md new file mode 100644 index 0000000..59dae32 --- /dev/null +++ b/docs/DATA_MODEL.md @@ -0,0 +1,57 @@ +# Модель данных lab5 + +Схема: [0001_init.sql](../migrations/0001_init.sql) (lab2), [0002_idempotency_keys.sql](../migrations/0002_idempotency_keys.sql) и [0003_post_message_function.sql](../migrations/0003_post_message_function.sql) (lab3), [0004_attachments.sql](../migrations/0004_attachments.sql) (lab4), [0005_pipeline.sql](../migrations/0005_pipeline.sql) (lab5: задания, outbox, попытки, варианты). Миграции применяет один раз отдельный сервис `migrate` до старта реплик API; миграции lab3–lab5 только добавляют объекты (0004 ослабляет `CHECK` длины текста, 0005 — `CHECK` статуса и ключа объекта), поэтому совместимы с работающей предыдущей версией. Байты вложений живут **только** в двух приватных bucket S3 (SeaweedFS): `messenger-staging` (оригинал до обработки) и `messenger-attachments` (опубликованный оригинал и варианты); в PostgreSQL — метаданные, задания и их история. Порядок записи и окна отказа — [PIPELINE.md](PIPELINE.md). Источник истины для пользователей, чатов, участников и сообщений — PostgreSQL 18. Для сессий источник истины — хранилище, выбранное через `SESSION_STORE`. По умолчанию это Valkey с AOF, его можно переключить на таблицу `sessions` в PostgreSQL. + +## Таблицы и ограничения + +| Таблица | Ключ | Ограничения | Зачем | +| --- | --- | --- | --- | +| `users` | `id uuid` | `UNIQUE (username)`, `CHECK` формата username, длина `display_name` | уникальность имени держит БД, а не код: гонку регистрации разрешает уникальный индекс | +| `chats` | `id uuid` | FK `created_by → users`, длина `title` | `last_message_at` — «часы» чата для упорядочивания сообщений | +| `chat_members` | `(chat_id, user_id)` | FK на `chats` и `users`, `UNIQUE (chat_id, position)` | `position` хранит порядок `member_ids`; `chat_created_at` — копия времени чата для keyset-списка чатов | +| `messages` | `id uuid` | FK `(chat_id, sender_id) → chat_members`, длина `text` | отправитель обязан быть участником — это гарантирует сама БД | +| `sessions` | `token_hash bytea` | FK `user_id → users`, длина хеша 32 байта | хранится SHA-256 токена; сам токен не хранится нигде | +| `idempotency_keys` | `(user_id, chat_id, key)` | FK на `users`, `chats`; `message_id → messages` (DEFERRABLE, `UNIQUE`); `CHECK` формата ключа и длины SHA-256 | общая для всех реплик идемпотентность отправки: ключ → отпечаток тела → сообщение. Хранится ≥ `IDEMPOTENCY_TTL_SECONDS` (24 ч), очистка — пачками раз в 10 мин под advisory-замком | +| `attachments` (lab4, lab5) | `id uuid` | FK `(chat_id, owner_id) → chat_members`; `UNIQUE object_key`, `UNIQUE staging_key` (`COLLATE "C"`); `CHECK` статуса `pending/queued/processing/ready/failed`, формата ключей, типа, размера, пикселей ≤ 40 млн; **`attachments_active_has_source`**: у `queued/processing` есть опубликованный оригинал или staging `present`; `ready` ⇒ `object_key` и `published_version`; `failed` ⇔ `error_code` + `failed_at` | метаданные оригинала. `staging_key` (`s/<128 бит>`) — копия в staging, `staging_state none/present/deleting/deleted`; `object_key` — опубликованный оригинал (`a///original`, у строк lab4 — `o/`). `published_version` — версия pipeline, чьи варианты видны, только растёт | +| `jobs` (lab5) | `id uuid` = job_id | FK на `attachments`; `CHECK` состояния, вида (`upload/replay/reprocess/migrate`), `attempt ≤ max_attempts`, lease есть ⇔ `processing`, `finished_at` ⇔ конечное; частичный `UNIQUE (attachment_id, pipeline_version) WHERE state IN ('queued','processing')` | одна логическая работа «версия V для вложения A». `available_at` — backoff, `lease_token`/`lease_until`/`lease_owner` — аренда текущей попытки (fencing). Индексы: истекающие lease, queued, failed | +| `job_attempts` (lab5) | `token uuid` | FK на `jobs`; `UNIQUE (job_id, attempt)`; `CHECK` исхода `running/succeeded/retry/failed/abandoned/superseded`; опубликованную попытку нельзя «почистить» | один claim worker. `planned_keys` — ключи всех объектов попытки, записаны ДО записи в S3: уборке не нужен List. Частичный индекс — кандидаты на уборку | +| `attachment_variants` (lab5) | `(attachment_id, pipeline_version, name)` | FK на `attachments`, `job_attempts`; `UNIQUE object_key`, `CHECK` имени, типа, размера, длины SHA-256 | опубликованные варианты; первичный ключ — ключ эффекта контракта, дубль физически невозможен | +| `outbox` (lab5) | `id bigint` identity | FK на `jobs`; `attempt ≥ 1` | намерение опубликовать сообщение; пишется в одной транзакции с изменением задания. Частичный индекс `WHERE published_at IS NULL` — работа relay | +| `job_events` (lab5) | `id bigint` identity | FK на `jobs` | аудит: создание, claim, retry с задержкой, lease_expired, replay/reprocess (оператор и причина), результат, внедрённые отказы. Без секретов и имён файлов. View `failed_jobs` — реестр failed | +| `message_attachments` (lab4) | `(message_id, position)` | FK на `messages` и `attachments`, `UNIQUE (message_id, attachment_id)`, индекс по `attachment_id` | целостность ссылок (вложение, на которое ссылается сообщение, удалить нельзя) и обратный поиск «используется ли вложение» | +| `schema_migrations` | `version` | checksum файла | какие миграции применены; изменённую задним числом миграцию мигратор не применит | + +**Почему `bytea` для текста.** Контракт разрешает символ U+0000, а тип `text` в PostgreSQL не может содержать байт NUL (`DataError`). Поэтому `display_name`, `title` и `text` хранятся как байты UTF-8. Длину в code points проверяет API, а `CHECK` в байтах — страховка (1 code point ≤ 4 байта). + +## Индексы и запросы + +- `messages_chat_keyset (chat_id, created_at, id)`. Первая страница — `WHERE chat_id=$1 ORDER BY created_at, id LIMIT n`, следующая — `WHERE chat_id=$1 AND (created_at, id) > ($2, $3) ORDER BY ... LIMIT n`. Сравнение строк `(created_at, id) > (...)` попадает в `Index Cond`: поиск начинается прямо с позиции cursor и читает только `n+1` строк. Запросов два, а не один с `($2 IS NULL OR ...)`: иначе при generic plan условие cursor уходит в `Filter`, и поздняя страница сканирует всю историю чата до неё. +- `chat_members_user_keyset (user_id, chat_created_at, chat_id)` — список чатов пользователя тем же keyset-способом. +- `users_username_key` — вход по username и уникальность. +- `sessions_expires_at` — очистка истёкших сессий. + +## Транзакционные границы + +| Операция | Транзакция | Что гарантирует | +| --- | --- | --- | +| Регистрация | один `INSERT` | `UniqueViolation` → 409; ровно одна строка при гонке | +| Создание чата | `INSERT chats` → `INSERT chat_members` (все участники одним запросом) → `COMMIT` | неизвестный участник вызывает FK-ошибку **после** вставки чата; откат удаляет и чат, и частичное членство | +| Сообщение (lab3, с ключом) | проверка членства → `INSERT idempotency_keys … ON CONFLICT DO UPDATE … WHERE ключ старше 24 ч` → если вставлен: `UPDATE chats … RETURNING` → `INSERT messages`; если нет: прочитать сохранённое сообщение и сравнить отпечаток → `COMMIT`. По умолчанию всё это — одна SQL-функция `post_message` в autocommit (одно обращение к БД) | ключ, сообщение и «результат» коммитятся вместе или не коммитятся вовсе: «висящего» ключа нет. Конкурентный повтор ждёт на уникальном индексе завершения первой транзакции и затем видит её результат (READ COMMITTED, новый снимок на каждый оператор). Другое тело → 409, тот же — тот же Message | +| Сообщение с `attachment_ids` (lab4, lab5) | функция `post_message_v3` (0005): проверка членства → проверка вложений (этого чата, не `pending`; `failed`/карантин → 409; `FOR SHARE`) → только если всё хорошо — захват ключа → `UPDATE chats` → `INSERT messages (…, attachment_ids)` → `INSERT message_attachments` | чужое/неизвестное/незавершённое вложение — 404, в карантине — 409, ключ при этом не «сгорает». Порядок `attachment_ids` хранится массивом в строке сообщения: страница истории остаётся одним диапазонным сканом индекса | +| Загрузка вложения (lab5) | `INSERT attachments … 'pending'` (autocommit) → S3 PUT в staging (Content-MD5) → **одна транзакция**: `UPDATE … SET status='queued' WHERE status='pending'` + `INSERT jobs` + `INSERT outbox` + `INSERT job_events` → 202 | 202 только когда оригинал в staging и задание с outbox зафиксированы. Сбой до COMMIT оставляет невидимый `pending`, его убирает janitor. Компенсации в обработчике нет | +| Claim (worker) | `SELECT jobs … FOR UPDATE` → решение (no-op / superseded / работа) → `SELECT attachments … FOR UPDATE` → `UPDATE jobs` (processing, attempt+1, lease, token) + `INSERT job_attempts` + `UPDATE attachments` (processing) + событие | дубль доставки видит конечное состояние или чужой lease и ничего не делает | +| Результат (worker) | `SELECT jobs … FOR UPDATE` (проверка токена) → `SELECT attachments … FOR UPDATE` → если версия не новее опубликованной: `superseded`; иначе `INSERT attachment_variants` ×3 + `UPDATE attachments` (ready, published_version, object_key) + `UPDATE jobs/job_attempts` + событие → потом ack | результат публикуется атомарно и только владельцем текущей аренды; версия только растёт | +| Retry / failed (worker), lease (relay) | под блокировкой задания: попытка `retry`/`failed`/`abandoned`; задание `queued` с `available_at` + новая строка outbox, или `failed` (реестр) | повтор идёт тем же путём outbox; бесконечного немого retry нет | +| Replay / reprocess (jobctl), уборка staging | `SELECT attachments … FOR UPDATE` (одна и та же блокировка) → проверки → новое задание + outbox, либо `staging_state='deleting'` | уборка и replay сериализованы строкой вложения | +| Порядок блокировок | везде, где нужны обе строки: сначала `jobs`, потом `attachments` | нет взаимных ожиданий в разном порядке | +| Сообщение (lab2-часть) | проверка членства → `UPDATE chats SET last_message_at = greatest(clock_timestamp(), last_message_at + 1 мкс) RETURNING` → `INSERT messages` → `COMMIT` | строка чата заблокирована до конца транзакции, поэтому писатели одного чата идут по очереди. Время сообщений строго растёт **в порядке коммитов**: страница по cursor не пропустит сообщение, закоммиченное «задним числом» | +| Вход | `SELECT` пользователя, проверка Argon2id, запись сессии | неверный пароль ничего не пишет | +| Logout | `DELETE` сессии (или `DEL` в Valkey) | повтор с тем же токеном — 401 | + +Чтение истории не требует snapshot между HTTP-запросами (так в контракте): новое сообщение появится на следующей странице. Список чатов сортируется по `chats.created_at = clock_timestamp()` без блокировки. Два чата, создаваемые одновременно, могут закоммититься не в порядке времени. Тогда у обхода, который уже начался, такой чат может оказаться «до» cursor; новый обход его увидит. Чаты создаются редко, поэтому мы не сериализуем их глобальным замком; это ограничение описано в REPORT.md. + +## Сессии + +- Токен: `secrets.token_urlsafe(32)` — 256 бит случайности, в ответе 43 символа. В хранилище лежит только SHA-256 токена. Для случайного 256-битного значения быстрого хеша достаточно, медленный KDF нужен только для низкоэнтропийных паролей. +- `SESSION_STORE=valkey` (по умолчанию): ключ `session:`, значение `{user_id, expires_at}`. Срок жизни задаётся абсолютным `PXAT expires_at`, поэтому рестарт его не продлевает. Включён `appendonly yes` + `appendfsync always`: подтверждённые вход и logout сохраняются до ответа клиенту. Valkey — **единственное** хранилище сессий, это не кэш над PostgreSQL. Поэтому нет второй копии, которая могла бы «оживить» отозванный токен после отказа. Если Valkey недоступен, проверить сессию нельзя: защищённые запросы и logout получают 503, анонимный доступ не открывается. +- `SESSION_STORE=postgres`: таблица `sessions`, проверка `expires_at > now()` в запросе. diff --git a/docs/OBSERVABILITY.md b/docs/OBSERVABILITY.md new file mode 100644 index 0000000..063c9aa --- /dev/null +++ b/docs/OBSERVABILITY.md @@ -0,0 +1,110 @@ +# Наблюдаемость: схема сигналов (lab 6) + +## Путь данных + +``` +api ×2 ─┐ ┌─► Prometheus 3.16 (метрики + recording/alert rules, том promdata) +relay ─┼─ OTLP/HTTP protobuf ─► otel-collector ─┼─► Loki 3.7 (логи, том lokidata) +worker ─┘ :4318, сеть telemetry 0.165 contrib └─► Tempo 2.10 (трассы, том tempodata) + ▲ + Grafana 13.2 (127.0.0.1:3000) ────────────┘ datasources с фиксированными UID, + dashboard из Git (provisioning) +Prometheus сам опрашивает (scrape): otel-collector:8888, loki, tempo, grafana, себя. +``` + +| Компонент | Зачем | Что хранит / делает | Где конфиг | +| --- | --- | --- | --- | +| OpenTelemetry SDK (Python 1.45.2) | Создаёт сигналы в процессе | spans, metrics, log records → OTLP | `src/messenger/telemetry.py` | +| OTel Collector contrib 0.165.0 | Принять, ограничить, сгруппировать, разослать | **ничего не хранит**: memory_limiter → batch → 3 exporter-а с ограниченной очередью | `infra/otel/collector.yaml`, `traces-*.yaml` | +| Prometheus 3.16.0 | Метрики: «сколько и как быстро» во времени | TSDB 15 дней / 2 GB; OTLP receiver; правила SLI и алертов | `infra/prometheus/` | +| Loki 3.7.10 | Логи: «что именно произошло» | строки + structured metadata, 7 дней | `infra/loki/loki.yaml` | +| Tempo 2.10.10 | Трассы: «где по пути ушло время» | spans, 72 ч, поиск TraceQL | `infra/tempo/tempo.yaml` | +| Grafana 13.2.6 | Интерфейс и запросы | только свою БД настроек (том grafanadata); данные не хранит | `infra/grafana/` | + +Grafana не хранит сигналы — она спрашивает три хранилища. Collector не долговременная БД: при недоступном backend он держит ограниченную очередь (100 пачек на exporter) и повторяет до 60 с, потом **отбрасывает и считает** (`otelcol_exporter_send_failed_*`). + +## Ресурсные атрибуты + +| Атрибут | Значение | Откуда | +| --- | --- | --- | +| `service.name` | `messenger-api`, `messenger-relay`, `messenger-worker` | `telemetry.setup()` (+ `OTEL_SERVICE_NAME` в compose) | +| `service.version` | `1.6.0` | `messenger.__version__` | +| `service.instance.id` | hostname контейнера = `X-Instance-Id` | `Settings.instance_id` | +| `deployment.environment.name` | `lab` | `OTEL_RESOURCE_ATTRIBUTES` | + +В Prometheus: `job` = service.name, `instance` = service.instance.id (так делает OTLP receiver), `deployment_environment_name` и `service_version` — promoted labels. В Loki индексные метки: `service_name`, `service_instance_id`, `deployment_environment_name`. + +## Метрики: контракт → имя в SDK → имя в Prometheus + +Prometheus переводит имена OTel с суффиксами единиц и типа (`UnderscoreEscapingWithSuffixes`): точка → `_`, единица `s` → `_seconds`, счётчик → `_total`. + +| Сигнал контракта (уровень) | Инструмент SDK, единица | В Prometheus | Атрибуты (labels) | +| --- | --- | --- | --- | +| HTTP requests, counter (3) | `_count` гистограммы ниже (второго инструмента нет) | `http_server_request_duration_seconds_count` | `http_request_method`, `http_route` (шаблон), `http_response_status_code`, `http_response_status_class` | +| HTTP duration, histogram s (3) | `http.server.request.duration`, s | `http_server_request_duration_seconds_bucket/_sum/_count` | те же; buckets 1 мс…10 с | +| Jobs processed / failed (3) | `messenger.jobs.processed`, {job} | `messenger_jobs_processed_total` | `messenger_job_type`, `outcome` (succeeded, retry, failed, fenced, superseded, released, deferred, cancelled, rejected, noop_*) | +| Job processing duration (3) | `messenger.job.duration`, s | `messenger_job_duration_seconds_*` | `messenger_job_type`, `outcome` | +| Queue depth (4) | `messenger.queue.depth`, {job} (relay, из PostgreSQL) | `messenger_queue_depth` | `messaging_destination_name`, `state` (queued/processing) | +| Oldest job age (4) | `messenger.queue.oldest_age`, s | `messenger_queue_oldest_age_seconds` | `messaging_destination_name` | +| Outbox (диагностика брокера) | `messenger.outbox.pending`, `messenger.outbox.oldest_age` | `messenger_outbox_pending`, `messenger_outbox_oldest_age_seconds` | `state` (due/delayed) | +| DB pool (4) | `db.client.connection.count/max/pending_requests` | `db_client_connection_count` и т. д. | `db_client_connection_pool_name`, `db_client_connection_state` | +| DB время (4, диагностика) | `db.client.operation.duration`, `db.client.connection.wait_time`, s | `db_client_operation_duration_seconds_*`, `db_client_connection_wait_time_seconds_*` | `db_operation_name` (имя функции кода), `outcome`, pool | +| Worker saturation (4) | `messenger.worker.busy` / `messenger.worker.capacity` | `messenger_worker_busy`, `messenger_worker_capacity` | — | +| CPU/RAM (4) | `container.cpu.time` (s), `container.memory.usage/limit` (By), `process.memory.usage` | `container_cpu_time_seconds_total`, `container_memory_usage_bytes` … | — (job/instance) | +| End-to-end time to ready (4) | `messenger.attachment.time_to_ready`, s | `messenger_attachment_time_to_ready_seconds_*` | `messenger_job_kind` | +| HTTP в работе | `http.server.active_requests` | `http_server_active_requests` | `http_request_method` | +| Цена телеметрии (трек 1) | `messenger.telemetry.spans.ended/exported` | `messenger_telemetry_spans_ended_total`, `…_exported_total` | `result` | + +CPU/RAM контейнера читаются из cgroup v2 (`/sys/fs/cgroup/cpu.stat`, `memory.current`) — те же числа, что у `docker stats`, вместе с дочерними процессами worker-а. + +**Почему нет user_id/chat_id/message_id/attachment_id/request_id в labels.** Каждое новое значение label — новый временной ряд (своя запись в индексе, свои chunks в памяти). Чатов миллионы → миллионы рядов → памяти и диска Prometheus не хватит («cardinality explosion»). `http_route` — шаблон `/api/v1/chats/{chat_id}/messages`, неизвестные пути — одно значение `UNMATCHED`. Проверка: `student-tests/test_observability.py::test_no_ids_or_raw_paths_in_metric_labels`. + +**Почему buckets свои.** Стандартные границы OTel (0, 5, 10, 25 … 10000) рассчитаны на миллисекунды; при единице «секунды» все запросы попали бы в один bucket 0–5 с, и p95 показал бы ~4,75 с при реальных 5 мс (так было у других студентов). Границы задаются на каждом инструменте (`explicit_bucket_boundaries_advisory`), проверка: `test_http_metric_attributes_are_low_cardinality_and_buckets_fit_seconds`. + +**Перцентили** считаются только как `histogram_quantile(q, sum by (le) (rate(..._bucket[w])))` — buckets всех реплик складываются до вычисления. Усреднять p99 двух реплик нельзя: p99 — не линейная величина, у реплики с 10 запросами и реплики с 10 000 вес разный. + +## Трассы + +| Span | Kind | Процесс | Важные атрибуты | +| --- | --- | --- | --- | +| `POST /api/v1/chats/{chat_id}/attachments` (и все маршруты) | SERVER | api | `http.route`, `http.response.status_code`, `messenger.request_id`; ERROR только при 5xx | +| `db <функция>` | CLIENT | все | `db.system.name=postgresql`, `db.operation.name`, `db.client.connection.wait_time_ms` | +| `s3 put/get/head/delete/list`, `s3 download` | CLIENT / INTERNAL | api, worker | `aws.s3.bucket`, без ключа объекта | +| `messenger.jobs publish` | PRODUCER | relay | `messaging.*`, `messenger.job.id`, `messenger.job.attempt` | +| `messenger.attachment-jobs process` | CONSUMER | worker | `messenger.job.outcome`, `messenger.job.attempt`, `messenger.attachment.id`, `messenger.job.error_code` | +| `image render` | INTERNAL | worker | content type, размер, список вариантов | + +**Как очередь переносит причинную связь.** В транзакции upload (`jobs.create_job`) текущий W3C context запроса сохраняется в `jobs.traceparent/tracestate` (миграция 0006). Relay публикует каждую строку outbox этого задания как PRODUCER span-потомок сохранённого контекста и кладёт **свой** `traceparent` в тело сообщения (поле `traceparent` из `contracts/jobs.schema.json`) и в AMQP headers. Worker извлекает его и создаёт CONSUMER span-потомок PRODUCER. Retry (через outbox) и истечение lease публикуются снова от того же сохранённого контекста — поэтому все попытки видны в одной трассе upload. Выбор parent-child, а не link: у одной логической работы один причинный предок, а задание из jobctl (без контекста) просто начинает новую трассу. + +Без root span-ов из фоновых циклов: `db`/`s3` span создаётся, только если уже есть записываемый родитель (`telemetry.child_span`). `/health/*` не трассируется (HAProxy опрашивает каждую секунду), но учитывается в метриках. + +## Логи + +Каждая запись — OTLP log record: `timestamp`, `severity_text/number`, `service.name` (ресурс), `event` (= тело записи, короткое имя события: `request`, `attachment_queued`, `job_done`…), `trace_id`/`span_id` активного span-а и поля события (`request_id`, `route`, `status`, `job_id`, `outcome`…). В Loki они — structured metadata, не метки потоков. Тот же JSON с `trace_id`/`span_id` пишется в stdout (`docker compose logs`). Успешные health-пробы в Loki не отправляются (остаются в stdout). + +Никогда не экспортируются: пароль, `Authorization`, session token, текст сообщения, байты изображения, ключи S3, signed URL, query string (cursor, filename), SQL. Проверка: `test_no_secrets_or_message_text_in_logs_and_traces`. + +## Поведение при отказах телеметрии + +| Что упало | Что происходит | Ограничение памяти | Как видно потери | +| --- | --- | --- | --- | +| Tempo / Loki / Prometheus | Collector копит пачки в `sending_queue` (≤100 на exporter), повторяет ≤60 с, потом отбрасывает | memory_limiter 400 MiB (soft 320), GOMEMLIMIT 360 MiB, лимит контейнера 512 MiB | `otelcol_exporter_send_failed_*`, алерт `TelemetryExportFailing` | +| Collector | SDK: экспорт в фоновом потоке, таймаут 3 с; очереди BatchSpanProcessor / BatchLogRecordProcessor по 2048 записей, лишнее отбрасывается | очереди SDK ограничены; запросы не ждут экспорта | `messenger_telemetry_spans_exported_total{result="failure"}` (доставится после восстановления), «дырка» в графиках | +| Grafana | Ничего: приложение о Grafana не знает | — | — | + +Приложение не зависит от телеметрии: ни один сервис приложения не имеет `depends_on` на телеметрию, readiness API её не проверяет. Доказательства: `evidence/incidents/backend-down.txt`, `collector-down.txt`. + +## Переменные окружения (`compose.yaml`, якорь `x-otel-env`) + +| Переменная | По умолчанию | Смысл | +| --- | --- | --- | +| `OTEL_SDK_DISABLED` | `false` | `true` — телеметрия выключена (трек 1, baseline) | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://otel-collector:4318` | Collector | +| `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/protobuf` | как в `.env.example` | +| `OTEL_EXPORTER_OTLP_TIMEOUT` | `3` (секунды) | таймаут одного экспорта | +| `OTEL_TRACES_SAMPLER` / `_ARG` | `parentbased_always_on` / `1.0` | head sampling | +| `OTEL_METRIC_EXPORT_INTERVAL` | `5000` мс | как часто SDK отправляет метрики | +| `OTEL_BSP_MAX_QUEUE_SIZE`, `OTEL_BLRP_MAX_QUEUE_SIZE` | `2048` | ограничение очередей span/log в процессе | +| `OTEL_COLLECTOR_TRACES` | `traces-all` | `traces-tail` — tail sampling в Collector | +| `OTEL_SERVICE_NAME` | по сервису | задано в compose для api/relay/worker | +| `OTEL_RESOURCE_ATTRIBUTES` | `deployment.environment.name=lab` | ресурс | diff --git a/docs/PIPELINE.md b/docs/PIPELINE.md new file mode 100644 index 0000000..fe6c192 --- /dev/null +++ b/docs/PIPELINE.md @@ -0,0 +1,128 @@ +# Pipeline обработки вложений (lab5) + +Схема: [migrations/0005_pipeline.sql](../migrations/0005_pipeline.sql). Код: API — [attachments.py](../src/messenger/attachments.py), переходы заданий — [jobs.py](../src/messenger/jobs.py), relay — [relay.py](../src/messenger/relay.py), worker — [worker.py](../src/messenger/worker.py), картинки — [imaging.py](../src/messenger/imaging.py), версии — [pipeline.py](../src/messenger/pipeline.py), оператор — [jobctl.py](../src/messenger/jobctl.py), аудит — [audit.py](../src/messenger/audit.py). + +## Кто что делает + +```text +клиент ──POST──▶ LB ──▶ API ──(1) INSERT attachments 'pending' ──▶ PostgreSQL + │ (2) PUT оригинал в messenger-staging ──▶ S3 (staging) + │ (3) ОДНА транзакция: 'queued' + jobs + outbox ──▶ PostgreSQL + └─ 202 queued +relay: outbox ─(4) publish + publisher confirm─▶ RabbitMQ (quorum queue) ─(5) deliver─▶ worker +worker: (6) claim: lease + token попытки ─▶ (7) читает источник, сверяет SHA-256 ─▶ (8) варианты + в дочернем процессе ─▶ (9) PUT a///* в messenger-attachments ─▶ + (10) ОДНА транзакция: варианты + attachment 'ready' (с проверкой токена) ─▶ (11) ack ─▶ + (12) staging 'deleting' → S3 DELETE → 'deleted' +``` + +- **Источник истины — PostgreSQL**: состояние задания, попытки, lease, время следующей попытки (`available_at`), реестр failed, аудит (`job_events`). Брокер только доставляет `job_id`. +- **API не знает брокер** (нет даже сети `queue`). Брокер упал — upload всё равно 202, задания копятся в outbox. +- В сообщении только поля [jobs.schema.json](../contracts/jobs.schema.json): `schema_version, job_id, type, attachment_id, pipeline_version, attempt, created_at`. Никаких байтов, URL, ключей S3, имени файла. Worker берёт `content_type`, размер, SHA-256 и ключ источника из БД. + +## Что сохранено в момент 202 + +1. Полный, **проверенный** оригинал лежит в приватном bucket `messenger-staging`: S3 подтвердил PUT и Content-MD5. Проверки 413/415 делаются до этого, синхронно, теми же валидаторами, что в lab4 (PNG — свой потоковый, JPEG — `djpeg -strict`). +2. Строка `attachments` в статусе `queued`, строка `jobs` (`queued`, attempt 0) и строка `outbox` — **в одной транзакции**, закоммичены (fsync PostgreSQL). + +Значит, после 202 можно убить API, relay, broker и worker: работа восстановится из этих двух записей. Честная граница: staging — это уже S3, а не «временная папка». На одном Docker-хосте «устойчиво» значит «переживает рестарт процессов и контейнеров с volumes», а не потерю диска. + +## Состояния + +Вложение (`attachments.status`): + +| Статус | Видно клиенту | Как попадает | Как выходит | +| --- | --- | --- | --- | +| `pending` | нет (404) | INSERT до PUT в staging | → `queued` (COMMIT задания) или удаляется janitor через `PENDING_GRACE_SECONDS` | +| `queued` | да, content 409 | COMMIT задания; retry; истёк lease; replay | → `processing` при claim | +| `processing` | да, content 409 | claim worker | → `ready` / `queued` (retry, lease) / `failed` | +| `ready` | да, варианты | COMMIT результата | никогда не возвращается назад. Reprocess новой версии не меняет статус | +| `failed` | да, `error_code`, content 409 | постоянная ошибка или попытки кончились | → `queued` только через `jobctl replay` | + +Задание (`jobs.state`): `queued → processing → succeeded | failed | superseded`, `processing → queued` (retry, lease, graceful stop). `superseded` — старая версия pipeline, когда опубликована более новая. + +Ограничения в самой БД (CHECK) не дают коду ошибиться: +- `attachments_active_has_source`: у `queued/processing` есть источник — опубликованный оригинал или staging в состоянии `present`. **Уборка физически не может пометить staging принятой работы**; +- `jobs_lease`: lease есть ровно тогда, когда `processing`; +- `jobs_one_active`: одно активное задание на `(attachment, pipeline_version)`; +- PK `attachment_variants (attachment_id, pipeline_version, name)` — ключ эффекта из контракта. + +## Окна отказа (contracts/attachment-states.md) + +| Окно | Что остаётся | Кто восстанавливает | Проверка | +| --- | --- | --- | --- | +| после staging, до записи задания | `pending` + объект staging, задания нет, 503 клиенту | janitor API: объект, потом строка (после grace) | `API_FAULT_POINTS=after_s3_put`, test_consistency | +| после COMMIT, до publish | строка outbox без `published_at` | relay при следующем проходе; никто не создаёт задание вручную | broker/relay остановлены, test_pipeline_flow | +| после publish, до записи confirm | сообщение в очереди + неотмеченная строка outbox | relay публикует ещё раз → дубль → no-op | `RELAY_FAULT_POINTS=crash_after_publish` | +| после записи S3, до COMMIT результата | объекты под ключами попытки 1, не опубликованы | lease истекает → reaper → попытка 2 со своими ключами; уборка удаляет ключи попытки 1 | `WORKER_FAULT_POINTS=crash_after_s3_write` | +| после COMMIT результата, до ack | `ready` | redelivery → claim видит `succeeded` → ack без работы | `WORKER_FAULT_POINTS=crash_after_commit` | +| worker умер/завис в processing | lease без продления | reaper (в relay, раз в 5 с) → `queued` + outbox; commit старой попытки отвергается токеном | `crash_after_claim`, `docker pause` | + +## Publisher confirm ≠ consumer ack + +- **Publisher confirm** (relay ← broker): «брокер принял сообщение и записал его в quorum log». Это граница «намерение передано в очередь»; после неё relay ставит `published_at`. +- **Consumer ack** (worker → broker): «результат работы устойчиво зафиксирован». Worker шлёт ack только **после COMMIT** результата (или после COMMIT решения «retry/failed/no-op»). +- Между ними может пройти сколько угодно времени и случиться любой сбой. Confirm без ack = сообщение ждёт в очереди; потеря ack = повторная доставка. + +## Идемпотентность и повторная доставка + +Доставка at-least-once: дубль может появиться из relay (crash до отметки), из брокера (нет ack из-за падения worker, разрыв соединения, consumer_timeout), от оператора. Поэтому каждая доставка начинается с `claim` под блокировкой строки `jobs`: + +| Состояние задания | Решение | ack | +| --- | --- | --- | +| `succeeded/failed/superseded` | no-op (`noop_finished`) | да | +| `processing` (lease держит другой) | no-op (`noop_leased`), его смерть обработает reaper | да | +| `queued`, `available_at` в будущем | no-op (`noop_not_due`), outbox опубликует вовремя | да | +| `queued`, опубликована версия ≥ своей | `superseded` | да | +| `queued`, пора | claim: attempt+1, новый `lease_token`, строка `job_attempts` с заранее известными ключами | после результата | + +Ключ идемпотентности задания — `job_id` (строка в БД), ключ эффекта — `(attachment_id, pipeline_version, variant)`. Объекты пишутся под ключами `a///`: у каждой попытки свои. Опубликовано ровно то, на что ссылается COMMIT результата. **Fencing**: COMMIT проходит, только если `jobs.lease_token` всё ещё равен токену попытки. Reaper обнуляет токен, поэтому «проснувшаяся» старая попытка ничего не опубликует. + +Это не exactly-once **доставка**. Сообщение может прийти несколько раз, а работа выполниться дважды (например, зависший worker досчитает варианты). Exactly-once — только **видимый эффект**: одна опубликованная запись на ключ эффекта, монотонная версия, мусор попыток убирается. + +## Зависший vs долго работающий worker + +- Долго работающий продлевает lease каждые `JOB_LEASE_SECONDS/3` (heartbeat в БД, `WHERE lease_token = мой`). +- Зависший (`docker pause`, deadlock, потеря сети к БД) не продлевает; через `JOB_LEASE_SECONDS` reaper возвращает задание. +- Worker, у которого жив heartbeat, но зависла обработка, ограничен `JOB_TIMEOUT_SECONDS`: дочерний процесс убивается, heartbeat перестаёт продлевать lease после этого срока. +- Если heartbeat узнал, что lease потерян, попытка отменяется сама. Даже если не отменилась — её COMMIT отвергнет fencing. +- Брокер со своей стороны: AMQP heartbeat 10 с закрывает соединение замороженного клиента и возвращает его неподтверждённые сообщения; `consumer_timeout` 5 мин — для подключённого, но не отвечающего ack. + +## Retry, failed, replay + +- `JOB_MAX_ATTEMPTS=5` claim-ов на задание. Backoff — full jitter: `uniform(0, min(JOB_RETRY_MAX_SECONDS, JOB_RETRY_BASE_SECONDS·2^(n−1)))`. Задержка хранится в `jobs.available_at` и строке outbox — повтор проходит тем же путём outbox → broker, без TTL-очередей. +- Постоянные ошибки (сразу `failed`): `invalid_image`, `image_too_large`, `source_missing`, `source_corrupt`. Временные: `storage_unavailable`, `processing_timeout`, `processing_killed`, `processing_failed`. Когда попытки кончились — `retry_exhausted`. +- Реестр failed — view `failed_jobs` (`jobctl list-failed`). DLQ RabbitMQ (`messenger.attachment-jobs.dlq`) — для «ядовитых» сообщений: не по схеме или превысили `x-delivery-limit=20`. +- Страховка от потерянного сообщения: `queued`-задание без claim и без публикаций дольше `QUEUED_REPUBLISH_SECONDS` получает новую строку outbox. +- `jobctl replay `: только для `failed` с живым источником, создаёт **новое** задание `kind=replay, replay_of=`, пишет оператора и причину в `job_events`. Для `ready` — отказ `already_ready`, ничего не создаётся. + +## Уборка (worker), всегда под блокировкой строки + +- staging `ready` — сразу после COMMIT результата; staging `failed` — через `STAGING_RETENTION_SECONDS`. Порядок: под `UPDATE … WHERE <условие заново>` пометить `deleting` → S3 DELETE → `deleted`. Replay берёт ту же блокировку: либо replay первым (строка уже `queued`, уборка её пропустит), либо уборка первой (replay видит `deleting` и отказывает `source_missing`). +- Объекты попыток, которые не опубликовали результат (`retry/failed/abandoned/superseded`): удаляются по `planned_keys` через `ORPHAN_GRACE_SECONDS`. Перед этим проверяется, что токен не текущий и ни один ключ не опубликован. Новые результаты (replay, другая попытка) лежат под другими ключами — устаревший проход не может их удалить. +- `pending` без задания — janitor API (как в lab4). +- Опубликованные варианты старых версий pipeline сохраняются (ограничение, см. REPORT). + +## Версии pipeline (трек 2) + +Версия фиксируется в задании при создании (`PIPELINE_VERSION` для upload, `jobctl reprocess --pipeline N` для готового вложения). Версии 1/2/3 отличаются параметрами кодеков, геометрия — по контракту. Публикация: только если `N > published_version`; иначе `superseded`. Reprocess неготового вложения запрещён: его единственный источник — staging текущего задания. + +## Лимиты worker + +| Что | Чем | +| --- | --- | +| параллельность | prefetch = `WORKER_CONCURRENCY` (2) + семафор на дочерние процессы | +| bytes | размер из БД ≤ `MAX_UPLOAD_BYTES` проверяется до скачивания; длина и SHA-256 скачанного = БД | +| пиксели | `width×height` из заголовка ≤ `MAX_IMAGE_PIXELS` до декодирования; JPEG декодируется с DCT-масштабом (`draft`) | +| память | `RLIMIT_AS = IMAGE_MAX_MEMORY_MB` (768) у дочернего процесса; контейнер 1536m без swap | +| время | `JOB_TIMEOUT_SECONDS` (60): дочерний процесс убивается, lease перестаёт продлеваться | + +## Варианты + +| Вариант | Формат | Геометрия | Параметры v1 | +| --- | --- | --- | --- | +| thumbnail | JPEG baseline 4:2:0 | вписан в 256×256, без увеличения, округление вниз, ≥1 px | q=85, optimize | +| crop | JPEG | центральный квадрат → 128×128 (маленькие увеличиваются) | q=85 | +| optimized | WebP lossy | вписан в 1280×1280, без увеличения, alpha сохраняется | q=80, method=4 | + +EXIF orientation применяется к пикселям; в варианты не копируются EXIF, XMP, ICC, комментарии. Пиксели считаются sRGB. Alpha при ресайзе — premultiplied (без цветных ореолов), для JPEG композится на белый. 16-битный серый масштабируется (`/257`), а не обрезается. Оригинал публикуется побайтно без изменений. Уменьшение размера маленьких файлов не обещается. diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md new file mode 100644 index 0000000..7a46d17 --- /dev/null +++ b/docs/RUNBOOK.md @@ -0,0 +1,54 @@ +# Runbook: что делать, когда сработал алерт + +Общий порядок: **метрика говорит «что и насколько», трасса — «где по пути», лог — «что именно случилось»**. Начинать с dashboard «Messenger lab 6» (Grafana, http://127.0.0.1:3000), потом Explore → Tempo/Loki. Без Grafana: `python scripts/obs.py alerts|promql|search|trace|logs`. + +## MessengerApiHighErrorRate + +Больше 5 % бизнес-запросов отвечают 5xx. + +1. Dashboard → «Error ratio» и «Requests per second by route»: какой маршрут даёт 5xx, все реплики или одна (`sum by (instance)`). +2. Логи предупреждений: `{service_name="messenger-api"} | detected_level=~"warn|error"` — смотреть `event`: `database_unavailable` (поле `op`), `s3_unavailable`, `unhandled_error`, `fault_injected`. +3. Трасса ошибочного запроса: Tempo, TraceQL `{ resource.service.name = "messenger-api" && status = error }`. Какой дочерний span красный и долгий: + * `db …` с `error.type = LockNotAvailable / QueryCanceled` → блокировка или медленный запрос в PostgreSQL (шаг 4); + * `db …` с `PoolTimeout` → пул исчерпан (см. MessengerDbPoolSaturated); + * `s3 …` с ошибкой → S3 (`docker compose ps s3`, логи s3); + * дочерних span-ов нет, сам SERVER красный → ошибка в коде (`unhandled_error`, stack в stdout реплики). +4. БД: `docker compose exec postgres psql -U messenger -d messenger -c "SELECT pid, wait_event_type, wait_event, state, now()-xact_start AS age, left(query,60) FROM pg_stat_activity WHERE state <> 'idle' ORDER BY age DESC"`. Долгая транзакция, держащая блокировку, — `pg_terminate_backend(pid)` (только чужой/зависший сеанс, после согласования). +5. Готово, когда ratio < 5 % и алерт resolved (≈ 1–2 мин после устранения). + +## MessengerQueueLagGrowing + +Старейшее незавершённое задание старше 60 с — загрузки не становятся ready. + +1. Dashboard → «Queue depth», «Oldest job age», «Jobs handled per second by outcome», «Worker saturation». + * `jobs succeeded/s = 0`, busy = 0 → **worker не работает**: `docker compose ps worker`, `docker compose logs --tail 50 worker`; поднять `docker compose start worker`. + * busy/capacity ≈ 100 %, succeeded/s > 0 → **worker не успевает** (насыщение): рост загрузок или медленная обработка («Job duration p95»); масштабировать `docker compose up -d --scale worker=2` или поднять `WORKER_CONCURRENCY`. + * много `retry`/`failed` в outcome → обработка падает: логи `{service_name="messenger-worker"} | event="attempt_failed"` (поле `code`), трасса `{ span.messenger.job.outcome = "retry" }`. + * «oldest due outbox row» растёт → не публикуется: брокер или relay (`docker compose ps broker relay`, лог `publish_failed`). +2. После устранения backlog должен уменьшаться («Queue depth» вниз), алерт — resolved. + +## MessengerApiLatencyHigh + +p99 бизнес-запросов > 1 с в течение 2 минут. Главный вопрос: **медленная БД или медленный код обработчика?** + +1. Сравнить на dashboard «Latency p50/p95/p99» с «DB unit of work p95» и «DB pool wait p95». + * DB p95 вырос вместе с HTTP, есть ожидание пула → **БД** (блокировки, тяжёлый запрос, нехватка соединений): дальше как в шаге 4 MessengerApiHighErrorRate. + * DB p95 прежний (единицы мс), HTTP p99 вырос → **код обработчика / CPU реплики**: «Container CPU», «Requests in flight». +2. Подтвердить трассой: TraceQL `{ resource.service.name = "messenger-api" && kind = server && duration > 1s }`. Время внутри дочернего `db …` span-а → БД; длинный SERVER span с короткими детьми (пустой промежуток) → код самого обработчика. +3. Проверить, не включены ли экспериментальные отказы: `docker compose exec api printenv FAULT_POINTS`. + +## MessengerDbPoolSaturated + +Запросы ждут свободное соединение PostgreSQL. Соединения заняты дольше обычного (медленные запросы, блокировки) или пул мал для нагрузки. Смотреть «DB pool: used / max, waiting» по `job`, затем `pg_stat_activity` (как выше). Увеличивать `DB_POOL_MAX` только после того, как исключены блокировки: больше соединений к заблокированной таблице лишь удлинят очередь. + +## MessengerQueueMetricsAbsent + +Нет метрик очереди: relay не работает или не может читать БД. `docker compose ps relay`, `docker compose logs --tail 50 relay` (события `database_unavailable`, `publish_failed`). Пока алерт активен, MessengerQueueLagGrowing **не может сработать** — очередь не наблюдается. + +## TelemetryExportFailing + +Collector не может отправить данные в Tempo/Loki/Prometheus (`exporter` в метках алерта). Приложение не затронуто, но наблюдения теряются после заполнения очереди (≤100 пачек, ≤60 с повторов). + +1. `docker compose ps tempo loki prometheus`, `up{job=~"tempo|loki|prometheus"}` на dashboard. +2. Поднять backend: `docker compose start tempo loki`. +3. Оценить потерю: прирост `otelcol_exporter_send_failed_spans` / `_log_records` за время отказа (панель «Collector: spans accepted / sent / failed»). diff --git a/docs/SLO.md b/docs/SLO.md new file mode 100644 index 0000000..7c81d8a --- /dev/null +++ b/docs/SLO.md @@ -0,0 +1,32 @@ +# SLI, SLO и алерты (lab 6, уровень 4) + +Окна укорочены под учебный стенд: в продакшене SLO берут на 28–30 дней, здесь — 1 час, чтобы результат был виден за время защиты. + +## SLI и SLO + +| SLO | SLI (что меряем) | Цель | Окно | Запрос (recording rule) | +| --- | --- | --- | --- | --- | +| Доступность API | доля бизнес-запросов (все маршруты, кроме `/health/*`), ответивших **не 5xx** | ≥ 99 % | 1 ч | `1 - messenger:http_error_ratio:rate1h` | +| Скорость API | доля бизнес-запросов быстрее 250 мс (bucket `le="0.25"`) | ≥ 95 % | 5 мин | `messenger:http_fast_ratio:rate5m` | +| Время до ready | доля загрузок, ставших ready за ≤ 30 с от 202 (bucket `le="30"`) | ≥ 99 % | 1 ч | `messenger:ready_within_30s_ratio:rate1h` | + +**Числитель и знаменатель ошибок.** Числитель — ответы 5xx (500, 503); знаменатель — все бизнес-запросы. 4xx не ошибка сервиса: неверный пароль, чужой чат (404), повтор ключа с другим телом (409) — правильный ответ на неправильный запрос. Health-пробы исключены: их шлёт инфраструктура, не пользователь. + +**Почему 250 мс и 30 с.** На стенде p95 бизнес-запросов около 10–60 мс, p99 < 150 мс (dashboard, нагрузка `tests/load.py`), так что 250 мс — запас в несколько раз, но медленная БД (секунды) его нарушает. Публичный smoke ждёт ready до 60 с; обычная обработка — около 1–2 с, поэтому 30 с ловит остановленный или перегруженный worker раньше, чем клиент сдастся. + +**Что значит 99 % за час.** Бюджет ошибок — 1 % запросов. При 10 запросах в секунду это 360 ошибочных ответов в час; полный отказ API «съедает» такой бюджет за 36 секунд. + +## Алерты (`infra/prometheus/rules/alerts.yml`) + +| Алерт | Условие | `for` | Связь с SLO | Runbook | +| --- | --- | --- | --- | --- | +| `MessengerApiHighErrorRate` | 5xx/все за 1 мин > 5 % и трафик > 0,2 req/s | 1 мин | доступность: 5 % ошибок съедают часовой бюджет за 12 мин | [RUNBOOK](RUNBOOK.md#messengerapihigherrorrate) | +| `MessengerQueueLagGrowing` | старейшее незавершённое задание > 60 с и есть queued | 1 мин | время до ready (30 с) уже нарушается | [RUNBOOK](RUNBOOK.md#messengerqueuelaggrowing) | +| `MessengerApiLatencyHigh` | p99 бизнес-запросов за 2 мин > 1 с | 2 мин | скорость API | [RUNBOOK](RUNBOOK.md#messengerapilatencyhigh) | +| `MessengerDbPoolSaturated` | есть ожидающие соединения с БД | 1 мин | причина обоих выше | [RUNBOOK](RUNBOOK.md#messengerdbpoolsaturated) | +| `MessengerQueueMetricsAbsent` | нет метрики очереди 2 мин | 2 мин | очередь не наблюдается вообще | [RUNBOOK](RUNBOOK.md#messengerqueuemetricsabsent) | +| `TelemetryExportFailing` | Collector не может отправить в backend | 30 с | сама наблюдаемость деградировала | [RUNBOOK](RUNBOOK.md#telemetryexportfailing) | + +Время обнаружения ≈ время, пока условие станет истинным по окну rate (до 1 мин) + `for` + до 15 с интервала вычисления. Порог «трафик > 0,2 req/s» убирает ложное срабатывание на пустом стенде, где одна ошибка из пяти запросов — уже 20 %. + +Доставки наружу нет (нет Alertmanager): состояния pending → firing → resolved видны в Prometheus (`/api/v1/alerts`, ряд `ALERTS`), на dashboard (панели «Alerts firing» и таблица) и через `python scripts/obs.py alerts`. Проверка искусственными отказами: `bench/incidents.py`, результаты в `evidence/incidents/`. diff --git a/docs/WINDOWS.md b/docs/WINDOWS.md new file mode 100644 index 0000000..4a66f58 --- /dev/null +++ b/docs/WINDOWS.md @@ -0,0 +1,103 @@ +# Запуск на Windows и сценарий защиты ЛР 6 + +Команды — в **PowerShell** из папки проекта (где лежит `compose.yaml`). Переменные `$env:...` действуют до закрытия окна. + +## 1. Что установить один раз + +| Программа | Зачем | Важно | +| --- | --- | --- | +| [Git for Windows](https://git-scm.com/download/win) | clone и Git Bash | путь по умолчанию `C:\Program Files\Git`: оттуда `scripts\*.cmd` запускают `.sh`-хуки | +| [Docker Desktop](https://www.docker.com/products/docker-desktop/) | весь стенд: 9 сервисов ЛР 5 + Collector, Prometheus, Loki, Tempo, Grafana | backend WSL 2; Settings → Resources ≥ 4 CPU и ≥ 10 ГБ RAM (сумма лимитов ~9,5 ГБ, реально занято ~2,5 ГБ) | +| [Python 3.12+](https://www.python.org/downloads/windows/) | secrets, тесты, сценарии, чтение наблюдений | галочка **Add python.exe to PATH** | +| GNU make (необязательно) | `make check/test/...` | `winget install ezwinports.make`; в каждом окне `$env:Path += ";C:\Program Files\Git\usr\bin"` | + +## 2. Развернуть (заранее, нужен интернет) + +```powershell +git clone https://gitea.privcloud.tech/wfa/mtusi2026lab6 mtusi2026lab6 +cd mtusi2026lab6 +git checkout solution/bvt2302-bodanyuk +python scripts\init_secrets.py # БД, Valkey, S3, RabbitMQ, пароль Grafana -> .\secrets +Copy-Item .env.example .env +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build --wait +``` + +Первый запуск качает ~2 ГБ образов (Grafana ~1,9 ГБ в распакованном виде) и собирает образ приложения. Медленный интернет: образы можно скачать заранее в другом месте и перенести `docker save` / `docker load` — теги и digest в `compose.yaml` совпадут. + +Окружение для тестов (один раз): + +```powershell +python -m venv .venv +.venv\Scripts\python -m pip install --require-hashes --no-deps -r requirements.txt +.venv\Scripts\python -m pip install -r requirements-test.txt -r requirements-dev.txt +``` + +Стенды ЛР 3–5 занимают порт 8080: `docker compose -p mtusi-lab5 stop`. + +## 3. Перед защитой + +```powershell +$env:PYTHONUTF8 = "1" +docker compose up -d --wait +python tests\smoke.py --base-url http://localhost:8080 # = make test +python scripts\obs.py alerts # пусто = ничего не горит +``` + +Grafana: **http://127.0.0.1:3000**, пользователь `admin`, пароль — `Get-Content secrets\grafana_admin_password`. Dashboard «Messenger lab 6» открывается домашней страницей (папка Messenger). + +## 4. Сценарий защиты README — по шагам + +**Шаг 1. С нуля, provisioning, smoke и нагрузка.** + +```powershell +docker compose down -v; Remove-Item -Recurse secrets # ТОЛЬКО если нужен чистый лист: удаляет учебные данные +python scripts\init_secrets.py +docker compose up -d --build --wait +python tests\smoke.py --base-url http://localhost:8080 +python tests\load.py --base-url http://localhost:8080 --duration 60 --concurrency 4 +``` + +В Grafana dashboard и три datasource уже есть — ничего не набирается руками (`infra/grafana/provisioning`). Проверка всех запросов dashboard без браузера: `python scripts\check_dashboard.py`. + +**Шаг 2. Свежие метрики, одна трасса и её логи API и worker.** + +```powershell +python scripts\trace_demo.py +``` + +Скрипт отправляет upload со **своим** `traceparent`, ждёт ready и печатает дерево span-ов из Tempo (API SERVER → relay PRODUCER → worker CONSUMER → s3/db) и записи Loki с этим `trace_id` (API `request`, worker `job_done`). В Grafana: Explore → Tempo → вставить trace id → у span-а кнопка «Logs for this span»; в Loki у записи поле `trace_id` ведёт обратно в Tempo. + +**Шаг 3 (уровень 4). Upload → worker в одной трассе; worker остановлен → firing → resolved.** + +```powershell +.venv\Scripts\python -m pytest student-tests\test_observability.py -v # цепочка, retry в той же трассе, логи, labels, секреты +python bench\incidents.py worker-stop # ~5 мин: MessengerQueueLagGrowing firing, затем resolved +python bench\incidents.py db-lock # ~4 мин: блокировка таблицы -> 5xx/latency, trace показывает db span +python bench\incidents.py slow-handler # ~6 мин: контраст - медленный код, БД в норме +``` + +Вручную то же самое: `docker compose stop worker` → на dashboard растут «Queue depth» и «Oldest job age», через ~2 мин алерт firing (`python scripts\obs.py alerts`) → `docker compose start worker` → backlog уходит, алерт resolved. + +**Шаг 4. Остановить telemetry backend — API работает, exporter ограничен.** + +```powershell +python bench\incidents.py backend-down # Tempo+Loki остановлены 3 мин, клиентские ошибки = 0, RSS Collector ограничен +python bench\incidents.py collector-down # сам Collector остановлен 2 мин +``` + +Для 5 (трек 1) — повторить эксперимент: `python bench\track1.py --runs 1 --duration 60 --output evidence\track1-demo` (~15 мин). Готовые результаты: [TRACK1.md](TRACK1.md). + +## 5. Если что-то пошло не так + +| Симптом | Что сделать | +| --- | --- | +| `error during connect … dockerDesktopLinuxEngine` | Docker Desktop не запущен | +| `port is already allocated` на 8080/3000 | другой стенд; или в `.env` `APP_PUBLISH_PORT=8081`, `GRAFANA_PORT=3001` | +| Grafana unhealthy / медленная | `docker stats`: лимит 1 ГБ; `docker compose restart grafana` | +| в Grafana «No data» | подождать 15–30 с (метрики отправляются раз в 5 с); проверить `python scripts\check_dashboard.py` | +| нет трассы по id | spans приходят в Tempo через 2–5 с; `docker compose logs otel-collector` | +| `UnicodeDecodeError` в `tests\*.py` | `$env:PYTHONUTF8 = "1"` | +| локальный `.env` устарел | сравнить с `.env.example` | + +Остановить после защиты: `docker compose down` (данные и история телеметрии сохранятся в volumes). diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 0000000..43d487c --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,1881 @@ +{ + "uid": "messenger-lab6", + "title": "Messenger lab 6: API, worker, queue, SLO", + "description": "Generated by scripts/build_dashboard.py - edit the script, not the JSON.", + "tags": [ + "messenger", + "lab6" + ], + "timezone": "browser", + "schemaVersion": 39, + "version": 1, + "editable": false, + "graphTooltip": 1, + "refresh": "10s", + "time": { + "from": "now-30m", + "to": "now" + }, + "templating": { + "list": [] + }, + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "panels": [ + { + "type": "row", + "title": "API: requests, errors, latency (all replicas)", + "id": 2, + "collapsed": false, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + } + }, + { + "type": "timeseries", + "title": "Requests per second by route", + "id": 3, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Business requests (no /health/*) per second, summed over the API replicas. Counter = _count of the histogram http.server.request.duration (no second instrument).\n\nUnit: reqps.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "lineWidth": 1, + "fillOpacity": 40, + "showPoints": "never", + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (http_route) (rate(http_server_request_duration_seconds_count{job=\"messenger-api\", http_route!~\"/health/.*\"}[$__rate_interval]))", + "legendFormat": "{{http_route}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Error ratio (5xx and 4xx / all business requests)", + "id": 4, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Numerator: 5xx (or 4xx) business requests; denominator: all business requests. Alert MessengerApiHighErrorRate: 5xx > 5 % for 1 min.\n\nUnit: percentunit.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + }, + "thresholdsStyle": { + "mode": "line+area" + } + }, + "min": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 0.05 + } + ] + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "(sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\", http_route!~\"/health/.*\", http_response_status_class=\"5xx\"}[$__rate_interval])) or vector(0)) / sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\", http_route!~\"/health/.*\"}[$__rate_interval]))", + "legendFormat": "5xx (SLI: server failures)", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "(sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\", http_route!~\"/health/.*\", http_response_status_class=\"4xx\"}[$__rate_interval])) or vector(0)) / sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\", http_route!~\"/health/.*\"}[$__rate_interval]))", + "legendFormat": "4xx (client errors, not in the SLI)", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Latency p50 / p95 / p99 (all routes, all replicas)", + "id": 5, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "histogram_quantile over the buckets of http.server.request.duration summed by le across replicas (buckets 1 ms ... 10 s). Not an average, not per-replica p99s averaged.\n\nUnit: s.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\", http_route!~\"/health/.*\"}[$__rate_interval])))", + "legendFormat": "p50", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\", http_route!~\"/health/.*\"}[$__rate_interval])))", + "legendFormat": "p95", + "range": true + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\", http_route!~\"/health/.*\"}[$__rate_interval])))", + "legendFormat": "p99", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "p95 by route", + "id": 6, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Per route template, buckets of all replicas.\n\nUnit: s.", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 9 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\", http_route!~\"/health/.*\"}[$__rate_interval])))", + "legendFormat": "{{http_route}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Requests in flight by replica", + "id": 7, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "UpDownCounter http.server.active_requests per API replica (saturation of the HTTP layer).\n\nUnit: short.", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 9 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (instance) (http_server_active_requests{job=\"messenger-api\"})", + "legendFormat": "{{instance}}", + "range": true + } + ] + }, + { + "type": "row", + "title": "Worker and queue", + "id": 8, + "collapsed": false, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 17 + } + }, + { + "type": "timeseries", + "title": "Jobs handled per second by outcome", + "id": 9, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "messenger.jobs.processed: succeeded / retry / failed / fenced / superseded / noop_* / deferred / rejected.\n\nUnit: ops.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 18 + }, + "fieldConfig": { + "defaults": { + "unit": "ops", + "custom": { + "lineWidth": 1, + "fillOpacity": 40, + "showPoints": "never", + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (outcome) (rate(messenger_jobs_processed_total[$__rate_interval]))", + "legendFormat": "{{outcome}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Job duration p50 / p95 / p99 (succeeded)", + "id": 10, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "One delivery in the worker: claim -> S3 read -> variants -> S3 writes -> COMMIT -> ack.\n\nUnit: s.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 18 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome=\"succeeded\"}[$__rate_interval])))", + "legendFormat": "p50", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome=\"succeeded\"}[$__rate_interval])))", + "legendFormat": "p95", + "range": true + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome=\"succeeded\"}[$__rate_interval])))", + "legendFormat": "p99", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Time to ready p50 / p95 / p99 (uploads)", + "id": 11, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "From the durable acceptance (job COMMIT before 202) to the COMMIT of status ready. Includes queue wait and retries. SLO: 99 % within 30 s.\n\nUnit: s.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 18 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "p50", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "p95", + "range": true + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "p99", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Queue depth (PostgreSQL) and outbox", + "id": 12, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "messenger.queue.depth: unfinished jobs (queued incl. retry wait / processing); messenger.outbox.pending: unpublished messages (due / delayed). Reported by the relay every 5 s.\n\nUnit: short.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 26 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (state) (messenger_queue_depth)", + "legendFormat": "jobs {{state}}", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (state) (messenger_outbox_pending)", + "legendFormat": "outbox {{state}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Oldest job age / oldest due outbox row", + "id": 13, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Age of the oldest unfinished job (now - acceptance). Grows when nobody processes the queue. Alert MessengerQueueLagGrowing: > 60 s for 1 min with queued jobs.\n\nUnit: s.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 26 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + }, + "thresholdsStyle": { + "mode": "line+area" + } + }, + "min": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 60 + } + ] + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(messenger_queue_oldest_age_seconds)", + "legendFormat": "oldest unfinished job", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(messenger_outbox_oldest_age_seconds)", + "legendFormat": "oldest due outbox row (broker)", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Worker saturation (busy / capacity)", + "id": 14, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "messenger.worker.busy (attempts running) / messenger.worker.capacity (WORKER_CONCURRENCY), all worker processes. 100 % for long = the worker is the bottleneck.\n\nUnit: percentunit.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 26 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0, + "max": 1 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(messenger_worker_busy) / sum(messenger_worker_capacity)", + "legendFormat": "busy share", + "range": true + } + ] + }, + { + "type": "row", + "title": "Database pool and resources", + "id": 15, + "collapsed": false, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 34 + } + }, + { + "type": "timeseries", + "title": "DB pool: used / max, waiting requests", + "id": 16, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "psycopg_pool counters per service (all replicas summed). Waiting > 0 = pool exhausted.\n\nUnit: short.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 35 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (job) (db_client_connection_count{db_client_connection_state=\"used\"})", + "legendFormat": "{{job}} used", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (job) (db_client_connection_max)", + "legendFormat": "{{job}} max", + "range": true + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (job) (db_client_connection_pending_requests)", + "legendFormat": "{{job}} waiting", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "DB unit of work p95 by service", + "id": 17, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "db.client.operation.duration: pool wait + statements + COMMIT of one Database.run().\n\nUnit: s.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 35 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le, job) (rate(db_client_operation_duration_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "{{job}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "DB pool wait p95 by service", + "id": 18, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "db.client.connection.wait_time: time to get a connection from the pool.\n\nUnit: s.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 35 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le, job) (rate(db_client_connection_wait_time_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "{{job}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Container CPU (cores)", + "id": 19, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "cgroup cpu.stat of each application container (1 = one full core); Collector: its own counter.\n\nUnit: short.", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 43 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (job, instance) (rate(container_cpu_time_seconds_total[$__rate_interval]))", + "legendFormat": "{{job}} {{instance}}", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "rate(otelcol_process_cpu_seconds[$__rate_interval])", + "legendFormat": "otel-collector", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Container memory", + "id": 20, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "cgroup memory.current of each application container; Collector RSS (memory_limiter: 400 MiB).\n\nUnit: bytes.", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 43 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (job, instance) (container_memory_usage_bytes)", + "legendFormat": "{{job}} {{instance}}", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "otelcol_process_memory_rss", + "legendFormat": "otel-collector RSS", + "range": true + } + ] + }, + { + "type": "row", + "title": "SLO (docs/SLO.md) and alerts", + "id": 21, + "collapsed": false, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 51 + } + }, + { + "type": "stat", + "title": "Availability, last 1 h (target 99 %)", + "id": 22, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "1 - 5xx/all business requests over 1 h.\n\nUnit: percentunit.", + "gridPos": { + "h": 5, + "w": 6, + "x": 0, + "y": 52 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "decimals": 3, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": null + }, + { + "color": "orange", + "value": 0.99 + }, + { + "color": "green", + "value": 0.995 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "area", + "textMode": "value" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "1 - messenger:http_error_ratio:rate1h", + "instant": false, + "range": true + } + ] + }, + { + "type": "stat", + "title": "Requests under 250 ms, last 5 min (target 95 %)", + "id": 23, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Share of business requests in buckets le=0.25.\n\nUnit: percentunit.", + "gridPos": { + "h": 5, + "w": 6, + "x": 6, + "y": 52 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "decimals": 3, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": null + }, + { + "color": "green", + "value": 0.95 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "area", + "textMode": "value" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger:http_fast_ratio:rate5m", + "instant": false, + "range": true + } + ] + }, + { + "type": "stat", + "title": "Uploads ready within 30 s, last 1 h (target 99 %)", + "id": 24, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Share of uploads with time_to_ready <= 30 s.\n\nUnit: percentunit.", + "gridPos": { + "h": 5, + "w": 6, + "x": 12, + "y": 52 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "decimals": 3, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": null + }, + { + "color": "green", + "value": 0.99 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "area", + "textMode": "value" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger:ready_within_30s_ratio:rate1h", + "instant": false, + "range": true + } + ] + }, + { + "type": "stat", + "title": "Alerts firing", + "id": 25, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Number of firing Prometheus alerts (table below).\n\nUnit: none.", + "gridPos": { + "h": 5, + "w": 6, + "x": 18, + "y": 52 + }, + "fieldConfig": { + "defaults": { + "unit": "none", + "decimals": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "background", + "graphMode": "area", + "textMode": "value" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "count(ALERTS{alertstate=\"firing\"}) or vector(0)", + "instant": false, + "range": true + } + ] + }, + { + "type": "table", + "title": "Alerts (pending / firing)", + "id": 26, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "ALERTS series of Prometheus (rules: infra/prometheus/rules/alerts.yml, runbook: docs/RUNBOOK.md).", + "gridPos": { + "h": 6, + "w": 24, + "x": 0, + "y": 57 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "ALERTS", + "instant": true, + "format": "table" + } + ], + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "Value": true, + "__name__": true + }, + "indexByName": {}, + "renameByName": {} + } + } + ], + "fieldConfig": { + "defaults": {}, + "overrides": [] + }, + "options": { + "showHeader": true + } + }, + { + "type": "row", + "title": "Telemetry pipeline (Collector, SDK)", + "id": 27, + "collapsed": false, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 63 + } + }, + { + "type": "timeseries", + "title": "Collector: spans accepted / sent / failed per second", + "id": 28, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "otelcol_* self-metrics, scraped from :8888. sent < accepted with tail sampling (dropped by policy).\n\nUnit: ops.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 64 + }, + "fieldConfig": { + "defaults": { + "unit": "ops", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_receiver_accepted_spans[$__rate_interval]))", + "legendFormat": "accepted", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_receiver_refused_spans[$__rate_interval]))", + "legendFormat": "refused (memory_limiter)", + "range": true + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_exporter_sent_spans[$__rate_interval]))", + "legendFormat": "sent to Tempo", + "range": true + }, + { + "refId": "D", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_exporter_send_failed_spans[$__rate_interval]))", + "legendFormat": "send failed (dropped)", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Collector: logs and metric points per second", + "id": 29, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Same for the logs and metrics pipelines.\n\nUnit: ops.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 64 + }, + "fieldConfig": { + "defaults": { + "unit": "ops", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_receiver_accepted_log_records[$__rate_interval]))", + "legendFormat": "logs accepted", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_exporter_send_failed_log_records[$__rate_interval]))", + "legendFormat": "logs failed", + "range": true + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_receiver_accepted_metric_points[$__rate_interval]))", + "legendFormat": "metric points accepted", + "range": true + }, + { + "refId": "D", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_exporter_send_failed_metric_points[$__rate_interval]))", + "legendFormat": "metric points failed", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Collector: exporter queues", + "id": 30, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Bounded sending_queue (batches) per exporter: fills while a backend is down, never above capacity.\n\nUnit: short.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 64 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (exporter) (otelcol_exporter_queue_size)", + "legendFormat": "{{exporter}} size", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (exporter) (otelcol_exporter_queue_capacity)", + "legendFormat": "{{exporter}} capacity", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "SDK: spans recorded vs exported (all processes)", + "id": 31, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Spans finished in the process (sampled) and handed to the OTLP exporter: success / failure (Collector down).\n\nUnit: ops.", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 72 + }, + "fieldConfig": { + "defaults": { + "unit": "ops", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (job) (rate(messenger_telemetry_spans_ended_total[$__rate_interval]))", + "legendFormat": "{{job}} recorded", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (job, result) (rate(messenger_telemetry_spans_exported_total[$__rate_interval]))", + "legendFormat": "{{job}} export {{result}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Telemetry components up", + "id": 32, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "1 = the scrape succeeded.\n\nUnit: short.", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 72 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none", + "group": "A" + } + }, + "min": 0, + "max": 1 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "up{job=~\"otel-collector|prometheus|loki|tempo|grafana\"}", + "legendFormat": "{{job}}", + "range": true + } + ] + }, + { + "type": "row", + "title": "Logs and traces", + "id": 33, + "collapsed": false, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 80 + } + }, + { + "type": "logs", + "title": "Application logs (Loki): warnings and errors", + "id": 34, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "description": "OTLP log records of api/relay/worker. Expand a line: trace_id links to Tempo. Query: {service_name=~\"messenger-.+\"} | detected_level=~\"warn|error\".", + "gridPos": { + "h": 10, + "w": 12, + "x": 0, + "y": 81 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "{service_name=~\"messenger-.+\"} | detected_level=~\"warn|error\"", + "queryType": "range" + } + ], + "options": { + "showTime": true, + "wrapLogMessage": true, + "enableLogDetails": true, + "sortOrder": "Descending", + "dedupStrategy": "none", + "prettifyLogMessage": false + } + }, + { + "type": "table", + "title": "Recent upload traces (Tempo)", + "id": 35, + "datasource": { + "type": "tempo", + "uid": "tempo" + }, + "description": "TraceQL: POST of an attachment. Click a trace id: upload -> enqueue -> publish -> process -> S3/DB.", + "gridPos": { + "h": 10, + "w": 12, + "x": 12, + "y": 81 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "tempo", + "uid": "tempo" + }, + "queryType": "traceql", + "limit": 20, + "tableType": "traces", + "query": "{ span.http.route = \"/api/v1/chats/{chat_id}/attachments\" }" + } + ], + "fieldConfig": { + "defaults": {}, + "overrides": [] + }, + "options": { + "showHeader": true + } + } + ] +} diff --git a/infra/grafana/provisioning/dashboards/dashboards.yaml b/infra/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 0000000..c884de0 --- /dev/null +++ b/infra/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,16 @@ +# Dashboards from JSON files in Git (infra/grafana/dashboards, mounted read-only). Editing in the +# UI is possible but not saved: the files are the source of truth (scripts/build_dashboard.py +# generates messenger.json). +apiVersion: 1 + +providers: + - name: messenger + orgId: 1 + folder: Messenger + type: file + disableDeletion: true + allowUiUpdates: false + updateIntervalSeconds: 30 + options: + path: /var/lib/grafana/dashboards + foldersFromFilesStructure: false diff --git a/infra/grafana/provisioning/datasources/datasources.yaml b/infra/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 0000000..a788578 --- /dev/null +++ b/infra/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,73 @@ +# Grafana datasources, provisioned at start (nothing is clicked by hand). The UIDs are FIXED: +# the dashboard JSON, the trace->logs and logs->trace links refer to exactly these UIDs +# (prometheus / loki / tempo). A datasource without a fixed uid gets a random one and every +# reference to it breaks ("data source not found"). +apiVersion: 1 + +deleteDatasources: + - {name: Prometheus, orgId: 1} + - {name: Loki, orgId: 1} + - {name: Tempo, orgId: 1} + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: false + jsonData: + httpMethod: POST + timeInterval: 15s # = scrape/evaluation interval: $__rate_interval >= 4 x 15 s + prometheusType: Prometheus + prometheusVersion: 3.16.0 + manageAlerts: true # show the Prometheus alert rules in Grafana's alert list + exemplarTraceIdDestinations: [] + + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + editable: false + jsonData: + maxLines: 1000 + # log line -> its trace in Tempo (trace_id is structured metadata of the OTLP record) + derivedFields: + - name: trace_id + matcherType: label + matcherRegex: trace_id + datasourceUid: tempo + url: "$${__value.raw}" + urlDisplayLabel: "Trace in Tempo" + + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 + editable: false + jsonData: + # span -> the log records of the same trace (and service) in Loki + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: "-5m" + spanEndTimeShift: "5m" + customQuery: true + query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__trace.traceId}"' + tracesToMetrics: + datasourceUid: prometheus + spanStartTimeShift: "-5m" + spanEndTimeShift: "5m" + tags: + - {key: service.name, value: job} + queries: + - name: HTTP p95 of this service + query: 'histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{$$__tags}[1m])))' + search: + hide: false + nodeGraph: + enabled: false + lokiSearch: + datasourceUid: loki diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 0000000..13172af --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,116 @@ +# HAProxy 3.2 LTS — the single public entry point of the lab 4 stand (compose service `lb`). +# +# Backend discovery: Docker DNS name `api` returns one A record per RUNNING replica of the +# compose service `api` (deploy.replicas / --scale). server-template keeps 8 slots and +# re-resolves every second, so scale up/down, a restarted container with a new IP and a +# full stack restart are picked up without restarting the LB. A stopped container drops +# out of DNS and its slot goes to MAINT. +# +# Readiness: an ACTIVE check `GET /health/ready` (PostgreSQL + Valkey + S3 reachable, not +# draining) every 1 s; 2 failures -> DOWN, 2 successes -> UP. Passive errors do not decide +# anything on their own, and there are NO fallback servers without checks: a replica that +# answers /health/live but not /health/ready never gets traffic while a fully ready one exists. +# +# Degraded mode (lab 4): S3 is a SHARED dependency. If it is down, /health/ready is 503 on +# every replica and backend `api` has no server. Instead of answering 503 to everything, the +# frontend then switches to backend `api_core`: the same replicas, checked by +# /health/ready/core (PostgreSQL + Valkey, not draining). Chats and text messages keep working, +# every attachment request is answered 503 by the API itself (fast, S3_TIMEOUT_SECONDS). +# A replica that alone lost S3 (e.g. its storage network) is DOWN in `api` while the others are +# UP, so it gets no traffic at all. +# Worst case detection of a failed replica (a check answered at once counts at once, a check +# that hangs counts only after `timeout check`): +# fast explicit 503 (drain after SIGTERM): inter 1 s + fastinter 0.5 s ~= 1.5 s; +# slow ready (PostgreSQL/Valkey unreachable: the answer takes ~1 s = timeout check) +# or frozen process: inter 1 s + 1 s + fastinter 0.5 s + 1 s ~= 3.5 s. +# Requests that could not even be SENT (connection refused/reset before the request) +# are retried on another replica (retry-on conn-failure + redispatch) - safe for POST, +# because the API has not seen them. Nothing that may have reached the API is retried by +# the LB: an uncertain POST is retried by the CLIENT with the same Idempotency-Key. +# No sticky sessions: sessions live in Valkey, every replica serves every user. + +global + log stdout format raw local0 info + maxconn 4096 + # Runtime API for `show servers state` / `show stat` (scripts and tests, no network port). + stats socket /var/lib/haproxy/admin.sock mode 600 level admin + hard-stop-after 15s + +resolvers docker + nameserver dns1 127.0.0.11:53 + accepted_payload_size 8192 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 1s + hold other 1s + hold refused 1s + hold nx 1s + hold timeout 1s + hold obsolete 1s + +defaults + mode http + log global + option httplog + option dontlognull + option http-keep-alive + timeout connect 1s + timeout client 30s + timeout server 10s # > DB_TIMEOUT_SECONDS (3 s): the API answers 503 itself first + timeout http-request 10s + timeout http-keep-alive 10s + timeout queue 3s + timeout check 1s + retries 2 + retry-on conn-failure + option redispatch 1 + # Errors generated by the LB itself, in the contract error format with the same request id. + # They carry no X-Instance-Id: no API replica produced them. 502/504 = the outcome of the + # request is unknown (a replica died mid-request / did not answer in time): retry with the + # same Idempotency-Key. 503 = no ready replica at all. + http-error status 502 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API-реплика оборвала ответ; повторите с тем же Idempotency-Key\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]" + http-error status 503 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"Нет готовых API-реплик\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]" + http-error status 504 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API-реплика не ответила вовремя; повторите с тем же Idempotency-Key\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]" + +frontend public + bind :8080 + # One request id end to end: keep a valid client X-Request-Id, otherwise create one; the + # API echoes it, and errors generated by the LB itself carry the same value. + http-request set-header X-Request-Id %[uuid()] unless { req.hdr(x-request-id) -m reg ^[A-Za-z0-9._:-]{1,128}$ } + http-request set-var(txn.request_id) req.hdr(x-request-id) + log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq rid=%[var(txn.request_id)] \"%HM %HPO\"" + use_backend api if { nbsrv(api) gt 0 } + default_backend api_core + +backend api + balance roundrobin + # Uploads (<= 10 MiB body + verification + S3 PUT): the API's own budget is + # UPLOAD_READ_TIMEOUT 30 s + IMAGE_VERIFY 10 s + S3; the LB must not cut it at 10 s (a 504 + # after a successful upload would make the client upload a duplicate). + acl is_upload path_reg ^/api/v1/chats/[^/]+/attachments$ + http-request set-timeout server 60s if is_upload METH_POST + option httpchk + http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api + http-check expect status 200 + default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 + server-template api 8 api:8080 + +# Degraded mode only (see the header): used when NO replica is fully ready. +backend api_core + balance roundrobin + acl is_upload path_reg ^/api/v1/chats/[^/]+/attachments$ + http-request set-timeout server 60s if is_upload METH_POST + option httpchk + http-check send meth GET uri /health/ready/core ver HTTP/1.1 hdr Host api + http-check expect status 200 + default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 + server-template core 8 api:8080 + +# Local-only status page (127.0.0.1:8404 on the host): which replica is UP/DOWN right now. +frontend stats + bind :8404 + stats enable + stats uri / + stats refresh 2s + stats show-legends diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml new file mode 100644 index 0000000..c4b8f29 --- /dev/null +++ b/infra/loki/loki.yaml @@ -0,0 +1,60 @@ +# Loki 3.7 (grafana/loki:3.7.10), single binary, lab 6: the LOGS store. +# +# Logs arrive from the Collector over OTLP (POST /otlp/v1/logs). Loki turns a few RESOURCE +# attributes into index labels (service_name, service_instance_id, deployment_environment_name): +# few values, small index. Log-record attributes (event, request_id, job_id, trace_id, span_id, +# route, status...) are stored as STRUCTURED METADATA next to the line - searchable +# (`{service_name="messenger-api"} | trace_id="..."`) without creating a stream per value. +# That is why an id such as request_id/attachment_id never becomes a label (it would create a +# new stream - and index entries - per request, see docs/DEFENSE.md). +auth_enabled: false + +server: + http_listen_port: 3100 + grpc_listen_port: 9096 + log_level: warn + +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2026-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +limits_config: + allow_structured_metadata: true + retention_period: 168h # 7 days of logs, deleted by the compactor + ingestion_rate_mb: 8 + ingestion_burst_size_mb: 16 + max_query_lookback: 168h + volume_enabled: true + +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem + +ingester: + wal: + dir: /loki/wal # on the named volume: a restart does not lose buffered logs + +pattern_ingester: + enabled: false + +analytics: + reporting_enabled: false diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 0000000..c034934 --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,93 @@ +# OpenTelemetry Collector (otel/opentelemetry-collector-contrib 0.165.0), lab 6. +# +# API x2 / relay / worker --OTLP/HTTP protobuf :4318--> [receiver otlp] +# -> memory_limiter -> batch -> exporters: +# traces -> Tempo (otlp_http/tempo, http://tempo:4318/v1/traces) +# metrics -> Prometheus (otlp_http/prometheus, http://prometheus:9090/api/v1/otlp/v1/metrics) +# logs -> Loki (otlp_http/loki, http://loki:3100/otlp/v1/logs) +# +# The Collector stores nothing for long: it receives, limits, batches and forwards. When a backend +# is down, each exporter keeps a BOUNDED queue (sending_queue) and retries for at most +# max_elapsed_time; then the data is dropped and counted (otelcol_exporter_send_failed_*, +# otelcol_exporter_enqueue_failed_*). memory_limiter refuses new data above its limit (the SDKs +# get a retryable error and drop after their own bounded queue) instead of growing until OOM. +# Its own metrics: Prometheus scrapes :8888 (otelcol_*). Only on the internal `telemetry` network. +# +# Traces pipeline variants (track 1, docs/TRACK1.md): this file keeps EVERY span; the overlay +# traces-tail.yaml (passed as a second --config, compose OTEL_COLLECTOR_TRACES) adds tail sampling. + +extensions: + health_check: + endpoint: 0.0.0.0:13133 + +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + max_request_body_size: 8388608 # 8 MiB per export request + +processors: + # First in every pipeline. Container limit 512 MiB: soft limit = 400 - 80 = 320 MiB (start + # refusing + GC), hard limit 400 MiB (forced GC). The contrib binary alone is ~150 MiB RSS; + # 256 MiB of container memory left the limiter refusing data at idle. GOMEMLIMIT = 360 MiB. + memory_limiter: + check_interval: 1s + limit_mib: 400 + spike_limit_mib: 80 + # Fewer, larger requests to the backends; at most 2 s of delay. + batch: + send_batch_size: 1024 + send_batch_max_size: 2048 + timeout: 2s + +exporters: + otlp_http/tempo: + endpoint: http://tempo:4318 + timeout: 5s + sending_queue: &queue + enabled: true + num_consumers: 2 + queue_size: 100 # batches (<= 2048 items each): bounded, in memory only + retry_on_failure: &retry + enabled: true + initial_interval: 1s + max_interval: 10s + max_elapsed_time: 60s # then the batch is dropped (counted), never retried forever + otlp_http/prometheus: + endpoint: http://prometheus:9090/api/v1/otlp + timeout: 5s + sending_queue: *queue + retry_on_failure: *retry + otlp_http/loki: + endpoint: http://loki:3100/otlp + timeout: 5s + sending_queue: *queue + retry_on_failure: *retry + +service: + extensions: [health_check] + telemetry: + logs: + level: warn + metrics: + level: normal + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp_http/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp_http/prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp_http/loki] diff --git a/infra/otel/traces-all.yaml b/infra/otel/traces-all.yaml new file mode 100644 index 0000000..91a722a --- /dev/null +++ b/infra/otel/traces-all.yaml @@ -0,0 +1,6 @@ +# Overlay for collector.yaml: keep every received span (no tail sampling). Selected by +# OTEL_COLLECTOR_TRACES=traces-all (compose). Lists are replaced, maps are merged by the Collector. +service: + pipelines: + traces: + processors: [memory_limiter, batch] diff --git a/infra/otel/traces-tail.yaml b/infra/otel/traces-tail.yaml new file mode 100644 index 0000000..134ee8a --- /dev/null +++ b/infra/otel/traces-tail.yaml @@ -0,0 +1,39 @@ +# Overlay for collector.yaml: TAIL sampling of traces (track 1 "balanced" configuration, +# docs/TRACK1.md). The decision is taken per trace after decision_wait, when its spans are in: +# keep ALL traces with an error span (status ERROR: HTTP 5xx, failed/retried job, S3/DB error), +# keep ALL slow traces (root to last span >= 250 ms), +# keep 10 % of the rest (probabilistic, by trace id: the same trace -> the same decision). +# Head sampling in the SDK (OTEL_TRACES_SAMPLER_ARG) decides at the first span and cannot know +# whether the request will fail or be slow; tail sampling can, at the price of buffering spans +# in the Collector (num_traces x spans) for decision_wait. +# +# A job is processed seconds after its upload: those spans may arrive after the upload trace was +# decided. decision_cache remembers the decision per trace id, so late spans of a kept trace are +# kept, and late spans of a dropped one are dropped (unless they are errors/slow by themselves: +# then they form a partial trace - a documented limit of the approach). +processors: + tail_sampling: + decision_wait: 5s + num_traces: 20000 + expected_new_traces_per_sec: 200 + decision_cache: + sampled_cache_size: 100000 + non_sampled_cache_size: 100000 + policies: + - name: errors + type: status_code + status_code: + status_codes: [ERROR] + - name: slow + type: latency + latency: + threshold_ms: 250 + - name: baseline + type: probabilistic + probabilistic: + sampling_percentage: 10 + +service: + pipelines: + traces: + processors: [memory_limiter, tail_sampling, batch] diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml new file mode 100644 index 0000000..4c4591c --- /dev/null +++ b/infra/prometheus/prometheus.yml @@ -0,0 +1,36 @@ +# Prometheus 3.16 (prom/prometheus:v3.16.0), lab 6: the METRICS store. +# +# Application metrics are PUSHED by the Collector over OTLP (flag --web.enable-otlp-receiver, +# endpoint /api/v1/otlp/v1/metrics). Prometheus derives `job` = service.name and +# `instance` = service.instance.id from the OTLP resource, and translates the OTel names with +# suffixes: http.server.request.duration (unit s) -> http_server_request_duration_seconds_bucket, +# messenger.jobs.processed -> messenger_jobs_processed_total (mapping: docs/OBSERVABILITY.md). +# The telemetry components themselves are SCRAPED (pull) below. +global: + scrape_interval: 15s + evaluation_interval: 15s # alert rules: detection delay = condition + `for` + <= 15 s + +otlp: + # deployment.environment.name=lab as a label on every series (low cardinality, one value). + promote_resource_attributes: [deployment.environment.name, service.version] + keep_identifying_resource_attributes: true + +storage: + tsdb: + # OTLP pushes from several processes arrive slightly out of order; accept 10 min of it. + out_of_order_time_window: 10m + +rule_files: + - /etc/prometheus/rules/*.yml + +scrape_configs: + - job_name: otel-collector # otelcol_* : accepted/refused/sent/failed, queue size, RSS + static_configs: [{targets: ["otel-collector:8888"]}] + - job_name: prometheus + static_configs: [{targets: ["localhost:9090"]}] + - job_name: loki + static_configs: [{targets: ["loki:3100"]}] + - job_name: tempo + static_configs: [{targets: ["tempo:3200"]}] + - job_name: grafana + static_configs: [{targets: ["grafana:3000"]}] diff --git a/infra/prometheus/rules/alerts.yml b/infra/prometheus/rules/alerts.yml new file mode 100644 index 0000000..aa9f628 --- /dev/null +++ b/infra/prometheus/rules/alerts.yml @@ -0,0 +1,90 @@ +# Alert rules (evaluated by Prometheus every 15 s; state pending -> firing -> resolved is visible +# in Prometheus /api/v1/alerts, the ALERTS series and the Grafana dashboard "Alerts" panel). +# No delivery outside (no Alertmanager): the task asks for the local firing/resolved state only. +# Runbook of every alert: docs/RUNBOOK.md#. +groups: + - name: messenger-alerts + rules: + - alert: MessengerApiHighErrorRate + # 5xx share of business requests over 1 min, summed over all API replicas. The traffic + # guard (> 0.2 req/s) keeps a single failed request on an idle stand from paging. + expr: messenger:http_error_ratio:rate1m > 0.05 and messenger:http_requests:rate1m > 0.2 + for: 1m + labels: + severity: page + slo: api-availability + annotations: + summary: "API: {{ $value | humanizePercentage }} of business requests answer 5xx" + description: >- + More than 5 % of non-health API requests failed with 5xx for over a minute (SLO: 99 % + non-5xx over 1 h). Typical causes: PostgreSQL/Valkey/S3 unavailable or too slow (503), + pool exhausted, crash (500). + runbook: docs/RUNBOOK.md#messengerapihigherrorrate + + - alert: MessengerQueueLagGrowing + # Oldest unfinished job older than 60 s while jobs are waiting: nobody processes the queue + # (worker stopped/stuck, broker unreachable) or processing is far slower than arrivals. + # Measured in PostgreSQL by the relay: retries and unpublished jobs count too. + expr: max(messenger_queue_oldest_age_seconds) > 60 and max(messenger_queue_depth{state="queued"}) > 0 + for: 1m + labels: + severity: page + slo: time-to-ready + annotations: + summary: "Queue: the oldest job waits {{ $value | humanizeDuration }}" + description: >- + Accepted uploads are not becoming ready. Check messenger_worker_busy / capacity, the + worker container, messenger_outbox_oldest_age_seconds (broker) and job outcomes. + runbook: docs/RUNBOOK.md#messengerqueuelaggrowing + + - alert: MessengerApiLatencyHigh + # p99 of business requests over 2 min, from the buckets of all replicas. + expr: messenger:http_latency:p99_2m > 1 + for: 2m + labels: + severity: ticket + slo: api-latency + annotations: + summary: "API p99 = {{ $value | humanizeDuration }} (> 1 s)" + description: >- + Slow API. Compare db.client.operation.duration and the DB pool (pending requests) with + the HTTP duration: slow database vs slow handler code (docs/RUNBOOK.md). + runbook: docs/RUNBOOK.md#messengerapilatencyhigh + + - alert: MessengerDbPoolSaturated + # Requests waiting for a database connection in any process, for 1 min. + expr: max by (job) (db_client_connection_pending_requests) > 0 + for: 1m + labels: + severity: ticket + annotations: + summary: "{{ $labels.job }}: requests wait for a PostgreSQL connection" + description: The pool is exhausted - queries hold connections too long (slow DB, locks) or the pool is too small. + runbook: docs/RUNBOOK.md#messengerdbpoolsaturated + + - alert: MessengerQueueMetricsAbsent + # The relay reports the backlog from PostgreSQL every 5 s; no value for 2 min means the + # relay is down or cannot read the database - the queue is then NOT observed at all. + expr: absent(messenger_queue_oldest_age_seconds) + for: 2m + labels: + severity: ticket + annotations: + summary: "No queue metrics (relay down or database unreachable)" + runbook: docs/RUNBOOK.md#messengerqueuemetricsabsent + + - alert: TelemetryExportFailing + # The Collector cannot deliver to a backend (Tempo/Loki/Prometheus down): data is buffered + # in its bounded queue and then dropped. The application itself is not affected. + expr: | + sum by (exporter) ( + rate(otelcol_exporter_send_failed_spans[2m]) + or rate(otelcol_exporter_send_failed_log_records[2m]) + or rate(otelcol_exporter_send_failed_metric_points[2m]) + ) > 0 + for: 30s + labels: + severity: ticket + annotations: + summary: "Collector exporter {{ $labels.exporter }} fails to send" + runbook: docs/RUNBOOK.md#telemetryexportfailing diff --git a/infra/prometheus/rules/slo.yml b/infra/prometheus/rules/slo.yml new file mode 100644 index 0000000..dec7c44 --- /dev/null +++ b/infra/prometheus/rules/slo.yml @@ -0,0 +1,38 @@ +# Recording rules: SLIs of docs/SLO.md (lab windows). All ratios are computed from COUNTERS and +# histogram BUCKETS summed over every replica first, then divided - never an average of +# per-replica ratios or percentiles. +# +# Business requests = every API request except /health/* (load-balancer/Docker probes). +# "Bad" for availability = HTTP 5xx only: 4xx (wrong password, 404 of an outsider, 409) is a +# correct answer to a wrong request, not a failure of the service. +groups: + - name: messenger-sli + interval: 15s + rules: + - record: messenger:http_requests:rate1m + expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[1m])) + - record: messenger:http_errors5xx:rate1m + expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*", http_response_status_class="5xx"}[1m])) or vector(0) + - record: messenger:http_error_ratio:rate1m + expr: messenger:http_errors5xx:rate1m / messenger:http_requests:rate1m + - record: messenger:http_error_ratio:rate5m + expr: | + (sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*", http_response_status_class="5xx"}[5m])) or vector(0)) + / sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[5m])) + - record: messenger:http_error_ratio:rate1h + expr: | + (sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*", http_response_status_class="5xx"}[1h])) or vector(0)) + / sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[1h])) + # Latency SLI: share of business requests answered within 250 ms (bucket le="0.25"). + - record: messenger:http_fast_ratio:rate5m + expr: | + sum(rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*", le="0.25"}[5m])) + / sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[5m])) + # p50/p95/p99 over ALL replicas: buckets summed by le, then histogram_quantile. + - record: messenger:http_latency:p99_2m + expr: histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*"}[2m]))) + # Time-to-ready SLI: share of uploads ready within 30 s (bucket le="30"). + - record: messenger:ready_within_30s_ratio:rate1h + expr: | + sum(rate(messenger_attachment_time_to_ready_seconds_bucket{le="30"}[1h])) + / sum(rate(messenger_attachment_time_to_ready_seconds_count[1h])) diff --git a/infra/rabbitmq/enabled_plugins b/infra/rabbitmq/enabled_plugins new file mode 100644 index 0000000..57afcca --- /dev/null +++ b/infra/rabbitmq/enabled_plugins @@ -0,0 +1 @@ +[]. diff --git a/infra/rabbitmq/rabbitmq.conf b/infra/rabbitmq/rabbitmq.conf new file mode 100644 index 0000000..05165e0 --- /dev/null +++ b/infra/rabbitmq/rabbitmq.conf @@ -0,0 +1,24 @@ +# RabbitMQ 4.3 of the lab 5 stand (compose service `broker`), mounted as conf.d/20-lab5.conf. +# Only AMQP 0-9-1 on 5672 inside the internal network `queue`: no management UI, no Prometheus +# listener (enabled_plugins is empty), nothing published on the host. +listeners.tcp.default = 5672 + +# Users, permissions and topology are imported from files at every boot (idempotent): +# /etc/rabbitmq/definitions.d/topology.json exchanges, quorum queues, bindings (this repo) +# /etc/rabbitmq/definitions.d/users.json users relay/worker + permissions (Docker secret, +# generated by scripts/init_secrets.py) +# With imported definitions no default `guest` user is created. +definitions.import_backend = local_filesystem +definitions.local.path = /etc/rabbitmq/definitions.d +definitions.skip_if_unchanged = false + +# A delivery that stays unacked longer than this closes the consumer's channel and the message +# is returned to the queue (a worker that hangs while connected). Far above JOB_TIMEOUT_SECONDS. +consumer_timeout = 300000 + +# The container has a 512 MiB limit; flow control starts well before the cgroup OOM. +vm_memory_high_watermark.relative = 0.5 +disk_free_limit.absolute = 200MB + +log.console = true +log.console.level = info diff --git a/infra/rabbitmq/topology.json b/infra/rabbitmq/topology.json new file mode 100644 index 0000000..301ef1c --- /dev/null +++ b/infra/rabbitmq/topology.json @@ -0,0 +1,21 @@ +{ + "vhosts": [{"name": "/"}], + "exchanges": [ + {"name": "messenger.jobs", "vhost": "/", "type": "direct", "durable": true, "auto_delete": false, + "internal": false, "arguments": {}}, + {"name": "messenger.jobs.dlx", "vhost": "/", "type": "fanout", "durable": true, "auto_delete": false, + "internal": false, "arguments": {}} + ], + "queues": [ + {"name": "messenger.attachment-jobs", "vhost": "/", "durable": true, "auto_delete": false, + "arguments": {"x-queue-type": "quorum", "x-delivery-limit": 20, "x-dead-letter-exchange": "messenger.jobs.dlx"}}, + {"name": "messenger.attachment-jobs.dlq", "vhost": "/", "durable": true, "auto_delete": false, + "arguments": {"x-queue-type": "quorum"}} + ], + "bindings": [ + {"source": "messenger.jobs", "vhost": "/", "destination": "messenger.attachment-jobs", "destination_type": "queue", + "routing_key": "attachment.process.v1", "arguments": {}}, + {"source": "messenger.jobs.dlx", "vhost": "/", "destination": "messenger.attachment-jobs.dlq", + "destination_type": "queue", "routing_key": "", "arguments": {}} + ] +} diff --git a/infra/seaweedfs/start.sh b/infra/seaweedfs/start.sh new file mode 100644 index 0000000..f496154 --- /dev/null +++ b/infra/seaweedfs/start.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# Entry point of the compose service `s3` (SeaweedFS 4.46, one container: master + volume + +# filer + S3 gateway). Renders the S3 identities from Docker secrets, then execs `weed`. +# +# Two private buckets (lab 5): S3_STAGING_BUCKET holds originals accepted by the API before 202, +# S3_BUCKET holds the published originals and variants written by the worker. +# Identities (SeaweedFS s3.json, actions scoped to a bucket): +# bootstrap-admin Admin (create buckets) -> only s3-init has these keys +# messenger-api Write staging, Read final -> API replicas (no List, no Admin) +# messenger-worker Read + Write staging, Read + Write final -> worker (no List, no Admin) +# messenger-auditor Read + List both buckets (no Write) -> invariant checker (tools profile) +# There is NO anonymous identity, so every unsigned request is refused: the buckets are private. +# +# Exposure: master (9333), volume (8080), filer (8888) with their web UIs and gRPC listen on +# 127.0.0.1 INSIDE the container only (-ip.bind); only the S3 API port 8333 listens on the +# container network `storage` (internal, not published on the host). Telemetry is off. +set -eu +umask 077 +secret() { tr -d '\r\n' < "/run/secrets/$1"; } +bucket="${S3_BUCKET:?S3_BUCKET is required}" +staging="${S3_STAGING_BUCKET:?S3_STAGING_BUCKET is required}" +cat > /tmp/s3.json < ($2, $3) ORDER BY created_at, id LIMIT n +-- becomes an index range scan that starts exactly at the cursor. +CREATE INDEX messages_chat_keyset ON messages (chat_id, created_at, id); + +-- Sessions for SESSION_STORE=postgres (the default store is Valkey; see docs/DATA_MODEL.md). +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, -- SHA-256 of the token; the token is not stored + user_id uuid NOT NULL REFERENCES users (id), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + expires_at timestamptz NOT NULL, + CONSTRAINT sessions_token_hash_len CHECK (octet_length(token_hash) = 32) +); +CREATE INDEX sessions_expires_at ON sessions (expires_at); diff --git a/migrations/0002_idempotency_keys.sql b/migrations/0002_idempotency_keys.sql new file mode 100644 index 0000000..108dafd --- /dev/null +++ b/migrations/0002_idempotency_keys.sql @@ -0,0 +1,25 @@ +-- 0002 (lab 3): shared idempotency of POST /chats/{chat_id}/messages. +-- Additive only (new table), so the lab 2 API keeps working while this runs: it is safe +-- to apply before a rolling update of the API replicas (see REPORT.md, "Миграции"). +-- +-- Scope of a key (contracts/README.md): current user + HTTP method + chat path + key. +-- The method (POST) and the path template are fixed for this table, so the scope +-- is (user_id, chat_id, key). The key row, the message and the result are written in +-- ONE transaction (repo.post_message): there is no "pending" state that a crash could +-- leave behind, and the stored result is the message row itself. + +CREATE TABLE idempotency_keys ( + user_id uuid NOT NULL REFERENCES users (id), + chat_id uuid NOT NULL REFERENCES chats (id), + key text NOT NULL, + request_hash bytea NOT NULL, -- SHA-256 of the canonical JSON body + -- Inserted before the message in the same transaction, hence checked at COMMIT. + message_id uuid NOT NULL REFERENCES messages (id) DEFERRABLE INITIALLY DEFERRED, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (user_id, chat_id, key), + CONSTRAINT idempotency_keys_key_format CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'), + CONSTRAINT idempotency_keys_hash_len CHECK (octet_length(request_hash) = 32), + CONSTRAINT idempotency_keys_message_key UNIQUE (message_id) +); +-- Housekeeping of keys older than IDEMPOTENCY_TTL_SECONDS (>= 24 h). +CREATE INDEX idempotency_keys_created_at ON idempotency_keys (created_at); diff --git a/migrations/0003_post_message_function.sql b/migrations/0003_post_message_function.sql new file mode 100644 index 0000000..268a0c0 --- /dev/null +++ b/migrations/0003_post_message_function.sql @@ -0,0 +1,50 @@ +-- 0003 (lab 3, track 1 improvement): the whole idempotent "send message" as ONE statement. +-- Additive (a new function), so replicas of the previous version keep working while it is +-- applied, and the previous write path (MESSAGE_WRITE_PATH=multi) stays usable for A/B runs. +-- +-- Same semantics and the same SQL as repo.post_message (multi-statement path), but executed +-- inside the server: the API sends one call instead of ~11 round trips in two transactions +-- (membership check, BEGIN, key claim, chat clock, message, COMMIT, pool checks). Called in +-- autocommit mode, so the function call IS the transaction: key row, chat clock and message +-- commit together or not at all. VOLATILE + READ COMMITTED: every statement inside takes a +-- fresh snapshot, so after waiting on a concurrent claim of the same key the stored result +-- of the winner is visible, exactly as in the multi-statement path. +-- +-- o_status: created | replayed | conflict | not_found | retry (key vanished in between: cleanup) +CREATE FUNCTION post_message(p_user uuid, p_chat uuid, p_key text, p_hash bytea, p_message uuid, + p_text bytea, p_ttl_seconds integer) +RETURNS TABLE (o_status text, o_id uuid, o_text bytea, o_created_at timestamptz) +LANGUAGE plpgsql VOLATILE AS $$ +DECLARE + v_created timestamptz; +BEGIN + PERFORM 1 FROM chat_members m WHERE m.chat_id = p_chat AND m.user_id = p_user; + IF NOT FOUND THEN + RETURN QUERY SELECT 'not_found'::text, NULL::uuid, NULL::bytea, NULL::timestamptz; + RETURN; + END IF; + + INSERT INTO idempotency_keys AS k (user_id, chat_id, key, request_hash, message_id) + VALUES (p_user, p_chat, p_key, p_hash, p_message) + ON CONFLICT (user_id, chat_id, key) DO UPDATE + SET request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp() + WHERE k.created_at < clock_timestamp() - make_interval(secs => p_ttl_seconds); + IF FOUND THEN + -- Per-chat clock under the chat row lock (see migrations/0001 and docs/DATA_MODEL.md). + UPDATE chats c SET last_message_at = greatest(clock_timestamp(), c.last_message_at + interval '1 microsecond') + WHERE c.id = p_chat RETURNING c.last_message_at INTO v_created; + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES (p_message, p_chat, p_user, p_text, v_created); + RETURN QUERY SELECT 'created'::text, p_message, p_text, v_created; + RETURN; + END IF; + + RETURN QUERY + SELECT CASE WHEN k.request_hash = p_hash THEN 'replayed' ELSE 'conflict' END, m.id, m.text, m.created_at + FROM idempotency_keys k JOIN messages m ON m.id = k.message_id + WHERE k.user_id = p_user AND k.chat_id = p_chat AND k.key = p_key; + IF NOT FOUND THEN + RETURN QUERY SELECT 'retry'::text, NULL::uuid, NULL::bytea, NULL::timestamptz; + END IF; +END +$$; diff --git a/migrations/0004_attachments.sql b/migrations/0004_attachments.sql new file mode 100644 index 0000000..efc1d5f --- /dev/null +++ b/migrations/0004_attachments.sql @@ -0,0 +1,145 @@ +-- 0004 (lab 4): attachments. Metadata live here, the bytes in the private S3 bucket. +-- Additive (new tables, a relaxed CHECK, a NEW function post_message_v2), so replicas of the +-- lab 3 version keep working while it is applied (they never send attachment_ids). +-- +-- Consistency between the two stores (docs/CONSISTENCY.md): +-- 1. INSERT the row as status='pending' (intent: the server-generated object_key is known +-- BEFORE anything is written to S3) and COMMIT; +-- 2. PUT the object into S3; +-- 3. UPDATE status='ready' WHERE status='pending'; only then 201. +-- Invariant: an object never exists without a row that names its key (row first, object +-- second; on cleanup object first, row second). A crash/outage between the steps leaves a +-- 'pending' row; the janitor deletes its object (idempotent) and then the row once it is older +-- than PENDING_GRACE_SECONDS. The reconciler (python -m messenger.reconcile) checks the +-- invariant over the whole bucket. + +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + owner_id uuid NOT NULL, + filename text NOT NULL, -- display name only, never a path or a key + content_type text NOT NULL, -- detected from the bytes, not from the header + size_bytes integer NOT NULL, + sha256 bytea NOT NULL, + width integer NOT NULL, + height integer NOT NULL, + -- Random server-generated key ("o/" + 128 random bits in hex), unrelated to id/filename. + -- COLLATE "C": byte order = S3 ListObjectsV2 order, the reconciler merge-joins both lists. + object_key text COLLATE "C" NOT NULL, + status text NOT NULL DEFAULT 'pending', + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + -- Set by the reconciler when the object of a READY row is missing or has the wrong size: + -- the row is quarantined (content -> 404, cannot be attached), never deleted, and the mark + -- is removed again if the object comes back (restore from backup). + lost_at timestamptz, + lost_reason text, + -- The uploader must be a member of the chat (enforced by the database too). + CONSTRAINT attachments_owner_is_member FOREIGN KEY (chat_id, owner_id) + REFERENCES chat_members (chat_id, user_id), + CONSTRAINT attachments_object_key_key UNIQUE (object_key), + CONSTRAINT attachments_object_key_format CHECK (object_key ~ '^o/[0-9a-f]{32}$'), + CONSTRAINT attachments_status CHECK (status IN ('pending', 'ready')), + CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')), + CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760), + CONSTRAINT attachments_sha256_len CHECK (octet_length(sha256) = 32), + CONSTRAINT attachments_pixels CHECK (width >= 1 AND height >= 1 AND width::bigint * height <= 40000000), + CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255), + CONSTRAINT attachments_lost CHECK ((lost_at IS NULL) = (lost_reason IS NULL) AND (lost_at IS NULL OR status = 'ready')) +); +-- Janitor: stale intents, oldest first; tiny partial index (only rows of unfinished uploads). +CREATE INDEX attachments_pending_created ON attachments (created_at) WHERE status = 'pending'; + +-- attachment_ids of a message, twice on purpose (both written in the message's transaction): +-- * messages.attachment_ids (ordered array): the history page reads it from the same row, so the +-- keyset range scan of messages stays ONE index scan, without a per-row sub-query; +-- * message_attachments: foreign keys (a referenced attachment can never be deleted) and the +-- reverse lookup "is this attachment used?" (janitor/reconciler) by an index on attachment_id. +ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}'; +ALTER TABLE messages ADD CONSTRAINT messages_attachment_ids_len CHECK (cardinality(attachment_ids) <= 10); + +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages (id), + position smallint NOT NULL, + attachment_id uuid NOT NULL REFERENCES attachments (id), + PRIMARY KEY (message_id, position), + CONSTRAINT message_attachments_unique UNIQUE (message_id, attachment_id), + CONSTRAINT message_attachments_position CHECK (position BETWEEN 0 AND 9) +); +-- "Is this attachment used by any message?" (janitor/reconciler never touch used ones). +CREATE INDEX message_attachments_attachment ON message_attachments (attachment_id); + +-- Lab 4: text may be "" when the message has attachments (the API enforces "text or files"). +-- DROP CONSTRAINT takes a short exclusive lock on messages and the new CHECK scans the table +-- once, inside this migration's transaction (seconds for a lab-sized table; for a big table +-- this would be ADD ... NOT VALID + VALIDATE in a separate migration). +ALTER TABLE messages DROP CONSTRAINT messages_text_len; +ALTER TABLE messages ADD CONSTRAINT messages_text_len CHECK (octet_length(text) <= 16000); + +-- post_message_v2: post_message (0003) + attachment_ids, still ONE statement and ONE transaction. +-- The attachments are checked BEFORE the key is claimed and the key is claimed only if they are +-- fine, so a failed check never leaves a key behind. A replay (same key, same body) returns the +-- stored message even if an attachment was quarantined since: the result of a key is final. +-- +-- o_status: created | replayed | conflict | not_found | retry | attachment_not_found | attachment_conflict +CREATE FUNCTION post_message_v2(p_user uuid, p_chat uuid, p_key text, p_hash bytea, p_message uuid, + p_text bytea, p_ttl_seconds integer, p_attachments uuid[]) +RETURNS TABLE (o_status text, o_id uuid, o_text bytea, o_created_at timestamptz, o_attachments uuid[]) +LANGUAGE plpgsql VOLATILE AS $$ +DECLARE + v_created timestamptz; + v_found integer; + v_usable integer; + v_check text := 'ok'; +BEGIN + PERFORM 1 FROM chat_members m WHERE m.chat_id = p_chat AND m.user_id = p_user; + IF NOT FOUND THEN + RETURN QUERY SELECT 'not_found'::text, NULL::uuid, NULL::bytea, NULL::timestamptz, NULL::uuid[]; + RETURN; + END IF; + + IF cardinality(p_attachments) > 0 THEN + -- Visible = ready attachment of THIS chat (pending, foreign or unknown -> 404). + -- Usable = visible and not quarantined (lost -> 409, like a failed attachment). + -- FOR SHARE: a concurrent quarantine waits until this message is committed. + SELECT count(*), count(*) FILTER (WHERE a.lost_at IS NULL) INTO v_found, v_usable + FROM (SELECT a.lost_at FROM attachments a + WHERE a.id = ANY (p_attachments) AND a.chat_id = p_chat AND a.status = 'ready' + FOR SHARE) a; + IF v_found <> cardinality(p_attachments) THEN + v_check := 'attachment_not_found'; + ELSIF v_usable <> v_found THEN + v_check := 'attachment_conflict'; + END IF; + END IF; + + IF v_check = 'ok' THEN + INSERT INTO idempotency_keys AS k (user_id, chat_id, key, request_hash, message_id) + VALUES (p_user, p_chat, p_key, p_hash, p_message) + ON CONFLICT (user_id, chat_id, key) DO UPDATE + SET request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp() + WHERE k.created_at < clock_timestamp() - make_interval(secs => p_ttl_seconds); + IF FOUND THEN + UPDATE chats c SET last_message_at = greatest(clock_timestamp(), c.last_message_at + interval '1 microsecond') + WHERE c.id = p_chat RETURNING c.last_message_at INTO v_created; + INSERT INTO messages (id, chat_id, sender_id, text, created_at, attachment_ids) + VALUES (p_message, p_chat, p_user, p_text, v_created, p_attachments); + INSERT INTO message_attachments (message_id, position, attachment_id) + SELECT p_message, (a.ord - 1)::smallint, a.id + FROM unnest(p_attachments) WITH ORDINALITY AS a(id, ord); + RETURN QUERY SELECT 'created'::text, p_message, p_text, v_created, p_attachments; + RETURN; + END IF; + END IF; + + RETURN QUERY + SELECT CASE WHEN k.request_hash = p_hash THEN 'replayed' ELSE 'conflict' END, m.id, m.text, m.created_at, + m.attachment_ids + FROM idempotency_keys k JOIN messages m ON m.id = k.message_id + WHERE k.user_id = p_user AND k.chat_id = p_chat AND k.key = p_key; + IF NOT FOUND THEN + RETURN QUERY SELECT CASE WHEN v_check = 'ok' THEN 'retry' ELSE v_check END, + NULL::uuid, NULL::bytea, NULL::timestamptz, NULL::uuid[]; + END IF; +END +$$; diff --git a/migrations/0005_pipeline.sql b/migrations/0005_pipeline.sql new file mode 100644 index 0000000..ac44388 --- /dev/null +++ b/migrations/0005_pipeline.sql @@ -0,0 +1,260 @@ +-- 0005 (lab 5): asynchronous processing of attachments. Details: docs/PIPELINE.md. +-- +-- Upload (API): INSERT attachment 'pending' (intent: the staging key is known before the PUT) +-- -> PUT original into the PRIVATE STAGING bucket +-- -> ONE transaction: attachment 'queued' + jobs row + outbox row -> 202. +-- Relay: outbox row -> publish to RabbitMQ with publisher confirm -> outbox.published_at. +-- Worker: claim job (lease + attempt token) -> variants into the final bucket under keys of +-- THIS attempt -> ONE transaction: variants + attachment 'ready' (fenced by the +-- lease token, never downgrading published_version) -> ack -> staging deleted. +-- +-- PostgreSQL is the source of truth for the work: state, attempts, lease, backoff (available_at) +-- and the failed registry. The broker only delivers job ids (at least once). + +-- ------------------------------------------------------------------ attachments +ALTER TABLE attachments DROP CONSTRAINT attachments_status; +ALTER TABLE attachments ADD CONSTRAINT attachments_status + CHECK (status IN ('pending', 'queued', 'processing', 'ready', 'failed')); +-- object_key = key of the ORIGINAL in the final bucket. NULL until the worker publishes it. +-- Keys of lab 4 ('o/') stay valid; lab 5 writes 'a///original'. +ALTER TABLE attachments ALTER COLUMN object_key DROP NOT NULL; +ALTER TABLE attachments DROP CONSTRAINT attachments_object_key_format; +ALTER TABLE attachments ADD CONSTRAINT attachments_object_key_format + CHECK (object_key ~ '^(o/[0-9a-f]{32}|a/[0-9a-f-]{36}/[0-9a-f]{32}/original)$'); +ALTER TABLE attachments + -- Key of the original in the staging bucket ('s/<128 random bits>'), written by the API. + ADD COLUMN staging_key text COLLATE "C", + -- none (lab 4 row) | present | deleting (marked, S3 DELETE pending) | deleted + ADD COLUMN staging_state text NOT NULL DEFAULT 'none', + -- pipeline version whose variants are published (GET shows them); only ever grows. + ADD COLUMN published_version integer, + ADD COLUMN error_code text, + ADD COLUMN failed_at timestamptz, + ADD CONSTRAINT attachments_staging_key_key UNIQUE (staging_key), + ADD CONSTRAINT attachments_staging_key_format CHECK (staging_key ~ '^s/[0-9a-f]{32}$'), + ADD CONSTRAINT attachments_staging_state CHECK (staging_state IN ('none', 'present', 'deleting', 'deleted')), + ADD CONSTRAINT attachments_staging_has_key CHECK (staging_state = 'none' OR staging_key IS NOT NULL), + ADD CONSTRAINT attachments_published_version CHECK (published_version >= 1), + ADD CONSTRAINT attachments_error_code CHECK (error_code ~ '^[a-z_]{1,64}$'); + +-- Lab 4 rows: a 'pending' intent of lab 4 never got its object confirmed and has no staging copy; +-- it becomes a failed upload (invisible: its id was never returned). A lab 4 'ready' row has its +-- original in the final bucket but no thumbnail yet: it is queued for pipeline 1 (below). +UPDATE attachments SET status = 'failed', error_code = 'upload_incomplete', failed_at = clock_timestamp() +WHERE status = 'pending'; +UPDATE attachments SET status = 'queued' WHERE status = 'ready'; + +-- Structural guarantees (the database refuses a buggy cleanup or worker): +-- * work that is queued/processing always has a source: the published original or the staging +-- copy - the cleanup can never mark the staging of an accepted upload as deleting; +-- * ready = published original + published pipeline version; failed = error code. +ALTER TABLE attachments + ADD CONSTRAINT attachments_pending_staging CHECK (status <> 'pending' OR staging_state = 'present'), + ADD CONSTRAINT attachments_active_has_source + CHECK (status NOT IN ('queued', 'processing') OR object_key IS NOT NULL OR staging_state = 'present'), + ADD CONSTRAINT attachments_ready_published + CHECK (status <> 'ready' OR (object_key IS NOT NULL AND published_version IS NOT NULL)), + ADD CONSTRAINT attachments_failed_code + CHECK ((status = 'failed') = (error_code IS NOT NULL AND failed_at IS NOT NULL)); +-- Janitor of the API: the lab 4 partial index on pending rows stays as is. +-- Cleanup of the worker: staging copies that may be deleted (ready: at once; failed: after retention). +CREATE INDEX attachments_staging_cleanup ON attachments (updated_at) + WHERE staging_state IN ('present', 'deleting') AND status IN ('ready', 'failed'); + +-- ------------------------------------------------------------------ jobs +-- One row = one logical piece of work: "build pipeline version V for attachment A". +-- job_id never changes on redelivery; `attempt` counts claims by workers (managed attempts). +CREATE TABLE jobs ( + id uuid PRIMARY KEY, + attachment_id uuid NOT NULL REFERENCES attachments (id), + pipeline_version integer NOT NULL, + kind text NOT NULL, -- upload | replay | reprocess | migrate + replay_of uuid REFERENCES jobs (id), + state text NOT NULL DEFAULT 'queued', + attempt integer NOT NULL DEFAULT 0, + max_attempts integer NOT NULL, + available_at timestamptz NOT NULL DEFAULT clock_timestamp(), -- backoff: not before + lease_token uuid, -- token of the attempt that holds the job + lease_owner text, + lease_until timestamptz, + error_code text, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + finished_at timestamptz, + CONSTRAINT jobs_pipeline_version CHECK (pipeline_version >= 1), + CONSTRAINT jobs_kind CHECK (kind IN ('upload', 'replay', 'reprocess', 'migrate')), + CONSTRAINT jobs_replay CHECK ((kind = 'replay') = (replay_of IS NOT NULL)), + CONSTRAINT jobs_state CHECK (state IN ('queued', 'processing', 'succeeded', 'failed', 'superseded')), + CONSTRAINT jobs_attempts CHECK (attempt >= 0 AND max_attempts BETWEEN 1 AND 100 AND attempt <= max_attempts), + -- A lease exists exactly while the job is processing. + CONSTRAINT jobs_lease CHECK ((state = 'processing') = (lease_token IS NOT NULL AND lease_until IS NOT NULL)), + CONSTRAINT jobs_finished CHECK ((state IN ('succeeded', 'failed', 'superseded')) = (finished_at IS NOT NULL)), + CONSTRAINT jobs_failed_code CHECK (state <> 'failed' OR error_code IS NOT NULL), + CONSTRAINT jobs_error_code CHECK (error_code ~ '^[a-z_]{1,64}$') +); +-- At most ONE active job per effect set (attachment, pipeline version): a second upload job, +-- replay or reprocess of the same version cannot exist while one is queued/processing. +CREATE UNIQUE INDEX jobs_one_active ON jobs (attachment_id, pipeline_version) WHERE state IN ('queued', 'processing'); +CREATE INDEX jobs_attachment ON jobs (attachment_id, created_at); +CREATE INDEX jobs_lease_expiry ON jobs (lease_until) WHERE state = 'processing'; -- reaper +CREATE INDEX jobs_queued ON jobs (updated_at) WHERE state = 'queued'; -- lost-message guard +CREATE INDEX jobs_failed ON jobs (finished_at) WHERE state = 'failed'; -- failed registry + +-- One row per claim of a job by a worker. The token is part of every object key the attempt +-- writes, so the keys of an attempt are known without listing the bucket (planned_keys), and an +-- attempt that is no longer the lease holder can never publish (fencing by token). +CREATE TABLE job_attempts ( + token uuid PRIMARY KEY, + job_id uuid NOT NULL REFERENCES jobs (id), + attempt integer NOT NULL, + worker text NOT NULL, + source text NOT NULL, -- staging | original + planned_keys text[] NOT NULL, + outcome text NOT NULL DEFAULT 'running', + error_code text, + started_at timestamptz NOT NULL DEFAULT clock_timestamp(), + finished_at timestamptz, + objects_cleaned_at timestamptz, + CONSTRAINT job_attempts_number UNIQUE (job_id, attempt), + CONSTRAINT job_attempts_source CHECK (source IN ('staging', 'original')), + CONSTRAINT job_attempts_outcome + CHECK (outcome IN ('running', 'succeeded', 'retry', 'failed', 'abandoned', 'superseded')), + CONSTRAINT job_attempts_finished CHECK ((outcome = 'running') = (finished_at IS NULL)), + -- Objects of a successful attempt are published: they are never cleaned. + CONSTRAINT job_attempts_cleaned CHECK (objects_cleaned_at IS NULL OR outcome NOT IN ('running', 'succeeded')) +); +CREATE INDEX job_attempts_cleanup ON job_attempts (finished_at) + WHERE outcome IN ('retry', 'failed', 'abandoned', 'superseded') AND objects_cleaned_at IS NULL; + +-- Published variants. The primary key is the idempotency key of the EFFECT from the contract: +-- (attachment_id, pipeline_version, variant) exists at most once, whatever the deliveries. +CREATE TABLE attachment_variants ( + attachment_id uuid NOT NULL REFERENCES attachments (id), + pipeline_version integer NOT NULL, + name text NOT NULL, + object_key text COLLATE "C" NOT NULL, + content_type text NOT NULL, + size_bytes integer NOT NULL, + width integer NOT NULL, + height integer NOT NULL, + sha256 bytea NOT NULL, + attempt_token uuid NOT NULL REFERENCES job_attempts (token), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (attachment_id, pipeline_version, name), + CONSTRAINT attachment_variants_key UNIQUE (object_key), + CONSTRAINT attachment_variants_key_format CHECK (object_key ~ '^a/[0-9a-f-]{36}/[0-9a-f]{32}/(thumbnail|crop|optimized)$'), + CONSTRAINT attachment_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')), + CONSTRAINT attachment_variants_type CHECK (content_type IN ('image/jpeg', 'image/webp')), + CONSTRAINT attachment_variants_size CHECK (size_bytes >= 1 AND width >= 1 AND height >= 1), + CONSTRAINT attachment_variants_sha256 CHECK (octet_length(sha256) = 32) +); + +-- Transactional outbox: written in the SAME transaction as the job (upload, retry, replay, +-- reprocess, lease expiry). The relay publishes due rows and marks them; a crash after the +-- publish but before the mark publishes again (a duplicate the worker ignores). +CREATE TABLE outbox ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + job_id uuid NOT NULL REFERENCES jobs (id), + attempt integer NOT NULL, -- the attempt this delivery is meant for + available_at timestamptz NOT NULL DEFAULT clock_timestamp(), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + published_at timestamptz, + publish_failures integer NOT NULL DEFAULT 0, + CONSTRAINT outbox_attempt CHECK (attempt >= 1) +); +CREATE INDEX outbox_due ON outbox (available_at, id) WHERE published_at IS NULL; +CREATE INDEX outbox_job ON outbox (job_id); +CREATE INDEX outbox_published ON outbox (published_at) WHERE published_at IS NOT NULL; -- purge + +-- Audit of every transition (no secrets, no file names): replay/reprocess requests with the +-- operator and reason, claims, retries with their delay, lease expiries, results. +CREATE TABLE job_events ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + job_id uuid NOT NULL REFERENCES jobs (id), + at timestamptz NOT NULL DEFAULT clock_timestamp(), + event text NOT NULL, + attempt integer, + actor text NOT NULL, + error_code text, + detail jsonb NOT NULL DEFAULT '{}' +); +CREATE INDEX job_events_job ON job_events (job_id, id); + +-- Failed registry for the operator (jobctl list-failed). +CREATE VIEW failed_jobs AS +SELECT j.id AS job_id, j.attachment_id, j.pipeline_version, j.kind, j.attempt, j.max_attempts, j.error_code, + j.finished_at, a.status AS attachment_status, a.staging_state +FROM jobs j JOIN attachments a ON a.id = j.attachment_id +WHERE j.state = 'failed'; + +-- Lab 4 'ready' rows (now queued): a job for pipeline 1 from their published original. +WITH queued AS ( + SELECT a.id, gen_random_uuid() AS job_id FROM attachments a WHERE a.status = 'queued' +), created AS ( + INSERT INTO jobs (id, attachment_id, pipeline_version, kind, max_attempts) + SELECT q.job_id, q.id, 1, 'migrate', 5 FROM queued q RETURNING id +) +INSERT INTO outbox (job_id, attempt) SELECT c.id, 1 FROM created c; + +-- post_message_v3 = post_message_v2 (0004) with the lab 5 attachment states: queued, processing +-- and ready attachments of this chat may be attached; failed (or quarantined) -> 409; pending, +-- foreign or unknown -> 404. Everything else (key claim, chat clock, one transaction) unchanged. +CREATE FUNCTION post_message_v3(p_user uuid, p_chat uuid, p_key text, p_hash bytea, p_message uuid, + p_text bytea, p_ttl_seconds integer, p_attachments uuid[]) +RETURNS TABLE (o_status text, o_id uuid, o_text bytea, o_created_at timestamptz, o_attachments uuid[]) +LANGUAGE plpgsql VOLATILE AS $$ +DECLARE + v_created timestamptz; + v_found integer; + v_usable integer; + v_check text := 'ok'; +BEGIN + PERFORM 1 FROM chat_members m WHERE m.chat_id = p_chat AND m.user_id = p_user; + IF NOT FOUND THEN + RETURN QUERY SELECT 'not_found'::text, NULL::uuid, NULL::bytea, NULL::timestamptz, NULL::uuid[]; + RETURN; + END IF; + + IF cardinality(p_attachments) > 0 THEN + -- FOR SHARE: a concurrent transition to failed/quarantine waits until this message commits. + SELECT count(*), count(*) FILTER (WHERE a.lost_at IS NULL AND a.status <> 'failed') INTO v_found, v_usable + FROM (SELECT a.lost_at, a.status FROM attachments a + WHERE a.id = ANY (p_attachments) AND a.chat_id = p_chat AND a.status <> 'pending' + FOR SHARE) a; + IF v_found <> cardinality(p_attachments) THEN + v_check := 'attachment_not_found'; + ELSIF v_usable <> v_found THEN + v_check := 'attachment_conflict'; + END IF; + END IF; + + IF v_check = 'ok' THEN + INSERT INTO idempotency_keys AS k (user_id, chat_id, key, request_hash, message_id) + VALUES (p_user, p_chat, p_key, p_hash, p_message) + ON CONFLICT (user_id, chat_id, key) DO UPDATE + SET request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp() + WHERE k.created_at < clock_timestamp() - make_interval(secs => p_ttl_seconds); + IF FOUND THEN + UPDATE chats c SET last_message_at = greatest(clock_timestamp(), c.last_message_at + interval '1 microsecond') + WHERE c.id = p_chat RETURNING c.last_message_at INTO v_created; + INSERT INTO messages (id, chat_id, sender_id, text, created_at, attachment_ids) + VALUES (p_message, p_chat, p_user, p_text, v_created, p_attachments); + INSERT INTO message_attachments (message_id, position, attachment_id) + SELECT p_message, (a.ord - 1)::smallint, a.id + FROM unnest(p_attachments) WITH ORDINALITY AS a(id, ord); + RETURN QUERY SELECT 'created'::text, p_message, p_text, v_created, p_attachments; + RETURN; + END IF; + END IF; + + RETURN QUERY + SELECT CASE WHEN k.request_hash = p_hash THEN 'replayed' ELSE 'conflict' END, m.id, m.text, m.created_at, + m.attachment_ids + FROM idempotency_keys k JOIN messages m ON m.id = k.message_id + WHERE k.user_id = p_user AND k.chat_id = p_chat AND k.key = p_key; + IF NOT FOUND THEN + RETURN QUERY SELECT CASE WHEN v_check = 'ok' THEN 'retry' ELSE v_check END, + NULL::uuid, NULL::bytea, NULL::timestamptz, NULL::uuid[]; + END IF; +END +$$; diff --git a/migrations/0006_observability.sql b/migrations/0006_observability.sql new file mode 100644 index 0000000..dc41bdf --- /dev/null +++ b/migrations/0006_observability.sql @@ -0,0 +1,19 @@ +-- Lab 6: trace context of a job and an index for the queue gauges. +-- +-- jobs.traceparent / jobs.tracestate: W3C trace context of the request that created the job +-- (the upload, taken inside its HTTP server span). The relay publishes every outbox row of the +-- job (first attempt, retries, lease expiry, republish) as a PRODUCER span whose parent is this +-- context, and puts the producer's own context into the message (`traceparent` of +-- contracts/jobs.schema.json). One upload is therefore ONE trace: HTTP POST -> db enqueue -> +-- publish (relay) -> process (worker) -> S3/DB ... -> publish of the retry -> process ... +-- A job created by the operator CLI (jobctl replay/reprocess) has no context: NULL, and the relay +-- starts a new trace for it. The value is a 55-character technical id, never user data. +ALTER TABLE jobs + ADD COLUMN traceparent text COLLATE "C", + ADD COLUMN tracestate text COLLATE "C", + ADD CONSTRAINT jobs_traceparent CHECK (traceparent IS NULL OR traceparent ~ '^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$'), + ADD CONSTRAINT jobs_tracestate CHECK (tracestate IS NULL OR length(tracestate) <= 512); + +-- Queue gauges of the relay (messenger.queue.depth / messenger.queue.oldest_age, every 5 s): +-- unfinished jobs by age. Partial index = only the few active rows, not the whole history. +CREATE INDEX jobs_active_age ON jobs (created_at) WHERE state IN ('queued', 'processing'); diff --git a/requirements-test.txt b/requirements-test.txt new file mode 100644 index 0000000..fea533d --- /dev/null +++ b/requirements-test.txt @@ -0,0 +1,6 @@ +# Student tests (in-process, via Starlette TestClient). Runtime deps come from requirements.txt. +pytest==9.1.1 +httpx2==2.13.1 +jsonschema==4.26.0 +# Lab 4 tests: generate PNG/JPEG fixtures (valid, corrupt, oversized) on the fly. +pillow==12.3.0 diff --git a/requirements.in b/requirements.in new file mode 100644 index 0000000..f6015f2 --- /dev/null +++ b/requirements.in @@ -0,0 +1,30 @@ +# Direct runtime dependencies. The pinned lock with hashes is requirements.txt: +# docker run --rm -v "$PWD:/w" -w /w python:3.13.16-slim-bookworm \ +# sh -c "pip install -q pip-tools==7.6.1 && pip-compile --generate-hashes --strip-extras --no-emit-index-url -o requirements.txt requirements.in" +starlette==1.7.0 +uvicorn==0.54.0 +# Fast C parser/event loop used by uvicorn in the container (Linux only). +httptools==0.9.0 +uvloop==0.23.0 ; sys_platform != "win32" +# PostgreSQL driver (libpq bundled in the binary wheel) and its async connection pool. +psycopg==3.3.6 +psycopg-binary==3.3.6 +psycopg-pool==3.3.3 +# Valkey client (Valkey speaks the Redis protocol). +redis==8.1.0 +# Argon2id password KDF. +argon2-cffi==25.1.0 +# Lab 4: S3 client (async botocore over aiohttp; requests are cancellable, unlike libpq cancel). +aiobotocore==3.9.2 +# Lab 5: AMQP 0-9-1 client for RabbitMQ (publisher confirms, consumer acks, prefetch); last 9.x line. +aio-pika==9.6.2 +# Lab 5: image variants in the worker only (thumbnail/crop JPEG, WebP). Same version as the tests. +pillow==12.3.0 +# Uploads are still checked without Pillow: PNG by src/messenger/images.py, JPEG by libjpeg-turbo +# `djpeg -strict` (Debian package libjpeg-turbo-progs, see Dockerfile). +# Lab 6: OpenTelemetry SDK (traces, metrics, logs) and the OTLP/HTTP (protobuf) exporter to the +# Collector. Instrumentation is written by hand in telemetry.py/app.py/db.py/storage.py/relay/worker +# (no auto-instrumentation packages): span names, attributes and buckets are under our control. +opentelemetry-api==1.45.2 +opentelemetry-sdk==1.45.2 +opentelemetry-exporter-otlp-proto-http==1.45.2 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..722cd4d --- /dev/null +++ b/requirements.txt @@ -0,0 +1,1709 @@ +# +# This file is autogenerated by pip-compile with Python 3.13 +# by the following command: +# +# pip-compile --generate-hashes --no-emit-index-url --no-index --output-file=requirements.txt --strip-extras requirements.in +# +aio-pika==9.6.2 \ + --hash=sha256:2a5478af920d169795071c9c09c7542cd8cdece60438cf7804533dcbcce93b7f \ + --hash=sha256:c49e9246080dc8ffa1bb0e4aca407bf3d8ad78c3ee3a93df88b68fe65d7a49b9 + # via -r requirements.in +aiobotocore==3.9.2 \ + --hash=sha256:363b4892423b272eb84afbb58000da0be6ccd0cf8a68b98438c957d05b841efc \ + --hash=sha256:8e32238c5bd77717ab1ac90077ff51ab141d025528115ccc7cc9b50b2d176e5f + # via -r requirements.in +aiohappyeyeballs==2.7.1 \ + --hash=sha256:065665c041c42a5938ed220bdcd7230f22527fbec085e1853d2402c8a3615d9d \ + --hash=sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472 + # via aiohttp +aiohttp==3.14.5 \ + --hash=sha256:0133c3c3b54a0bf1e71fa5c1ad95c93f07fd54e24ef1fe182f5122e1573d2bf1 \ + --hash=sha256:038c2c7e8caa26b6c8423779b5eaf1893904048a512c19b32fe841ffa5592b50 \ + --hash=sha256:0684952aeae1f5dbfe02d46039338513b94009baecd15d8e4098a357c4c4a2a6 \ + --hash=sha256:0790ec66fa4013e83c53b9025a45d454723da1a2fce28b3208c9b32d08af162f \ + --hash=sha256:083673c7a94c3ea035caaa5ca04288bdb44887abfe1f5ba23294e6a4b03efd2d \ + --hash=sha256:09e0eb18c7e0c8777e2f9149de63799195b9b3ca1b5c81ba6f32f2c6b8628210 \ + --hash=sha256:09ec102b4b8c9a920275733bbc11fdbb615efe6f9231a06007c0218d336fb77a \ + --hash=sha256:0a8ea271867e360ac985ae607f4a23ad9a38414b9aca1d49ec98839ae660e49f \ + --hash=sha256:0e6f16f5e49c4b8267988c05ab07760d7064cea57d077c3d068d04b0fbb992cb \ + --hash=sha256:1061b364556e8172e8d46b0b183adeeb73e8c42d30ebc745591e1bd89acad52e \ + --hash=sha256:1220353657ad49493551f089ce02f1a348fd57ffd585bfec77f2f3c4fe3a7346 \ + --hash=sha256:137351bf20bbed9a65e839f4a4452ac377389bdb2f2857d2acffef38f5e9f2d1 \ + --hash=sha256:149fb56caf7acb67073126f675d0958d9c4b3125fcd3f6d4877df98aa8a97ce9 \ + --hash=sha256:14f04769cfefe4734016a856a83af36133cd17779cef9ae817f812b8ba9d6d51 \ + --hash=sha256:15a310d3c71398e3d7bfc93a1a73fbe664315cd9e9016b8efc1cff85eeab7155 \ + --hash=sha256:1612fa5857b37bf32e5c1eaeefb96e3b01e9c70679eec81f0934e8a600080863 \ + --hash=sha256:16c8abd5bca220a47efe667d26f8460124c81810787e79ee87b242677563d9dd \ + --hash=sha256:19e2ba471507c34f8252402ab50f5ab512398b9ea8c8f1cb26beb3f75793ba30 \ + --hash=sha256:1aead151c3abbac6b32942e452020cb66d7efc099d253cc6c20f748e926c858b \ + --hash=sha256:1b438b73c38111818d0c9d6a5c2bfed8584c8e503a49ef085d70e874ec846738 \ + --hash=sha256:1b5416552740edf07234cc9437d0706f2acb67b93c198670b1a68e1b2b587dec \ + --hash=sha256:1d2d981b53dd09a319e3570ef8cc3bbc3ef86f5a7abef0f6b2bff3867db3a9e7 \ + --hash=sha256:1eb8167961ec4dfcc8cb9dd50bd0ee72519f7ef496be95203e49e27b01618382 \ + --hash=sha256:1ffa3a523a36d8628f98c06492ae16a31a23d14c0b4ec721757b477319f656d6 \ + --hash=sha256:20064a177a070d789ee64a50b01a9161d3468e989baacfc6c714aa685c4b332f \ + --hash=sha256:20726f9782d5c2744c1c66255842d1d163bb3edcf768b8de25216bf47f7b6ccf \ + --hash=sha256:20f085697d7e911f1f73c43ed03fafbed1e7121797e2eb5428efa80398060584 \ + --hash=sha256:225c579c23b68b343cccea27a7e06e3bd8ec23a09c30b427eb3f1e4ca6239b20 \ + --hash=sha256:24409db442e2fb6e766bc7f3943851a8381dec3098140e43bb2e843b79e31b12 \ + --hash=sha256:248d779ad720b49d4fb355720e60c9e5f444f95887bc16974fea48fc56c41789 \ + --hash=sha256:2528cb4c6b92008c76ac9ac6298624069bb2db91ff4929905512d1d84485f658 \ + --hash=sha256:276a4fc00b1d9ae492b802763a789c5b86328b989c5ea169f2faa447d6a11c7c \ + --hash=sha256:27c2322e03f66101acb09869ce1cf1efc04994ee95e1735b69827bf8c8b9d781 \ + --hash=sha256:293d3ae7c6a0ed176a42e59a1b5fde825ead65c835360f734148e96729f928d2 \ + --hash=sha256:2cc38a4f2b516bef1714e690df87a0e043faf1a7693c82d860091684453d5111 \ + --hash=sha256:3093b72c215bda16ce961a6d073f6e71d46e022962a9d5d457c5d4d421c78b57 \ + --hash=sha256:32e8fa6644e541fcd7e02430588c7fc93b602c1778ea0bc345505db76b61cfb4 \ + --hash=sha256:330900acd0dc4cb8b27f9c127fbaad770964845338493e7906ae3822e82dbf8d \ + --hash=sha256:33f706574e32c6e694f352a856e05caf18f7f2c871b3e87b41c55ea452b409ab \ + --hash=sha256:3ae800a20947e2c2e53088047d021e6bf7d51560cc49f6a0737a1f79d2e3a13c \ + --hash=sha256:3be7dd397d64ca3e1869626fa9318aaebb54b7bf93bc72d7a205448d83e4f748 \ + --hash=sha256:3e0eb43bed3c6801a6cee315195377789e90b2a72c2277a475b578535312488d \ + --hash=sha256:3e51a27980c3788e6e6b3325d694fdd4898087fa8a86b2763af77b39353da41e \ + --hash=sha256:3edbece0379b8b4aaa67619b8aa2399bb66fce372cd5911098a434ea77220aa0 \ + --hash=sha256:3f2dcc00191fd563e9075181a14ec31d7dd63223ced7582cc70a15a499de0c79 \ + --hash=sha256:42b5e616946dbaf505e2bff18c9af2cd4ef9e7ef300ee58a6e951a5b7cf147ae \ + --hash=sha256:42f320d4a5b00b9af0bddcfec5407dc6f2d9816f006b2f79ebbaa31f16895df3 \ + --hash=sha256:43351bdb5e4c3cb7d1772368e988534e869a74db7778079a83782c11c69535c7 \ + --hash=sha256:43e1b7994a8b038125f722bff07492ef501110722c2727c408995d9fb864c421 \ + --hash=sha256:4887d130a7bbfed3a85493bb5a25e5b5b558d40c1d986dd16970d2bb26d63793 \ + --hash=sha256:4f07fe3ac408d8b3f768be471dc3f56d43843c47d97c66120534467a15ead197 \ + --hash=sha256:50343c1757b4b6f6708eeaf24534b32f19dfb99fb1b762c00420867a62fc81e0 \ + --hash=sha256:50983e3be33d8c0942ab88cec3905b10602f64c469b20153c48c5d4e558dd016 \ + --hash=sha256:50a195903119008fe9cc68710535eb37f556ffffd6a7759afe70a2c145587045 \ + --hash=sha256:5558a7f5a05af9ecf744af91e5baefc436f93c9333e656c27ec253f9a6bbe178 \ + --hash=sha256:56572c42e3ecd636de8d2c3dd54cf5fc939cb5c32eb56297f176a0d366fac622 \ + --hash=sha256:56d9828f204331a5ca8850fcfe2bcce95a149f1f223f60cc7216e5524978e480 \ + --hash=sha256:579f97d5120f2971876d2ddca2968135f6944d00c44c3a6590ad7d86ca9b403f \ + --hash=sha256:5af42135fdfebdadbc2bcd9c0842a48ccf0d62794c36a260b21dc4b94d1e0119 \ + --hash=sha256:5ba14a839fbe87cf7c12a6b5661c05f324a296eb8363141edb3944ba63d4c9d3 \ + --hash=sha256:5c76f1802bab718a68ac3cce447160605c734551f95c67ae90fa1132b215cb29 \ + --hash=sha256:5e8f97c0488ffda3082766ac0f2c8150a9a58c4d05788330e479cfd449b37939 \ + --hash=sha256:5f3e96071686755d9cd3600c3880183eb94b012178e92746d68101800f0ed8a3 \ + --hash=sha256:5fb6a6e919bfb703227bc1ce6579281b84b1a2ba57deb9794dfdbec7dcd1e40c \ + --hash=sha256:602c1e9b718a3275c580149f947e7fac65044c0a20e599553fb12e9700da9eca \ + --hash=sha256:657291433bf4dd3142f3abac495764cd47d0c7c92087751e6666c6447e65fcef \ + --hash=sha256:6774814fd5c338e72ee0da5cbb9432816df450e69c019f72b5d29bdec2a1792d \ + --hash=sha256:6da32b5ff3fd78d244e37300463434c7145162bfd2b6e9e915ab164da37f7343 \ + --hash=sha256:6e1d8637cf73eebc92eba2e11d4cfff98a3b562f2505bd75bba766d908926e8d \ + --hash=sha256:6e4251c0ba4624a68a2c11471a1ac54c3306876c21f0ae86de085cc9241c8905 \ + --hash=sha256:6f275c11d1aa6d4c458e05a68be084efe3c55a113d99e3f46a318098e52948fc \ + --hash=sha256:6f967dde489ca6a8c02d093ab245d2cbf50ccb5c36adf0188b17b0ca39d24b67 \ + --hash=sha256:6fdcd6af7e2e51d1ba1b4bea16e97b074bcb7b5dd0246a9d8201341bb28085a0 \ + --hash=sha256:70cb4008ac2ed1e0ca9e824deb4b53d3aa0d939109698ebf1e723a84337bd794 \ + --hash=sha256:7457580535e019e1247ea35d6a02bf081ad30c26d0cbc210c93f6c3ab67a0835 \ + --hash=sha256:74b0a9c8270f9b0a11410e124ff8d4f18bfc1f1837440ec84da5ae7b50927b5d \ + --hash=sha256:74efb69332b85675b1eabd760a8cfc2e2cf42c60607c66f88014c1bdfb40942d \ + --hash=sha256:755933b107ea7a6a9ac916f635a70595a5b1a32fac10a8ff0b9f2ab88555550c \ + --hash=sha256:7779cd97e61ebe583ec2f1c5616cdd038aa08a4453b1848c67842176d054948e \ + --hash=sha256:788ecaa9c10533b786ce5ba70c4f2df78ad41819fd00a6c99d92b66f9a32e1da \ + --hash=sha256:7bd8ac754ebd6733a3e2a0dd1674c4d8ab086196803fd8dcd776f07b4e2607d9 \ + --hash=sha256:81c2b3dfd56c62bee6108e4852d5970b4cf9086390b6983f52b666e878c1f115 \ + --hash=sha256:823c910f046f23f4c713b8d99a2242dc65f591cb45ee86418fa11762a3c2963c \ + --hash=sha256:82c7583cd3dfdc7dcc927835b4f6c7faae7ecc1ba3ca5879321621ae2e6f8e84 \ + --hash=sha256:8966ecac808dd5f473c9c4cefd10cd3ffda71c18a4d3493b7c7d2ae1803bf2cc \ + --hash=sha256:8df7d481654ac96fe1ba9a02a9f67770fdd367823e0d5ef01b922725c4bd2cfa \ + --hash=sha256:8e317e0fb6b16212c881d2205a7d87414c29acd69320b3aa6dce9d9c7b86fe4f \ + --hash=sha256:932ce7e694bbc29b2bf6f64f2343c27d148d4997c771d01bdade4639b6749ff4 \ + --hash=sha256:939042d5cda21d41a6f512e7cc8b8e33a2aebff863352251da495fbd91b673b5 \ + --hash=sha256:94684b879ac1d71e4238850c99b62dc1b28d9086b156a2555f082010b85a865c \ + --hash=sha256:96a2e584f0b9ed8f1fa33211397dcf67bb7069866402cb405d191c2f0defb9a3 \ + --hash=sha256:9ad7e6aa38c20da1be697874349c4c273c8a03b7887169665081706398d0439a \ + --hash=sha256:9b42db919715e91eb76acf3bc492a9a7ccd8bd9adc6745c1412b689735269f14 \ + --hash=sha256:9bab2045550c4fe0f7baf89574db1b455c195750702ba96fef1f16972b146617 \ + --hash=sha256:9bf1d5dcc15204d9ec8b8ea4c18fd66e6b80e5de1f4ecbafb3a2f2740f8039d4 \ + --hash=sha256:9c061aa954daaf57d2a4b8374f9fca621ef0e1b603584431c220c22458c59b6d \ + --hash=sha256:9c428eb2bd8817588d16a0ab898aa4eb5d141f896aa2b394cc79a4cf61d9a8e2 \ + --hash=sha256:9cc882cf8619109583c906b4d4a85d6a111a98afa34b7a450d1e08118d016820 \ + --hash=sha256:9ce66feae6ac65327379460380549bf1b8df8e17c4e25df2a2bcf168272e3bed \ + --hash=sha256:a23fe35d776bc03cb495938b9594450d047e3bc08c5255315a82323e9cb7d2dd \ + --hash=sha256:a2c473a355f9239efcb72c92d5abfd8fcdb0cc78c8e9af607e72ca12dbb36593 \ + --hash=sha256:a63afd1f757de949028387e65a7127b61ad0f775432dbb0e62816ae619fe69ac \ + --hash=sha256:a6d02b4c38de03d9c7617813433e6a0fb6b522797974177d69d9dad431900833 \ + --hash=sha256:a7d470cf7b206e6359fc77b1b860632fde400d5a2ed59cd0181b93a686bc81ee \ + --hash=sha256:a95529a92a446db351675f4aab518feaf5e99842f63f5dd17160c2b74f382db3 \ + --hash=sha256:a9918e58faf62ba2c7147927d06057aec78f42475aff5048047ec47e7265a600 \ + --hash=sha256:a9d3983bd6ab7aa1cfd573544ae98df9b6cb6912a5185a198263e024a636861d \ + --hash=sha256:ab52d8f1fc1b64821c1fbad64a647ed6203627004059a6d1ed4f0858a1499703 \ + --hash=sha256:abfda5cb094a829f7bc25216a32f7db2e85cc65bd59910f8e7b40b3d9b224764 \ + --hash=sha256:adbeee7d6fd4cf5fe0aece2fb3edc4243615d3180430ba8149d01a90670cac99 \ + --hash=sha256:ae53924aa853a7a2ca20ed4142c7c6b56338e4d4cd999e2980075b9efc2e257a \ + --hash=sha256:b032a0023eb41d768ce77d83210ab2a3c389bc0b09313273c7e1eca48c10a755 \ + --hash=sha256:b1b8ece1e71132d2afba4dbc0c3d62c766e25165990b25db1196c04969eb3d84 \ + --hash=sha256:b2966998927d7bed9db12c0a4647b0c7b179755878fc9c357fe1ffd3e3b0c1a5 \ + --hash=sha256:b3cc509327c7b27f6f4727a8830f4004f6df7766e179f2f4b8e54e65c0bec5d3 \ + --hash=sha256:b7806e804889231b0e06469fd4a5c06313d1c0a3377322b6d9237fa5e0fe4167 \ + --hash=sha256:bea559ad70218d230663e4210875735076a9bfea5994cef34a55a25faeaf2544 \ + --hash=sha256:bf163cc701f3d4ac43ba7d97771bf5fd955220ef5500ef3ee847bc0ecfbf4ec1 \ + --hash=sha256:c147451b4a58e7050f7f7394e6c467867c84161560001f9ad4fb2d1446743946 \ + --hash=sha256:c172db893e516e1358e65a95ee20b7ce7173963eefe318b6ab2a2220688b999e \ + --hash=sha256:c1d60eafd9c7e8e74abd03a5b00df44e7febfe6d9b89b559c0a6551eef0699d4 \ + --hash=sha256:c2c30484dd1417ef98b51021ffa2cc0d7f3c78918adaaaab7e70817335ab3e02 \ + --hash=sha256:c32e26310cc10e547f53cd13d39a369034f69dcb7d749d5cb0e5f67bc196b6ba \ + --hash=sha256:c5ed596aedb9c42afd3fe0aae3117725378ac73d2cc5ddc735056fbdb96c5d02 \ + --hash=sha256:c8859a013ae0de1074660992139a1a440df3e6b219b86cf0d3f11c2692bb4fe3 \ + --hash=sha256:c8c4478bef6d57fcfda15dae461ea3c9f06aa7b257c58df3f2300174ccbb185a \ + --hash=sha256:cb11a971a3aea10f9b8373be628f1df932964fc6c6b174516d318a48c3ac4412 \ + --hash=sha256:cb131d775a1573c1aee66656bd78b023577bbdb6cb8349a07773bd4f73e68a6e \ + --hash=sha256:cd88b01f3d37b7a2a34f91d98f14720206f1ea3d540843fab2d649dd5fb91fec \ + --hash=sha256:d05e94cdfe0d15d0206f970722d2554780ce562787b21b218b275447f8751319 \ + --hash=sha256:d079c0a0135c36e7beb6f1c88087c8f108dc5891cdd0b5eafa778421bda70ed2 \ + --hash=sha256:d3112585250b199296c26ca6e0131640b6a8d01bab8b232d2eb3763ed469de11 \ + --hash=sha256:d418ce2af40c6bb685b3f663e9e8de27cb0a22431d8e88a167348d7f01878073 \ + --hash=sha256:d51db97c96384fbfcaf8f4c65922183a68b94f891c3c10c862ef5f6df2adbb1f \ + --hash=sha256:d94e44be379e569758fee8a9a58431cfc3c2598c708b92b1cfe96c66b4c94aef \ + --hash=sha256:dab9ac5a67c8d1f070c00fa8fccb7cbd1b8dcc1a8d6b42f37540df9b3d4cc603 \ + --hash=sha256:dbf53ae2601b7fd5a93c3944deea3a78d40f495226d582c35ef7a433425ce2b2 \ + --hash=sha256:dca3fa8d8a0a26679862eccb0b1a9151b2b9f1cd2c212e7a6335778faaff5833 \ + --hash=sha256:df37b620684e19b5e25724412518ccafc3b1a49cdac706fdbd2f983fad943450 \ + --hash=sha256:e1cc2bfaee8c214f06080a7c7d5772419b8a1108e8e5349236189811823fb02a \ + --hash=sha256:e29347c142cf6e99e0dff5e2995ead1d50fa3b51bf37a7c726a7ccfe5419745a \ + --hash=sha256:e4f5cf4dc72a71c4cfa9751b4950be22f733626670230d46e7d606592aa22d59 \ + --hash=sha256:e724a7b6091f0b1ac064f9d1b15ff9ec52e6033a86cdae649e5f086e32a3c0db \ + --hash=sha256:e87046c8ff77a8decdb6a41d8ab25824b47531b2da933aeab0c1e21c7acff329 \ + --hash=sha256:e95c8def4b81c5d68d5cf1f54c07acd7c0d2577af244e5b6da802120825737c6 \ + --hash=sha256:eb324e2009fb54db30a071dad7caf6998ee2879c4704007efb244514dad1fec1 \ + --hash=sha256:ef60869969180ec2464f1349aff07138ae35ca2200f0946cb3552e49e8f301a8 \ + --hash=sha256:ef692a24087a699c0a4a26af45e746e0c1eae2116f6d8a5ff91d8aae2b867b45 \ + --hash=sha256:efc21a454892828368b11c2c780de0ff8bc991f73f6b99c6b66e56205470929b \ + --hash=sha256:f001b571ead90ca1770f1e616db255351a1703317f20374c361ef22f12c06d09 \ + --hash=sha256:f2a7966bda23dd85051f1661ce0ace38d6890e05ec6c357ecae9d2479cba377e \ + --hash=sha256:f2ebb54b3f932210503072f09974b4fb574d823e497a944adfdcd140a6a00255 \ + --hash=sha256:f2ed8b64dc0c651c0f5a9c926777719770021251b8f336d97c4b80b660836ce1 \ + --hash=sha256:f375db73a39f5cf83696d500e21a67f418dc9a988955756f254be8f03b7b3651 \ + --hash=sha256:f59c7673465908cbe506117176156c127f29f917677afceada34957179221d91 \ + --hash=sha256:f8d40ce41991e9d56fab4f5dc4a51fe59bc3b5c77c27f4b148963064d00232e8 \ + --hash=sha256:f9033b43f511f27547c557dcaba0177649e10a3725336ccd2cce0fdc1dc4850d \ + --hash=sha256:fba47bc2c3d7303c3d027c6cf4d07626c37b1314ac81f5820c31032e0ca1f677 \ + --hash=sha256:fbdc5ec49f9ca3cd24955cf3520b10a4d4c901ba2572094c84274e9e7eb30534 \ + --hash=sha256:fce9523df31cea6284f3e2c479876750d7687cf671d7b25d32b19effc0e86441 \ + --hash=sha256:ff75a7537413a86e7cafe98e0e1d6e3dc4b15c6349896e7d5c6b881bfdb6d550 + # via aiobotocore +aioitertools==0.13.0 \ + --hash=sha256:0be0292b856f08dfac90e31f4739432f4cb6d7520ab9eb73e143f4f2fa5259be \ + --hash=sha256:620bd241acc0bbb9ec819f1ab215866871b4bbd1f73836a55f799200ee86950c + # via aiobotocore +aiormq==6.9.4 \ + --hash=sha256:0e7c01b662804e1cc7ace9a17794e8c1192a27fc2afa96162362a6e61ae8e8ef \ + --hash=sha256:726a8586695e863fba68cf88842065ab12348c9438dcebdfc9d0bddaf6083277 + # via aio-pika +aiosignal==1.4.0 \ + --hash=sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e \ + --hash=sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7 + # via aiohttp +anyio==4.15.1 \ + --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101 \ + --hash=sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94 + # via starlette +argon2-cffi==25.1.0 \ + --hash=sha256:694ae5cc8a42f4c4e2bf2ca0e64e51e23a040c6a517a85074683d3959e1346c1 \ + --hash=sha256:fdc8b074db390fccb6eb4a3604ae7231f219aa669a2652e0f20e16ba513d5741 + # via -r requirements.in +argon2-cffi-bindings==26.1.0 \ + --hash=sha256:061a6919145bbf282ebf1f9c59d3135d4833c25313c8595c0d68cf7712ddfce2 \ + --hash=sha256:0cc40f7b4050bb93eb67de95d2d759322fc7ce4930b9d645581ecf4913ec651e \ + --hash=sha256:151dfaad9de753f4af2a7854e707e4784f2acc434340ade64239c5b104b2d605 \ + --hash=sha256:19423e5d7ac1cc354baab59eaabf18db2ec04ef6593b5abe5a34f323c4a8f87a \ + --hash=sha256:19b562b1de4b9052ef1214a2821c44b6e6f22945daa102c32ae4eff929d8b6d8 \ + --hash=sha256:1a0a29ed86960e44eaace7e081bdfab4f08b012fd96ec8edba71e2ad020939e4 \ + --hash=sha256:1af817e84578ef8b7295ad17de0f9896e4c8520dbf2233c7aa5aa3d487256fc4 \ + --hash=sha256:1b0bcac4d490a237e18cf91f57352920c29f77f2fa39efd0813fb81298bf17ba \ + --hash=sha256:1d98e33bd8bd67d7206c124e200bf2229c4cfa8c9c19f7b44a897f0fc71837eb \ + --hash=sha256:21ca0396fe5ec995dd54431c32698189666f9224810acfa752e50d2bd94d9df2 \ + --hash=sha256:224865cbbcb7a2bd1356741dff12b0134df726b6d44bb7b500df8e303cbd9e81 \ + --hash=sha256:242bb0cda2ae3650764fc194593d9ea45fc9e72729acd89778c7cfe184cec2a5 \ + --hash=sha256:27f1821903e2ceadcb88ec2b45ef190897b7682449c772f4d9b53e42c520cf29 \ + --hash=sha256:28524438cd3e723f25412f63d4fd516ff5bae9ae5aa56acbe2a1404398a0cf31 \ + --hash=sha256:2b741888c93147444fdfc851abd81cc207f37f7f7da42062a00deb3888e57da8 \ + --hash=sha256:2c36ff87b5dfaa477d0bd51e9d7f6abdae7c8955d2983c97419085d842154b3e \ + --hash=sha256:34b7d9c24a4165a2c61cc8ae11d44d48c9ce2830fb536cb7914e11fdd9962728 \ + --hash=sha256:49d525938467d52c923a890153c99087c9d5a937d1f6b585dbdba34ec82e397a \ + --hash=sha256:4f84cdd868978d7b7350a566c254042d44216d9e37f241f3a6d3b1dfebeede35 \ + --hash=sha256:62ff20cd130c956c7c9144d5fe35228f98b51c579b2439e988b27ef93e16c02a \ + --hash=sha256:63505c71542a44b68b1e38060450fb006404170da375feb31af153e7f9c6205d \ + --hash=sha256:6376d4b3aca039375ca8bf92f770da0ec424a1ce3a37077a8d3c557411aa56ca \ + --hash=sha256:6a4e68eed961a8de6928d1c17ff3dc2a547e0e923c17f8f1cd79fb7bc9502f98 \ + --hash=sha256:6ab674f668d5962a3a4136ae0812519b0f1586874263723a32181d60d64137e1 \ + --hash=sha256:7014ab7e6f5d8511af92544667a0346ea6dfc314ea9a7cad1dba9fdb5c9a6e33 \ + --hash=sha256:76ae29acace5d33355344612844d588e19deaaba4639d8bb01601e4b1418ef36 \ + --hash=sha256:78de2d65e0b9ea7ce9d1b1c3e87297b2d7305a02c266ee2a2d6910daddd7ee69 \ + --hash=sha256:9bacedc04b0402837586a17f0919e3dfdd95291f441f1f56bd80ec274c2840a1 \ + --hash=sha256:a86c069c91a747a2c4e5c51473590aeb48172fff9b2130d23729a42d98665ecb \ + --hash=sha256:ac82fc756a446b6ccd7139ce70efa9d8bbe541e7ad579a12dcb52764b7175c5f \ + --hash=sha256:af11ac37a7c53dc16cb7950a6190851b0870fe218b6c60c0bb7ac355234e3083 \ + --hash=sha256:b70225b5fd1e0d2ef4f7fd30d24658454535f0924dff0caca5dc08efbbbadfbb \ + --hash=sha256:c49e853a3bef9dd10329f31f702e7fa9b5c58229ff9c2ff6d069efaf09177c08 \ + --hash=sha256:ccaf0a46cbb380f1fd102a874e32aa629fd3cb0c0e94f4943fa1f6d5edc5dac6 \ + --hash=sha256:d157ddfab1e8b21f2f1dedda9c09645d98b5ed0b667b0626be600a345d426440 \ + --hash=sha256:d88e5f7e60f28ae0b0cc6b2f16c43e87cd642a196a86f85e0d8bb6fe016fc16d \ + --hash=sha256:db0fcd827ca61622a01b220aadfbece01939acf53888f2cb98cd93e9b1e2c97e \ + --hash=sha256:df612391feca41c44d20118f3b88d1b86419465cd1f5496859f715ca60ec2210 \ + --hash=sha256:f0c3103fcff20183e593459cfea6e012281c0e76ae3ed8b5565ad1b92eac3990 \ + --hash=sha256:f9c4420a7a864fe1b86ce35befc95b8e39fb852493b81cf798671ddc265de638 \ + --hash=sha256:ffff613aaa9ce6236766e2fc6dc560bb5abde7a2e2416e3db1f9ae395a2b4dd4 + # via argon2-cffi +attrs==26.1.0 \ + --hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 \ + --hash=sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32 + # via aiohttp +botocore==1.43.106 \ + --hash=sha256:006870b3b4e40547232ad12c3bb4faec91bbbe0659aafaa3b7fa48a112c4ee97 \ + --hash=sha256:c1fb8818f9957cb5037f73db34ac1a12ba43562e31d6e7f9cb7e5fc64e1dba78 + # via aiobotocore +certifi==2026.10.23 \ + --hash=sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd \ + --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1 + # via requests +cffi==2.1.1 \ + --hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \ + --hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \ + --hash=sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2 \ + --hash=sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0 \ + --hash=sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6 \ + --hash=sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971 \ + --hash=sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c \ + --hash=sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d \ + --hash=sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9 \ + --hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \ + --hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \ + --hash=sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80 \ + --hash=sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f \ + --hash=sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1 \ + --hash=sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29 \ + --hash=sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8 \ + --hash=sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c \ + --hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \ + --hash=sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48 \ + --hash=sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813 \ + --hash=sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac \ + --hash=sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632 \ + --hash=sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6 \ + --hash=sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1 \ + --hash=sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659 \ + --hash=sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688 \ + --hash=sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004 \ + --hash=sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0 \ + --hash=sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062 \ + --hash=sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779 \ + --hash=sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94 \ + --hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \ + --hash=sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab \ + --hash=sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac \ + --hash=sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6 \ + --hash=sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676 \ + --hash=sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1 \ + --hash=sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9 \ + --hash=sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf \ + --hash=sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13 \ + --hash=sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e \ + --hash=sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e \ + --hash=sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973 \ + --hash=sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527 \ + --hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72 \ + --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \ + --hash=sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c \ + --hash=sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990 \ + --hash=sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd \ + --hash=sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9 \ + --hash=sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94 \ + --hash=sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3 \ + --hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \ + --hash=sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41 \ + --hash=sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5 \ + --hash=sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c \ + --hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \ + --hash=sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4 \ + --hash=sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e \ + --hash=sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6 \ + --hash=sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98 \ + --hash=sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b \ + --hash=sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1 \ + --hash=sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03 \ + --hash=sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af \ + --hash=sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231 \ + --hash=sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2 \ + --hash=sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3 \ + --hash=sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836 \ + --hash=sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5 \ + --hash=sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399 \ + --hash=sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96 \ + --hash=sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e \ + --hash=sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be \ + --hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \ + --hash=sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc \ + --hash=sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455 \ + --hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \ + --hash=sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12 \ + --hash=sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b \ + --hash=sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7 \ + --hash=sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692 \ + --hash=sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54 \ + --hash=sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3 \ + --hash=sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b \ + --hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \ + --hash=sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d \ + --hash=sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358 \ + --hash=sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a \ + --hash=sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7 \ + --hash=sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc \ + --hash=sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960 \ + --hash=sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125 \ + --hash=sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb \ + --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \ + --hash=sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa \ + --hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf \ + --hash=sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3 \ + --hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \ + --hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264 + # via argon2-cffi-bindings +charset-normalizer==3.5.2 \ + --hash=sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e \ + --hash=sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf \ + --hash=sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5 \ + --hash=sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56 \ + --hash=sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26 \ + --hash=sha256:0891b9d3903c5571c03771ca669a4b0ec5618ca722a5c957d3d29cd4e5062848 \ + --hash=sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718 \ + --hash=sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93 \ + --hash=sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640 \ + --hash=sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3 \ + --hash=sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875 \ + --hash=sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e \ + --hash=sha256:1461ac396c4fdb983a675f20aa555624f0ee18ac83d832b9244ffff3d8055275 \ + --hash=sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204 \ + --hash=sha256:15bb4005af6320d259dc7593ca84a38d7fe06a421dbcf7b910ae23979101e787 \ + --hash=sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234 \ + --hash=sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3 \ + --hash=sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98 \ + --hash=sha256:195c26fb65950f8fce54e26349852b7bdd7c5f120aeefbcc440b8a20faaed4a3 \ + --hash=sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187 \ + --hash=sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d \ + --hash=sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f \ + --hash=sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7 \ + --hash=sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011 \ + --hash=sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f \ + --hash=sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869 \ + --hash=sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1 \ + --hash=sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d \ + --hash=sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847 \ + --hash=sha256:28a15fdad492a99b6eccfaaed66ef3f74050680545ea61ec8b2f4c538f1f1320 \ + --hash=sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9 \ + --hash=sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93 \ + --hash=sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd \ + --hash=sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00 \ + --hash=sha256:2cc961b171b3f3440f410489ab3573e86aea8736134ebbb40ea1338b7f0831bc \ + --hash=sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0 \ + --hash=sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09 \ + --hash=sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac \ + --hash=sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621 \ + --hash=sha256:30fcd120b732aa79317f08dee04d7de0847822e4cf7ee0e9f445bb958832252c \ + --hash=sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8 \ + --hash=sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a \ + --hash=sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51 \ + --hash=sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0 \ + --hash=sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef \ + --hash=sha256:3d14b50de6bf4d0edf857a9386836846f982b8f524e188e2e68b96d702bcf4aa \ + --hash=sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6 \ + --hash=sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649 \ + --hash=sha256:3ddacd27458c45bdacd6bd6db644bfb730efbf9e830310186e3045c9c5be8fb2 \ + --hash=sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229 \ + --hash=sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e \ + --hash=sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd \ + --hash=sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115 \ + --hash=sha256:447441e76ec720b15e64418d32e092297340387053047c7c694f579efb0ee1d9 \ + --hash=sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c \ + --hash=sha256:44bd4fbb29dfbeba60e7d2bd000c59e4b21ddb3cc53912b14048d37092706d7c \ + --hash=sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab \ + --hash=sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253 \ + --hash=sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995 \ + --hash=sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438 \ + --hash=sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0 \ + --hash=sha256:50e3adfb96fc189eb27b1cf62d3b598b89b4bb0420d93a3d3e42e137409011be \ + --hash=sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b \ + --hash=sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7 \ + --hash=sha256:55ea99acb17b9325618de155a0cd6a2e8f5d10be008113e1d433bbb58db543b2 \ + --hash=sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a \ + --hash=sha256:588461c2e8384d309bd63e5826019b6977bc66d629b99ac8737bb795d7b2cb5a \ + --hash=sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a \ + --hash=sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c \ + --hash=sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5 \ + --hash=sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37 \ + --hash=sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e \ + --hash=sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4 \ + --hash=sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800 \ + --hash=sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055 \ + --hash=sha256:619799369eeef6366ed3e8755a5670f4f2f0fb6b30a0fd7264dc0fdc2357058e \ + --hash=sha256:62588a277bfb59def052abd940703fa35107152bf479781a878617d60faf8fb5 \ + --hash=sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c \ + --hash=sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b \ + --hash=sha256:68eb192d85ab8e5f6ec69c2bc6ac0179fbf04a5ac1569d12fbef74883fe102d0 \ + --hash=sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80 \ + --hash=sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a \ + --hash=sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4 \ + --hash=sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2 \ + --hash=sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58 \ + --hash=sha256:75a3ceed0724d625d64b86ca20aba182e4df462e04c2414fc941c0f523f06aac \ + --hash=sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc \ + --hash=sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639 \ + --hash=sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf \ + --hash=sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d \ + --hash=sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f \ + --hash=sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c \ + --hash=sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc \ + --hash=sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4 \ + --hash=sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253 \ + --hash=sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade \ + --hash=sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858 \ + --hash=sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26 \ + --hash=sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96 \ + --hash=sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8 \ + --hash=sha256:8a893cc101149f80a653f82062ebc95b34525a2614382e1da5458fe7c6997249 \ + --hash=sha256:8b2bfab86aa71ae13aa41a6a26aab338e0db2b8bc75434b05aea89e011ff35a4 \ + --hash=sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13 \ + --hash=sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1 \ + --hash=sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03 \ + --hash=sha256:93223adc95033dd47133a46ccfc316a0139176fd79085762e27202ec56018f03 \ + --hash=sha256:9373ad13ef0d2c0fb761e04e55bfdee5a08b52cef2c882c8fbe9935b1517152e \ + --hash=sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364 \ + --hash=sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4 \ + --hash=sha256:9bde855991b7e362c146535e3136a50bfaffc0487d38b33ca7e5edefc6e23849 \ + --hash=sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0 \ + --hash=sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a \ + --hash=sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036 \ + --hash=sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3 \ + --hash=sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21 \ + --hash=sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3 \ + --hash=sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e \ + --hash=sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413 \ + --hash=sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21 \ + --hash=sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346 \ + --hash=sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429 \ + --hash=sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685 \ + --hash=sha256:b736353c0a625bbd5fcec108576e2385db3496f4f771f785ff32e108d3c3bc45 \ + --hash=sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f \ + --hash=sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c \ + --hash=sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d \ + --hash=sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad \ + --hash=sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400 \ + --hash=sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb \ + --hash=sha256:c6708715abcf3c73b99508253e961a9967f02fe536532834149574eda6de0d1c \ + --hash=sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc \ + --hash=sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c \ + --hash=sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74 \ + --hash=sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf \ + --hash=sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604 \ + --hash=sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f \ + --hash=sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105 \ + --hash=sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a \ + --hash=sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d \ + --hash=sha256:d4a7319f304a774bed22115bc891618e45f85065ab44ea6acd07d274e750519a \ + --hash=sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1 \ + --hash=sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5 \ + --hash=sha256:d913de495d90407cd859d263bee2e5d1a4ed3eb6573c04e70d9ec619a7cbed7f \ + --hash=sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e \ + --hash=sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709 \ + --hash=sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874 \ + --hash=sha256:ddf19c062bea7a0cc80f519243d2c01dd091be0cf952a0750d4ad576709559f5 \ + --hash=sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc \ + --hash=sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95 \ + --hash=sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd \ + --hash=sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0 \ + --hash=sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d \ + --hash=sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3 \ + --hash=sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c \ + --hash=sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3 \ + --hash=sha256:e80e6c2f55656b4824d72065abb4ddd6a525c74bd78a0aab5d9fc2cf4fb5af50 \ + --hash=sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491 \ + --hash=sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5 \ + --hash=sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5 \ + --hash=sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655 \ + --hash=sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288 \ + --hash=sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd \ + --hash=sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084 \ + --hash=sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d \ + --hash=sha256:f5833ad231be5eb6553de524a70f48d71b2c8563101750531e0b80184e175cd4 \ + --hash=sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915 \ + --hash=sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1 \ + --hash=sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd \ + --hash=sha256:fc14a032f813bf5fe624d991960ea83e9715adc27e4c1830a2361eb1d02ac341 \ + --hash=sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424 \ + --hash=sha256:fd1fbe0f116b6e55da77aca2c6ddcddcfac2186cbf78bdebf40fc156efca389d \ + --hash=sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f + # via requests +click==8.5.0 \ + --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \ + --hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34 + # via uvicorn +frozenlist==1.8.0 \ + --hash=sha256:0325024fe97f94c41c08872db482cf8ac4800d80e79222c6b0b7b162d5b13686 \ + --hash=sha256:032efa2674356903cd0261c4317a561a6850f3ac864a63fc1583147fb05a79b0 \ + --hash=sha256:03ae967b4e297f58f8c774c7eabcce57fe3c2434817d4385c50661845a058121 \ + --hash=sha256:06be8f67f39c8b1dc671f5d83aaefd3358ae5cdcf8314552c57e7ed3e6475bdd \ + --hash=sha256:073f8bf8becba60aa931eb3bc420b217bb7d5b8f4750e6f8b3be7f3da85d38b7 \ + --hash=sha256:07cdca25a91a4386d2e76ad992916a85038a9b97561bf7a3fd12d5d9ce31870c \ + --hash=sha256:09474e9831bc2b2199fad6da3c14c7b0fbdd377cce9d3d77131be28906cb7d84 \ + --hash=sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d \ + --hash=sha256:0f96534f8bfebc1a394209427d0f8a63d343c9779cda6fc25e8e121b5fd8555b \ + --hash=sha256:102e6314ca4da683dca92e3b1355490fed5f313b768500084fbe6371fddfdb79 \ + --hash=sha256:11847b53d722050808926e785df837353bd4d75f1d494377e59b23594d834967 \ + --hash=sha256:119fb2a1bd47307e899c2fac7f28e85b9a543864df47aa7ec9d3c1b4545f096f \ + --hash=sha256:13d23a45c4cebade99340c4165bd90eeb4a56c6d8a9d8aa49568cac19a6d0dc4 \ + --hash=sha256:154e55ec0655291b5dd1b8731c637ecdb50975a2ae70c606d100750a540082f7 \ + --hash=sha256:168c0969a329b416119507ba30b9ea13688fafffac1b7822802537569a1cb0ef \ + --hash=sha256:17c883ab0ab67200b5f964d2b9ed6b00971917d5d8a92df149dc2c9779208ee9 \ + --hash=sha256:1a7607e17ad33361677adcd1443edf6f5da0ce5e5377b798fba20fae194825f3 \ + --hash=sha256:1a7fa382a4a223773ed64242dbe1c9c326ec09457e6b8428efb4118c685c3dfd \ + --hash=sha256:1aa77cb5697069af47472e39612976ed05343ff2e84a3dcf15437b232cbfd087 \ + --hash=sha256:1b9290cf81e95e93fdf90548ce9d3c1211cf574b8e3f4b3b7cb0537cf2227068 \ + --hash=sha256:20e63c9493d33ee48536600d1a5c95eefc870cd71e7ab037763d1fbb89cc51e7 \ + --hash=sha256:21900c48ae04d13d416f0e1e0c4d81f7931f73a9dfa0b7a8746fb2fe7dd970ed \ + --hash=sha256:229bf37d2e4acdaf808fd3f06e854a4a7a3661e871b10dc1f8f1896a3b05f18b \ + --hash=sha256:2552f44204b744fba866e573be4c1f9048d6a324dfe14475103fd51613eb1d1f \ + --hash=sha256:27c6e8077956cf73eadd514be8fb04d77fc946a7fe9f7fe167648b0b9085cc25 \ + --hash=sha256:28bd570e8e189d7f7b001966435f9dac6718324b5be2990ac496cf1ea9ddb7fe \ + --hash=sha256:294e487f9ec720bd8ffcebc99d575f7eff3568a08a253d1ee1a0378754b74143 \ + --hash=sha256:29548f9b5b5e3460ce7378144c3010363d8035cea44bc0bf02d57f5a685e084e \ + --hash=sha256:2c5dcbbc55383e5883246d11fd179782a9d07a986c40f49abe89ddf865913930 \ + --hash=sha256:2dc43a022e555de94c3b68a4ef0b11c4f747d12c024a520c7101709a2144fb37 \ + --hash=sha256:2f05983daecab868a31e1da44462873306d3cbfd76d1f0b5b69c473d21dbb128 \ + --hash=sha256:33139dc858c580ea50e7e60a1b0ea003efa1fd42e6ec7fdbad78fff65fad2fd2 \ + --hash=sha256:332db6b2563333c5671fecacd085141b5800cb866be16d5e3eb15a2086476675 \ + --hash=sha256:33f48f51a446114bc5d251fb2954ab0164d5be02ad3382abcbfe07e2531d650f \ + --hash=sha256:34187385b08f866104f0c0617404c8eb08165ab1272e884abc89c112e9c00746 \ + --hash=sha256:342c97bf697ac5480c0a7ec73cd700ecfa5a8a40ac923bd035484616efecc2df \ + --hash=sha256:3462dd9475af2025c31cc61be6652dfa25cbfb56cbbf52f4ccfe029f38decaf8 \ + --hash=sha256:39ecbc32f1390387d2aa4f5a995e465e9e2f79ba3adcac92d68e3e0afae6657c \ + --hash=sha256:3e0761f4d1a44f1d1a47996511752cf3dcec5bbdd9cc2b4fe595caf97754b7a0 \ + --hash=sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad \ + --hash=sha256:3ef2d026f16a2b1866e1d86fc4e1291e1ed8a387b2c333809419a2f8b3a77b82 \ + --hash=sha256:405e8fe955c2280ce66428b3ca55e12b3c4e9c336fb2103a4937e891c69a4a29 \ + --hash=sha256:42145cd2748ca39f32801dad54aeea10039da6f86e303659db90db1c4b614c8c \ + --hash=sha256:4314debad13beb564b708b4a496020e5306c7333fa9a3ab90374169a20ffab30 \ + --hash=sha256:433403ae80709741ce34038da08511d4a77062aa924baf411ef73d1146e74faf \ + --hash=sha256:44389d135b3ff43ba8cc89ff7f51f5a0bb6b63d829c8300f79a2fe4fe61bcc62 \ + --hash=sha256:48e6d3f4ec5c7273dfe83ff27c91083c6c9065af655dc2684d2c200c94308bb5 \ + --hash=sha256:494a5952b1c597ba44e0e78113a7266e656b9794eec897b19ead706bd7074383 \ + --hash=sha256:4970ece02dbc8c3a92fcc5228e36a3e933a01a999f7094ff7c23fbd2beeaa67c \ + --hash=sha256:4e0c11f2cc6717e0a741f84a527c52616140741cd812a50422f83dc31749fb52 \ + --hash=sha256:50066c3997d0091c411a66e710f4e11752251e6d2d73d70d8d5d4c76442a199d \ + --hash=sha256:517279f58009d0b1f2e7c1b130b377a349405da3f7621ed6bfae50b10adf20c1 \ + --hash=sha256:54b2077180eb7f83dd52c40b2750d0a9f175e06a42e3213ce047219de902717a \ + --hash=sha256:5500ef82073f599ac84d888e3a8c1f77ac831183244bfd7f11eaa0289fb30714 \ + --hash=sha256:581ef5194c48035a7de2aefc72ac6539823bb71508189e5de01d60c9dcd5fa65 \ + --hash=sha256:59a6a5876ca59d1b63af8cd5e7ffffb024c3dc1e9cf9301b21a2e76286505c95 \ + --hash=sha256:5a3a935c3a4e89c733303a2d5a7c257ea44af3a56c8202df486b7f5de40f37e1 \ + --hash=sha256:5c1c8e78426e59b3f8005e9b19f6ff46e5845895adbde20ece9218319eca6506 \ + --hash=sha256:5d63a068f978fc69421fb0e6eb91a9603187527c86b7cd3f534a5b77a592b888 \ + --hash=sha256:667c3777ca571e5dbeb76f331562ff98b957431df140b54c85fd4d52eea8d8f6 \ + --hash=sha256:6da155091429aeba16851ecb10a9104a108bcd32f6c1642867eadaee401c1c41 \ + --hash=sha256:6dc4126390929823e2d2d9dc79ab4046ed74680360fc5f38b585c12c66cdf459 \ + --hash=sha256:7398c222d1d405e796970320036b1b563892b65809d9e5261487bb2c7f7b5c6a \ + --hash=sha256:74c51543498289c0c43656701be6b077f4b265868fa7f8a8859c197006efb608 \ + --hash=sha256:776f352e8329135506a1d6bf16ac3f87bc25b28e765949282dcc627af36123aa \ + --hash=sha256:778a11b15673f6f1df23d9586f83c4846c471a8af693a22e066508b77d201ec8 \ + --hash=sha256:78f7b9e5d6f2fdb88cdde9440dc147259b62b9d3b019924def9f6478be254ac1 \ + --hash=sha256:799345ab092bee59f01a915620b5d014698547afd011e691a208637312db9186 \ + --hash=sha256:7bf6cdf8e07c8151fba6fe85735441240ec7f619f935a5205953d58009aef8c6 \ + --hash=sha256:8009897cdef112072f93a0efdce29cd819e717fd2f649ee3016efd3cd885a7ed \ + --hash=sha256:80f85f0a7cc86e7a54c46d99c9e1318ff01f4687c172ede30fd52d19d1da1c8e \ + --hash=sha256:8585e3bb2cdea02fc88ffa245069c36555557ad3609e83be0ec71f54fd4abb52 \ + --hash=sha256:878be833caa6a3821caf85eb39c5ba92d28e85df26d57afb06b35b2efd937231 \ + --hash=sha256:8a76ea0f0b9dfa06f254ee06053d93a600865b3274358ca48a352ce4f0798450 \ + --hash=sha256:8b7b94a067d1c504ee0b16def57ad5738701e4ba10cec90529f13fa03c833496 \ + --hash=sha256:8d92f1a84bb12d9e56f818b3a746f3efba93c1b63c8387a73dde655e1e42282a \ + --hash=sha256:908bd3f6439f2fef9e85031b59fd4f1297af54415fb60e4254a95f75b3cab3f3 \ + --hash=sha256:92db2bf818d5cc8d9c1f1fc56b897662e24ea5adb36ad1f1d82875bd64e03c24 \ + --hash=sha256:940d4a017dbfed9daf46a3b086e1d2167e7012ee297fef9e1c545c4d022f5178 \ + --hash=sha256:957e7c38f250991e48a9a73e6423db1bb9dd14e722a10f6b8bb8e16a0f55f695 \ + --hash=sha256:96153e77a591c8adc2ee805756c61f59fef4cf4073a9275ee86fe8cba41241f7 \ + --hash=sha256:96f423a119f4777a4a056b66ce11527366a8bb92f54e541ade21f2374433f6d4 \ + --hash=sha256:97260ff46b207a82a7567b581ab4190bd4dfa09f4db8a8b49d1a958f6aa4940e \ + --hash=sha256:974b28cf63cc99dfb2188d8d222bc6843656188164848c4f679e63dae4b0708e \ + --hash=sha256:9ff15928d62a0b80bb875655c39bf517938c7d589554cbd2669be42d97c2cb61 \ + --hash=sha256:a6483e309ca809f1efd154b4d37dc6d9f61037d6c6a81c2dc7a15cb22c8c5dca \ + --hash=sha256:a88f062f072d1589b7b46e951698950e7da00442fc1cacbe17e19e025dc327ad \ + --hash=sha256:ac913f8403b36a2c8610bbfd25b8013488533e71e62b4b4adce9c86c8cea905b \ + --hash=sha256:adbeebaebae3526afc3c96fad434367cafbfd1b25d72369a9e5858453b1bb71a \ + --hash=sha256:b2a095d45c5d46e5e79ba1e5b9cb787f541a8dee0433836cea4b96a2c439dcd8 \ + --hash=sha256:b3210649ee28062ea6099cfda39e147fa1bc039583c8ee4481cb7811e2448c51 \ + --hash=sha256:b37f6d31b3dcea7deb5e9696e529a6aa4a898adc33db82da12e4c60a7c4d2011 \ + --hash=sha256:b4dec9482a65c54a5044486847b8a66bf10c9cb4926d42927ec4e8fd5db7fed8 \ + --hash=sha256:b4f3b365f31c6cd4af24545ca0a244a53688cad8834e32f56831c4923b50a103 \ + --hash=sha256:b6db2185db9be0a04fecf2f241c70b63b1a242e2805be291855078f2b404dd6b \ + --hash=sha256:b9be22a69a014bc47e78072d0ecae716f5eb56c15238acca0f43d6eb8e4a5bda \ + --hash=sha256:bac9c42ba2ac65ddc115d930c78d24ab8d4f465fd3fc473cdedfccadb9429806 \ + --hash=sha256:bf0a7e10b077bf5fb9380ad3ae8ce20ef919a6ad93b4552896419ac7e1d8e042 \ + --hash=sha256:c23c3ff005322a6e16f71bf8692fcf4d5a304aaafe1e262c98c6d4adc7be863e \ + --hash=sha256:c4c800524c9cd9bac5166cd6f55285957fcfc907db323e193f2afcd4d9abd69b \ + --hash=sha256:c7366fe1418a6133d5aa824ee53d406550110984de7637d65a178010f759c6ef \ + --hash=sha256:c8d1634419f39ea6f5c427ea2f90ca85126b54b50837f31497f3bf38266e853d \ + --hash=sha256:c9a63152fe95756b85f31186bddf42e4c02c6321207fd6601a1c89ebac4fe567 \ + --hash=sha256:cb89a7f2de3602cfed448095bab3f178399646ab7c61454315089787df07733a \ + --hash=sha256:cba69cb73723c3f329622e34bdbf5ce1f80c21c290ff04256cff1cd3c2036ed2 \ + --hash=sha256:cee686f1f4cadeb2136007ddedd0aaf928ab95216e7691c63e50a8ec066336d0 \ + --hash=sha256:cf253e0e1c3ceb4aaff6df637ce033ff6535fb8c70a764a8f46aafd3d6ab798e \ + --hash=sha256:d1eaff1d00c7751b7c6662e9c5ba6eb2c17a2306ba5e2a37f24ddf3cc953402b \ + --hash=sha256:d3bb933317c52d7ea5004a1c442eef86f426886fba134ef8cf4226ea6ee1821d \ + --hash=sha256:d4d3214a0f8394edfa3e303136d0575eece0745ff2b47bd2cb2e66dd92d4351a \ + --hash=sha256:d6a5df73acd3399d893dafc71663ad22534b5aa4f94e8a2fabfe856c3c1b6a52 \ + --hash=sha256:d8b7138e5cd0647e4523d6685b0eac5d4be9a184ae9634492f25c6eb38c12a47 \ + --hash=sha256:db1e72ede2d0d7ccb213f218df6a078a9c09a7de257c2fe8fcef16d5925230b1 \ + --hash=sha256:e25ac20a2ef37e91c1b39938b591457666a0fa835c7783c3a8f33ea42870db94 \ + --hash=sha256:e2de870d16a7a53901e41b64ffdf26f2fbb8917b3e6ebf398098d72c5b20bd7f \ + --hash=sha256:e4a3408834f65da56c83528fb52ce7911484f0d1eaf7b761fc66001db1646eff \ + --hash=sha256:eaa352d7047a31d87dafcacbabe89df0aa506abb5b1b85a2fb91bc3faa02d822 \ + --hash=sha256:eab8145831a0d56ec9c4139b6c3e594c7a83c2c8be25d5bcf2d86136a532287a \ + --hash=sha256:ec3cc8c5d4084591b4237c0a272cc4f50a5b03396a47d9caaf76f5d7b38a4f11 \ + --hash=sha256:edee74874ce20a373d62dc28b0b18b93f645633c2943fd90ee9d898550770581 \ + --hash=sha256:eefdba20de0d938cec6a89bd4d70f346a03108a19b9df4248d3cf0d88f1b0f51 \ + --hash=sha256:ef2b7b394f208233e471abc541cc6991f907ffd47dc72584acee3147899d6565 \ + --hash=sha256:f21f00a91358803399890ab167098c131ec2ddd5f8f5fd5fe9c9f2c6fcd91e40 \ + --hash=sha256:f4be2e3d8bc8aabd566f8d5b8ba7ecc09249d74ba3c9ed52e54dc23a293f0b92 \ + --hash=sha256:f57fb59d9f385710aa7060e89410aeb5058b99e62f4d16b08b91986b9a2140c2 \ + --hash=sha256:f6292f1de555ffcc675941d65fffffb0a5bcd992905015f85d0592201793e0e5 \ + --hash=sha256:f833670942247a14eafbb675458b4e61c82e002a148f49e68257b79296e865c4 \ + --hash=sha256:fa47e444b8ba08fffd1c18e8cdb9a75db1b6a27f17507522834ad13ed5922b93 \ + --hash=sha256:fb30f9626572a76dfe4293c7194a09fb1fe93ba94c7d4f720dfae3b646b45027 \ + --hash=sha256:fe3c58d2f5db5fbd18c2987cba06d51b0529f52bc3a6cdc33d3f4eab725104bd + # via + # aiohttp + # aiosignal +googleapis-common-protos==1.76.0 \ + --hash=sha256:59e13344a9f3651aa201a03e2bee815a3bf43a4baf1f9ff8a9b62a840ce25fac \ + --hash=sha256:71db0e44a1d4c2dd024ebad44ca67129cc1e2892e4861df466764749d5ef8642 + # via opentelemetry-exporter-otlp-proto-http +h11==0.16.0 \ + --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ + --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 + # via uvicorn +httptools==0.9.0 \ + --hash=sha256:02bc5b3dcb6394b9d825fd62a7bfa0b2943063a3c89abc4492ad45e334a20eb5 \ + --hash=sha256:050f7ab098121873c8f13e35857f97ab60a76185c8302bde9a384939bb7c3b96 \ + --hash=sha256:050f84b7ec46a6efe0e5f521cf8729e3397c1cef4384f62ed8d5d68ca0045776 \ + --hash=sha256:06bfe7fad972a417269d8a5fc53b87e4eca970354abf5e9e24336fd06d64292e \ + --hash=sha256:088de1738e1af624466a01c35d652dbe6fb825be887c76d68aa850621d81db88 \ + --hash=sha256:0adc974916efe1fbf89d0363a86dcb2c746727643e362ff398de1a4b50b6bc77 \ + --hash=sha256:0cc339a807c156d840b54f8bf050ba0fc265eb81692c24bca8535b52fbd797c6 \ + --hash=sha256:0fd73d0bbf700a30dd87e4412adf41cfa71542a533d6b390c7244bbb8a1152bb \ + --hash=sha256:130635fea6e611a6b2026120037965ddb88b3dafd11bb64e264b101a70a76630 \ + --hash=sha256:13873eb8aef5972fcfee614f63d47064312ad4efbfe65ade15b8a3b77f8c8659 \ + --hash=sha256:18d800aaa2d6bff7d889df810d1b19a5fde72b1f6c0ca96e8d9f28a692fe5460 \ + --hash=sha256:1a4050a651e1f2faf05eb028ce9f2168abbcee9e24b209f5c1f2eb96d8c569e4 \ + --hash=sha256:1a7f1df31829c258158be01bb04eb668c4fba7df1ddf2262131a972962e651b6 \ + --hash=sha256:1b01c0fcd6725a8d79a164ecdc4116866282479d68bb3d6d74a909bf994656c4 \ + --hash=sha256:1b95775f6292d72cb452c33e5c0f8b8551807c29a10e3c1671fef7f61361370a \ + --hash=sha256:1f6da814aeecbc6cb8872d6d3e85ed16e8ab1653f9557cea8658725ce212348a \ + --hash=sha256:2095207b75a83c9e947346da9c127fb7e4fb29f41589df2643764f06b750989c \ + --hash=sha256:22ab1b10b06d357f01092e60f5e6856a0d479ed79b0ec2166a339ea26c699be2 \ + --hash=sha256:2319858018eedd0c0b2f950a620413c0a9d1352607be4267eb28209eca8b1e3f \ + --hash=sha256:268d18601feb5367885c6ebf6f402c18fc25a324cee215784adafe0a1eef925f \ + --hash=sha256:26e1d9629f3bf70d23f0d22238152aec51c837a7c9e384cb74f356fdccad7eb3 \ + --hash=sha256:272db0c51e8b71e953c1f2ecbe63402b819680e4564be2ef285cfd4584ee8355 \ + --hash=sha256:289f213d2a3dde2e8312c415ffecec5a01698589ec6249ec4e8fb3b47c0444ba \ + --hash=sha256:29b0d823e3c1e7cd1093a5dc889245db693ef13ada624cd66e2262421ef38867 \ + --hash=sha256:310266a2db1377ffae3bdf6556ab4973f4f94508a8ce37b2f6bb096a89bcefa1 \ + --hash=sha256:3238e198429cb8909ec42951b82d6a33fe0fdfcf86371732f8f09311c5b8ac32 \ + --hash=sha256:34266cec8c1d4e3e91fcca7efe38971d6bdda64a7944f2a46ab576da15173680 \ + --hash=sha256:36fac804b8cfd6b935ae64f71349f833d2b6298404626d017a2c57bb942bc643 \ + --hash=sha256:3af4e45ff455fce5511fdf2653c1ce428ef09c56fe37a83eb4d924c2d474f31e \ + --hash=sha256:3e3201fe4d46e0d15d7ff9fafc94a605da9eb82d2c5b9837f0368acb325481f1 \ + --hash=sha256:45b3002392948dcf578029c89f6318e1289a993a1a5ec38a4161560fab60f811 \ + --hash=sha256:465bc1526debf53a3be92022a16ca0c38f891ea3b5c1587af4f52e44020f8a07 \ + --hash=sha256:48c705bd0b1afb6253ed71eca9f9ba7ac7d47838e5fed1ef7891d67f21ecd4de \ + --hash=sha256:4a4d8c2c7e73ba5967be74d7c3a5ff81fde815ee1b48d9c5c0f14de8463a847b \ + --hash=sha256:4a85401b0c3f893cf5695c1199e8679fbf673f7f78c2f6c11d6b1850f8c7e358 \ + --hash=sha256:4c58dc91aefb31adad500aa68054334f429b840b36dd29e34e834101044cb2ef \ + --hash=sha256:4efbee349138a3fee7a4cc3a95abd2d499fae70dd5bff9fed9138d6f570f4283 \ + --hash=sha256:4fb995082fe41ec410b33c48b54fb1d44abb8a6ee762c31e8c42519e8c3a30a9 \ + --hash=sha256:5042aa1c7e2b1a24c17dab31d8770b63a5101c9abc25f832c6aef6b201e1ca4f \ + --hash=sha256:52fe0176682a25b15370f23f5b0f1366a84771df89144fb0cd979cb72a94b5ca \ + --hash=sha256:5332a020a60bbe32ede4bda1a62b3d56c4831d309cdf0932842c0fca8ad6aaa3 \ + --hash=sha256:563e4568217dc907a91843f38c737be865222c0400a38cdcd0d26ce92b3db271 \ + --hash=sha256:581b27663c6e9f4df68068f32fe6d1cd7647b31fac90237221a66f8821c342eb \ + --hash=sha256:58a1b0ec4cbb930e69669f9771715b2c7898d3cdf064d9811f7a66afef96b544 \ + --hash=sha256:5cc5d3a29f9ec86ce406e5ec09c241dd8dc4d30e838f74f68d728b89131a3acf \ + --hash=sha256:63d38e9a9a10a20fb57593742e63c6b1e78dd7f6ef5472de8e0b1e4cf4f3db26 \ + --hash=sha256:6b1ac7f1bc6c0dbf90684b77571a51a21b2463909fd916ce0ac9bfc4d566dc75 \ + --hash=sha256:6b900073e7b8481ef1aaf4f6c1789d210a1db01a9da8789821578cfeb4c2d540 \ + --hash=sha256:6c12d0393a903b58bc5f5a7406d6c5290acfb8284290d68547ce620c06f7d133 \ + --hash=sha256:6e2780e33a58a93f27cc3bb74a55bae6f9a8278a1dbabdff392940d30d381671 \ + --hash=sha256:6ebd39ee26db460cfe5ab8b71a15d1149b289139a0d3981522757d6af620887e \ + --hash=sha256:6f8b41299b203ce8f627db670cfea82067d9638853dbeaf86dccd93878879b85 \ + --hash=sha256:6f9549ca354a1d6d6167c458a1f1b12147726b968f02dd64b6a5801dba91ae0f \ + --hash=sha256:6ff0145b34610e57c9fae20df4e133c8d54266447387de6fcc0bdabfe4db4569 \ + --hash=sha256:6ff5f0ed70783dcb9562dbd20edca51c3d4d277f128223709e3da6b75986d1d4 \ + --hash=sha256:714bf348f468532d86bed670837e7d5ddff3834dd7f5d3c08066da400c86f088 \ + --hash=sha256:757e3f79cb865a7db94e0db5f4d0ed3284a69e39d53568f433982ea13c60cac1 \ + --hash=sha256:7e32b83bd8c2f8b6fa726ef34e63e21c4d7eddc277d40d4ef7245ea3ed28e5b6 \ + --hash=sha256:805b0f2618e5d4c3e28f45b731eb1a0539691ae4a2f97b4ce014de0bf96a1ff5 \ + --hash=sha256:80eae881cfb69383303e9a4d7961a478025b89c24f38f2e69b30c516fa0d57f2 \ + --hash=sha256:813a32f94991b9627795528053c73a57d2ce3eb98ede89f0e1c7a31095938e81 \ + --hash=sha256:8463b34ebde3f000627e9dbd8a545f995ad49fbf7ff9dd5abc0cd507da98a603 \ + --hash=sha256:8a59c749a73fbdbc8e63b895a3079825fa085d752e75bc0a500042cb8a801e48 \ + --hash=sha256:8d90d10e9b6594c28f27896a68fab97fd784c43804e9fe419dab8e8dcfcf4b02 \ + --hash=sha256:8e1e037bb57dbc549c6fe20370b763ea74bdb09413cdcf857e4f14d9e4e2fb13 \ + --hash=sha256:931f45f84e15daafec5f82cc92e6710569e1f50933f3253d206eab4132bec678 \ + --hash=sha256:995b52f7c260ac7023640221f27472303968753cb6fc6fce1ddfb0e9db59a398 \ + --hash=sha256:9b4da5789d7cf576c7e81f0088c632f6ee3786d87d17f08e90e703c22ce15633 \ + --hash=sha256:a3ed60ea9a7c352c590182c67404599e6b5a0c901e75ae4cceee9a9fd6bfa455 \ + --hash=sha256:a4d1ecad62e83cc65b411ea0125972cf3af98821e8117129947fd1e3a113f8d2 \ + --hash=sha256:ae9bb62a7902e2ab65782447cd3eeb753510feace4e3ea03937a85489b01b16b \ + --hash=sha256:b2ab3aad55d75d0b8df8d8a1b5920baaec9b161112cd5e95984848b4d2cd3dfe \ + --hash=sha256:b2cc6991f16f6d666d48e4b57318104e7b29109e32e2f6b86e9d44c4e6a27f4e \ + --hash=sha256:b5a3f5f70967a1aa2bc47fec42a1e19d2fb38c61700e3ee62b63a4af4f4fd001 \ + --hash=sha256:b68fb053b37c258a473ab67f4965c3b439500dc160fe364667035a6833eaf50a \ + --hash=sha256:b6ee42112d785a913dd63ec0335435a3dddbea5040c151252db815b0095cf066 \ + --hash=sha256:b928ab0ecaa664e8caecc529dcb8bc881b6b35bb2b74bf9a39ae25f982ee8812 \ + --hash=sha256:b9430f65db521db7962ad951571d446171213686f96c998a54dc18ed574821e2 \ + --hash=sha256:b9cd15cb7cf0d5cc41f649fd789aae12c56c3b83eff593f8e095c1d4555ad5c3 \ + --hash=sha256:bb1533541c729ad422f870a780d8b4af924f9817d45b5f580390418cda72eaa2 \ + --hash=sha256:bbf7377fbd41b7c87d47820e25b9876724963681c2a1d6f6ff2adb4db46ac174 \ + --hash=sha256:bca180cbe84e4fba7807eb408a8655295f697928512324517e30a091ede522a8 \ + --hash=sha256:beb2c8a34cc90fb4d862b7284eafdb322030d6a8b2ee5eb6a744f84205beedc3 \ + --hash=sha256:bfdabac0c6d3d6a5be8c2a100a001c92c14a39bbafd5999545a675c493626e64 \ + --hash=sha256:c0e45def4d9ce7073e2226535572442d9d6efb4047c7a5fd8960807e877ce70a \ + --hash=sha256:c0f537e5e8152e8d9cae82804024790cb973061abd3b7ef8f66f46e2b5c7bb51 \ + --hash=sha256:c195a69df0ab2541252ab5b1d76e3c182e5688ac2a9b708e5e6f66aaeda91e9a \ + --hash=sha256:c271bfb832be5c5c020b4e2fcbc1e70a0b990adba6de874b0bba1184b89cdea3 \ + --hash=sha256:c42424213c28804f8d0e20f5692106cfb57bf72e1dbc4092b8481fb2f9e4c707 \ + --hash=sha256:c4fa57d3c31889722f64bfa785545a5e603a893b6f29ac1a41bfa830abeaefd5 \ + --hash=sha256:cb2bb3ac0af7fdab2311b895c9eb95442b45deb14cc949b9e65545e74aa0be69 \ + --hash=sha256:cb3e7a4fd0168e362673a980380bf4fd6ae3b1555150e60c5390b4b10d9c50c4 \ + --hash=sha256:cbbfcd5d15056fbd1edd5e725cf3feeb47c7cbccbe205927ebab422cc229f417 \ + --hash=sha256:cd3e55223a77d6e08d5730ebacb4930ecca5d2ce7c57e7ba10833be7e52903f1 \ + --hash=sha256:ce8e723b4637034b76f5382a30a6b725518c332273e8d62a6c7d46e90837c947 \ + --hash=sha256:d1e329a1866981efe0201d05a374617f6c6cf14434a501d78ab22793d1ab1fa6 \ + --hash=sha256:d20ba5c84cf0592afb2713336f07e2b6ced082e4ae803ceada153a85613efc9f \ + --hash=sha256:d2b095129b9a98eb46a271ee9631089529c4e40354576b4aa74e24de9d2bf2f7 \ + --hash=sha256:d3906b5c549ff2ad2473cb711e1fc65d76715c2726a402108fbf55eab6c6b49d \ + --hash=sha256:d484ebb7e3a3f3597b0f645fbd1b85633674ca808c1f5ba11c2caf7c66f5c8b6 \ + --hash=sha256:db735a23ecb0f0450d2b24e0a05fb00a8a35c9db172919c4d3e023e7c7ee4c9b \ + --hash=sha256:dbc9fd1521e573045d71b6afab7398439c5cc259e8cb9d416fe62d485c4899c6 \ + --hash=sha256:df3867518b205be3648e2fbd522bf380c851b5c2500588047505afdd786b6669 \ + --hash=sha256:e0acbd474d0af4afacc6e66c4273f8a19e25f8af4379fc816388095ea6b01371 \ + --hash=sha256:eacf0f45ca3ff84c01481c60c15da9ee56711f7292f66663df0f57af61e011c2 \ + --hash=sha256:ead1a40543a033a6732a9e1e515944979a19db3737ce77363fc0660e38554344 \ + --hash=sha256:eae4e9c7a0785a1a715de0a74fb822ab40084c060f444f18f075d05e322aa7ef \ + --hash=sha256:ecf7037e491c220cd73987838c1ac3958d787bb098c3be0bfaf7f04204a6162c \ + --hash=sha256:ecfeee649184ffd800955068be9a6b579a0f33fc3c98535d685d5779cb59347f \ + --hash=sha256:edd5aa045fa3cc57143db018dd32ce7962bd5b525d05230709015d7e570100aa \ + --hash=sha256:f0ef48ce353f6b6a52232ba23d0983d4c2c84c84a778899404e34b4718509bf2 \ + --hash=sha256:f1734bd6f588975ffc246211e8b96c11933344087ca280d2cbcbf35cf835d7a9 \ + --hash=sha256:f67db0ba2bedafec15b8e5330d40da1e1c7921559fa715af021252bfef81a6f8 \ + --hash=sha256:f6ac1414556b910a879c108d79736f77e797871f9919ed0d2c3cf8cf3ecca986 \ + --hash=sha256:f78f7ae1c2e5aabf29583fc0d302d8081a663776f84578025662eb6f5d63a921 \ + --hash=sha256:f9489c1d87160c126f73b004742fe8654fa1ce37ed89e9e01330a1c10aaecde4 \ + --hash=sha256:f9ccc9884241efceb4547a92955d128574c864681f11b7ea3ecbde295fafbe8b \ + --hash=sha256:fc1a4f9d18d32a6e0a0a0a382986a60a2126f5144dd08715be7adb8df18e8a46 + # via -r requirements.in +idna==3.20 \ + --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \ + --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c + # via + # anyio + # requests + # yarl +jmespath==1.1.0 \ + --hash=sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d \ + --hash=sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64 + # via + # aiobotocore + # botocore +multidict==6.9.1 \ + --hash=sha256:006c4478de0a1876f4834e14255776286f09b9846b505fe63f67f9d173a9487c \ + --hash=sha256:024123f0ab402ab33828e24eb80fa8f25167d0d3783ba5f287e39ed741e6abf9 \ + --hash=sha256:02f6d0c4b70f783305e73f9944d8efe6be1022550f0974ba0ae9d8893c0350fa \ + --hash=sha256:02fe09dc197b8ae7e355371e51e5dce2f39060cd5a8badf94904527e23a3f188 \ + --hash=sha256:03731f6fc036180700c9dc2308205a48e5ca6f3ff03087739ab746f294022201 \ + --hash=sha256:03d47df72f084f757c1cb771188d5f4e3a805e4abc4d67e32509272343ae9382 \ + --hash=sha256:03fac50ddfd8302175b77863a015eccfae76767cda5506eef86df559ba861e1f \ + --hash=sha256:042fb0196047e786936a730bd302de83143950da45f2c16078da8f35e1cf7919 \ + --hash=sha256:083735b7f395894e43adb278d5dae901448883a835ff8f1977e285fefdb10418 \ + --hash=sha256:095d900c242e00fbe5f321ee072e7278b4153e78c5ce9c1efde167d62c1e4771 \ + --hash=sha256:0a5769559e3312dd96731fbe15b4abb6033368ac1cad5a98dadd21946a4c7d6c \ + --hash=sha256:0b2fb8c349d1103863750b5d8cb5ace766917f4b35f3d883c8f778853eaa9f76 \ + --hash=sha256:0dd655518f136febd96c05131a76a863e32fc2a1d7acd4e3c959e3ceb77d8345 \ + --hash=sha256:0f06e60fa190aa7abd0914c2a766736fdc8e9f34878c4346338534b73d1b20e2 \ + --hash=sha256:0f2ce963299d42fa3f22a90adc0fdf174792ffef5ff4c7ffb68260548fb05580 \ + --hash=sha256:0f3bd290711c6e9486173a6ee7cd4e7f00c3971c7908c1ec1b6e5437c5e4c6f9 \ + --hash=sha256:10083a8a0f4e1b26b599889e90b9802504ce5d3f7722f925bbb7ca47dd22a7c1 \ + --hash=sha256:13849a1d4f54c3809ae721e9e83ab28f5ea602f33660cb84eb6ef261eac706c1 \ + --hash=sha256:14c56f73e78faa1f68bbb826197cd5871994e70e841b8590829c35912ece5c64 \ + --hash=sha256:15db6a102cbaf1949cf028ecf080aac76d20bcd29ad4e092574db6c6b7af78a5 \ + --hash=sha256:19e31815d41cefc365489e591d105d2baceb2f65aa75d29471fbdbda8651e006 \ + --hash=sha256:1a53de2772cfb74559df2eb4456ec4eeb908435ec55a84b69370d9d745d62aa8 \ + --hash=sha256:1a8adfcaf96f587ab138476eaddef95f29b8a2a8a9afbfea8d2fd62180995d02 \ + --hash=sha256:1a938761c77e0e6edb0c93d02f4e988d44a69e5195e5a3b893e5553311347132 \ + --hash=sha256:1c9f3c25df6c9d3bbae4f6fd3f514b1c5c740a2110f56ccf36069c85417e289c \ + --hash=sha256:1ca5ebe6d454f1e5496cf052386a559f1080bf2de75bf327ebca0a6003b79f19 \ + --hash=sha256:1d804e4caf5d5da37d6dac1325da5629ebef1e27a294c2b568b295814aa36c7b \ + --hash=sha256:1fee9a16d88a1c4865610de31ef5c666671020d7a81d1f510eaf3c97d00ebeba \ + --hash=sha256:23136f5a564654eb61061ec6d5620a4c1ea32c8f552b65e9982a12b72bff601b \ + --hash=sha256:2784090c30a586d5b45197bd9c32f87fb927216cde302f6cfd76d76577e90f08 \ + --hash=sha256:29138fef49828542e859828107e42e50d0e587c513b7eb4b2d92bade2b0860fe \ + --hash=sha256:2c1aeb92eea59d824f004341b26d5e4b47a8a441cf9726769b9a90abf9d0e08f \ + --hash=sha256:2c5d675da8f1cb5650271c8ad5e95c0a3e5a183c105e72d953b12877b1c8d0fd \ + --hash=sha256:3100d169ceb7bc8f05f89a6db11d1b21f119975fc26f29dc45a472e3569f0879 \ + --hash=sha256:31199204b3ced121ff5407a2c342326a5d27e3870abbf94bd80dbd2451b7bc8f \ + --hash=sha256:32217133dddc58c927805cf6c0731d8144584176b768042ee886d51e71860bc9 \ + --hash=sha256:33fa55b990f81c2927e01399ace0d18926c69d69baa8cdaa819424132fb97987 \ + --hash=sha256:35ba0263bae5dd3ad5aad767cc9afc01a8598c7dae30f1b3b2de98b1b32c28bd \ + --hash=sha256:35fc236507fb1b3138f0af5ecd5f94ed752d4d6d826248eae425f86204013eea \ + --hash=sha256:361f7206cf341ba94fb015688f5c8b480f8e63bd58a4c14a48aeca7851a241cc \ + --hash=sha256:369b5aa01b241cd3fea6890bdbb11a1425d87bf1515831500d518f4223e9d72c \ + --hash=sha256:37245ca4105386194dd1d292a6f2aae09bfe1bd7ac6f9ec25093e3cf8e9b143b \ + --hash=sha256:372c063f37480f62c1ae32dc3a1a0a5942b180c883f99789075a8a8ec3c4e709 \ + --hash=sha256:37a9ebe00c698279213d56e6c64e1962ab1e092918270649b397cac3dc196ca4 \ + --hash=sha256:38c9986f9ce50c459b10de216a05f4bd7ed5ac63887d56e500a52bb464b861ce \ + --hash=sha256:3adf06c66041aa21eeb8a71e82379b74773298c8e6d3d839b151aae441a99b94 \ + --hash=sha256:3c95601ed98fad3f6e2f8fe809c3b526b0fab31ef525e00a155e227f3d17f58a \ + --hash=sha256:40aec5299e1ed71fbb988389059da381c3c1a60e0c649acceb2a35d9b128848e \ + --hash=sha256:43124fe172ada86d03ac3c8dc8179091341f6724d5e5d5b160e1587e4cd3761b \ + --hash=sha256:4736d350371337825cac1793c9f7c40701c32a03912548c2a7608e51679cbb96 \ + --hash=sha256:475d04d5192eba487a3e2f935976340baa24529046e9c1c9c7a3b7bf80445ae1 \ + --hash=sha256:4a409ccc42aefec904038695d5d7fd6d8f3af2721b7b6401d55135ec7d6d298e \ + --hash=sha256:4d718fa1b5f0d0dd75e86fbbc5b0c93ea3a5d65216c85c61cd5d7cdddfe08455 \ + --hash=sha256:501ed8b02a5990c67a91c732843609d43a6be1f7576fcdfc867331239f37fbd3 \ + --hash=sha256:539c2cd5fed0947c135cd7eabaaac55f48300dfa1de0f3ca4edb5efa6606f471 \ + --hash=sha256:557a4e1708df428ebe6c3081c83a273d275dad2446ce0d81fc648ac71afdb18d \ + --hash=sha256:56d834b74c993a7d7cb2b8ab33a0d55c3e0d4a3d2f2da2808a4ad3d79189711b \ + --hash=sha256:5800368526647146978389dfaa46da3356291e9f0fff9a4ef12e8c2bef964a0d \ + --hash=sha256:59c123d0e948d760a5f930f316cfefa07e8d632ab84327c0693ee6a88171154f \ + --hash=sha256:5b30ddf7234e611ca877575b62840e6af5977f92f1f9d532eedbb05a44ff8004 \ + --hash=sha256:5ecace251ccfa705bf3d7d35c5032cf750f5c629809740405697bce5c118c4a4 \ + --hash=sha256:5f89dad732280e7a10b74d40b91364f88e13c3f2c08c2ef83a8cd42f7a61af2e \ + --hash=sha256:637f4ae36264bd7b8d9a60193acddc1d735ad52e8ed53a19931ea6d921fea8e5 \ + --hash=sha256:63ada7ee2e9345695f9e9bc4c65d72222253f07b1ac94fd0e37555cc6f3c7f60 \ + --hash=sha256:6441cc837aea58be7d9baef1b2383eb8311ab9303f500f99ac90b584cd78bb14 \ + --hash=sha256:658f90f49cf5af2441cad0a2b801c3ef520471989a1ec55bcb25b255b2ca8d2f \ + --hash=sha256:66987aa68b0f7c2a1cc5f388ca962b8ed92b10f79de38d6d0d8c716154f519d9 \ + --hash=sha256:696477ad71385c4795e3b8e4cf10b0d2c28c2a1ca6a955e031cb1e62993e9ee3 \ + --hash=sha256:6b7e54fd883671d1a8810704851c044b7173287c552b9f5c3d9e0eb9f00ae194 \ + --hash=sha256:6bc94fe17c3c56e5418f79515b786b101845f70609b0d19d0c1ba13448e5633a \ + --hash=sha256:6e6b7e3a1520c39a2772f414cd9ddf5995f77e4e823dfa1522af383addd465a3 \ + --hash=sha256:6ed30be8918e18c8bed0a2e8b70639ecf02feb61ed00ca2e41cfcb2a50fa3f42 \ + --hash=sha256:73533644e1f69ea1164d56cc6505f564c6c44072b646b66d67df2d31fed0348c \ + --hash=sha256:73bcafa21a78d0776b3ee7cd2a63c66f968eb7db8e8d594e32d7329950f6e828 \ + --hash=sha256:7814bbee202acd3bd240204c17d8b87a4c48c81064fd8674dbe527d94d5a4290 \ + --hash=sha256:783ba7d845d79ce976afd9c1e91a4e5714671defa198ee789e8b23316083a485 \ + --hash=sha256:79da2491348b30810728050b4a8ec0416f85884125c2fd44655b3d01150d9c3e \ + --hash=sha256:7a0c98f6a636adf0d7edd60c61589eaf52d149239af754d0bfeb0effedba53a8 \ + --hash=sha256:7ab379f95caee071a37cbd8be86d4c65accc651d391f9f97748fef006f38769c \ + --hash=sha256:7bf6478188f4e47bf5686e8a33da4ae28bf43b1b2528d9ee144d28492bfac60b \ + --hash=sha256:7c6eecfab7ce4cd9487ff8ba936fe38cdfd68c04faf3d5c710363c6a8e695659 \ + --hash=sha256:7c708566da8014b120a64b1eb6d200c6c0c8cb36296383723cdb6fc82038270b \ + --hash=sha256:7c8d5882ba25ac0282258be435d8a05aa0cbcacfce15799154a338f847f159b9 \ + --hash=sha256:7fc59e9ba821b220944ccfe0f89c9dc4745f6d097569992356eb03869f21e953 \ + --hash=sha256:7fd79c521f6290c69125fa2b85fa65d9e657e6a8ffaf722dc881b926bef4aa5c \ + --hash=sha256:803f8b575a71b1b299d677c28db0653459c79b5308874efec813f17b7457c7f1 \ + --hash=sha256:8050e75af7e4c6e2d5260b84eeedb618f3e452e66473432e085b5d1b81429299 \ + --hash=sha256:81cdc537e0a42e3c0170752fcadbe450246d5c3b4b7231d6eb9672456605ac94 \ + --hash=sha256:827c92145b3b976b39430129c89d213b250dacbe5fce678e9a03940e6e848983 \ + --hash=sha256:854fd2f1bc6e8a56b89910b5cd7261a8b40f13ebb31572da985ce59c7da0886d \ + --hash=sha256:877ca17fdcfdf5c397493a71e5ff97a87bb181417fe717fdadc77c08c09301ac \ + --hash=sha256:87cc632c88ee5dc80e12681047839304d98ee5c9a708d686505767001c9b8b9a \ + --hash=sha256:8879510a76940670517ea1cb589978da44b86e286ec3e50d664ef330817afce7 \ + --hash=sha256:8885e3808aedbd6725b921fb67dacaae0678933561ddd47c2b01315198c70e2e \ + --hash=sha256:8b193bf7a443c97d81c47052f60c486071a4bdef4a573fa2514f920089414d45 \ + --hash=sha256:8ed78ccad4c7b421804f5d524b7740946a7ef75d89dc0dac52e9d7c24c472410 \ + --hash=sha256:8f2973bbd2bebd9d2e0cd6394c1292a1a19ccd56bdcbe1e174059f1a39be5b40 \ + --hash=sha256:910d4260512660484c0dc1588a316fbb35a40c081c36fc51d1225351af17cfe4 \ + --hash=sha256:95052e8777a86bae87c0bd0b5ab22d809e3d1d02bf69e3e66ddda5ba75a05805 \ + --hash=sha256:95f273bea318a194f656527ee2ed19494327bc500b8e87d9358e3222579aa28d \ + --hash=sha256:963a8d8f97057082679523d0fd4c53a38f86bc58cabe4556faef682ae53fa2fa \ + --hash=sha256:976fd7689d69ec78d67d31d38d396d8adb562f7e8368279f76aed4aa451fa06d \ + --hash=sha256:989261c5f1735a165f2e4e87cf6d5f17ab734fa18f9ad0383d5adfcdaefce701 \ + --hash=sha256:9ae9614c317c50836689ce2dfde07c05fe0b16378562e2221746c3913ede3c80 \ + --hash=sha256:9b0124b9c17e9890f0819b2e7a5f65ec9a2f5aabd6c8e7ad090c1675cf70dee6 \ + --hash=sha256:9c4880d017555d70dea367dd49271830842d48e3891c2da97da7ce8c4abcee40 \ + --hash=sha256:9c62e71e6289d78c0108d8aeb495f8bd3cad4bc1632fedddc9297ddf287ecc20 \ + --hash=sha256:9d0a21cf76153de8f2d96a877991d6bc59b9ab5180b949e50db73cc193b4a694 \ + --hash=sha256:9e14d17773b1b3c758ff153659a1824608a0cb562c45f484b5ed8a433428444a \ + --hash=sha256:a16a1dc8529f9e734a41c3b856f3eae7ebacdc061dde3f8a844e0c7889c97203 \ + --hash=sha256:a2212a0c842c723d919ea4a22a9296cb6b244b386e4e6ea92adfc7fbf3095519 \ + --hash=sha256:a313bad717dde740959d50850c315b75fd4eb0c5e6b4dc8535db0f1c369be125 \ + --hash=sha256:a32b78c1e52ebd8e247bb68300b90b233300d8816faa008ed0713bc539fb6af0 \ + --hash=sha256:a3ffe881246d28a862f1985824f484cb7361f44d6b99c4c620436ef56462f38d \ + --hash=sha256:a49ff5cdb33654cb7d6a3c377aa2a83ddefaa1db31eb10bcf3c180aa84f9af8a \ + --hash=sha256:a8b75dd3d3638d9a19f23e84af4ffab3b8940422c0df2da2a77005ef5aa3d7ea \ + --hash=sha256:ab64ace1a68682d191d9bedd9d4c939406ad86b1d9f628180410644249ad46c2 \ + --hash=sha256:abc7c2e4b47bfe6a9aea434d3fdebb9597ee636e914e92ba352f2068b9142f4c \ + --hash=sha256:ac348379cf4de5538a0a213be1532d289aa801ec5d267c5909446b9ea2f8e2c3 \ + --hash=sha256:ac51cd64bae51c462ea58ad2492c9b8209667a4ef60c45c4a304518b67598d5d \ + --hash=sha256:acddcac38adc8342ba48aba98896faa7928854bebb62542362138655b5367ee3 \ + --hash=sha256:ad4528cdce058b684f75fad1faf4a6a6c992fe2f08376370ca66e4ce5916a84a \ + --hash=sha256:aec65b53a07f580606593f877eefbb29a45939bfc0d3fe6e6d9f42b41b749f68 \ + --hash=sha256:aef74e9beabbd6c4aafc091dabff86d046ccf013ce1e4396c0fbb01b4cad9de8 \ + --hash=sha256:af1b5a92315048c3e36bbebfa7d4760a9c3e910bc4166f11b20d77d20d6bcfca \ + --hash=sha256:b22ff30006a2f28f8bff878fb93413cbe3a4d1fd517c28081d848c90e9cfd2c8 \ + --hash=sha256:b2483da477932ad1983d1d33c18bc3771c6fb00cfbaaed70a875fd547ef8e840 \ + --hash=sha256:b2f0adc22a4eb31e545221d93fc73a0f6a8cc2379d0f4309f71d1d17ba938b82 \ + --hash=sha256:b4c9e5d05b126b267ac048a89a0e2d9b48b1b648add62d4872906304a8590610 \ + --hash=sha256:b4da208a63434d21a3df64d29758e650fc4aa8cb05848554b76949c296539cca \ + --hash=sha256:b5f8771aaaed7f80e84a4e471d2f29ab6721e4595075e54d03ae1ed951b2000a \ + --hash=sha256:b65121091567847a8cb520d364ab22ba90e00d3cc55fa9eb34bb439f0684bcd1 \ + --hash=sha256:b66ccc5c2cdd26e74fa5d4c29ffae424cc6148bf93ce574821783fb3b6d452c5 \ + --hash=sha256:b69651732c64afb691e50cdc3387cae305e0eeff8804fe3e3ce203876494932a \ + --hash=sha256:b828cf64d62dc09ac183f03c1aeedd164ade96a2ce4934109452edf29de1dd13 \ + --hash=sha256:b8a65621b98984a62e59403009591b8a5a7736273aefe1cab64cfb85b365cc07 \ + --hash=sha256:bb0d664505f4b112f384cffeee82e91e3f6448d8e574989479db4439b68cba05 \ + --hash=sha256:bb58ba73a3f96f9a3e46b1fab69929d7edbbddb3133ee74b5c3c54074a53c4f1 \ + --hash=sha256:bc94a68ea5e18f8e85dc6b522bcb53093f692c8eb62b4837ac047da73956cbe4 \ + --hash=sha256:bd82c4977196681a499bb6ca9e462afbc5c91c1c15b6a991dfbd72733fea4dd2 \ + --hash=sha256:c0c88085affd35c33e124e36930c5ad96aff9294ce195eaa0fd9cec962b64a82 \ + --hash=sha256:c148e8b596000dd3e4bfe206e70f3e666be18d72032e0012555f2373c52e35d6 \ + --hash=sha256:c57541034d12b215ab0a2bfa371d1a8a198da18176d0426c27105b9161a6862d \ + --hash=sha256:c9648ed33dc8179e4ec04bbc73bd7f0038e1e81217a69467f61f02a78bf07e88 \ + --hash=sha256:ca65cced0d67a9039e93bcd98a369920e499bf98296844ff56ead01c9085321f \ + --hash=sha256:cf22b43f35b7dbb9f71e8ee2041b5c00029cdfc28ede3a2f31cf8906f9a6c126 \ + --hash=sha256:d35a4f1c63f07fbb8c8f9946dea98b21eddf6c57421585f71d91864be3ba2a24 \ + --hash=sha256:d3b6e6840421c83ccb60398e333b44f910b0907bb409597685ab2eedd1e22eab \ + --hash=sha256:d73fed4e37158ff00cd271871170b79e40138db51e625fd352fa17c6acb34f67 \ + --hash=sha256:d7bf9e43282d69561618e8a0ea33368d532ebef42f15c096f427090521dd74f3 \ + --hash=sha256:d9d6544790ba50438a9c1a903c3c4afb1ec8a7832db5518549275b40ef0dd4b1 \ + --hash=sha256:db4d697b18b6ef5528b1f36bfa25072cd2a421869f5963bc0e92c8a34b9e2800 \ + --hash=sha256:dd9a137a4a9becda3094f3831cd026380f75f6855e051eefe4c73ade524f1cc3 \ + --hash=sha256:de7738b8c0bb74c4cc16bbd7fb49fc2bcf6430dba11b3432cd52768ae40933e8 \ + --hash=sha256:e3b1aa25f01238886a6baed9e13b9a9240ed344346c79ae280ae65e8603b21d5 \ + --hash=sha256:e58952f04772f59f11c6e007471449809a30165188669bca8fdb19dde40a8f24 \ + --hash=sha256:e5ccad4b7bac125722f48d6f862bed3b514d8526deea06316bb72f152cd30a7c \ + --hash=sha256:e7386aa18d98d6b8af44b92173654ec469237fda35f8e8523e43b581a86f476a \ + --hash=sha256:e81ae656b9935ac4528a71f96bb7a14d949778ed1897c573d3e7ebb9187f8841 \ + --hash=sha256:e8f1e362c9352b50ed120f001046fdbb80810c9d56580f4c3fc13bbe30823387 \ + --hash=sha256:e96ca64383efa107262ee3949f047af5ee4f1845ba09463466c04d35a83bd3ec \ + --hash=sha256:ea999ae6e80e66ad5eea287860951b033d0104ca34d6d87c7b5125ebe0e12721 \ + --hash=sha256:ecc89dbd4155b2f8a47f4bbd89242a35ed15e8e0ec581cab5ac65fa38407329d \ + --hash=sha256:ef01d29fca550ab871fd99154f82c6472aacf8e7def272dfb07b460123850390 \ + --hash=sha256:f04551dce5a7db8c9659f2e4245494c182d0663b83661803e08d46bfcae5eda1 \ + --hash=sha256:f0700527dd5bfa8b7204b08330542f4f388899d3c14d885d8a368992e0eb562d \ + --hash=sha256:f2524ec55b3e65cbe235a8b3c36e2af3b635be02ed05e20c94e70c5c943c009e \ + --hash=sha256:f5844e7befc707367807586f550fa97e23dcfef0728f02b98c7bc498a961a5df \ + --hash=sha256:f9dad513626a33670f17cddc6078e30e311f444c957e8dbfc5b2b4603c8b4edb \ + --hash=sha256:fc0dcb22fa9aeabfe3fa4e0430099acff985ec5d77a851382f76cc6146e780e5 \ + --hash=sha256:fd882aa29bf402b62bf1fd7c19fd5df4b6528cf468a908864b39368572b662a9 + # via + # aiobotocore + # aiohttp + # yarl +opentelemetry-api==1.45.2 \ + --hash=sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34 \ + --hash=sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4 + # via + # -r requirements.in + # opentelemetry-exporter-http-transport + # opentelemetry-exporter-otlp-proto-http + # opentelemetry-sdk + # opentelemetry-semantic-conventions +opentelemetry-exporter-http-transport==0.66b2 \ + --hash=sha256:66d6ed810a515432c8891da9a834464332fd70badeca45bdeeae81b4280c903b \ + --hash=sha256:fd5f5b490c099acda1cd7b909d5e8981436bf18cc8c6098d302d114c271720e9 + # via opentelemetry-exporter-otlp-proto-http +opentelemetry-exporter-otlp-common==0.66b2 \ + --hash=sha256:06f5a9b88638e310efa1f1d206cdf6b75393e112aba4e174a963416192bd1028 \ + --hash=sha256:ace86efb75489f925f1ef809856ae5f0c7db534e4afdc624530222228b1236a5 + # via opentelemetry-exporter-otlp-proto-http +opentelemetry-exporter-otlp-proto-common==1.45.2 \ + --hash=sha256:af483b24217028892f017096731b794b196b785025d2e6808874720fd0b05a80 \ + --hash=sha256:f1f2806f3f28ce7938033823e50934fcd91595a39de38e69a28a51e19f40fc6d + # via opentelemetry-exporter-otlp-proto-http +opentelemetry-exporter-otlp-proto-http==1.45.2 \ + --hash=sha256:5984a3fb46bc4628e4e2b85d4a6e72637e03962aae6cf372791137768a4ad939 \ + --hash=sha256:6e4d025138829d0ee57946930c2ccad6491ad4d92a958e9c7eea69278fe60cfc + # via -r requirements.in +opentelemetry-proto==1.45.2 \ + --hash=sha256:03a7ca1b43f89fd5b965d5975902bb2515c0c86e2428b456836e9a6149c6235a \ + --hash=sha256:bd8d23cf770605b0af9b7be2071d26a464fea289d35429abfd2a66226114ad64 + # via + # opentelemetry-exporter-otlp-proto-common + # opentelemetry-exporter-otlp-proto-http +opentelemetry-sdk==1.45.2 \ + --hash=sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d \ + --hash=sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6 + # via + # -r requirements.in + # opentelemetry-exporter-otlp-common + # opentelemetry-exporter-otlp-proto-http +opentelemetry-semantic-conventions==0.66b2 \ + --hash=sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8 \ + --hash=sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976 + # via opentelemetry-sdk +pamqp==3.3.0 \ + --hash=sha256:40b8795bd4efcf2b0f8821c1de83d12ca16d5760f4507836267fd7a02b06763b \ + --hash=sha256:c901a684794157ae39b52cbf700db8c9aae7a470f13528b9d7b4e5f7202f8eb0 + # via aiormq +pillow==12.3.0 \ + --hash=sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756 \ + --hash=sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a \ + --hash=sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59 \ + --hash=sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45 \ + --hash=sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3 \ + --hash=sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df \ + --hash=sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139 \ + --hash=sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b \ + --hash=sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39 \ + --hash=sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e \ + --hash=sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8 \ + --hash=sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1 \ + --hash=sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8 \ + --hash=sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89 \ + --hash=sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5 \ + --hash=sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130 \ + --hash=sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd \ + --hash=sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d \ + --hash=sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b \ + --hash=sha256:25b9b82bb22e6e2b3cd07b39c68b7b862001226cb3dff7130d1cb914121b39ed \ + --hash=sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace \ + --hash=sha256:300557495eb45ebb8aec96c2da9c4be642fbf7cd937278b4013ba894ea8eb0eb \ + --hash=sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931 \ + --hash=sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510 \ + --hash=sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6 \ + --hash=sha256:37dc8f7bbb66efe481bb60defacef820c950c24713fb44962ed6aa2a50966de1 \ + --hash=sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce \ + --hash=sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385 \ + --hash=sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e \ + --hash=sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c \ + --hash=sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7 \ + --hash=sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace \ + --hash=sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c \ + --hash=sha256:514435a37670e3e5e08f3945b68718b6ed329bb84367777e16f9f4dfe1e61a0f \ + --hash=sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64 \ + --hash=sha256:5594fc43d548a7ed94949d139aa1341b270f1863f11cfd37f5a6c8b778a6b67f \ + --hash=sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a \ + --hash=sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827 \ + --hash=sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17 \ + --hash=sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4 \ + --hash=sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a \ + --hash=sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701 \ + --hash=sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e \ + --hash=sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91 \ + --hash=sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66 \ + --hash=sha256:85f998ea1848bc6757289e739cfbdda3a04adfd58b02fc018ce54d754a5ce468 \ + --hash=sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217 \ + --hash=sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658 \ + --hash=sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418 \ + --hash=sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a \ + --hash=sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c \ + --hash=sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330 \ + --hash=sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402 \ + --hash=sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09 \ + --hash=sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930 \ + --hash=sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f \ + --hash=sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec \ + --hash=sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a \ + --hash=sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94 \ + --hash=sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468 \ + --hash=sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b \ + --hash=sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965 \ + --hash=sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8 \ + --hash=sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd \ + --hash=sha256:bcc33feacfaefce60c12fd500a277533bdc02b10a19f7f6d348763d8140bbba7 \ + --hash=sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c \ + --hash=sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777 \ + --hash=sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35 \ + --hash=sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9 \ + --hash=sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f \ + --hash=sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f \ + --hash=sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0 \ + --hash=sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c \ + --hash=sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71 \ + --hash=sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3 \ + --hash=sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838 \ + --hash=sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf \ + --hash=sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321 \ + --hash=sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26 \ + --hash=sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ec \ + --hash=sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9 \ + --hash=sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65 \ + --hash=sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5 \ + --hash=sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e \ + --hash=sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d \ + --hash=sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198 \ + --hash=sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7 + # via -r requirements.in +propcache==0.5.4 \ + --hash=sha256:004e685b315646c410771836e72a44f143bbe624f29653a42687815069a303d5 \ + --hash=sha256:02c0a34f16889cf800f10f0247a564d8ce6eeab6ffcd7c87198f769067eb8432 \ + --hash=sha256:03969626faf0783a592dfa17e28eac06018bd0b44dafae6943d53b92421a7f72 \ + --hash=sha256:03b229037d25b801e7af53fd52b9fc49d9439b036fca1e087e02780631adfa97 \ + --hash=sha256:0951315a6b3142ee2167404d707743f0157c110091342b1aa0accac5cf0e4acf \ + --hash=sha256:0a095db8e15a6020db149ecbed6461939fe74f6acaa3ae8b702a1fe8c38cd983 \ + --hash=sha256:0c889f6fa84957bc7e8b4eab71fd16a0455068d5045e3aa40c733071d2b2fd77 \ + --hash=sha256:0d21d0d2c82bbfeb1677a9711f38df968f9837576102bb4add1bd449d28d88f1 \ + --hash=sha256:10ef33a68a61ce317e095fd2e202a592ea92392b90944a78c993f0d9a73ab06c \ + --hash=sha256:12682126712ddc19b70ff819debbd279e58adf1f0c8f8f8138c18ade2044b284 \ + --hash=sha256:135036c5cfc93864affb0f9af9a27e5d7a71cb7bd745e7b6dbfc2d56cc30e827 \ + --hash=sha256:13e52b6e0bde97dee98ab66552dbff2931649c96f1ac432eac299fe689ec373b \ + --hash=sha256:141fdbd73748db0cf7636035030aaac383d2efde8f34e7bc24594cc776d225b8 \ + --hash=sha256:146f48a9e4812611a7581003b1a39de56c34967046310c4171a68ef908c9a745 \ + --hash=sha256:174507f82d3594622acb1dd2dafecf2d899d6d506335494e7107767bf05f3aae \ + --hash=sha256:1783582065a1f07f9d9ee1e992e13f15d7dc8fb1eb3a7476d43eb3f2e69d26bb \ + --hash=sha256:17a7400cec0256f0a71ae71f9da398f9894c956ff6668a1c9d317b3367316320 \ + --hash=sha256:1b2f3bec4261a94019575481c726c29850f72e27907773c75b1de421e20e9f9d \ + --hash=sha256:1d759d05634f1b038fb625a66662a8c85e5a8fec912da381b5149ddac107482b \ + --hash=sha256:1df8d8561b21465c5dd56110a01caf897e026d065b4b84e98a488209094272ec \ + --hash=sha256:213bb68d9ced5cf2bf717b1071bf2b09b4b04c426256f9fe6d054c60318424c4 \ + --hash=sha256:23278f808cd81d5ada7184a76606b925fb3389c60e1077b2cd7da7b1fcf0553c \ + --hash=sha256:251c63dd46a0659bb875cb254dc4c1e79ee91a847c737cd62373295afc2235dc \ + --hash=sha256:279655a16973f1ee2bd2fe79973137681642fd9ae0d89215bba263726eb0dc3a \ + --hash=sha256:2814ecd8e818f487bee4b0f921bc4d1c176cc5fc71ac0f072d0fa67eda4ac14b \ + --hash=sha256:286867fb156488c251a3721766e380ac4495e4fd6b51aaa1403d89ce7f4359d9 \ + --hash=sha256:2dba2f02d2d5c09ef8a0e6c1a42aeaa451f4be9898cb00b04fe98717da2eb23b \ + --hash=sha256:30cc1cebaf9aef49db06357a50398323ae04d70460c0491837d026ab7d6452ea \ + --hash=sha256:31eb43ba2edc704ab2ec27815315dd8a19def0fb16215be4cfe8d32fe78ffd51 \ + --hash=sha256:350b272b2279f4135a64fc0c304a5d08e28a137c9573442c606152446638a831 \ + --hash=sha256:36c0d9db44b523ef93d03341b1c42d69ff01d673c053d1b1c6c3a363bcaa39ba \ + --hash=sha256:3af0c8642b2da4815d86e631232ac8286e17644fad907c19508aa8e7cb4ba8ad \ + --hash=sha256:3cd3a7edb6b95b9b33998135ebfa18d709da82290fb8f27c858970b5a12c8b56 \ + --hash=sha256:3d605bb239b796e82a81c6709548b2bd460ab73b4590cb0c83de8a2dd9694d0f \ + --hash=sha256:3e413d7a4a9b4866b7a761d6060d434b64d23cd35122eda3b026a0bbe8196b25 \ + --hash=sha256:3eb2e820e8e2101407da93f17c57cbb7d225461955fc60105daaba14cd421ee2 \ + --hash=sha256:3fa15757fea1dfcd5b7745cad9f4638929605531bd4018ab2adff7955f1a403d \ + --hash=sha256:3fc24f209c1b7f7f688b66b98293954f5504279760999b58920ee12dd8471c1d \ + --hash=sha256:4054acf80d40456a0537f2913b349718649d8d6458a14ab7f48d0ce28c30869d \ + --hash=sha256:40e94adb1e7d39ff28a8bd8d8b8fbd1df6b9f40976dbe379134f1ce058e532dd \ + --hash=sha256:420162a77f94eb1cf5ef7893f500016dabd548e73de956785a1dd899cc73006a \ + --hash=sha256:425f8cc86ab5018b4b8d4a23bc8e74d964bd3d757c3702e301aa79be76c53f6c \ + --hash=sha256:44149f46500a0a41b95b4d99c2e586a77319539730607b9892974a092788b111 \ + --hash=sha256:445ee3bfb46e85838387fb3c536a73cc0b994dc192b004e40e170adc54aa2a7e \ + --hash=sha256:45488d1a5f9ab5bd90aaa1ca20f50fe1922b8ffad71a2009d2adf41355897aac \ + --hash=sha256:45bebbe252550fec975ba3b62bc6f931643cfd3b5464ef47619cf3fef154e01c \ + --hash=sha256:45bf2e730ab8905d0527fe05a86500f406e64305c34cc81ebe64b4617cab9760 \ + --hash=sha256:48cb48c5346a97de792254af77715aa2529c2a1ebc5f586aa0aae44a02f1fe57 \ + --hash=sha256:4a1f4f5ffa55dce6307631f3cb2948e117e665966ea512e0d502b16c24f567e7 \ + --hash=sha256:4cfe0a92ae30151869e67a4b5f5e105e4e03ad30b3f38e5211b5bf77d0881993 \ + --hash=sha256:4d86476a935c88963d9b8e1a9a0d38188790e9622169bfbafa173046846709d3 \ + --hash=sha256:4e985382be6d15da8d0c2710a6fa7b9070fc9ecdeefb7f580e88373984ec8be3 \ + --hash=sha256:4f2d880ff60f45898f4acfa152aac8d04e3ee627d90ff4003491bf92239d5757 \ + --hash=sha256:4fbc1a15dc8cd1689508758d626b372b1f09d28d9577667feaf9e6bfcd8efcbc \ + --hash=sha256:50e337653721d20ead710da33bf44487fbe8a0db8782714b60306481e9f95b51 \ + --hash=sha256:53eaa697c4d0422ff4cb714d00231b43352064d97b944033b30c1d57cc506ec0 \ + --hash=sha256:56fc3f7599528db40b1efa0889a620116e2704144495273d66066e8164e45838 \ + --hash=sha256:58134228927cee6c047d626c08e60a81be604a20578a12ce752cc5c9a84d4826 \ + --hash=sha256:594eb4c6ec35e7179b058481f4e9f02521b56de16fa577c4b85c76fb1bf8a9f8 \ + --hash=sha256:5cacf3c9efd09df409dc33654dd077e1c245ba8fb747b0f0236ef41b7c49b589 \ + --hash=sha256:60a64cbccaa11b7760ce705a14ada17ba459e7ca9f23ba587eb013821032d7ef \ + --hash=sha256:62530ca89187827e4a4fe733f971abe81a7542eeea48ff61995f19b64d7199c8 \ + --hash=sha256:62c60aec739ed00124573cce1178138fd690c7676352d67a37328c1cf51d7468 \ + --hash=sha256:69fc35c0779522da366c563e5faf203ffc1f8ff0021d5b1337fa4efa5be73177 \ + --hash=sha256:6af4693716bfb03f1752ef1b30faa593db2c01d5272e9b8564a1549452a979ab \ + --hash=sha256:6c7599df2b57ebeea8de011b5f2f7b85de95e76037d43d34b95e328430275487 \ + --hash=sha256:6e9368e87a3efc285e559131092c5db643eb8e56de4ee42064d5baec22ef2bb5 \ + --hash=sha256:6f0093ac3e9daada202c2082439d414a625c57184727a46e112a3fb2a81cb788 \ + --hash=sha256:7177c43eddf10a0893c4fec52ebb408fdcd7f7d63962caace9180d8f81b14ece \ + --hash=sha256:720cf832eb2d0b0dfee129cb3335a26f6ce3cc45ee1187e8f0731758caa16792 \ + --hash=sha256:770e8209d018175fc0063936fa9583b6d27e88c5ad31543f3383d66080efdd62 \ + --hash=sha256:7a8d5ff04eb1f85698a78d20c62a14676e7b960dcafde09a388d60ad377d355d \ + --hash=sha256:7b9100a93b372418d8688f3f2a3e5b45c64d70ca4d6176e121aca1e3bfc1e32f \ + --hash=sha256:7cc528e760a8af06f2b13e9b9f362cd90c7c718ea61228a96dbd31ba16ed7f47 \ + --hash=sha256:7ffafcbfc7b549ab940047e505c831eabac5e67de53e1bc174adbc5285c55944 \ + --hash=sha256:87a3caecf8095e48dc72f84bfa42e23a848cf410cc9cc13031fba4869b706a21 \ + --hash=sha256:886b59c4d28ca97dd23b025fdfc50a0356be934efbbbca89ad26230067f86fe5 \ + --hash=sha256:8876b39961e33d912afe3c1bee18ee564fdad0206f873cc15d522756b7f50737 \ + --hash=sha256:897d1ddf6716e8f47200f7aad9a0efa6cc7586df66c6defa572f9eab379c078e \ + --hash=sha256:8a1fc236528c457cd739c88abe823da851b7ab645d72792f88658114cc340c12 \ + --hash=sha256:8a235f73d6e020855dc29dff012d920c02ee0feab8d73a24185a7569f4be1161 \ + --hash=sha256:8f911c395cef73c510bac566da9507bb6a43e7763d0c79138dc60ee53f11207e \ + --hash=sha256:96f7c5c15656040ddcbc51e56dc59b58aa25999d743c126abd425b9766ab43e9 \ + --hash=sha256:978f28401afbc76cdc3df9e1717b4229a06b626a1dcc75db4e1f2beb3884c3e9 \ + --hash=sha256:98914de2c4d7f0f9f4a8c6ea4bf05841f4175796941e3ef7d47eb718f22311fb \ + --hash=sha256:9a2a8a50a93dee0268a860a07fa3b4bd968f8ce4dbd794957da772f395368526 \ + --hash=sha256:9cbfff4423eef4cc6cafc021469641a2b835f610b2647a6c5281903e21b8670d \ + --hash=sha256:9e9ab13760aa8b6d0881ae7cb04fd891d8d490cd2554ea8e79bb278399169bcc \ + --hash=sha256:9f3551b8a35c1df3e7ea4d2d86edee15f0dde1bddd434a71744048683544d0ef \ + --hash=sha256:9f86f7259efe2c951f43e57d471c9b41daa5bfc7db9f67189059cf1ae6d77fd9 \ + --hash=sha256:9fb0a5be8d9aa213150e8d8148a42aca4984b285bcad1e69587dc4298edd929b \ + --hash=sha256:a219f0ac59817a9114dd2aa57c13180f993e819ba658c7ddab4b66ed1ee0d370 \ + --hash=sha256:a419ee85e654927baabda3929c03c0cc1112bf472ff0dfd6142f4e3a81ca4162 \ + --hash=sha256:a4d7a54719b67338a305dca2ce6aafe366817df94ddfd4b5514374356f5ca546 \ + --hash=sha256:a5793c7698a53f56f4a1889a4737c7eeb1b7ad0842fa6b1abca22913ff79c8c1 \ + --hash=sha256:a5e8ef588c109725dc713ba69aadcac00a1ef90c2ce9c0a8c7075128f569f47f \ + --hash=sha256:a74bfa37147cc08fb29df10bd9c16f40fa7f860cd3a6d2fff853323a94f6e17f \ + --hash=sha256:ada748108a43d29b7c328ba7db3755327cd94f028bcc1a7ee3f0addcfacd9c38 \ + --hash=sha256:ae58f361bd5dae942717c65d3413b478c70aea9c462599e7b9adad3731db3894 \ + --hash=sha256:b28f41fa3b8c6900457f858ec5b03998f3a6d535fbc1bb2edec5961ea05ec429 \ + --hash=sha256:b3083bfe87f95c756e610bd8025f26cbd1cd4aaa03a422f2d65efb7a97cd53d8 \ + --hash=sha256:b61805357d966680acf68b3b6d49772631ed9df44ebece10ff1460e117a7da8a \ + --hash=sha256:b77c313314524ca9c38fbd70f73515d04597ac58c40c939bc0e71eeb4abff680 \ + --hash=sha256:bee7d3aed13d56f54e681df38c3a23031bc9e3863f687d9d598825c9146acd7d \ + --hash=sha256:c02c0e570c5c7e077b0181a9f3cdb7d4c3617d1cda6b5c95bd5d34022923d82c \ + --hash=sha256:c174bfd1c48a1b51a3078e95586dde718374bac79719ab3541ec9e74aec40574 \ + --hash=sha256:c2ba30a89035b57b73e00475de948521602f543d79ce01db10b04b36c4c76fc8 \ + --hash=sha256:c3e98c55bde2bcf7db3c70d1aed7ae9aa8aebbf19a250c66645cde44cdb8b867 \ + --hash=sha256:c3ef2818d63bc86071e9d2989ae75a1bc32b8f7059cfd9f5abbbee70c32e2ed6 \ + --hash=sha256:c83acbce9f2b5e3f5f5eda9e53d2001fed22fcdfef81274a9e02d8fd53b70a30 \ + --hash=sha256:c9281e922c072158c91974d4589f1dbe0fee6d467f284c28e463f9f5a4d933f4 \ + --hash=sha256:cc07876cfb079b6f6f36d21ce75784ad6c2c6b563eeac0ed26c2fa2669b85df9 \ + --hash=sha256:ccf4f7a79e26bb7efb06ecd50c177833b71df05cbc748701372325e6bcc17f6f \ + --hash=sha256:cdee8205a44d0be91bbac4c41b95d86641b72dfc7aef1279400e4fda3f26a937 \ + --hash=sha256:ceb3e879afac028f93d272c957814695dc5569e4904262dbee92f6c41bd5e4a3 \ + --hash=sha256:d1f5a500bfcbb2c0ab85e98a0dcd70f5899d34efe365a0187700369a79603031 \ + --hash=sha256:d42a9a856a4a6e2f6c10f1318c07e7daa498d6593abe745c71dae4521a26ca39 \ + --hash=sha256:d83b12902eb8bce151259c86c03ba746600b2d994543de46e370cecf96c452f2 \ + --hash=sha256:d8e017eeb7482bed34cdb0d61cf2bcfc88d104bbab296a17cd16a6af8aabc70e \ + --hash=sha256:db3ae52ccc150dbc84704e9d642743897f3e1c54742ff34cacb661e52e3818a9 \ + --hash=sha256:dbab5f5ff6897c81f355d079010cdae85b02e5a0b518b5251523b8ad8ae9ac3c \ + --hash=sha256:dc4242ca653c9b30ab51c5f8193323e7bc0928f897ee9103201e59a43abcb72e \ + --hash=sha256:dcbf346a318a5e30063f547630b02bb787ce2f45b6368d5da143660b6a3835d8 \ + --hash=sha256:dd2ac8f5b643454c2cc6b6118b13da16e88f4a6434fc3ba61aca384029f04f36 \ + --hash=sha256:e1d52a05dc417279f7e5c7618c5dfbbc29923aaf9bc0a5c1802ddcebf54c61a0 \ + --hash=sha256:e6720ba44ad7e72174314d0e1fb0172494cff5c73a3a8a2159c3d2402ff15565 \ + --hash=sha256:e738ab81179510ce79b2eac9a6ecf47feffd9e76d1c72e403005dddb6e36c06c \ + --hash=sha256:e904d4d01f36bd6e197590be1533c44e06058771e0746dd073a8ebb3ef880858 \ + --hash=sha256:e9f165403b81fea7e89c932d89046a1e3d9a3a60e8d7ef2f249dccdcb0982bf5 \ + --hash=sha256:ec6a85f424afa8d23e0d9a094e5dbb6eda01da91c92b9183cd433768247ffc97 \ + --hash=sha256:ee19113bce2f3acd46432050688b70f61acd6857d75abb9ec96341b7e9ced123 \ + --hash=sha256:ef3b928d9c984322b5c44e6964d8dbc653da87d2d8ee1647fa6da43072e650a9 \ + --hash=sha256:f273dcf7149a50527c4fd1f55cfe9eac0f60753f5af544b4c9352578e20c0874 \ + --hash=sha256:f5470694918830da62fac9e69133b53d23b736d7070e587b27a4a2be37e08e68 \ + --hash=sha256:f574e460d1c8a08384a016fdb09ccf3543433263ed6b2f97104f979e64ea57c2 \ + --hash=sha256:f85915e00dcb1cd9f2f890ead064ed40a27df06f0db65be427b29482ae357572 \ + --hash=sha256:fc2461ecc45f17893f8207e73b46ea8ba93e33630e51cf4af3fbc21d47462b1a \ + --hash=sha256:ff6b113f50bc066a698db5d944d2c6dc7507168dd3341e255a8892fd0715a558 + # via + # aiohttp + # yarl +protobuf==7.36.2 \ + --hash=sha256:497d0463ff3316681da6c0b9e8d06cb465d61abce00b613ab42226175644d1bb \ + --hash=sha256:89f23aa53c24553a2416fd4fd1ec06f74fa42b14b546d8883128813f775bbfd2 \ + --hash=sha256:912c1221170e16c08d1f086762f563dd61ff83c18b5fa6652952dfaded66f728 \ + --hash=sha256:a300819d441e078a5608c0d3c709796bb548136058fda017ae51d425b44fd353 \ + --hash=sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e \ + --hash=sha256:cbc70b17ee27e28894c7fee8bb04be1abead49e936bc70eb60052531eee2079e \ + --hash=sha256:e11e1f0180583a2af89db6a2ecd9e8dc40aa6d2988ca175bfd0e6d12ea72d74e \ + --hash=sha256:f4fee11ec330d238b34a05c9b675f693c20415d1c5bd7d5320cc2f8a798eb9cf + # via + # googleapis-common-protos + # opentelemetry-proto +psycopg==3.3.6 \ + --hash=sha256:a1db9f7148b06a28606767efaca51fa6f9398c5c0a3810519be69d7000bdb631 \ + --hash=sha256:c081f2250df751a943036e42db6df4571c66cd0aabe8291a7a506512b12007d2 + # via -r requirements.in +psycopg-binary==3.3.6 \ + --hash=sha256:05a83ac9fd52b9bca7cb5ab04b3691163170bd16f53defa27216ea3aa07ee781 \ + --hash=sha256:0a52991594ac4db888c7d39bccef331797e30cb31a95cae02cf2607f83a42dc2 \ + --hash=sha256:0bf08b749cc144f33b44a91b78e3f71c60eb07963746a0df5a100b36ce3d7475 \ + --hash=sha256:0ebfad5d131de9f892ae9e70cc7616207768b6714b66a52d4612b8ceaf78b372 \ + --hash=sha256:1679a1cb93fbe5a6d1fd58d82cbddcc6fcb8c61446ba7cae6eb2a7b19bc585de \ + --hash=sha256:198a48e68cc99ccac03ba95ac857e73aa66f3bf6be77019fafb0832a05f7ad03 \ + --hash=sha256:1fbd30e537dab22cafdf080608f10148fe2a5f3a61294ddb5113caac8a623840 \ + --hash=sha256:289aadd6a00e151203c081f708348ec89f1e483c9b510ef4ac3981f847f01f79 \ + --hash=sha256:2f122603f36050937982abf9668d8bc4769a79f7c93a65013b1c49f1cab7b56b \ + --hash=sha256:303732e798fe6729f8e12021b9c96107df8e95ecec4dd487c67b98ec2a59435e \ + --hash=sha256:31cd942c23f613276b81a6e6598cefa12960058b0f46e1e874b540c793f6aca5 \ + --hash=sha256:366db6e97e66b37211475f20c4c1324a2dc0dd825e46d4e87f9d599304d276f9 \ + --hash=sha256:373704aea331d3f3e3402c125a1543f5875e2986ebb54f97d1647942161f803f \ + --hash=sha256:37d40450659401600e6d043ff586c89a71a69f33cbb8bcdba6cdb2569beecdbe \ + --hash=sha256:37e517c146b185f9c0c6e8d0a0ebbdeeeb67896af28466e032bc810d0c7dc7a7 \ + --hash=sha256:3af90f92769d8cc10f94515ee7a0aef36ea85ca733a0ce22858f6e0953f41138 \ + --hash=sha256:3c9e663b2e800e3218994cf948c11bcc2844e6491b34aa80d089baf6531827bf \ + --hash=sha256:3f84dab25e0385692ee13274c68678377e0b1a70ab9d14e56264cbf61f60c62d \ + --hash=sha256:4690cf67738f0e0e49a32aeec99bf0e4595cc2b4f1af984a4345394b1dcff91a \ + --hash=sha256:566dd827f17728efdf7d88a5b066f815170f6fdad13967ae952842d90e6aaa9f \ + --hash=sha256:5927b7ba63153cd8e9862987290a2b783a5c590daf2a4ef981700cc3569166d4 \ + --hash=sha256:5ad8f35e67cc16d1fad1fa8c88972dc9b3a3141ea67897399904edab96a301b6 \ + --hash=sha256:5ea8beeb5541780b4b50b462eeacbc4f594ce3b911dc20c81c75f267876f71d2 \ + --hash=sha256:5f598f19fa9a91540b5cee17932ffd227b7b53a481605bcc4573c0eafa647300 \ + --hash=sha256:612382ac3ed13651c7fa44b5fee9fbf7baaa2ddbc6f500391672682c5f1df9e0 \ + --hash=sha256:6ff05561e4a067d35507dc5c90f1deb2ec1c9703ac5cccc1bc26e08a197f9c5a \ + --hash=sha256:7308c93cf0b19bbaf8e6ff0a6ad50d3c442385739245fe15a8d593bf841734a6 \ + --hash=sha256:79a2a1c3449f6c3409427078ed1cec10de79f3023cb5f2504f0597d350ad46c7 \ + --hash=sha256:7beb3e41c9a1e509f3ed85263386588cbe3e975aa67be21f79f44fd35ffaeefc \ + --hash=sha256:86147cb5d140341c3363fb5bacce31f8d5543902a46699d3c536b101bbceaf9e \ + --hash=sha256:889e42acec10450185e0cdfb396f375e2c1a8d7737c114830a7fde4654f59e30 \ + --hash=sha256:910ace140e3e7b7596898d083f37a8fe90c5c40684252ad4e682364b2cd3deba \ + --hash=sha256:955e3dd94da361e052d2e49acf591017158dc8f8ed2c8a42c2e3943403c39dc2 \ + --hash=sha256:9892188bb15e5803beb51afe8a25add6b56be391a53058e8bca03b74e1e6bf22 \ + --hash=sha256:98c02090d88f2ebc0ec1e8da538f77d225ce0fffecf372aa39262e62a1b054ef \ + --hash=sha256:9b2f11794e017ce340934e35de46181c46ef71ec75ea3d85dd75cd836761c01e \ + --hash=sha256:a2e44a342d2aee40508e28a563d8961c39d9bbd8cae36d8578f0a3c6658aab0f \ + --hash=sha256:a4ee3bdd5468a725f2a4d9aab8a74b6d0279f768c8b5d3aeb102c5307ff3d59c \ + --hash=sha256:a5165300324efd5a772c48a88ab3a928513ab3979fca76553e62ee815f7b2b9c \ + --hash=sha256:a9348c5b43a3bb5ef8c2e89d5237c9c87eeafb01d338c84a7aebbc5cd0313299 \ + --hash=sha256:aa73160077345ec21b3f51e8e24b3de2e99586217e497629326eb9b2ea88c52e \ + --hash=sha256:ad1c785e784cfd87e8436c6b7702f2d321fc39601bbaf29bc63a41a867091638 \ + --hash=sha256:b3f75dee0f9afafabe4edc52c4842f1e1878ed2069bd05b22d6fe961e97e4dba \ + --hash=sha256:b599defe9190b17e9907c8b4d114c181e702c87efcd1b8a0ad40971cdcc4634a \ + --hash=sha256:b82491019b884d62318b5f30706c3d7e6d4e5a6cb7eabcb3edc0c1b0fdaceae9 \ + --hash=sha256:b8ece331509f7a975b90501f41e83ad905e4141753fedf3f2711b2bc70a8efbc \ + --hash=sha256:b979a42815410432420275412633960807178b1ce26591a16ce06e78a5bd4bb2 \ + --hash=sha256:be4f9b3c9338ac5dd217c5847e21521b396c8117f78dc420d495a5c49bbef874 \ + --hash=sha256:bf8c8481d026b85dd70c5fa7dde85b2333aed0b32a2602bcd38a900cbd78a49c \ + --hash=sha256:c61617eaae0112ca154da87ffb99b73af2c74067acac28dfb9a4455b019dff2e \ + --hash=sha256:c6d19cb4999d03231e8730a5f66c8f5068bc3b532677eb39dab0f600bff3e312 \ + --hash=sha256:c7753871eb57e6a5f4646f6168590c6653073dea5e9e720b201c8875332df4c8 \ + --hash=sha256:c7f92daa0d2a1c76f07264abddf8cbabd30152a2f09c3270e50f0c7efdf5dcac \ + --hash=sha256:cbd5f73073ed19c378d4c35499db1e3e703a5b1a324e521204065967bfaa7a18 \ + --hash=sha256:cec5ea900390897d0b46130f60bc2883bf19c314f9044235217c8be88b0ef269 \ + --hash=sha256:d636338c8f21b0df2f84657b00bc34f9313f826ef93f1155bc743607e4a0c5eb \ + --hash=sha256:dc75da5a20951049f7b773145f998f69d181adad9c58a0ff36e0cf1d73c10e10 \ + --hash=sha256:e23a66a763fbe83fcc210bc77c27e5a5ea380ebf091c06f34d8561b695e5a40f \ + --hash=sha256:e8cbb54454dbf1bbf2ff08dd7693e8d94ac94b1a20f70f4b3b813d52ecb5cbc1 \ + --hash=sha256:ee2c4728c691245e24501fcd7a97b5b381236b9985bc445bba88cdce7d1b5784 \ + --hash=sha256:f0535693ce476a722b718b002d5d2c27d47e71ca945276ac194409c98e74c492 \ + --hash=sha256:f19cc87343eaa55255e76b31259a570072ac95d6ae82c92dd34b97691f5e49dc \ + --hash=sha256:f21d057f3e5f5491067e5b292498073b73847d48799b099803fef100775fcc52 \ + --hash=sha256:f87dbdc42e78ee0f7ea180c03f8c78e80a949e373066629bd90fefff10552dff \ + --hash=sha256:fa34eb47969297471db7b7f193622c7e3ee839ec05abd05f1fe104d5b1b1dcf4 \ + --hash=sha256:fdccb3a0e184b03e9baa673b15a809cf36c339c85dbda0ebc25a698846dfbee8 + # via -r requirements.in +psycopg-pool==3.3.3 \ + --hash=sha256:9b9cd6a4fcec47a410f7e82d408540e7f77b478509e91b44c1a5457a13e5ff37 \ + --hash=sha256:df87b5d9d0ad7db37f6cdad4fa8ce113d250f5997f6db38e9a99192fb67f9e1d + # via -r requirements.in +pycparser==3.11 \ + --hash=sha256:51d5a8ba2be0bbe440b99d2112604c95bbbc3c2748a64260186c541e1729cd80 \ + --hash=sha256:d875f09c3507d00e1aba0eecc6dcadc1352f30fff09dc6bff2f1c2935e97c2bc + # via cffi +python-dateutil==2.9.0.post0 \ + --hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \ + --hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427 + # via + # aiobotocore + # botocore +redis==8.1.0 \ + --hash=sha256:6e1a19beef9225c83efd689c7e6b7da2d5215b1f42cd13b7fc3714d0a09c7b25 \ + --hash=sha256:a4fe1aac3d3b3cc791d4b3d5931c5a956045dc951ee74d1c913ee3ac4d2ee9fb + # via -r requirements.in +requests==2.34.2 \ + --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \ + --hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed + # via + # opentelemetry-exporter-http-transport + # opentelemetry-exporter-otlp-proto-http +six==1.17.0 \ + --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \ + --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81 + # via python-dateutil +starlette==1.7.0 \ + --hash=sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93e \ + --hash=sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d + # via -r requirements.in +typing-extensions==4.16.0 \ + --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \ + --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5 + # via + # anyio + # opentelemetry-api + # opentelemetry-exporter-otlp-proto-http + # opentelemetry-sdk + # opentelemetry-semantic-conventions + # psycopg-pool +urllib3==2.8.0 \ + --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \ + --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63 + # via + # botocore + # requests +uvicorn==0.54.0 \ + --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \ + --hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620 + # via -r requirements.in +uvloop==0.23.0 ; sys_platform != "win32" \ + --hash=sha256:0305871ac712f54b62af73f943dbf21ae3ce80a44bc0f0151424484affa85645 \ + --hash=sha256:090865d8ce7a03986755a3ce711b7dd0d4b44eb14ab74368b717f3fad1180208 \ + --hash=sha256:098a85e1393ef5202767b7e5fb41a32cd8bd81e6ee4af364c179801c4aa3f6d4 \ + --hash=sha256:0efdd55bddbd36bb2fcb842d64c0d5f6407c6958c68088cc25df8c09edc5b5fd \ + --hash=sha256:12634f15e6625f78b3f2922f91404c4d7173487eba11746764153f556e9852dc \ + --hash=sha256:1748321e3c59a14a75404b1ae8d5a8d81c4e201803ea0e14c1b6fd84421024b5 \ + --hash=sha256:19c64108b507cd0bc140e400e3396bacebd9d504956aa7726272bf6de7d9aabb \ + --hash=sha256:1e84575f11873c109cf3962ad0bdf679094466184125f4cadcc41a73febff41f \ + --hash=sha256:24c58ae4a83e93a04c504bcc678125e36a0bfc44af928ad69444880c60f187a5 \ + --hash=sha256:28d160f51ab4da3b187063652e643dea6831072add4adc1e6d62afbe73b6be27 \ + --hash=sha256:2dcff2d69be43e6559e5dad2c5a7a2dbfb60e05a77311b6c4b7a4a8123d86c65 \ + --hash=sha256:31e0cf90bc8fd88784f6802cdba968a51fb1aec1cc3feec74d862b2d371d1330 \ + --hash=sha256:378188efbb1524f2219d05246a3e1e5907217848d2882144dff59585f1b81d55 \ + --hash=sha256:42feced24b9b44b856c633eafb5cc5dec354972da55ce77598db6844c054bc7c \ + --hash=sha256:4448e9124537620f9c25d004c227bb5104440b58955c19bbd312d910af919a63 \ + --hash=sha256:4a08875543bbd4519faf30497506c9cda8a48470467ffdf967c7313c7a5981a8 \ + --hash=sha256:4b8e207c67d207a8608fec57e116511030af3495dc0109b8c333cf9cb412b16f \ + --hash=sha256:4bb7f5d0b62b5afaaaea2b7b60d508921c24b0fe39c22c1438bec1811ffe10ec \ + --hash=sha256:4f1798f56c6f4ba5ac11fa2869e5717926e4470d97a1dd42b4f59219d43b5027 \ + --hash=sha256:514698d3683189031dcbfdc31e87115992e5ce9e1b19fe5359941323f2df800c \ + --hash=sha256:53c2c5d7e2024e46776c2d90e6c637d01102126b61aaf5faa5edaf05f8b5722a \ + --hash=sha256:55d6f4135d914305929fe9e9c44d8b5383a9b3fa1bee3bfcf60ee97e01af07ea \ + --hash=sha256:5a2bbad3a63007f7e9524d4903ba04fee252557c2acd86f9a3d4f91786695254 \ + --hash=sha256:5a3e0f56ec19bfd9ad1605572878dd6ff7f01b325f4fc154812ae70d615c3aff \ + --hash=sha256:5bb9be71d9ee39b4359b832f9569518ec9bc08704194034e79e4958e6bc4d46d \ + --hash=sha256:60ec798c40a1810d282ee046f61ecac1c5675cb898763d9f08d97d53a5e00a81 \ + --hash=sha256:6b3cbc4f96ddfa1fb88a78a69dd851369825b7816d9702eee8c4461505ba172e \ + --hash=sha256:6c7ef4701a96553514b2688e342ef1bf2beae6cfd172d89a76c768292aabf405 \ + --hash=sha256:7337b06a9f9ed9ea3049f04b76f65819db9b19bb832ee598e97b388eadf25e5f \ + --hash=sha256:76345f51367fb1f23e08605c6efb18374f669be5b223658fbab6b17627950507 \ + --hash=sha256:7e35c9bc977760981693e1a7a51493b58ee5a501f9ebb1e547565ee40b6c6208 \ + --hash=sha256:80cac5cb90ed7b9b72a217a1d6982b15b829cdbd0ee6bc19b93e3a9e47fb0ac9 \ + --hash=sha256:8af88fe5c7dd68fe1fec6dea8155caa1a47155d219a750ff34049541cf536a5e \ + --hash=sha256:8fcd721113260ffb5e38bf14a8725b17d431f34209f7d1c7005b667946e630b3 \ + --hash=sha256:93087a845cdfb35753e539354ac9551bdd2ff528c202a98df0ae46e852bcf021 \ + --hash=sha256:93935ab27b6eaef4c3e5489aebc84284f0644592f7ab516df60ee1b27eaf5eb3 \ + --hash=sha256:9bf08e4b6362dd1c08623bbfa2d061e8bac0f1da8fc2007062cfe1dc360a49fa \ + --hash=sha256:a6ac96da66c35bf789bdcde78a88dc7d56b7907d8379648c54adc1c61594575d \ + --hash=sha256:ab17b3a8aa754be0de0e397f7b95f13b14e56f077a4c6ae295e3d4afd199b325 \ + --hash=sha256:b0d106d9314546d69b3df1b5352639aa628530ec3ecef8a98a21942d2a2a64f5 \ + --hash=sha256:b90397a50ad6332ed3e459c648ac20d182cce24a557354363ad85fc9ea4a17cd \ + --hash=sha256:bbbdb8fcd5e7062e546eec1ac78c28bb21ae7df54c18f8e4b06e15a18d661a49 \ + --hash=sha256:bd6f2f81c7b9da99d301c0b16b82044e76fe887086e42e1590ecf520b94dbdac \ + --hash=sha256:be53e1d5f83de43dc175c87612ecc128d444b38e5c56cb3f807f5a73d6887476 \ + --hash=sha256:c3f23f403a273900d57de6ee5ca0614c650f7f58563065dad1a4744498960e53 \ + --hash=sha256:cbe8d03d4efcccdb7fcedecbaa1e1fa02913eaf3a74cb933634a6bc6d2ea9e2a \ + --hash=sha256:ce17bc317d089f361b33521654c13e30eacfd3d2034fd34e613ca9c51c969686 \ + --hash=sha256:d918d6f304a309222a784bbd140b85ec5594d97e4dc0e79f590549d28970663a \ + --hash=sha256:dc61e4f9e37b507069dc7e659ae28bca7adcb04c993c3508214315d12c63f848 \ + --hash=sha256:e095f9e105af76593b4c183bb0bcbdae64bd913a59ec595732dc108b48730ab5 \ + --hash=sha256:e2cba180d6451822763eda8364f342435a873bcfb3849cbd82fdeca248ca65eb \ + --hash=sha256:e49eba8f1e28e7c03648b7a476e1ba05309e087ccdea859fc6dd659564aa8d7e \ + --hash=sha256:f1341c6abcee1c31277cfe28d34e46196f2143ec3d755e6efe7452126e1f626d \ + --hash=sha256:f3fbfe82829d8e381426a289b87e59e585278728361db9ce975b88b51f64f410 \ + --hash=sha256:f50b580fad005a092ed87c5a3a4683459b21d1620497d6a5bccad203bee4c071 \ + --hash=sha256:f5576e8ae1723ece60d8f93c6710abf784714e99388bcf023ba9ca800bc587f6 \ + --hash=sha256:f673d835bdb1a60229cc3609a113fd2c9ce3f4a3c75ad4eaed111180c00199d2 \ + --hash=sha256:f7548ede3ee908cfabc0d068106e303a9a2d811af959cdf6ab85676344cedcda \ + --hash=sha256:fa8ed556fcc87a4091cf61587ef172fa104323dc89ecc085a618ba7ff8629a8f \ + --hash=sha256:fefea5cf8cdda9053b962ca8a90216fb0b1d40907dcb6819382b42e483e6e9f6 \ + --hash=sha256:ff7144d8167e513fe39fbb46bffb4f6f192dfb1f4b0b4e9102e1fd4f212e4747 + # via -r requirements.in +wrapt==2.5.1 \ + --hash=sha256:016602dd8827d190280a707c5e67f9a80038f54bac1782cc8ff68a2a16c618bc \ + --hash=sha256:03aa7d2256309b57ddbf317bff2cae5f47e50ea9ae8d582780ebe0b554347b42 \ + --hash=sha256:051220e5071fdfb1a6678707c8abb7bbf4824d40f99758394b2b4d64855fb284 \ + --hash=sha256:0591e6eace0d186c9ef1ecd1244be5a04e98041424cfca425b684ffe4f0d8030 \ + --hash=sha256:05f6138d5833edf68d88f950ea71bd96daf0a9505b53abd48aa002a0b6d05765 \ + --hash=sha256:06740dbf984af8a26d4b63b75a6ee4e88846c068dc865486ad906448079f50d4 \ + --hash=sha256:094b847491b813b6e6c1775e03770930d75078c0821adf929ac712830951ef25 \ + --hash=sha256:09b1893ee4063706574c1813abf479b8b51926633fbdb6f96aab8dc7b0976668 \ + --hash=sha256:0a526227efe17dd94bd16b123d170f879bce42c15f10eb92495a745f54caa943 \ + --hash=sha256:0c9480bdee340a1602cae5a777146ab4be3e384fdcb569fffdf8721032314645 \ + --hash=sha256:129cab3c7b21e68e693c2819a95c47f3b1c41a834b931154688c83b6aef6bdab \ + --hash=sha256:12bee472452019706fa1d4ead093f52a9683b4fe6617953e15bab9acdfdc013f \ + --hash=sha256:12d3d2b9d6553df6e2421ab99e1cc5413509076788f57fcb3169f5ce100a19d1 \ + --hash=sha256:1425fcf0e70b27053bd610d57bae975856e7897e3f6ba1456d2b80b9d7fd15d1 \ + --hash=sha256:183bf0bb893f783c9d22f953cb01fababb9f618e098763f8e66337b575b0647a \ + --hash=sha256:1910be5adc0232cc6e8c0673bf3f41c2ee724547543526bed8d00734458e7bc5 \ + --hash=sha256:1a96e2671c60f9f09ae547b5a815cecb29af16caa68d73693387d0028788cb32 \ + --hash=sha256:22300c5f254627f24ad2197998fde26db6eacbb0f879162944bf7bd79dd5ee5b \ + --hash=sha256:22a9fda6ac53536ec74e3e334f3568af2535a3df1ae70e8f2816f77160c386d9 \ + --hash=sha256:25eb4d928a9abeaf70ca786a35861b46d1ab37cc4ce49ea70a070dacdead4dfe \ + --hash=sha256:25ed8b1b39234140d5b5c6a273130c7595e0abece417c3ca3cb378fcea5cd0fe \ + --hash=sha256:26313f38d18d40a9975123a4ebff9da125ec63ab9ece4f05320a3d8d37d2c1fe \ + --hash=sha256:26d8ea2ec6818aeb656bd8a9e745a6f1fb0edfcd8f54291ccd94f62eb5f5e3bd \ + --hash=sha256:29b62e87fcd6a1893f669abfd02a596a7fc5cfa79fa57e42c4e650a6c170c67b \ + --hash=sha256:2c642a83b6703804b571caa3b8b205aacd341b1b37e2b2d89cd70e03e0e9caa6 \ + --hash=sha256:36d7d0ad593c4f1a651e4032de834db59aee1a929ee396cd483895b673328e51 \ + --hash=sha256:380f72610181883f66b41442cfc7c0f7552b42169efb2113def26e6380013d37 \ + --hash=sha256:3cf273b7e8d2038abb7f0a8c6550aff4f617b9d486a9965c8e8acc96a3a04de9 \ + --hash=sha256:3f93ceb0ac4896de45d5a45a8f4e69474da583440589de10b362ddc1db4691ed \ + --hash=sha256:4b3f410c416752e1dba53d361e2e6562f22c2c3ec855740dfa5836e061b22571 \ + --hash=sha256:521bd5ef2a33171fac08a0a302d51a983c19c3519406c1ee8da7ce29285488da \ + --hash=sha256:5ad562c23e61e626f9d27aa37aa5679f1c29085de1f998466d107854048bba9e \ + --hash=sha256:5b53000b424dc2133eaaf22838a2352d3497f5d7c2e7d9a2acfe675ab7225bb1 \ + --hash=sha256:5be9816d9de88f02fce23cf55f392403411d9bd9c7ae57fdc965a43b22e2de5e \ + --hash=sha256:6201c7e122f40060a9b50696d80deec8f93b1a235ec0443f51d7a8a42f7044a6 \ + --hash=sha256:6405ff2160af9d59132ebb076eda0304db44d9d09809582932412ef7c0788a36 \ + --hash=sha256:69fd0fbb3daf7c8c6f5e062847a0061f880f347374d74cf1daba57220fb64cd0 \ + --hash=sha256:6e3eff05ae616671b40d7ad0a504210329e4adc9fb91415663570aca93c5f5cc \ + --hash=sha256:711e73da3d7983547fc9dd208973b6b0c52640822f5d477910ba24622df6ba64 \ + --hash=sha256:729d644b6acaf4846a4ef81b037857b66a01dea6d227f827c6d71c0b6d656d6c \ + --hash=sha256:736c1de0230c6d24327b14684794214167b2c5ebb6332e28a10f504641b600df \ + --hash=sha256:76f230a9b07e3cb66646d265398f579abb6128b1bb4cb97c74b1ae5d09e96f31 \ + --hash=sha256:7fa321270b40f3e8cdfd954b3a8dcafc6db1d8bbd4d681b92dfa6b9ef91a9a99 \ + --hash=sha256:8078186f719a92693199f1e06c4ec72e1e6d374c2e459da18ed5c39d6966d727 \ + --hash=sha256:859f67bfc31eb7ab55f237b629cd4ab0441b075912446481f910f7d02066811e \ + --hash=sha256:8922821f66ec08a39f72247776c6158db5bfaa09d0c8f607cd854bdf6b2a2c10 \ + --hash=sha256:89d9a8607b7028054bb6fd01d437f205534a5d59d53c3665d15949a99a2fce0d \ + --hash=sha256:8a7c078323e6e1534968cb85488c5eb7ee2b9bbd0f8a291095213a763da40dab \ + --hash=sha256:8bdf4696fb5bb141a7f96710ac6d9a6aa9a57a14c54075f9c7d3946869d457df \ + --hash=sha256:920f700ef41ee774a1e4778c1f4295e117f1ff3435a7e0cd3e997d10da819d32 \ + --hash=sha256:9a34640eb6295f33ca23462977de275fe8f3a50ab339b8918b96d69a7451e2e1 \ + --hash=sha256:9aa7660684d73925c0d1e4f8536ccbaf233cef3897e33a8c2ec462f83b338323 \ + --hash=sha256:9bad4dbb4e61624fcce5f301e37f9e743ecae4f1259a3777b3207eb7eba3dccd \ + --hash=sha256:9bc472825027b276d4bf678d2ac64149db0b122f80ae6f59c423e6d31f0c4bb7 \ + --hash=sha256:9f0750cbc2e29e4f3c9529d3587d4e7ed8f60638ceafb80b87a95833b0c5acd9 \ + --hash=sha256:9f437dd704abc4ee1bd03bb2d796d362d0e75915e8f3113a7900b3b7ec5f8b47 \ + --hash=sha256:a18e63910252eb75d8806b4baefbc3a03612502f63eab042e3741b00b719f043 \ + --hash=sha256:a1e823aecb3746b8f9e0aee2e1413887871ee2f5c502a3e0ef8d466dbd4adde1 \ + --hash=sha256:a424e8a9776c06aef6313af1d0e3fe6e0838af4241d0c09eb0a3b46f2c9a5ff3 \ + --hash=sha256:a88370a7d89fcb1c4953a87673fdd7b4a0eb14a1a4dfce49771f0c827ef44893 \ + --hash=sha256:ab6db7d2a18d366cc57c2228253cf26443190aba0a6dd0939b3c1e8ac6e29e2c \ + --hash=sha256:ad81bf81b0a0b6c6ec74169638202851962843e86749570c463eecc55072f93b \ + --hash=sha256:aed178902c2386d7c5d3d23eb96d32c100e34cb8c2390e7ece0e4901ae43f0e7 \ + --hash=sha256:b0c82c19baca8ddeb4f513f584f53f6d3aa96b1a273f1a507d6d70620b01ba92 \ + --hash=sha256:b238e955ba34ef2b8897f358b7b868b41b9a02ffd338014b62985fa91898cc4a \ + --hash=sha256:b40f814df9e106371fea48911814383284e99df34ec1aa1fdd9b07d2055345d0 \ + --hash=sha256:b40fb47d637df8da7b02d76f242688416c23e53195ea5748895db671c01759d2 \ + --hash=sha256:bc5c0203d383403043fb86c964bd0bab4fcbfb26004ff4bb9c6d02ebc1d608ae \ + --hash=sha256:bde5d1b37101b1e9dd3da1f35072e2e7028e9c5e3511f7d76d3fdd4d071b7663 \ + --hash=sha256:bfaa998ceeea4d0aa72b40cdd0023d19409504e244b439ff2aa9f01729341c5f \ + --hash=sha256:c25c594f58ecb676358d6d6b0ff068b8bbbc506dc831c6d17876460c66ce39c2 \ + --hash=sha256:c39c7130ea0702c4ab0faf12da1df1e02d5174305c17edf02309e2f058c4114f \ + --hash=sha256:c40f3b1cd3ff9dd9f4ae829e4301f0d3a553e3467058b8c3f5528fee2c768a20 \ + --hash=sha256:c44dd9881626da7d621c23805f26726f6b023cf3e9755f48d092bc9cbef4a8e7 \ + --hash=sha256:c4d9c76e9a16a8bae0bdcc57efabad499192565bd9a95258b01fb0b49a62bd63 \ + --hash=sha256:c6e6c226b1ca5402d7ae5fb34a0d21f1b49124fe4200e5884d1e19e53c47ac1d \ + --hash=sha256:ca7b967e96384abdf7e7182c79f71529997981ece8169f8a8ddb31bc5b57cbec \ + --hash=sha256:cab37b82ec328173222e4f9da5eec4f2ec9e8e506f83557c8be8e1bffad351cc \ + --hash=sha256:ce3889e3815f97d46414eb574bffdd9bdb41ff70f503097e2707615a87d4e92c \ + --hash=sha256:cef2a8f006410b6134a0d273ec037fea8cc7a6a914f1bd7555ad9788ad788c6e \ + --hash=sha256:cf63fffcdcd8c60f223d3967bb92cc4fc2e8b46f09e75b67a6a75e6f47c0fc43 \ + --hash=sha256:d5b665a43fe0d3b390cbdd3c003d61c92fa07bd5e3fb1ed3f47920c2d03cd9fd \ + --hash=sha256:d6d274ec50a5b208be75596dc44ea253e65deaa6ee3a600babc86dafbb957dfc \ + --hash=sha256:d800c7689154622b0ba2922ceca44a3cf2ef61c3b9a4c4eeb1d8b3050d7ededa \ + --hash=sha256:d90c91cb4ef83b2ff00db4e0a7bdd9602902504ef9b26d0f9d7ecf6cd05c7554 \ + --hash=sha256:da42395e7add724c1f7caf18a2977b1fbdfd5aab314e5622731f0ed66731eaaf \ + --hash=sha256:da847332447db5505162759a4cd5ac374eb8b74841fe97a98ef3de14edd2586d \ + --hash=sha256:dc401274fcc7b15b3b2c12df2ff34024a11925243a7d3daee91c6d7d14f9addf \ + --hash=sha256:df6e3a36170cda0d313be50fe5065948e7f12f3a181b38cbc262e9f2ee4824e1 \ + --hash=sha256:e089a22ff5af1290b8c759a610830bdb2a829ef9c3d7797e4ee32c2f795ed482 \ + --hash=sha256:e85a9db9e5a5ccc326edb19e35a5106ba16e451d570a2ec8ea9deb1ea52a3c42 \ + --hash=sha256:ea27bcf5c56b13463ba5b9bbfa4d6544997e47ba6db77c59a259b09daa802d4d \ + --hash=sha256:f063c696328408fc4f259b9d7d439398d36b709e12445a904e7b047f0a84c3c5 \ + --hash=sha256:f1630201b0e2a96bb26304b7adfbd91a4ef486abb5a4c48377444a0bed749f37 \ + --hash=sha256:f1c911818fb076910ef509f2298dfcb966a54a6ff068eebd459632102cf589fb \ + --hash=sha256:f280c115ea64eff3dcbd68a668ce3f63476a4ba386bbabb318017e286196ea2c \ + --hash=sha256:f595bb0185aab3e9dc31950c95d914f56ea8278810c3b928f3426e12ed6d27bc \ + --hash=sha256:f98eaf784cd12bc69c77af398084174531007cd81849c962163ccfc6e791f3ea \ + --hash=sha256:fc0eb73b450b53950b7879ac7642889c82918d17bd2d877fd7270348dfd5550c \ + --hash=sha256:fcccaa1484f7dd1091602970988ab741491f9f974013c844f70e45ac1196b80d \ + --hash=sha256:fd3f878a4aac3c262447ddf43c5f4c18fc67dfc3ba69c4fb1c7a4c4af96abe7e + # via aiobotocore +yarl==1.25.1 \ + --hash=sha256:0136d640dfa9b0523853e411430a99f8a91eca85774c6420285a33b755bc6de3 \ + --hash=sha256:03dd38de09bc213e9a8b29761eec33ee1d5318dac0e49d8af36e4d27830e23a7 \ + --hash=sha256:0a191bfdb30a79b98e5d175d75285f9fcb78bf0e46ba5efda042e1c72071a0de \ + --hash=sha256:0a66db89ea473abeac4b70523cafd94db3772380e565f9d28af7a179b7af71fa \ + --hash=sha256:0ae12ff2b805fa02c4dab838005caef735e39986322698c48588d3beacb65c62 \ + --hash=sha256:0f12afda4eea8c8994a76d4df1875c765194f5fbe8a9d197929ea303caee29ec \ + --hash=sha256:10b2fd95332f0d716d5eee3c9fb2ce8eada19082de7fee83d32e37992fd75c26 \ + --hash=sha256:126a2533570c554719ca40a1288fdee1700b6bc82e7131aa69fa85252d92e651 \ + --hash=sha256:12b6bc4906e11f5e1a1cdcb12296e7afbd366c783cc8073403cd2fb74334e453 \ + --hash=sha256:142c06c4d6a35ee3ec5da08499805e879cb3ca7c1fbfbecb0140fe72403818d6 \ + --hash=sha256:14b79a30a93a3ce2e8832603fd0ab780ada281b0ba5110b519a634f2d7d7d1fc \ + --hash=sha256:17c9877a89fb6e2bca6f9087eb24cd7fb434653946ef5075e470d23d49b52287 \ + --hash=sha256:192a866877a49993949ef1975864ad8728bea28ee810f6abe1a0729c2b500426 \ + --hash=sha256:1ab7618921a93767387a4b83776f751588f5b5ae9bb5bc96620e2e2e00bca868 \ + --hash=sha256:1e80dcf1446e1b080b1932b0d103c464a04112f5bc31f0f983ad418172063cde \ + --hash=sha256:1f51020b2eb8a003c84925638ec63c21a750a4bddd3a22ec8eac6a742dadf1b9 \ + --hash=sha256:1fb2a01ba8cd9c5d2c5dc1ec35e0fc951d04b4f037541d4ac090c993ce58b3d7 \ + --hash=sha256:2239a02249d9326655419e0168a28ca9008938eaab31dc29fc875c217927a6c0 \ + --hash=sha256:23bf5b403c879a54964e0feac7285688e04bb220074878d737d331522da0a5bf \ + --hash=sha256:24ce942011a61953e7d313438038f4d32ff21387b775f58a957f7a07dd55ef95 \ + --hash=sha256:25868beca8b6765f8f7d0e11fe6dd7c66dd4b0793b9500286d20cc92352126a5 \ + --hash=sha256:287e99ff5aa4dc1c7630bfc683ded6f106d756c99dec432a2d7f197a784f51c6 \ + --hash=sha256:29273edf1530e397bd07cb784db1fbe0d2590b77569f2e24679a9c0a2d763b94 \ + --hash=sha256:2b49375d22299b0a834c2bca72f39aaecc270d96fb24c30424899676f487b22a \ + --hash=sha256:30eec96e8a91bd588ce897c9543f6d5d8d34b28fbcba28a4dedf20ebeae9fe57 \ + --hash=sha256:319e070a01db9920fb63761843f96a104c8e2b9427266731810dc1e22595b17c \ + --hash=sha256:35dcbea443fafb3eece757ad4e514560ddeb6c34cfae1582c620d7b293d7feee \ + --hash=sha256:3f4d48a6112712973e676bd792121fee470e432d749177162d9949d5c9460a1b \ + --hash=sha256:3feb99222553a8cbedfa52c2f59dd84c3f50d5b582c728d522caf8d72769a54b \ + --hash=sha256:419f392a1da624877975709e3864dfe833af6cc7671b39318086d456e288380c \ + --hash=sha256:42a66563d8cc056ee32e6191e05097a7b2b3bc302e0bc3133daf8710eb18bd26 \ + --hash=sha256:48796ea00a303961507dc6c8437c4b325a6fc3f95f7c36c71b91ea9a8150963c \ + --hash=sha256:4bd6340d20ae2c7ca719b87b426e808e90743b676d05d4c26c4fb5ca71f41184 \ + --hash=sha256:4ca89e4e21854ed27ec753297dde84b16c9f8e53b14a4866fb44457d643c19f8 \ + --hash=sha256:4d781294bb815ecb5ea57ff6bbf8038e0a31a95fdf3e1788f66e0dc100d64b58 \ + --hash=sha256:4f1c91f5a5980a937ff8e238e98e6897e1ad74a4b1e2c0d68c73b5ffbb3f5c0b \ + --hash=sha256:564fdc7085d2245ab84f88882fdb1d6ac0723124bff6ded35bfb1c00f812630d \ + --hash=sha256:59ba3a6e1aa8cfe5adf4bd270fd965db21955401b7ca6f1696010c55ed4daec2 \ + --hash=sha256:5df89f769cc8ff94c3d7e7603386fba309d25ce5240132d26c15baa8d0e96c4c \ + --hash=sha256:632da579b2d879f6bad20f2cfa35ded1efe2f4f77f8abb26a6234a5b236acd2f \ + --hash=sha256:65b5b2066651b7432d389e9799d979c703bcc6ef44266bb8153ef54e91e4aab3 \ + --hash=sha256:664ec6a520b74a1df2810666eb67695fcb77fa663e6ea0a25aaf2e529cb24dfa \ + --hash=sha256:681c758b0490f9e96b78e5fa8e8dc6e648e9185bb6eaebe73183c33ea0c445f3 \ + --hash=sha256:683e362b8ba453080f7489c66f4ea794e751c35b72e7eab3575ef784c2fbc7fb \ + --hash=sha256:68782fdb4027b8d1eee25ec35e9a6db05e863b899eb0310b3a33b6c3fef55707 \ + --hash=sha256:6efaf45df6a849cef613a03a94c845647456662f85438c886bb67a9c027c8c2c \ + --hash=sha256:71f42c5b9a948c113bbdebfa544598321431d064ff959d32e99b1feb61d68345 \ + --hash=sha256:72849d892954be4d09e569b8b831ac39ce58417fedc767d4308a0fe542018a40 \ + --hash=sha256:72c34ac7ad4314c19362d5ce27626dcc8429bd30bbf8c179f4234078851f9492 \ + --hash=sha256:734f6e5400352ac4254456003d462866c684703570929cff7a7bde015d0cb371 \ + --hash=sha256:75baa6cf9b6d1c52f3e111a130e202fd8cf0a5b3a066c3f73d615e885092e4ec \ + --hash=sha256:77716e245c90f058466a05e6a465bb8600f767a8f4b18b4d40f3aff958e5f73c \ + --hash=sha256:77e5099b99b37f3cf79c246998ca9f7313a78054cd1809ec46bc1afad47e1c4c \ + --hash=sha256:783dd1467083f4d3f7722ad6a313f24c173e7571372738fcb7a6e6d1ba48df25 \ + --hash=sha256:7a5c3115595995779ee21f2567035793911c3802a43c74f3fbb0314929ec67ac \ + --hash=sha256:7c88edaec8c349ad4c5ad4c486a3defcc4b80ceb2f074436ffa0a87caf5e76a6 \ + --hash=sha256:7cb414a73e21a7ab58254926073f2930cb22f5b4314ea4260a687e2b3fd4dce3 \ + --hash=sha256:7d42e7e3ca399555578b4d617e3a6ecf13371b3743a115995fa010c7bf341459 \ + --hash=sha256:7d575b54cb3863ef9bc290ea4b009999d55dc237326131e4853cf33e888fee03 \ + --hash=sha256:7e4de3ac4adbad3d0bc7c6f4360a7dbff5de2f15e3b723be3198074e17fd9c40 \ + --hash=sha256:7efc9f082dfed77c316edffa9deb52888e1bc6789171887cc1f68e06d65465c8 \ + --hash=sha256:80a063f8297fc796296f00f100be520f209b23dc98f93ce8eba6ee7122598209 \ + --hash=sha256:80e47012e730da131c9f059c80936783f9659aae22dc31c03c0595590d11ed54 \ + --hash=sha256:83d4a37e4b95da4d8bda930d6d35b75b4cdadbacbb4980cae290ea3100b5d51d \ + --hash=sha256:83e9f4a25085bd4b7214701a0794ff1f50fc633ffb8bdfebf07abdd81c2db126 \ + --hash=sha256:85a18376073f8a39aa07be34f9fc77e2869aa72c55c441efdd2cf79a0407504d \ + --hash=sha256:87796fedc3ba97ec14fab55acb48584276e6c1e4c1e89c422bda62c838e754a9 \ + --hash=sha256:882569ff613758cac762a457a5d72d6e211b28d4bcfea89d1d71ea942b02eac0 \ + --hash=sha256:8ce4d6ccafb33d39bd78444612d14938ead674c25702ded2ee9c54a47735d225 \ + --hash=sha256:8e7d98cdbb6d71e726f7d525952867096053d1f290dd4e3c50d7d313a136f414 \ + --hash=sha256:8ee202350cf57abf0e9502a41601841019c25d3db7ff52d980aaf31446254059 \ + --hash=sha256:8fb0eb4955adf0579001581f2f71a126e8781ba61bcd120f127b0401163c6c2d \ + --hash=sha256:90c30ed53546da833c700115c0064c22120d1b1560f474699fd31f22dd668233 \ + --hash=sha256:9489e6abf47ba37f332075a91444c7cfedb03e6ce99fbb2f116bfe1ce810da3b \ + --hash=sha256:94d7aa6debf92a1dd14cb5280b083a764169a13cfb23a452111160274ed989f4 \ + --hash=sha256:98d370568f393215d605304cdb77b3d5539bd192c75b623c7304c42c8d6d8273 \ + --hash=sha256:9b1bdaae98bc016825dd3c9d8ee1832f829b3341f9cc6ebd1a1b0a7fef7367cc \ + --hash=sha256:9d693bf4bf534e9ba3ae2780cfd577f5135629f7b5ac653490859d0b77864865 \ + --hash=sha256:9d6ed3d17bccce4c05343e1ca8da13bc5c02c812a4e7282ddd05e8769322d3fc \ + --hash=sha256:9e23c82b63cd7652fc24d33ed6cc17099d607aa3b4fc4ddc75e95062f3d82df4 \ + --hash=sha256:a1daf47cd95a7c3a63456336bc5aaa8c86dd3a47d07ed3d0e76132ae4666a5a1 \ + --hash=sha256:a1e32763e641a1566507d90a8d3b19bfc3cc04a9d4e5ae3e32189874ed4b58a3 \ + --hash=sha256:a2059a2d891bd156bc5184e7ab7a56e78a84dfcfdeac8c501b552533ad1c36ee \ + --hash=sha256:a2ed0ba415ccdf08f14bf544cb78346d0f76086707ffee24921a2c84dbf1305a \ + --hash=sha256:a3faadac7d812ddac258feb57b9846b60c1b437c4f4b9ad42595c6f6fe4390df \ + --hash=sha256:a5877f2255aab518ebe528289037699201d5dc5f045f2396cb30aa02db22f57f \ + --hash=sha256:a78b50b4f7918a3de71105d5c0b93bbc57bb8339a4d03a9dfd449f9068e76f3d \ + --hash=sha256:a8c2b841478068440d8b733005d13a5ef535b9928cbc05f17182d410f32ba449 \ + --hash=sha256:a9ca696eb02e5c02a8afd872ada510eba9b7fe6e68b9572c2e9a9b1941e31e2e \ + --hash=sha256:aa4ed3dd308548f9e707d9caaf005d2d7f8c1e7868f858dfeb47fe76e16b391d \ + --hash=sha256:ab2054c5531af2a9ba7b69b8ec91e4f884420e83a8c5e579b013084cb57e5e5d \ + --hash=sha256:abb1384477f5901d436b5d2e5465954de46ea6098f59163d243660b5c4461d35 \ + --hash=sha256:acae6b45d1ace09b6ba3876da43b88366ef368f73b988c7f57e14231753d4420 \ + --hash=sha256:acfa7e22aa6c6e7a5996a41d275bfa01efa7ea56ab890590280e9063e2cf5c1b \ + --hash=sha256:af4ea5b37403ef4e30f3927eaed540db942bde01d8d3ff083527c0704d1c9c68 \ + --hash=sha256:b10dd0557ba422715b5206b3743192135a6022acca8baec51aa127d0a75db8fe \ + --hash=sha256:b13b88747769537f3d32e89e3a735da10c0a9e35d7322928c701b5f93d3afffd \ + --hash=sha256:b51c159a9794633f5e0db7ecec7b2b6e3734eca1f5d17dc989ff3552a43ff78b \ + --hash=sha256:b5402a340723fa7da00b5cff987ddab61276be6d11251ea71ae02bcac54890d8 \ + --hash=sha256:b7abffdf37af1cec6a2ad69b827aa84320db5894791bc8ed932dc93fb274b7e9 \ + --hash=sha256:b8075fe90bc08e40b8b8a1874fab42ee4c7b56af05c5886e9cc841397f916908 \ + --hash=sha256:bc3ac7bf569f6b64dad04dd7808c7872dae8a97df657856eac05e9b7e3614a85 \ + --hash=sha256:bd0912757081f89b107d6c00b2ff8a194401b0b87eadcf4481de2b865a8fd44f \ + --hash=sha256:bdc8d8b8c22e9e43ac68316b5e6cf083dec537f4ec213cb4aa967b583bc3fa64 \ + --hash=sha256:be80550d9bfe83d9b62398a37081a90434e6df2d978ec345c3d2820de6beddab \ + --hash=sha256:c6f117789d22dce188e5754e8bc65b7e6ebf8cb73963b9fa761f672a5883769d \ + --hash=sha256:ca32926d7d77bcc8838425c4c95e040a3ace1cb7dfdae599013458dcda2607ca \ + --hash=sha256:cce0727fd5ac04d372fa9bbfde9febc2bcf209aadfcf0468e45dec72719895d1 \ + --hash=sha256:d0f1489233a254bb3643d2f05de7d59019254d81daeca6b9162fe9edef57e0c7 \ + --hash=sha256:d1c557dfd5e3db046053a0bdc72261ade790ebe8e2c7a41b36b0ca1f14cb95f3 \ + --hash=sha256:d21f0fa80a02d05299207eeaafef345d812ace96d5306e4ef265e1d419a615fa \ + --hash=sha256:d45673badd08456d0340e9364eddafe1c53a9d2896424294de4d7dd71ad3ee57 \ + --hash=sha256:d5add7b4ca7afeea91d52e4d4e4db3b1fe9885b71f07054560d8c4296b7441a2 \ + --hash=sha256:d5f90e44653c4e0f78501ed9bb7d3fce835a8d62b7c6ed0cb16557534087e743 \ + --hash=sha256:d7306dee25b8a0e737363f347362b875094b4dc4e367311470656ae420fdbf8e \ + --hash=sha256:dbcef5a9119ef653653132cccaf999b30a0af6f33bb0a4ba80bec30056868487 \ + --hash=sha256:def538065f9e4d4cf1ae164bd59aba00dfa84f03923e0de4c3788f252d6bcd17 \ + --hash=sha256:df23df54b5114a17c2d0ef192433e2e5a9f0c5178c32375e90b7cfc965f349d0 \ + --hash=sha256:dfbf531053a0935f2e871bcd4753f90313688772ff8c017f5ea402e315a78c1f \ + --hash=sha256:e029648f9c951db30e98a7d7ec90835db88ec4b32820efe2a9bdc2287e032eb6 \ + --hash=sha256:e07595c7d6f4db270ceede356a1bd1c07a34f1c26f958d1ed0cd7b48e0d2bba3 \ + --hash=sha256:e12c538e00e7c1b286a07061046b90e8124e6a9793efae2c70db6a4aad07faad \ + --hash=sha256:e546fe1d4a93ebc2910f0d768baff19faa09843ab3f2036a67ed6e69fae4419d \ + --hash=sha256:e5637ca8d0bd7fb72648a6c7934af4baaccb697657f7438c9d264fc2abb8b0b1 \ + --hash=sha256:e636b64d24fd9c38053c5e389a1174c66361fa49dcfd220f4dd35b4abde7cb89 \ + --hash=sha256:e7011b8fb8c4054bf0c12e5edc6cd83778b0028e99ce59b18586ed036f92cfdc \ + --hash=sha256:e80f557716fd765439577131e526b8942ffc2c07bdbc5e39fa62f660ba1e963f \ + --hash=sha256:e92b6bcc741b86d67606c40d3cb9c7cc8e6c737f81e31f4a94efc204456c92e3 \ + --hash=sha256:eb96ed1ae6c7d072d60840c0434aef07a2df611812810807fbc54263a6053e9a \ + --hash=sha256:eda19ea5ee88742f47a2340816e6f2d40b53bed3ab5b69794769f36af9f35bb4 \ + --hash=sha256:ef74070ac553c59eb4f04258722066d6c6135b7baa03b2e9f2da65c096e96d98 \ + --hash=sha256:efb01a106f971cb3752856bca2318bbdf7f01bd8823779c461586cbe5ffd5258 \ + --hash=sha256:f074e8d4aa0a5798920ddb6de3d08b228c614ff3724c3e8bd7577f4bafea867b \ + --hash=sha256:f38a70074041d3b7e138e452799f5174198bae5bd5ab2000917badf403908c5f \ + --hash=sha256:f41753a76f4f63927d03a0d8ba8f5ce0f2083bec29a8cfaccc55371b1564b96b \ + --hash=sha256:f53dcd26694f148f738edc052b5a69234833e739f10f4c3287bdfd8ec0f7b326 \ + --hash=sha256:f61964f235a43738bfac50da46fc4254943a7eea3051aeb0b6fc7c992c29fadc \ + --hash=sha256:fe01645169a2112aa1d4ebc3e4c5f029c5c8f97adfc32e5d37c993b39a994d75 + # via + # aio-pika + # aiohttp + # aiormq diff --git a/scripts/build_dashboard.py b/scripts/build_dashboard.py new file mode 100644 index 0000000..865b8bb --- /dev/null +++ b/scripts/build_dashboard.py @@ -0,0 +1,294 @@ +#!/usr/bin/env python3 +"""Generate the Grafana dashboard infra/grafana/dashboards/messenger.json (provisioned at start). + + python scripts/build_dashboard.py + +Every panel names its query and unit here, in one place (docs/OBSERVABILITY.md copies the list). +Percentiles are ALWAYS histogram_quantile over buckets summed `by (le)` across every replica - +never an average of per-replica percentiles. Datasource UIDs are the fixed provisioned ones. +""" +from __future__ import annotations + +import json +import sys +from pathlib import Path + +OUT = Path(__file__).resolve().parents[1] / "infra" / "grafana" / "dashboards" / "messenger.json" + +PROM = {"type": "prometheus", "uid": "prometheus"} +LOKI = {"type": "loki", "uid": "loki"} +TEMPO = {"type": "tempo", "uid": "tempo"} + +BUSINESS = 'job="messenger-api", http_route!~"/health/.*"' + +panels: list[dict] = [] +_next_id = [1] +_y = [0] + + +def _id() -> int: + _next_id[0] += 1 + return _next_id[0] + + +def row(title: str) -> None: + panels.append({"type": "row", "title": title, "id": _id(), "collapsed": False, "panels": [], + "gridPos": {"h": 1, "w": 24, "x": 0, "y": _y[0]}}) + _y[0] += 1 + + +class Grid: + """Places panels left to right, wrapping at 24 columns.""" + + def __init__(self) -> None: + self.x = 0 + self.h = 0 + + def place(self, w: int, h: int) -> dict: + if self.x + w > 24: + _y[0] += self.h + self.x, self.h = 0, 0 + pos = {"h": h, "w": w, "x": self.x, "y": _y[0]} + self.x += w + self.h = max(self.h, h) + return pos + + def end(self) -> None: + _y[0] += self.h + self.x, self.h = 0, 0 + + +grid = Grid() + + +def ts(title: str, targets: list[tuple[str, str]], unit: str, description: str, *, w: int = 8, h: int = 8, + stack: bool = False, minimum: float | None = 0, maximum: float | None = None, thresholds=None) -> None: + defaults: dict = {"unit": unit, "custom": {"lineWidth": 1, "fillOpacity": 10 if not stack else 40, + "showPoints": "never", + "stacking": {"mode": "normal" if stack else "none", "group": "A"}}} + if minimum is not None: + defaults["min"] = minimum + if maximum is not None: + defaults["max"] = maximum + if thresholds: + defaults["thresholds"] = {"mode": "absolute", "steps": thresholds} + defaults["custom"]["thresholdsStyle"] = {"mode": "line+area"} + panels.append({ + "type": "timeseries", "title": title, "id": _id(), "datasource": PROM, + "description": description + f"\n\nUnit: {unit}.", + "gridPos": grid.place(w, h), + "fieldConfig": {"defaults": defaults, "overrides": []}, + "options": {"legend": {"displayMode": "list", "placement": "bottom", "showLegend": True}, + "tooltip": {"mode": "multi", "sort": "desc"}}, + "targets": [{"refId": chr(65 + i), "datasource": PROM, "expr": expr, "legendFormat": legend, "range": True} + for i, (expr, legend) in enumerate(targets)], + }) + + +def stat(title: str, expr: str, unit: str, description: str, steps, *, w: int = 6, h: int = 5, decimals: int = 2) -> None: + panels.append({ + "type": "stat", "title": title, "id": _id(), "datasource": PROM, + "description": description + f"\n\nUnit: {unit}.", + "gridPos": grid.place(w, h), + "fieldConfig": {"defaults": {"unit": unit, "decimals": decimals, + "thresholds": {"mode": "absolute", "steps": steps}}, "overrides": []}, + "options": {"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False}, + "colorMode": "background", "graphMode": "area", "textMode": "value"}, + "targets": [{"refId": "A", "datasource": PROM, "expr": expr, "instant": False, "range": True}], + }) + + +def q(phi: float, metric: str, selector: str, window: str = "$__rate_interval", by: str = "") -> str: + group = f"le{', ' + by if by else ''}" + return f"histogram_quantile({phi}, sum by ({group}) (rate({metric}_bucket{{{selector}}}[{window}])))" + + +# =============================================================================== API +row("API: requests, errors, latency (all replicas)") +ts("Requests per second by route", + [(f"sum by (http_route) (rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "{{http_route}}")], + "reqps", "Business requests (no /health/*) per second, summed over the API replicas. " + "Counter = _count of the histogram http.server.request.duration (no second instrument).", stack=True) +ts("Error ratio (5xx and 4xx / all business requests)", + [(f"(sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}, http_response_status_class=\"5xx\"}}[$__rate_interval])) or vector(0)) " + f"/ sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "5xx (SLI: server failures)"), + (f"(sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}, http_response_status_class=\"4xx\"}}[$__rate_interval])) or vector(0)) " + f"/ sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "4xx (client errors, not in the SLI)")], + "percentunit", "Numerator: 5xx (or 4xx) business requests; denominator: all business requests. " + "Alert MessengerApiHighErrorRate: 5xx > 5 % for 1 min.", + thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 0.05}]) +ts("Latency p50 / p95 / p99 (all routes, all replicas)", + [(q(0.50, "http_server_request_duration_seconds", BUSINESS), "p50"), + (q(0.95, "http_server_request_duration_seconds", BUSINESS), "p95"), + (q(0.99, "http_server_request_duration_seconds", BUSINESS), "p99")], + "s", "histogram_quantile over the buckets of http.server.request.duration summed by le across replicas " + "(buckets 1 ms ... 10 s). Not an average, not per-replica p99s averaged.") +ts("p95 by route", + [(q(0.95, "http_server_request_duration_seconds", BUSINESS, by="http_route"), "{{http_route}}")], + "s", "Per route template, buckets of all replicas.", w=12) +ts("Requests in flight by replica", + [("sum by (instance) (http_server_active_requests{job=\"messenger-api\"})", "{{instance}}")], + "short", "UpDownCounter http.server.active_requests per API replica (saturation of the HTTP layer).", w=12) +grid.end() + +# =============================================================================== worker +row("Worker and queue") +ts("Jobs handled per second by outcome", + [("sum by (outcome) (rate(messenger_jobs_processed_total[$__rate_interval]))", "{{outcome}}")], + "ops", "messenger.jobs.processed: succeeded / retry / failed / fenced / superseded / noop_* / deferred / rejected.", + stack=True) +ts("Job duration p50 / p95 / p99 (succeeded)", + [(q(0.50, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p50"), + (q(0.95, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p95"), + (q(0.99, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p99")], + "s", "One delivery in the worker: claim -> S3 read -> variants -> S3 writes -> COMMIT -> ack.") +ts("Time to ready p50 / p95 / p99 (uploads)", + [(q(0.50, "messenger_attachment_time_to_ready_seconds", ""), "p50"), + (q(0.95, "messenger_attachment_time_to_ready_seconds", ""), "p95"), + (q(0.99, "messenger_attachment_time_to_ready_seconds", ""), "p99")], + "s", "From the durable acceptance (job COMMIT before 202) to the COMMIT of status ready. " + "Includes queue wait and retries. SLO: 99 % within 30 s.") +ts("Queue depth (PostgreSQL) and outbox", + [("max by (state) (messenger_queue_depth)", "jobs {{state}}"), + ("max by (state) (messenger_outbox_pending)", "outbox {{state}}")], + "short", "messenger.queue.depth: unfinished jobs (queued incl. retry wait / processing); " + "messenger.outbox.pending: unpublished messages (due / delayed). Reported by the relay every 5 s.") +ts("Oldest job age / oldest due outbox row", + [("max(messenger_queue_oldest_age_seconds)", "oldest unfinished job"), + ("max(messenger_outbox_oldest_age_seconds)", "oldest due outbox row (broker)")], + "s", "Age of the oldest unfinished job (now - acceptance). Grows when nobody processes the queue. " + "Alert MessengerQueueLagGrowing: > 60 s for 1 min with queued jobs.", + thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 60}]) +ts("Worker saturation (busy / capacity)", + [("sum(messenger_worker_busy) / sum(messenger_worker_capacity)", "busy share")], + "percentunit", "messenger.worker.busy (attempts running) / messenger.worker.capacity (WORKER_CONCURRENCY), " + "all worker processes. 100 % for long = the worker is the bottleneck.", maximum=1) +grid.end() + +# =============================================================================== DB and resources +row("Database pool and resources") +ts("DB pool: used / max, waiting requests", + [("sum by (job) (db_client_connection_count{db_client_connection_state=\"used\"})", "{{job}} used"), + ("sum by (job) (db_client_connection_max)", "{{job}} max"), + ("sum by (job) (db_client_connection_pending_requests)", "{{job}} waiting")], + "short", "psycopg_pool counters per service (all replicas summed). Waiting > 0 = pool exhausted.") +ts("DB unit of work p95 by service", + [(q(0.95, "db_client_operation_duration_seconds", "", by="job"), "{{job}}")], + "s", "db.client.operation.duration: pool wait + statements + COMMIT of one Database.run().") +ts("DB pool wait p95 by service", + [(q(0.95, "db_client_connection_wait_time_seconds", "", by="job"), "{{job}}")], + "s", "db.client.connection.wait_time: time to get a connection from the pool.") +ts("Container CPU (cores)", + [("sum by (job, instance) (rate(container_cpu_time_seconds_total[$__rate_interval]))", "{{job}} {{instance}}"), + ("rate(otelcol_process_cpu_seconds[$__rate_interval])", "otel-collector")], + "short", "cgroup cpu.stat of each application container (1 = one full core); Collector: its own counter.", w=12) +ts("Container memory", + [("sum by (job, instance) (container_memory_usage_bytes)", "{{job}} {{instance}}"), + ("otelcol_process_memory_rss", "otel-collector RSS")], + "bytes", "cgroup memory.current of each application container; Collector RSS (memory_limiter: 400 MiB).", w=12) +grid.end() + +# =============================================================================== SLO +row("SLO (docs/SLO.md) and alerts") +stat("Availability, last 1 h (target 99 %)", "1 - messenger:http_error_ratio:rate1h", "percentunit", + "1 - 5xx/all business requests over 1 h.", + [{"color": "red", "value": None}, {"color": "orange", "value": 0.99}, {"color": "green", "value": 0.995}], decimals=3) +stat("Requests under 250 ms, last 5 min (target 95 %)", "messenger:http_fast_ratio:rate5m", "percentunit", + "Share of business requests in buckets le=0.25.", + [{"color": "red", "value": None}, {"color": "green", "value": 0.95}], decimals=3) +stat("Uploads ready within 30 s, last 1 h (target 99 %)", "messenger:ready_within_30s_ratio:rate1h", "percentunit", + "Share of uploads with time_to_ready <= 30 s.", + [{"color": "red", "value": None}, {"color": "green", "value": 0.99}], decimals=3) +stat("Alerts firing", "count(ALERTS{alertstate=\"firing\"}) or vector(0)", "none", + "Number of firing Prometheus alerts (table below).", [{"color": "green", "value": None}, {"color": "red", "value": 1}], + decimals=0) +panels.append({ + "type": "table", "title": "Alerts (pending / firing)", "id": _id(), "datasource": PROM, + "description": "ALERTS series of Prometheus (rules: infra/prometheus/rules/alerts.yml, runbook: docs/RUNBOOK.md).", + "gridPos": grid.place(24, 6), + "targets": [{"refId": "A", "datasource": PROM, "expr": "ALERTS", "instant": True, "format": "table"}], + "transformations": [{"id": "organize", "options": {"excludeByName": {"Time": True, "Value": True, "__name__": True}, + "indexByName": {}, "renameByName": {}}}], + "fieldConfig": {"defaults": {}, "overrides": []}, "options": {"showHeader": True}, +}) +grid.end() + +# =============================================================================== telemetry pipeline +row("Telemetry pipeline (Collector, SDK)") +ts("Collector: spans accepted / sent / failed per second", + [("sum(rate(otelcol_receiver_accepted_spans[$__rate_interval]))", "accepted"), + ("sum(rate(otelcol_receiver_refused_spans[$__rate_interval]))", "refused (memory_limiter)"), + ("sum(rate(otelcol_exporter_sent_spans[$__rate_interval]))", "sent to Tempo"), + ("sum(rate(otelcol_exporter_send_failed_spans[$__rate_interval]))", "send failed (dropped)")], + "ops", "otelcol_* self-metrics, scraped from :8888. sent < accepted with tail sampling (dropped by policy).") +ts("Collector: logs and metric points per second", + [("sum(rate(otelcol_receiver_accepted_log_records[$__rate_interval]))", "logs accepted"), + ("sum(rate(otelcol_exporter_send_failed_log_records[$__rate_interval]))", "logs failed"), + ("sum(rate(otelcol_receiver_accepted_metric_points[$__rate_interval]))", "metric points accepted"), + ("sum(rate(otelcol_exporter_send_failed_metric_points[$__rate_interval]))", "metric points failed")], + "ops", "Same for the logs and metrics pipelines.") +ts("Collector: exporter queues", + [("max by (exporter) (otelcol_exporter_queue_size)", "{{exporter}} size"), + ("max by (exporter) (otelcol_exporter_queue_capacity)", "{{exporter}} capacity")], + "short", "Bounded sending_queue (batches) per exporter: fills while a backend is down, never above capacity.") +ts("SDK: spans recorded vs exported (all processes)", + [("sum by (job) (rate(messenger_telemetry_spans_ended_total[$__rate_interval]))", "{{job}} recorded"), + ("sum by (job, result) (rate(messenger_telemetry_spans_exported_total[$__rate_interval]))", "{{job}} export {{result}}")], + "ops", "Spans finished in the process (sampled) and handed to the OTLP exporter: success / failure (Collector down).", + w=12) +ts("Telemetry components up", + [("up{job=~\"otel-collector|prometheus|loki|tempo|grafana\"}", "{{job}}")], + "short", "1 = the scrape succeeded.", w=12, maximum=1) +grid.end() + +# =============================================================================== logs and traces +row("Logs and traces") +panels.append({ + "type": "logs", "title": "Application logs (Loki): warnings and errors", "id": _id(), "datasource": LOKI, + "description": "OTLP log records of api/relay/worker. Expand a line: trace_id links to Tempo. " + "Query: {service_name=~\"messenger-.+\"} | detected_level=~\"warn|error\".", + "gridPos": grid.place(12, 10), + "targets": [{"refId": "A", "datasource": LOKI, "expr": "{service_name=~\"messenger-.+\"} | detected_level=~\"warn|error\"", + "queryType": "range"}], + "options": {"showTime": True, "wrapLogMessage": True, "enableLogDetails": True, "sortOrder": "Descending", + "dedupStrategy": "none", "prettifyLogMessage": False}, +}) +panels.append({ + "type": "table", "title": "Recent upload traces (Tempo)", "id": _id(), "datasource": TEMPO, + "description": "TraceQL: POST of an attachment. Click a trace id: upload -> enqueue -> publish -> process -> S3/DB.", + "gridPos": grid.place(12, 10), + "targets": [{"refId": "A", "datasource": TEMPO, "queryType": "traceql", "limit": 20, "tableType": "traces", + "query": "{ span.http.route = \"/api/v1/chats/{chat_id}/attachments\" }"}], + "fieldConfig": {"defaults": {}, "overrides": []}, "options": {"showHeader": True}, +}) +grid.end() + +dashboard = { + "uid": "messenger-lab6", + "title": "Messenger lab 6: API, worker, queue, SLO", + "description": "Generated by scripts/build_dashboard.py - edit the script, not the JSON.", + "tags": ["messenger", "lab6"], + "timezone": "browser", + "schemaVersion": 39, + "version": 1, + "editable": False, + "graphTooltip": 1, + "refresh": "10s", + "time": {"from": "now-30m", "to": "now"}, + "templating": {"list": []}, + "annotations": {"list": [{"builtIn": 1, "datasource": {"type": "grafana", "uid": "-- Grafana --"}, "enable": True, + "hide": True, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", + "type": "dashboard"}]}, + "panels": panels, +} + + +def main() -> int: + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_text(json.dumps(dashboard, indent=1, ensure_ascii=False) + "\n", encoding="utf-8", newline="\n") + print(f"written {OUT.relative_to(OUT.parents[3])}: {len(panels)} panels") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check_dashboard.py b/scripts/check_dashboard.py new file mode 100644 index 0000000..a283a6d --- /dev/null +++ b/scripts/check_dashboard.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Run EVERY query of the provisioned dashboard through Grafana (/api/ds/query) and report, per +panel: error / no data / number of series. Proves that the dashboard refers to metric names, +labels and datasource UIDs that really exist (not only that the JSON was imported). + + python scripts/check_dashboard.py [--minutes 30] [--output evidence/dashboard-check.txt] +Exit code 1 if a query fails. "no data" is reported, not failed: an incident-only series +(5xx, failed spans) is legitimately empty on a healthy stand. +""" +from __future__ import annotations + +import argparse +import json +import sys +import time +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +import obs # noqa: E402 + + +def post(path: str, body: dict) -> dict: + request = urllib.request.Request(obs.GRAFANA + path, data=json.dumps(body).encode(), method="POST", + headers={"Authorization": obs._auth(), "Content-Type": "application/json"}) + try: + with urllib.request.urlopen(request, timeout=60) as response: + return json.loads(response.read()) + except urllib.error.HTTPError as exc: + return json.loads(exc.read() or b"{}") | {"_status": exc.code} + + +def get(path: str) -> dict: + request = urllib.request.Request(obs.GRAFANA + path, headers={"Authorization": obs._auth()}) + with urllib.request.urlopen(request, timeout=30) as response: + return json.loads(response.read()) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--minutes", type=int, default=30) + parser.add_argument("--output") + args = parser.parse_args() + dashboard = get("/api/dashboards/uid/messenger-lab6")["dashboard"] + now = int(time.time() * 1000) + lines, failed = [], 0 + lines.append(f"dashboard {dashboard['uid']} \"{dashboard['title']}\" (provisioned), window {args.minutes} min") + for panel in dashboard["panels"]: + if panel["type"] == "row": + lines.append(f"== {panel['title']}") + continue + results = [] + for target in panel.get("targets", []): + query = {k: v for k, v in target.items()} + query.setdefault("datasource", panel["datasource"]) + query["intervalMs"], query["maxDataPoints"] = 15000, 200 + if query["datasource"]["type"] == "tempo": + query.update({"queryType": "traceql", "tableType": "traces"}) + response = post("/api/ds/query", {"queries": [query], "from": str(now - args.minutes * 60000), "to": str(now)}) + result = response.get("results", {}).get(target["refId"], {}) + if "_status" in response or result.get("error"): + failed += 1 + results.append(f"{target['refId']}: ERROR {result.get('error') or response.get('message')}") + continue + frames = result.get("frames", []) + rows = sum(len(f.get("data", {}).get("values", [[]])[0]) if f.get("data", {}).get("values") else 0 for f in frames) + results.append(f"{target['refId']}: {len(frames)} series/{rows} points" if rows else f"{target['refId']}: no data") + lines.append(f" [{panel['type']}] {panel['title']}: " + "; ".join(results)) + lines.append(f"queries failed: {failed}") + text = "\n".join(lines) + print(text) + if args.output: + Path(args.output).write_text(text + "\n", encoding="utf-8", newline="\n") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/collect_evidence.py b/scripts/collect_evidence.py new file mode 100644 index 0000000..d268d87 --- /dev/null +++ b/scripts/collect_evidence.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python3 +"""Run every check of REPORT.md on the current checkout and save the real output in evidence/. + + python scripts/collect_evidence.py # ~3 h; the stand must NOT be running yet + python scripts/collect_evidence.py --skip-track1 # without the 45 min track 1 experiment + +Intended for a CLEAN CLONE (fresh volumes): it creates secrets and .env, builds and starts the +stand, then runs make check/validate/test/test-persistence/test-failover, the lab 5 defense +scenario (scripts/demo_pipeline.py), lab 6: provisioning check of Grafana, the controlled trace +(scripts/trace_demo.py), every dashboard query (scripts/check_dashboard.py), the own tests, the +level 4 incidents (bench/incidents.py) and the track 1 experiment (bench/track1.py), and records +container states before/after every hook and the real resource limits (docker inspect). Prints no secrets +(hook output is shown by the public tests as suppressed; our scripts print names and states only). +On Windows the hooks are the scripts/*.cmd wrappers (Git Bash) and make needs Git's usr/bin. +""" +from __future__ import annotations + +import datetime as dt +import json +import os +import shutil +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +EVIDENCE = ROOT / "evidence" +WINDOWS = os.name == "nt" +HOOK = ".cmd" if WINDOWS else ".sh" +PYTHON = sys.executable +VENV_PY = str(ROOT / ".venv" / ("Scripts/python.exe" if WINDOWS else "bin/python")) +# Makefile recipes use $(PYTHON) unquoted: pass interpreters WITHOUT spaces in the path. +MAKE_PY = "python" if WINDOWS else "python3" +MAKE_VENV = ".venv/Scripts/python.exe" if WINDOWS else ".venv/bin/python" +ENV = {**os.environ, "PYTHONUTF8": "1"} +if WINDOWS: + ENV["PATH"] = ENV["PATH"] + os.pathsep + r"C:\Program Files\Git\usr\bin" + + +def now() -> str: + return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def sh(cmd: list[str], timeout: float = 1800, env: dict | None = None) -> tuple[int, str]: + started = time.monotonic() + result = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace", + timeout=timeout, env={**ENV, **(env or {})}) + took = time.monotonic() - started + return result.returncode, (result.stdout + result.stderr).rstrip() + f"\n[exit {result.returncode}, {took:.1f} s]\n" + + +class Log: + def __init__(self, name: str, title: str): + self.path = EVIDENCE / name + self.path.parent.mkdir(parents=True, exist_ok=True) + commit = subprocess.run(["git", "log", "-1", "--format=%h %s"], cwd=ROOT, capture_output=True, text=True, + encoding="utf-8").stdout.strip() + self.text = f"# {title}\n# {now()}, commit {commit}\n" + + def run(self, cmd: list[str], shown: str | None = None, **kwargs) -> int: + code, out = sh(cmd, **kwargs) + self.text += f"\n$ {shown or ' '.join(cmd)}\n{out}" + self.save() + print(f" {self.path.name}: {shown or ' '.join(cmd[:4])} -> exit {code}", flush=True) + return code + + def note(self, text: str) -> None: + self.text += f"\n{text}\n" + self.save() + + def save(self) -> None: + self.path.write_text(self.text, encoding="utf-8") + + +def states() -> list[str]: + ids = subprocess.run(["docker", "compose", "ps", "-a", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split() + rows = [] + for item in json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, text=True).stdout or "[]"): + st = item["State"] + rows.append(f"{item['Name'].lstrip('/'):24} host={item['Config']['Hostname']:13} {st['Status']:8} " + f"exit={st['ExitCode']:<3} pid={st['Pid']:<6} started={st['StartedAt'][:23]}") + return sorted(rows) + + +OBS_CHECK = """ +import json, sys, time, urllib.request +sys.path.insert(0, "scripts") +import obs +for _ in range(60): + try: + urllib.request.urlopen(obs.GRAFANA + "/api/health", timeout=5).read(); break + except Exception: + time.sleep(2) +def get(path): + req = urllib.request.Request(obs.GRAFANA + path, headers={"Authorization": obs._auth()}) + return json.loads(urllib.request.urlopen(req, timeout=30).read()) +for uid in ("prometheus", "loki", "tempo"): + print(uid, get(f"/api/datasources/uid/{uid}/health")) +for d in get("/api/search?type=dash-db"): + print("dashboard", d["uid"], d["title"], "folder:", d.get("folderTitle")) +print("prometheus rules:", [r["name"] for g in obs.get("prometheus", "api/v1/rules")["data"]["groups"] for r in g["rules"]]) +""" + + +def main() -> int: + EVIDENCE.mkdir(exist_ok=True) + make = shutil.which("make", path=ENV["PATH"]) or "make" + # 1. Clean clone -> secrets -> build -> start + log = Log("clean-clone.txt", "Clean clone: secrets, config, build, migrations from zero, start, versions") + log.run(["git", "status", "--short", "--branch"]) + log.run([PYTHON, "--version"]); log.run(["docker", "version", "--format", "client {{.Client.Version}} / server {{.Server.Version}}"]) + log.run(["docker", "compose", "version"]); log.run([make, "--version"], shown="make --version") + log.run([PYTHON, "scripts/init_secrets.py"], shown="python scripts/init_secrets.py") + if not (ROOT / ".env").exists(): + shutil.copy(ROOT / ".env.example", ROOT / ".env") + log.note("$ cp .env.example .env") + log.run(["docker", "compose", "--env-file", ".env", "config", "--quiet"]) + log.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--build", "--wait"], timeout=1800) + log.run(["docker", "compose", "ps", "-a", "--format", "table {{.Service}}\t{{.Image}}\t{{.Status}}"]) + log.run(["docker", "compose", "logs", "--no-log-prefix", "migrate"]) + log.run(["docker", "compose", "logs", "--no-log-prefix", "s3-init"]) # bucket + access-model verdicts + log.run([PYTHON, "scripts/lbctl.py", "replicas"]); log.run([PYTHON, "scripts/lbctl.py", "status"]) + log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_users"]) + log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "type", + "durable", "messages", "consumers", "arguments"]) + log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_permissions"]) + # lab 6: telemetry stores up, Grafana provisioned (datasources with fixed UIDs, dashboard) + log.run([PYTHON, "-c", OBS_CHECK], shown="python -c ") + ids = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split() + log.run(["docker", "inspect", "-f", "{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}} " + "memswap={{.HostConfig.MemorySwap}} image={{.Config.Image}}", *ids], shown="docker inspect (limits)") + # venv for validate / own tests + if not Path(VENV_PY).exists(): + log.run([PYTHON, "-m", "venv", ".venv"]) + log.run([VENV_PY, "-m", "pip", "install", "-q", "--require-hashes", "--no-deps", "-r", "requirements.txt"], timeout=1800) + log.run([VENV_PY, "-m", "pip", "install", "-q", "-r", "requirements-test.txt", "-r", "requirements-dev.txt"], timeout=1800) + + # 2. make check / validate / test + log = Log("make-check-validate-test.txt", "make check, make validate (venv), make test") + log.run([make, "check", f"PYTHON={MAKE_PY}"], shown="make check") + log.run([make, "validate", f"PYTHON={MAKE_VENV}"], shown=f"make validate PYTHON={MAKE_VENV}") + log.run([make, "test", f"PYTHON={MAKE_PY}"], shown="make test") + + # 3. persistence with states before/after + log = Log("test-persistence.txt", "make test-persistence: restart of LB, API replicas, relay, worker, PostgreSQL, " + "Valkey, S3, RabbitMQ") + log.note("Containers BEFORE:\n" + "\n".join(states())) + log.run([make, "test-persistence", f"ACTION_SCRIPT=scripts/restart{HOOK}", f"PYTHON={MAKE_PY}"], + shown=f"make test-persistence ACTION_SCRIPT=scripts/restart{HOOK}") + log.note("Containers AFTER (new pid/started for lb, api-*, relay, worker, postgres, valkey, s3, broker; volumes " + "kept):\n" + "\n".join(states())) + log.run([PYTHON, "scripts/lbctl.py", "wait-up", "2"]) + + # 4. failover: until BOTH replicas have been the stopped one (each run is a real public test) + log = Log("test-failover.txt", "make test-failover with scripts/stop-one: which container is really stopped, restore, repeat") + stopped: set[str] = set() + import urllib.request + for attempt in range(1, 7): + # The public test stops the replica that served its first POST; its request sequence is + # fixed, so with round robin it hits the same replica every time. Shift the rotation by + # (attempt - 1) extra requests so that the other replica becomes the target as well. + for _ in range(attempt - 1): + urllib.request.urlopen("http://127.0.0.1:8080/health/live", timeout=5).read() + before = {r for r in states() if "-api-" in r and " running " in r} + log.note(f"--- run {attempt}; running API replicas BEFORE:\n" + "\n".join(sorted(before))) + log.run([make, "test-failover", f"ACTION_SCRIPT=scripts/stop-one{HOOK}", f"PYTHON={MAKE_PY}"], + shown=f"make test-failover ACTION_SCRIPT=scripts/stop-one{HOOK}") + after = states() + gone = [r for r in after if "-api-" in r and " exited " in r] + log.note("AFTER (the stopped replica, left stopped by the hook):\n" + "\n".join(gone)) + log.run([PYTHON, "scripts/lbctl.py", "status"]) + stopped.update(r.split()[0] for r in gone) + log.run(["sh" if not WINDOWS else r"C:\Program Files\Git\bin\bash.exe", "scripts/restore-api.sh"], + shown="sh scripts/restore-api.sh") + log.run([PYTHON, "scripts/lbctl.py", "wait-up", "2"]) + if len(stopped) >= 2: + break + log.note(f"Replicas stopped by the public test across runs: {sorted(stopped)}") + + # 5a. lab 6 defense steps 2-3: controlled trace + logs; every dashboard query; load + log = Log("trace-demo.txt", "Defense step 2: upload with our own traceparent -> trace in Tempo + logs in Loki") + log.run([PYTHON, "tests/load.py", "--duration", "30", "--concurrency", "4", "--output", "evidence/load.json"]) + log.run([PYTHON, "scripts/trace_demo.py"], shown="python scripts/trace_demo.py", timeout=300) + log = Log("dashboard-check.txt", "Every query of the provisioned dashboard through Grafana /api/ds/query") + log.run([PYTHON, "scripts/check_dashboard.py"], shown="python scripts/check_dashboard.py", timeout=600) + + # 5. lab 5 defense scenario: worker stopped -> 202 -> 409 -> restart api+broker -> worker -> ready + log = Log("demo-pipeline.txt", "Defense steps 2-3: worker stopped, upload 202, content 409, restart API and broker " + "with volumes, worker started, ready + thumbnail") + log.note("Containers BEFORE:\n" + "\n".join(states())) + log.run([VENV_PY, "scripts/demo_pipeline.py"], shown="python scripts/demo_pipeline.py", timeout=900) + log.note("Containers AFTER (api-*, broker restarted; worker stopped and started):\n" + "\n".join(states())) + + # 6. own tests + log = Log("student-tests.txt", "Own tests: unit + stand (pytest -v); failures restored in finally") + log.run([VENV_PY, "-m", "pytest", "student-tests", "-v", "-p", "no:cacheprovider"], shown="python -m pytest student-tests -v", + timeout=5400) + + # 7. lab 6 level 4: incidents under load (alerts firing -> resolved, diagnosis by traces) + log = Log("incidents-runs.txt", "bench/incidents.py all: worker stop, DB lock, slow handler, Tempo+Loki down, " + "Collector down (details: evidence/incidents/*.txt)") + log.run([VENV_PY, "bench/incidents.py", "all"], shown="python bench/incidents.py all", timeout=5400) + log.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "auditor"], shown="docker compose run --rm auditor", + timeout=900) # lab 5 invariants still hold after all of it + + # 8. track 1: price of observability + if "--skip-track1" not in sys.argv: + log = Log("track1-runs.txt", "Track 1: bench/track1.py, off/full/head10/tail x 3 runs, then the summary") + log.run([VENV_PY, "bench/track1.py", "--runs", "3", "--output", "evidence/track1"], + shown="python bench/track1.py --runs 3", timeout=7200) + log.run([PYTHON, "bench/track1_summary.py", "evidence/track1"], shown="python bench/track1_summary.py") + log = Log("final-state.txt", "Final state of the stand") + log.run([PYTHON, "scripts/obs.py", "alerts"], shown="python scripts/obs.py alerts") + log.run(["docker", "compose", "ps", "-a", "--format", "table {{.Service}}\t{{.Status}}"]) + print("done:", EVIDENCE) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/collect_evidence_resume.py b/scripts/collect_evidence_resume.py new file mode 100644 index 0000000..5850e97 --- /dev/null +++ b/scripts/collect_evidence_resume.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Resume scripts/collect_evidence.py after an interruption, on the SAME clean-clone stand. + + python scripts/collect_evidence_resume.py + +Used once in this work: during the clean-clone run Docker Desktop itself stopped after the own +tests (every later step failed with "cannot connect to the docker API"). This script re-runs, with +the same logging, the tests that failed in that run and the steps that never executed: level 4 +incidents, the read-only audit and the final state. Earlier evidence files are kept unchanged. +""" +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +import collect_evidence as ce # noqa: E402 + +FAILED = [ + "student-tests/test_pipeline_flow.py::test_cleanup_racing_a_replay_never_deletes_the_replayed_source", + "student-tests/test_storage_failures.py::test_upload_survives_failover_of_the_serving_replica", + "student-tests/test_storage_failures.py::test_bucket_is_private_outside_the_api", + "student-tests/test_storage_failures.py::test_s3_restart_keeps_objects", +] + + +def main() -> int: + log = ce.Log("student-tests-rerun.txt", "Re-run of the 4 tests that failed in student-tests.txt (Docker Desktop " + "degraded and then stopped at the end of that run)") + log.note("Containers BEFORE:\n" + "\n".join(ce.states())) + log.run([ce.VENV_PY, "-m", "pytest", *FAILED, "-v", "-p", "no:cacheprovider"], + shown="python -m pytest <4 tests> -v", timeout=3600) + + log = ce.Log("incidents-runs.txt", "bench/incidents.py all: worker stop, DB lock, slow handler, Tempo+Loki down, " + "Collector down (details: evidence/incidents/*.txt)") + log.run([ce.VENV_PY, "bench/incidents.py", "all"], shown="python bench/incidents.py all", timeout=5400) + log.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "auditor"], shown="docker compose run --rm auditor", + timeout=900) + + log = ce.Log("final-state.txt", "Final state of the stand") + log.run([ce.PYTHON, "scripts/obs.py", "alerts"], shown="python scripts/obs.py alerts") + log.run(["docker", "compose", "ps", "-a", "--format", "table {{.Service}}\t{{.Status}}"]) + print("done:", ce.EVIDENCE) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/demo_attachments.py b/scripts/demo_attachments.py new file mode 100644 index 0000000..2e24432 --- /dev/null +++ b/scripts/demo_attachments.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Lab 4 defense scenario (kept in lab 5; upload is now 202 queued, the download waits for ready): +upload the fixture, send a message with attachment_ids, +download as the second member and compare SHA-256; the outsider gets 404; an unauthenticated +request straight to S3 (from inside the storage network) is refused, the signed one works. + + python scripts/demo_attachments.py [--base-url http://127.0.0.1:8080] + +Prints requests and answers; never prints tokens or keys. Creates synthetic users. +""" +from __future__ import annotations + +import argparse +import base64 +import hashlib +import json +import subprocess +import sys +import urllib.error +import urllib.request +import uuid +from email.message import Message +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +FIXTURE = ROOT / "tests" / "fixtures" / "sample.png" +PASSWORD = "Demo-password-Ω-12345" + + +class Client: + def __init__(self, base: str): + self.base = base.rstrip("/") + + def call(self, method: str, path: str, *, token: str | None = None, body=None, raw: bytes | None = None, + headers: dict | None = None) -> tuple[int, Message, bytes]: + h = dict(headers or {}) + if token: + h["Authorization"] = "Bearer " + token + data = raw + if body is not None: + data = json.dumps(body, ensure_ascii=False).encode() + h["Content-Type"] = "application/json" + req = urllib.request.Request(self.base + path, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, r.headers, r.read() # case-insensitive HTTPMessage + except urllib.error.HTTPError as e: + return e.code, e.headers, e.read() + + +def show(label: str, status: int, headers: Message, payload: bytes, *, binary: bool = False) -> None: + inst = headers.get("X-Instance-Id", "-") + if binary: + text = f"{len(payload)} bytes, Content-Type {headers.get('Content-Type')}" + else: + text = payload.decode("utf-8", "replace")[:300] + print(f" {label:58} -> {status} [X-Instance-Id {inst}] {text}") + + +def user(c: Client, label: str) -> dict: + name = f"{label}_{uuid.uuid4().hex[:8]}" + status, _, body = c.call("POST", "/api/v1/users", body={"username": name, "display_name": label.title(), + "password": PASSWORD}) + assert status == 201, body + basic = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode() + status, _, body = c.call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}) + session = json.loads(body) + return {"id": session["user"]["id"], "token": session["token"], "name": name} + + +def wait_ready(c: Client, actor: dict, attachment_id: str, timeout: float = 60): + import time + deadline = time.monotonic() + timeout + while True: + st, h, b = c.call("GET", f"/api/v1/attachments/{attachment_id}", token=actor["token"]) + if st != 200 or json.loads(b)["status"] in ("ready", "failed") or time.monotonic() > deadline: + return st, h, b + time.sleep(0.3) + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("--base-url", default="http://127.0.0.1:8080") + args = p.parse_args() + c = Client(args.base_url) + content = FIXTURE.read_bytes() + print(f"fixture {FIXTURE.name}: {len(content)} bytes, sha256 {hashlib.sha256(content).hexdigest()}") + alice, bob, eve = user(c, "alice"), user(c, "bob"), user(c, "eve") + print(f"users: alice, bob (members), eve (outsider)") + status, _, body = c.call("POST", "/api/v1/chats", token=alice["token"], + body={"title": "Демо lab5", "member_ids": [alice["id"], bob["id"]]}) + chat = json.loads(body) + + print("\n1. upload -> message -> download by the second member") + st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", token=alice["token"], + raw=content, headers={"Content-Type": "image/png"}) + show("POST /chats/{id}/attachments (alice, raw PNG)", st, h, b) + att = json.loads(b) + st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"], + body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}) + show("POST /chats/{id}/messages text='' attachment_ids=[id]", st, h, b) + st, h, b = wait_ready(c, bob, att["id"]) + show("GET /attachments/{id} (bob) until ready", st, h, b) + st, h, got = c.call("GET", f"/api/v1/attachments/{att['id']}/content", token=bob["token"]) + show("GET /attachments/{id}/content (bob)", st, h, got, binary=True) + same = hashlib.sha256(got).hexdigest() == hashlib.sha256(content).hexdigest() == att["sha256"] + print(f" SHA-256 of the download == fixture == metadata: {same}") + + print("\n2. outsider and direct S3 access") + for suffix in ("", "/content"): + st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", token=eve["token"]) + show(f"GET /attachments/{{id}}{suffix} (eve, not a member)", st, h, b) + key = subprocess.run(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", + "-At", "-c", f"SELECT object_key FROM attachments WHERE id = '{att['id']}'"], + cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip() + print(f" object key in PostgreSQL: {key} (random; not in any API response: " + f"{key not in json.dumps(att)})") + probe = ( + "import urllib.request as u, urllib.error as e, asyncio\n" + "def st(url):\n" + " try: return u.urlopen(url, timeout=3).status\n" + " except e.HTTPError as x: return x.code\n" + f"print('anonymous GET http://s3:8333/messenger-attachments/{key} ->', st('http://s3:8333/messenger-attachments/{key}'))\n" + "print('anonymous LIST http://s3:8333/messenger-attachments?list-type=2 ->', st('http://s3:8333/messenger-attachments?list-type=2'))\n" + "from messenger.config import Settings\nfrom messenger.storage import Storage\n" + "async def m():\n s = Storage(Settings.from_env()); await s.open()\n" + f" print('signed HEAD with the API key pair ->', (await s.head('{key}')).size, 'bytes'); await s.close()\n" + "asyncio.run(m())\n") + out = subprocess.run(["docker", "compose", "exec", "-T", "api", "python", "-c", probe], cwd=ROOT, + capture_output=True, text=True).stdout + for line in out.splitlines(): + print(" (inside network storage) " + line) + print(" S3 is not published on the host at all: only the LB has ports (127.0.0.1:8080, 8404).") + return 0 if same else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/demo_pipeline.py b/scripts/demo_pipeline.py new file mode 100644 index 0000000..79bb19e --- /dev/null +++ b/scripts/demo_pipeline.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Lab 5 defense scenario, steps 2-3 (README): worker stopped -> upload 202 -> content 409 while the +rest of the API works -> a message with the attachment is created -> API and broker restarted with +their volumes -> worker started -> the same attachment becomes ready, thumbnail downloadable. + + python scripts/demo_pipeline.py [--base-url http://127.0.0.1:8080] + +Prints every step with HTTP codes, IDs, the outbox row and the queue depth; never prints tokens or +keys. Creates synthetic users. Always starts the worker again at the end. +""" +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import subprocess +import sys +import time +import uuid +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from demo_attachments import FIXTURE, ROOT, Client, show, user, wait_ready # noqa: E402 + + +def compose(*args: str, check: bool = True) -> str: + return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", + check=check, timeout=300).stdout + + +def psql(sql: str) -> str: + return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", sql).strip() + + +def queue_depth() -> str: + """messages/consumers of the jobs queue; rabbitmqctl refreshes these counters every ~5 s.""" + time.sleep(6) + out = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "messages", "consumers") + line = next(l for l in out.splitlines() if l.startswith("messenger.attachment-jobs\t")) + _, messages, consumers = line.split("\t") + return f"messages={messages} consumers={consumers}" + + +def wait_api(c: Client, timeout: float = 120) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + if c.call("GET", "/health/ready")[0] == 200: + return + except OSError: + pass + time.sleep(1) + raise SystemExit("API did not become ready") + + +def step(text: str) -> None: + print(f"\n[{time.strftime('%H:%M:%S')}] {text}") + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("--base-url", default="http://127.0.0.1:8080") + args = p.parse_args() + c = Client(args.base_url) + content = FIXTURE.read_bytes() + alice, bob = user(c, "alice"), user(c, "bob") + _, _, body = c.call("POST", "/api/v1/chats", token=alice["token"], + body={"title": "Демо lab5", "member_ids": [alice["id"], bob["id"]]}) + chat = json.loads(body) + try: + step("1. docker compose stop worker") + compose("stop", "worker") + print(" " + compose("ps", "-a", "--format", "{{.Service}} {{.State}}", "worker").strip()) + + step("2. upload while the worker is stopped") + st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", token=alice["token"], + raw=content, headers={"Content-Type": "image/png"}) + show("POST /chats/{id}/attachments", st, h, b) + att = json.loads(b) + print(f" attachment_id = {att['id']} status = {att['status']}") + for query in ("", "?variant=thumbnail"): + st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}/content{query}", token=bob["token"]) + show(f"GET /attachments/{{id}}/content{query}", st, h, b) + st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=bob["token"], + body={"text": "обычное сообщение работает"}, headers={"Idempotency-Key": uuid.uuid4().hex}) + show("POST /messages (text only)", st, h, b) + st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"], + body={"text": "фото", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}) + show("POST /messages attachment_ids=[queued id]", st, h, b) + message_id = json.loads(b)["id"] + time.sleep(2) + print(" job + outbox in PostgreSQL: " + psql( + "SELECT j.id || ' state=' || j.state || ' attempt=' || j.attempt || ' | outbox published_at=' || " + f"coalesce(o.published_at::text, 'NULL') FROM jobs j JOIN outbox o ON o.job_id = j.id " + f"WHERE j.attachment_id = '{att['id']}'")) + print(" RabbitMQ queue messenger.attachment-jobs: " + queue_depth()) + + step("3. docker compose restart api broker (volumes preserved)") + compose("restart", "api", "broker") + wait_api(c) + time.sleep(3) + print(" RabbitMQ queue after the restart: " + queue_depth()) + st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}", token=bob["token"]) + show("GET /attachments/{id}", st, h, b) + finally: + step("4. docker compose start worker") + compose("start", "worker") + st, h, b = wait_ready(c, bob, att["id"], timeout=90) + show("GET /attachments/{id} until ready", st, h, b) + ready = json.loads(b) + thumb = next(v for v in ready["variants"] if v["name"] == "thumbnail") + st, h, data = c.call("GET", f"/api/v1/attachments/{att['id']}/content?variant=thumbnail", token=bob["token"]) + show("GET /content?variant=thumbnail", st, h, data, binary=True) + from PIL import Image + size = Image.open(io.BytesIO(data)).size + ok = (st == 200 and hashlib.sha256(data).hexdigest() == thumb["sha256"] and size == (256, 160) + and ready["status"] == "ready") + print(f" thumbnail: real JPEG {size[0]}x{size[1]}, sha256 matches metadata: {ok}") + st, h, orig = c.call("GET", f"/api/v1/attachments/{att['id']}/content", token=bob["token"]) + print(f" original unchanged byte for byte: {orig == content}") + print(f" message {message_id} still references it: " + f"{psql(f'SELECT attachment_ids FROM messages WHERE id = {chr(39)}{message_id}{chr(39)}')}") + step("5. job history (jobctl show)") + shown = json.loads(compose("run", "--rm", "--no-deps", "-T", "jobctl", "show", att["id"])) + for e in shown["events"]: + print(f" {e['at']} {e['event']:16} attempt={e['attempt']} actor={e['actor']}") + return 0 if ok and orig == content else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/explain_history.py b/scripts/explain_history.py new file mode 100644 index 0000000..0a929ed --- /dev/null +++ b/scripts/explain_history.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""EXPLAIN (ANALYZE, BUFFERS) of the history query on >= 10 000 messages (level 4). + + python scripts/explain_history.py --output evidence/explain-history.txt + +Creates (once, idempotent) a synthetic chat with 20 000 messages plus 30 000 messages in +30 other chats, then explains the EXACT statements of src/messenger/repo.py: + 1. first page (HISTORY_FIRST) + 2. late page via cursor (HISTORY_AFTER) — generic plan forced, as a prepared statement + reused by the driver would get it + 3. the rejected variant `($2 IS NULL OR (created_at, id) > ...)` — generic plan + 4. the rejected OFFSET pagination for the same late page +Runs psql inside the postgres container; no database port is published. +""" +from __future__ import annotations + +import argparse +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) +from messenger.repo import HISTORY_AFTER, HISTORY_FIRST # noqa: E402 (the app's real SQL) + +CHAT = "00000000-0000-4000-8000-00000000e002" +USER = "00000000-0000-4000-8000-00000000e001" +TARGET = 20_000 +LATE = 19_950 # cursor position: the 50 newest messages remain + +SEED = f""" +\\set ON_ERROR_STOP on +BEGIN; +INSERT INTO users (id, username, display_name, password_hash) +VALUES ('{USER}', 'explain_seed', convert_to('Explain seed', 'UTF8'), 'not-a-login') ON CONFLICT DO NOTHING; +INSERT INTO chats (id, title, created_by, created_at) +SELECT ('00000000-0000-4000-8000-0000000' || lpad(to_hex(n), 5, '0'))::uuid, convert_to('explain ' || n, 'UTF8'), + '{USER}', timestamptz '2026-01-01 00:00:00+00' +FROM generate_series(57346::int, 57376::int) AS n -- e002 .. e020: target + 30 noise chats +ON CONFLICT DO NOTHING; +INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) +SELECT id, '{USER}', 0, created_at FROM chats WHERE created_by = '{USER}' ON CONFLICT DO NOTHING; +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT gen_random_uuid(), '{CHAT}', '{USER}', convert_to('synthetic message ' || g, 'UTF8'), + timestamptz '2026-01-01 00:00:00+00' + g * interval '1 second' +FROM generate_series(1::int, {TARGET}::int) AS g +WHERE NOT EXISTS (SELECT 1 FROM messages WHERE chat_id = '{CHAT}'); +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT gen_random_uuid(), c.id, '{USER}', convert_to('noise ' || g, 'UTF8'), + timestamptz '2026-01-01 00:00:00+00' + g * interval '1 second' +FROM chats c CROSS JOIN generate_series(1::int, 1000::int) AS g +WHERE c.created_by = '{USER}' AND c.id <> '{CHAT}' + AND NOT EXISTS (SELECT 1 FROM messages m WHERE m.chat_id = c.id); +COMMIT; +ANALYZE messages; +""" + + +def pg(sql_param: str) -> str: + """Turn psycopg %s placeholders into $1..$n for a PREPARE statement.""" + parts = sql_param.split("%s") + return "".join(p + (f"${i + 1}" if i < len(parts) - 1 else "") for i, p in enumerate(parts)) + + +EXPLAIN = f""" +\\set ON_ERROR_STOP on +\\pset pager off +SELECT count(*) AS messages_total, count(*) FILTER (WHERE chat_id = '{CHAT}') AS messages_in_target_chat FROM messages; +SELECT created_at AS cur_ts, id AS cur_id FROM messages WHERE chat_id = '{CHAT}' +ORDER BY created_at, id OFFSET {LATE - 1} LIMIT 1 \\gset +SET plan_cache_mode = force_generic_plan; +PREPARE first_page(uuid, int) AS {pg(HISTORY_FIRST)}; +PREPARE after_page(uuid, timestamptz, uuid, int) AS {pg(HISTORY_AFTER)}; +PREPARE or_page(uuid, timestamptz, uuid, int) AS + SELECT id, sender_id, text, created_at FROM messages + WHERE chat_id = $1 AND ($2 IS NULL OR (created_at, id) > ($2, $3)) ORDER BY created_at, id LIMIT $4; +PREPARE offset_page(uuid, int, int) AS + SELECT id, sender_id, text, created_at FROM messages WHERE chat_id = $1 ORDER BY created_at, id OFFSET $2 LIMIT $3; +\\echo '=== 1. first page, app query HISTORY_FIRST, generic plan' +EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE first_page('{CHAT}', 51); +\\echo '=== 2. late page (cursor at {LATE}), app query HISTORY_AFTER, generic plan' +EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE after_page('{CHAT}', :'cur_ts', :'cur_id', 51); +\\echo '=== 3. REJECTED: one query with ($2 IS NULL OR ...), same late page, generic plan' +EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE or_page('{CHAT}', :'cur_ts', :'cur_id', 51); +\\echo '=== 4. REJECTED: OFFSET pagination, same late page' +EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE offset_page('{CHAT}', {LATE}, 51); +""" + + +def psql(script: str) -> str: + result = subprocess.run( + ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-f", "-"], + cwd=ROOT, input=script, capture_output=True, text=True, encoding="utf-8", check=True) + return result.stdout + + +def run() -> str: + psql(SEED) + return psql(EXPLAIN) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--output", default=None) + args = parser.parse_args() + text = run() + print(text) + if args.output: + Path(args.output).write_text(text, encoding="utf-8", newline="\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/init_secrets.py b/scripts/init_secrets.py new file mode 100644 index 0000000..eb7e13e --- /dev/null +++ b/scripts/init_secrets.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Create local synthetic credentials for the stand in ./secrets (ignored by Git). + + python scripts/init_secrets.py + +Idempotent: existing files are kept, so re-running never changes passwords of a +database that already has data. Prints only file names, never values. +Delete ./secrets together with the volumes (`docker compose down -v`) to start over. +""" +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import secrets +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SECRETS = ROOT / "secrets" + + +def write(name: str, value: str) -> None: + path = SECRETS / name + if path.exists(): + print(f"keep secrets/{name}") + return + path.write_text(value + "\n", encoding="utf-8", newline="\n") + # Readable by the container users (postgres, valkey, seaweedfs, rabbitmq, app uid 10001) + # through the compose bind mount. Local synthetic lab credentials only. + os.chmod(path, 0o644) + print(f"created secrets/{name}") + + +def read(name: str) -> str: + return (SECRETS / name).read_text(encoding="utf-8").strip() + + +def rabbit_hash(password: str) -> str: + """RabbitMQ `rabbit_password_hashing_sha256`: base64(salt + sha256(salt + password)), 4-byte salt. + The broker stores and compares only this hash; the plain password is in the client's URL.""" + salt = secrets.token_bytes(4) + return base64.b64encode(salt + hashlib.sha256(salt + password.encode("utf-8")).digest()).decode("ascii") + + +def main() -> int: + SECRETS.mkdir(exist_ok=True) + write("postgres_password", secrets.token_urlsafe(24)) # [A-Za-z0-9_-]: safe inside URLs + write("valkey_password", secrets.token_urlsafe(24)) + write("database_url", f"postgresql://messenger:{read('postgres_password')}@postgres:5432/messenger") + write("cache_url", f"redis://:{read('valkey_password')}@valkey:6379/0") + # S3 key pairs (SeaweedFS identities, infra/seaweedfs/start.sh): admin = bucket bootstrap only; + # api = Write staging + Read final; worker = Read/Write both; auditor = Read + List (no Write). + for who in ("admin", "api", "worker", "auditor"): + write(f"s3_{who}_access_key_id", "AK" + secrets.token_hex(9).upper()) + write(f"s3_{who}_secret_access_key", secrets.token_hex(20)) + # Lab 5: RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume + # the jobs queue; neither may declare/delete anything (configure "^$"). + write("rabbitmq_relay_password", secrets.token_urlsafe(24)) + write("rabbitmq_worker_password", secrets.token_urlsafe(24)) + users = { + "users": [{"name": who, "password_hash": rabbit_hash(read(f"rabbitmq_{who}_password")), + "hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []} for who in ("relay", "worker")], + "permissions": [ + {"user": "relay", "vhost": "/", "configure": "^$", "write": "^messenger\\.jobs$", "read": "^$"}, + {"user": "worker", "vhost": "/", "configure": "^$", "write": "^$", "read": "^messenger\\.attachment-jobs$"}, + ], + } + write("rabbitmq_users.json", json.dumps(users, indent=1)) + for who in ("relay", "worker"): + # AMQP heartbeat 10 s: a frozen client loses its connection after ~2 missed heartbeats, and + # the broker returns its unacked messages to the queue for the other consumers. + write(f"broker_url_{who}", f"amqp://{who}:{read(f'rabbitmq_{who}_password')}@broker:5672/?heartbeat=10") + # Lab 6: Grafana admin (UI on 127.0.0.1:3000 and the evidence scripts, via its datasource proxy). + write("grafana_admin_password", secrets.token_urlsafe(18)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/lbctl.py b/scripts/lbctl.py new file mode 100644 index 0000000..259d35e --- /dev/null +++ b/scripts/lbctl.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""What the load balancer thinks right now, mapped to real containers. + + python scripts/lbctl.py status # table: HAProxy slot, IP, UP/DOWN/MAINT, container, X-Instance-Id + python scripts/lbctl.py wait-up 2 # wait until exactly 2 API replicas are UP in HAProxy + python scripts/lbctl.py replicas # api containers of this compose project: name, hostname, state + +Reads HAProxy's runtime API (`show servers state api`) through `docker compose exec lb socat`, +so no admin port is published. Container hostname = X-Instance-Id of that replica. +Prints no secrets. Used by student-tests and bench scripts as a library as well. +""" +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +# srv_op_state of HAProxy (src/server.h): 0 stopped, 1 starting, 2 running, 3 stopping. +OP_STATE = {0: "DOWN", 1: "STARTING", 2: "UP", 3: "STOPPING"} +ADMIN_RMAINT = 0x20 # slot without a resolved address (no running container behind it) + + +def run(*args: str, timeout: float = 60) -> str: + result = subprocess.run(list(args), cwd=ROOT, capture_output=True, text=True, encoding="utf-8", + timeout=timeout) + if result.returncode != 0: + raise RuntimeError(f"{' '.join(args[:3])}... failed: {result.stderr.strip()[:300]}") + return result.stdout + + +def replicas(all_states: bool = True) -> list[dict]: + """API containers of this compose project (running and stopped).""" + ids = run("docker", "compose", "ps", "-q", *(["-a"] if all_states else []), "api").split() + if not ids: + return [] + data = json.loads(run("docker", "inspect", *ids)) + result = [] + for item in data: + networks = item["NetworkSettings"]["Networks"] or {} + result.append({ + "id": item["Id"][:12], + "name": item["Name"].lstrip("/"), + "hostname": item["Config"]["Hostname"], + "state": item["State"]["Status"], + "health": (item["State"].get("Health") or {}).get("Status", "-"), + "exit_code": item["State"]["ExitCode"], + "started_at": item["State"]["StartedAt"], + "pid": item["State"]["Pid"], + "ips": sorted(n["IPAddress"] for n in networks.values() if n.get("IPAddress")), + # compose network name without the project prefix -> IP, e.g. {"edge": ..., "data": ...} + "networks": {name.split("_", 1)[-1]: n["IPAddress"] for name, n in networks.items() if n.get("IPAddress")}, + }) + return sorted(result, key=lambda r: r["name"]) + + +def lb_servers() -> list[dict]: + raw = run("docker", "compose", "exec", "-T", "lb", "sh", "-c", + 'echo "show servers state api" | socat stdio /var/lib/haproxy/admin.sock') + by_ip = {ip: r for r in replicas() for ip in r["ips"]} + servers = [] + for line in raw.splitlines(): + parts = line.split() + if len(parts) < 7 or not parts[0].isdigit(): + continue + name, addr, op, admin = parts[3], parts[4], int(parts[5]), int(parts[6]) + if admin & ADMIN_RMAINT or addr == "-": + state = "MAINT" + else: + state = OP_STATE.get(op, str(op)) + container = by_ip.get(addr) + servers.append({"slot": name, "addr": addr, "state": state, + "container": container["name"] if container else None, + "instance_id": container["hostname"] if container else None}) + return servers + + +def up_instances() -> set[str]: + return {s["instance_id"] or s["addr"] for s in lb_servers() if s["state"] == "UP"} + + +def wait_up(count: int, timeout: float = 60) -> float: + """Seconds until exactly `count` servers are UP (raises TimeoutError otherwise).""" + started = time.monotonic() + while True: + try: + if len(up_instances()) == count: + return time.monotonic() - started + except RuntimeError: + pass # lb restarting + if time.monotonic() - started > timeout: + raise TimeoutError(f"HAProxy does not report {count} UP API replicas after {timeout:.0f} s") + time.sleep(0.25) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("status") + sub.add_parser("replicas") + wait = sub.add_parser("wait-up") + wait.add_argument("count", type=int) + wait.add_argument("--timeout", type=float, default=60) + args = parser.parse_args() + if args.command == "status": + for s in lb_servers(): + if s["state"] != "MAINT" or s["container"]: + print(f"{s['slot']:6} {s['addr']:15} {s['state']:8} {s['container'] or '-':24} X-Instance-Id={s['instance_id'] or '-'}") + print(f"(other slots: MAINT, no container)") + elif args.command == "replicas": + for r in replicas(): + print(f"{r['name']:24} X-Instance-Id={r['hostname']} {r['state']:8} health={r['health']:9} " + f"pid={r['pid']} started={r['started_at'][:23]} ip={','.join(r['ips']) or '-'}") + else: + took = wait_up(args.count, args.timeout) + print(f"{args.count} API replica(s) UP in HAProxy after {took:.1f} s: {sorted(up_instances())}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/obs.py b/scripts/obs.py new file mode 100644 index 0000000..218e838 --- /dev/null +++ b/scripts/obs.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""Read the stored observations (Prometheus, Loki, Tempo) through Grafana's datasource proxy. + +Only Grafana is published (127.0.0.1:3000); the stores stay on the internal network. The admin +password comes from secrets/grafana_admin_password and is never printed. + + python scripts/obs.py promql 'sum(rate(http_server_request_duration_seconds_count[1m]))' + python scripts/obs.py alerts # Prometheus alerts: state, since + python scripts/obs.py trace # span tree of one trace (Tempo) + python scripts/obs.py logs # log records of one trace (Loki) + python scripts/obs.py search '{ span.messenger.job.outcome = "retry" }' # TraceQL +Used as a library by student-tests/test_observability.py and bench/*.py. +""" +from __future__ import annotations + +import base64 +import json +import os +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +GRAFANA = os.environ.get("GRAFANA_URL", "http://127.0.0.1:3000").rstrip("/") + + +def _auth() -> str: + password = os.environ.get("GRAFANA_PASSWORD") or (ROOT / "secrets" / "grafana_admin_password").read_text( + encoding="utf-8").strip() + return "Basic " + base64.b64encode(f"admin:{password}".encode()).decode() + + +def get(uid: str, path: str, params: dict | None = None, timeout: float = 30) -> dict: + url = f"{GRAFANA}/api/datasources/proxy/uid/{uid}/{path.lstrip('/')}" + if params: + url += "?" + urllib.parse.urlencode(params) + request = urllib.request.Request(url, headers={"Authorization": _auth(), "Accept": "application/json"}) + with urllib.request.urlopen(request, timeout=timeout) as response: + return json.loads(response.read()) + + +# ----------------------------------------------------------------------------- Prometheus +def promql(expr: str, at: float | None = None) -> list[dict]: + params = {"query": expr} + if at is not None: + params["time"] = f"{at:.3f}" + return get("prometheus", "api/v1/query", params)["data"]["result"] + + +def scalar(expr: str, default: float | None = None) -> float | None: + """Single value of an instant query (first series), or `default` when there is none.""" + result = promql(expr) + if not result: + return default + value = float(result[0]["value"][1]) + return default if value != value else value # NaN -> default + + +def series(expr: str, start: float, end: float, step: float = 5) -> list[dict]: + return get("prometheus", "api/v1/query_range", + {"query": expr, "start": f"{start:.3f}", "end": f"{end:.3f}", "step": str(step)})["data"]["result"] + + +def alerts() -> list[dict]: + """Active alerts (pending/firing) of Prometheus: [{name, state, activeAt, value, labels}].""" + data = get("prometheus", "api/v1/alerts")["data"]["alerts"] + return [{"name": a["labels"].get("alertname"), "state": a["state"], "activeAt": a.get("activeAt"), + "value": a.get("value"), "labels": a["labels"]} for a in data] + + +def alert_state(name: str) -> str: + """inactive | pending | firing (highest of the alert's series).""" + states = {a["state"] for a in alerts() if a["name"] == name} + return "firing" if "firing" in states else "pending" if "pending" in states else "inactive" + + +# ----------------------------------------------------------------------------- Tempo +def trace_spans(trace_id: str) -> list[dict]: + """Flat list of spans: {service, name, kind, span_id, parent_id, start, end, duration_ms, status, attrs}.""" + data = get("tempo", f"api/v2/traces/{trace_id}") + spans = [] + for rs in data.get("trace", data).get("resourceSpans", []): + rattrs = _attrs(rs.get("resource", {}).get("attributes", [])) + for ss in rs.get("scopeSpans", []): + for sp in ss.get("spans", []): + start, end = int(sp["startTimeUnixNano"]), int(sp["endTimeUnixNano"]) + spans.append({ + "service": rattrs.get("service.name"), "instance": rattrs.get("service.instance.id"), + "name": sp["name"], "kind": sp.get("kind", "").replace("SPAN_KIND_", ""), + "span_id": _hex(sp.get("spanId", "")), "parent_id": _hex(sp.get("parentSpanId", "")), + "start": start, "end": end, "duration_ms": (end - start) / 1e6, + "status": sp.get("status", {}).get("code", "STATUS_CODE_UNSET").replace("STATUS_CODE_", ""), + "attrs": _attrs(sp.get("attributes", [])), + }) + return sorted(spans, key=lambda s: s["start"]) + + +def wait_trace(trace_id: str, predicate, timeout: float = 60) -> list[dict]: + """Poll Tempo until predicate(spans) is true (spans arrive within a few seconds).""" + deadline = time.monotonic() + timeout + spans: list[dict] = [] + while time.monotonic() < deadline: + try: + spans = trace_spans(trace_id) + if spans and predicate(spans): + return spans + except urllib.error.HTTPError as exc: + if exc.code != 404: + raise + time.sleep(2) + raise AssertionError(f"trace {trace_id}: condition not met within {timeout} s; {len(spans)} spans") + + +def search(traceql: str, minutes: int = 60, limit: int = 20) -> list[dict]: + end = int(time.time()) + return get("tempo", "api/search", {"q": traceql, "start": end - minutes * 60, "end": end, + "limit": limit}).get("traces", []) + + +def _hex(value: str) -> str: + if not value: + return "" + if all(c in "0123456789abcdef" for c in value.lower()) and len(value) in (16, 32): + return value.lower() + return base64.b64decode(value).hex() # OTLP JSON may carry ids base64-encoded + + +def _attrs(items: list) -> dict: + out = {} + for item in items: + value = item.get("value", {}) + out[item["key"]] = next(iter(value.values())) if value else None + return out + + +def tree(spans: list[dict]) -> str: + """Indented text tree (parent -> children), times relative to the first span.""" + by_parent: dict[str, list[dict]] = {} + ids = {s["span_id"] for s in spans} + for s in spans: + by_parent.setdefault(s["parent_id"] if s["parent_id"] in ids else "", []).append(s) + t0 = spans[0]["start"] if spans else 0 + lines: list[str] = [] + + def walk(parent: str, depth: int) -> None: + for s in by_parent.get(parent, []): + extra = {k: v for k, v in s["attrs"].items() if k in ( + "http.route", "http.response.status_code", "messenger.job.attempt", "messenger.job.outcome", + "messenger.job.error_code", "db.client.connection.wait_time_ms", "error.type")} + lines.append(f"{' ' * depth}+{(s['start'] - t0) / 1e6:9.1f} ms {s['duration_ms']:8.1f} ms " + f"[{s['service']}] {s['kind']:<8} {s['name']} {s['status'] if s['status'] != 'UNSET' else ''} " + f"{json.dumps(extra, ensure_ascii=False) if extra else ''}".rstrip()) + walk(s["span_id"], depth + 1) + walk("", 0) + return "\n".join(lines) + + +# ----------------------------------------------------------------------------- Loki +def logs(query: str, minutes: int = 60, limit: int = 200) -> list[dict]: + """Records of a LogQL query: {ts, service, line, metadata} (oldest first).""" + end = time.time_ns() + data = get("loki", "loki/api/v1/query_range", {"query": query, "start": end - minutes * 60 * 10**9, "end": end, + "limit": limit, "direction": "backward"}) + out = [] + for stream in data["data"]["result"]: + labels = stream["stream"] + for value in stream["values"]: + ts, line = value[0], value[1] + meta = value[2].get("structuredMetadata", {}) if len(value) > 2 and isinstance(value[2], dict) else {} + out.append({"ts": int(ts), "service": labels.get("service_name"), "line": line, + "metadata": {**{k: v for k, v in labels.items()}, **meta}}) + return sorted(out, key=lambda r: r["ts"]) + + +def trace_logs(trace_id: str, minutes: int = 60) -> list[dict]: + return logs(f'{{service_name=~"messenger-.+"}} | trace_id="{trace_id}"', minutes) + + +# ----------------------------------------------------------------------------- CLI +def main(argv: list[str]) -> int: + if len(argv) < 2: + print(__doc__) + return 2 + cmd, args = argv[1], argv[2:] + if cmd == "promql": + for s in promql(args[0]): + print(json.dumps(s["metric"], ensure_ascii=False), s["value"][1]) + elif cmd == "alerts": + for a in alerts(): + print(f"{a['name']:<32} {a['state']:<8} since {a['activeAt']} value={a['value']}") + elif cmd == "trace": + print(tree(trace_spans(args[0]))) + elif cmd == "logs": + for r in trace_logs(args[0]): + meta = r["metadata"] + print(f"{r['service']:<17} {meta.get('detected_level', meta.get('severity_text', '')):<6} {r['line']:<22} " + f"span={meta.get('span_id', '')} " + " ".join( + f"{k}={meta[k]}" for k in ("request_id", "route", "status", "job_id", "outcome", "attempt") + if k in meta)) + elif cmd == "search": + for t in search(args[0]): + print(t.get("traceID"), t.get("rootServiceName"), t.get("rootTraceName"), t.get("durationMs"), "ms") + else: + print(__doc__) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 0000000..f8a4ff9 --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,6 @@ +@echo off +rem Windows wrapper: tests/resilience.py starts the hook as a program, and Windows +rem cannot execute a .sh file directly. Runs the same scripts\restart.sh with Git Bash. +rem python tests/resilience.py --mode persistence --action-script scripts/restart.cmd +"%ProgramFiles%\Git\bin\bash.exe" "%~dp0restart.sh" +exit /b %ERRORLEVEL% diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 0000000..a16c322 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`. +# Restarts EVERY process of the stand: LB, all API replicas, relay, worker(s), PostgreSQL, Valkey, +# S3 (SeaweedFS) and the broker (RabbitMQ). Volumes, schema, data and queued messages are +# preserved: no `down -v`, no FLUSH, no purge, no re-seed. +# Output is suppressed by the test; run it by hand to see the steps. +set -eu +cd "$(dirname "$0")/.." + +# 1. Entry point, API and the pipeline processes first: nothing is served or processed while the +# stores restart underneath. +docker compose stop lb api relay worker +# 2. Stores: clean shutdown (PostgreSQL checkpoint, Valkey AOF fsync, SeaweedFS volume/filer +# flush, RabbitMQ quorum log), then start again. Bytes live on s3data, messages on rabbitmqdata. +docker compose restart postgres valkey s3 broker +# 3. API replicas (wait for healthy stores via depends_on), the LB, then relay and worker. HAProxy +# resolves the new replica addresses through Docker DNS by itself - no stale backend list. +docker compose start api +docker compose start lb +docker compose start relay worker +echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3 and broker restarted with volumes preserved" diff --git a/scripts/restore-api.sh b/scripts/restore-api.sh new file mode 100644 index 0000000..78a0684 --- /dev/null +++ b/scripts/restore-api.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# Start every stopped API replica again (after scripts/stop-one.sh) and wait until Docker +# reports them healthy. The LB picks them up by itself (DNS re-resolution + checks, ~2-3 s); +# `python scripts/lbctl.py wait-up 2` waits for that explicitly. +set -eu +cd "$(dirname "$0")/.." +docker compose up -d --no-recreate --no-deps --wait api +docker compose ps api --format '{{.Name}} {{.Status}}' diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100644 index 0000000..5a8e426 --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# Rolling update of the API without downtime (Compose has no built-in one for a scaled service). +# 1. build the new image from the working tree; +# 2. run migrations ONCE with the new image (they must be additive / compatible with the +# running old version: expand first, contract in a later release); +# 3. for every OLD replica: start one NEW replica (scale N+1, old ones untouched), wait until +# Docker says healthy AND HAProxy has N+1 replicas UP, then stop the old one gracefully +# (SIGTERM -> readiness 503 -> HAProxy DOWN -> drain -> exit) and remove it. +# At every moment at least N replicas serve traffic. Stops on the first error (set -e); +# the old replicas that were not replaced yet keep running. +set -eu +cd "$(dirname "$0")/.." +PY="${PYTHON:-$(command -v python3 || command -v python)}" +# New image = new revision label (git commit + UTC time), visible in docker inspect and logs. +BUILD_REVISION="${BUILD_REVISION:-$(git rev-parse --short HEAD 2>/dev/null || echo dev)-$(date -u +%Y%m%dT%H%M%SZ)}" +export BUILD_REVISION + +replicas="$(docker compose ps -q api | wc -l | tr -d ' ')" +[ "$replicas" -ge 1 ] || { echo "rolling-update: no running api replica" >&2; exit 2; } +old="$(docker compose ps -q api)" +echo "rolling-update: $replicas replica(s) to replace, new revision $BUILD_REVISION" + +docker compose build api +docker compose run --rm --no-deps migrate + +for id in $old; do + name="$(docker inspect -f '{{.Name}}' "$id" | tr -d '/')" + docker compose up -d --no-deps --no-recreate --wait --scale "api=$((replicas + 1))" api + "$PY" scripts/lbctl.py wait-up "$((replicas + 1))" --timeout 60 + docker stop --time 15 "$id" >/dev/null + docker rm "$id" >/dev/null + "$PY" scripts/lbctl.py wait-up "$replicas" --timeout 60 + echo "rolling-update: replaced $name" +done +for id in $(docker compose ps -q api); do + docker inspect -f '{{.Name}} revision={{index .Config.Labels "org.opencontainers.image.revision"}} {{.State.Status}}' "$id" +done diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 0000000..1292249 --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,7 @@ +@echo off +rem Windows wrapper: tests/resilience.py starts the hook as a program, and Windows +rem cannot execute a .sh file directly. Runs the same scripts\stop-one.sh with Git Bash; +rem TARGET_INSTANCE_ID and STOP_MODE are inherited from the environment. +rem python tests/resilience.py --mode failover --action-script scripts/stop-one.cmd +"%ProgramFiles%\Git\bin\bash.exe" "%~dp0stop-one.sh" +exit /b %ERRORLEVEL% diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 0000000..85bc37a --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# Failover hook for `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`. +# Stops exactly ONE API replica: the container whose X-Instance-Id (= container hostname, +# see src/messenger/config.py) is in TARGET_INSTANCE_ID. DB, Valkey, LB and volumes are +# not touched. The replica is LEFT STOPPED (`docker stop` = no restart by the policy); +# restore it explicitly afterwards: scripts/restore-api.sh. +# STOP_MODE=stop (default) SIGTERM: readiness 503, 3 s drain, graceful exit (~4 s) +# STOP_MODE=kill SIGKILL at once (`docker stop -t 0`): crash of the process +# Returns within 10 s. The test hides the output; run by hand to see it (no secrets printed). +set -eu +cd "$(dirname "$0")/.." +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +case "$TARGET_INSTANCE_ID" in + *[!A-Za-z0-9._-]*) echo "stop-one: invalid TARGET_INSTANCE_ID" >&2; exit 2 ;; +esac +mode="${STOP_MODE:-stop}" + +target="" +# Only RUNNING containers of THIS compose project's service `api` are candidates. +for id in $(docker compose ps -q api); do + if [ "$(docker inspect -f '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then + target="$id" + fi +done +if [ -z "$target" ]; then + echo "stop-one: no running api replica with X-Instance-Id=$TARGET_INSTANCE_ID" >&2 + exit 3 +fi +name="$(docker inspect -f '{{.Name}}' "$target")" +case "$mode" in + stop) docker stop --time 15 "$target" >/dev/null ;; + kill) docker stop --time 0 "$target" >/dev/null ;; + *) echo "stop-one: STOP_MODE must be stop or kill" >&2; exit 2 ;; +esac +echo "stop-one: $mode $name (X-Instance-Id=$TARGET_INSTANCE_ID) -> $(docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}}' "$target")" diff --git a/scripts/trace_demo.py b/scripts/trace_demo.py new file mode 100644 index 0000000..52ff523 --- /dev/null +++ b/scripts/trace_demo.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Controlled request -> its trace and logs (defense scenario, steps 2-3; evidence/trace-demo.txt). + + python scripts/trace_demo.py [--base-url http://localhost:8080] [--output evidence/trace-demo.txt] + +1. creates a synthetic user and chat, uploads tests/fixtures/sample.png with OUR OWN W3C + `traceparent` header (trace id chosen here) and X-Request-Id; +2. waits until the attachment is ready; +3. reads the trace from Tempo and the log records of that trace from Loki (through Grafana); +4. checks: the API continued OUR trace (same trace id, the SERVER span's parent = our span id), + the chain upload -> db enqueue -> relay PRODUCER -> worker CONSUMER -> s3/db spans exists, + and api + worker log records carry this trace_id. Prints the span tree and the log lines. +No token, password or image bytes are printed. +""" +from __future__ import annotations + +import argparse +import base64 +import json +import secrets +import sys +import time +import urllib.request +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +import obs # noqa: E402 + + +def call(base: str, method: str, path: str, body=None, headers=None, raw: bytes | None = None): + h = dict(headers or {}) + data = raw + if body is not None: + data = json.dumps(body).encode() + h["Content-Type"] = "application/json" + request = urllib.request.Request(base + path, data=data, method=method, headers=h) + with urllib.request.urlopen(request, timeout=30) as response: + return response.status, response.headers, json.loads(response.read() or b"null") + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://localhost:8080") + parser.add_argument("--output") + args = parser.parse_args() + base = args.base_url.rstrip("/") + "/api/v1" + out: list[str] = [] + + def say(line: str = "") -> None: + print(line) + out.append(line) + + username = "trace_" + uuid.uuid4().hex[:10] + password = "Trace-demo-" + secrets.token_hex(8) + _, _, user = call(base, "POST", "/users", {"username": username, "display_name": "Trace demo", "password": password}) + auth = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode() + _, _, session = call(base, "POST", "/auth/sessions", headers={"Authorization": auth}) + bearer = {"Authorization": "Bearer " + session["token"]} + _, _, chat = call(base, "POST", "/chats", {"title": "trace demo", "member_ids": [user["id"]]}, bearer) + + trace_id, parent_span = secrets.token_hex(16), secrets.token_hex(8) + request_id = "trace-demo-" + uuid.uuid4().hex[:8] + image = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() + status, headers, att = call(base, "POST", f"/chats/{chat['id']}/attachments?filename=sample.png", raw=image, + headers={**bearer, "Content-Type": "image/png", "X-Request-Id": request_id, + "traceparent": f"00-{trace_id}-{parent_span}-01"}) + say(f"upload: HTTP {status}, status={att['status']}, X-Request-Id={headers.get('X-Request-Id')}, " + f"X-Instance-Id={headers.get('X-Instance-Id')}, X-Trace-Id={headers.get('X-Trace-Id')}") + say(f"sent traceparent: 00-{trace_id}-{parent_span}-01") + assert headers.get("X-Trace-Id") == trace_id, "the API must continue the caller's trace" + deadline = time.monotonic() + 60 + while att["status"] not in ("ready", "failed"): + assert time.monotonic() < deadline, "not ready within 60 s" + time.sleep(0.5) + _, _, att = call(base, "GET", f"/attachments/{att['id']}", headers=bearer) + say(f"attachment {att['id']}: {att['status']}, variants={[v['name'] for v in att['variants']]}") + + def complete(spans): + kinds = {(s["service"], s["kind"]) for s in spans} + return (("messenger-api", "SERVER") in kinds and ("messenger-relay", "PRODUCER") in kinds + and ("messenger-worker", "CONSUMER") in kinds + and any(s["name"] == "db jobs.complete" for s in spans)) + spans = obs.wait_trace(trace_id, complete, timeout=90) + say(f"\nTempo: trace {trace_id}, {len(spans)} spans") + say(obs.tree(spans)) + + server = next(s for s in spans if s["service"] == "messenger-api" and s["kind"] == "SERVER") + producer = next(s for s in spans if s["kind"] == "PRODUCER") + consumer = next(s for s in spans if s["kind"] == "CONSUMER") + ids = {s["span_id"]: s for s in spans} + checks = { + "API SERVER span continues our traceparent (parent = our span id)": server["parent_id"] == parent_span, + "relay PRODUCER is inside the upload trace (ancestor = API SERVER span)": _ancestor(producer, server, ids), + "worker CONSUMER is a child of the PRODUCER": consumer["parent_id"] == producer["span_id"], + "worker wrote to S3 inside the job (s3 put spans)": any( + s["name"] == "s3 put" and _ancestor(s, consumer, ids) for s in spans), + "worker committed the result (db jobs.complete span)": any( + s["name"] == "db jobs.complete" and _ancestor(s, consumer, ids) for s in spans), + } + + time.sleep(3) + records = obs.trace_logs(trace_id) + say(f"\nLoki: {len(records)} log records with trace_id={trace_id}") + for r in records: + m = r["metadata"] + say(f" {r['service']:<17} {r['line']:<18} span_id={m.get('span_id', '')} " + " ".join( + f"{k}={m[k]}" for k in ("request_id", "route", "status", "job_id", "outcome") if k in m)) + services = {r["service"] for r in records} + checks["API log record of the request has this trace_id and our X-Request-Id"] = any( + r["service"] == "messenger-api" and r["metadata"].get("request_id") == request_id for r in records) + checks["worker log record (job_done) has this trace_id"] = any( + r["service"] == "messenger-worker" and r["line"] == "job_done" for r in records) + say("\nChecks:") + for name, ok in checks.items(): + say(f" [{'PASS' if ok else 'FAIL'}] {name}") + say(f"services in logs: {sorted(services)}") + if args.output: + Path(args.output).parent.mkdir(parents=True, exist_ok=True) + Path(args.output).write_text("\n".join(out) + "\n", encoding="utf-8", newline="\n") + return 0 if all(checks.values()) else 1 + + +def _ancestor(span: dict, ancestor: dict, ids: dict) -> bool: + seen = 0 + while span["parent_id"] and seen < 100: + if span["parent_id"] == ancestor["span_id"]: + return True + span = ids.get(span["parent_id"]) + if span is None: + return False + seen += 1 + return False + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/messenger/__init__.py b/src/messenger/__init__.py new file mode 100644 index 0000000..4ea994b --- /dev/null +++ b/src/messenger/__init__.py @@ -0,0 +1,3 @@ +"""Messenger for the MTUSI course «Высоконагруженные приложения» (lab 6: observability).""" + +__version__ = "1.6.0" diff --git a/src/messenger/__main__.py b/src/messenger/__main__.py new file mode 100644 index 0000000..badcc59 --- /dev/null +++ b/src/messenger/__main__.py @@ -0,0 +1,92 @@ +"""Entry point: `python -m messenger`. The HTTP server is the main process (PID 1 in Docker). + +Shutdown sequence on SIGTERM/SIGINT (lab 3: the replica stands behind HAProxy): +1. readiness flips to 503 (`app.state.draining = True`), requests are still served; +2. after DRAIN_SECONDS (compose: 3 s > HAProxy detection 2 x 1 s) the load balancer has + marked this replica DOWN and sends nothing new here; +3. uvicorn closes the listening socket; in-flight requests get up to + SHUTDOWN_TIMEOUT_SECONDS (compose: 8 s) to finish; +4. the lifespan closes the DB pool and the Valkey client; the process exits with code 0. + DRAIN + SHUTDOWN (11 s) < compose stop_grace_period (15 s), so Docker never needs SIGKILL. +A second signal during the drain skips the rest of it. Data stays in PostgreSQL and Valkey. +""" +from __future__ import annotations + +import logging +import os +import sys +import threading +from types import FrameType + +import uvicorn + +from . import __version__, logging_setup, telemetry +from .app import create_app +from .config import ConfigError, Settings + +log = logging.getLogger("messenger") + + +class GracefulServer(uvicorn.Server): + """uvicorn.Server that drains (readiness 503, still serving) before the normal graceful stop.""" + + def __init__(self, config: uvicorn.Config, drain_seconds: float): + super().__init__(config) + self.drain_seconds = drain_seconds + self.drain_timer: threading.Timer | None = None + + def handle_exit(self, sig: int, frame: FrameType | None) -> None: + self.config.app.state.draining = True # config.app is our Starlette instance + if self.drain_timer is None and self.drain_seconds > 0 and not self.should_exit: + log.info("drain_started", extra={"fields": {"signal": sig, "drain_s": self.drain_seconds, + "timeout_s": self.config.timeout_graceful_shutdown}}) + # uvicorn polls should_exit in its main loop, so setting it from a timer thread is safe. + self.drain_timer = threading.Timer(self.drain_seconds, self._stop, args=(sig, frame)) + self.drain_timer.daemon = True + self.drain_timer.start() + return + if self.drain_timer is not None: + self.drain_timer.cancel() # second signal: stop draining now + self._stop(sig, frame) + + def _stop(self, sig: int, frame: FrameType | None) -> None: + if not self.should_exit: + log.info("shutdown_requested", extra={"fields": {"signal": sig}}) + super().handle_exit(sig, frame) + + +def main() -> int: + try: + settings = Settings.from_env() + except ConfigError as exc: + print(f"configuration error: {exc}", file=sys.stderr) + return 2 + logging_setup.configure(settings.log_level) + telemetry.setup("messenger-api", settings.instance_id, __version__) + app = create_app(settings) + config = uvicorn.Config( + app, + host=settings.host, + port=settings.port, + log_config=None, + access_log=False, + server_header=False, + proxy_headers=False, + lifespan="on", + timeout_graceful_shutdown=settings.shutdown_timeout, + ) + server = GracefulServer(config, settings.drain_seconds) + log.info("starting", extra={"fields": { + "version": __version__, "revision": os.environ.get("APP_REVISION", "dev"), "env": settings.env, "host": settings.host, "port": settings.port, + "python": sys.version.split()[0], "storage": "postgresql", "instance_id": settings.instance_id, + }}) + try: + server.run() + finally: + log.info("stopped") + telemetry.shutdown() # flush buffered spans/logs/metrics, bounded by the exporter timeouts + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/messenger/app.py b/src/messenger/app.py new file mode 100644 index 0000000..cfc902f --- /dev/null +++ b/src/messenger/app.py @@ -0,0 +1,682 @@ +"""HTTP layer: Starlette routes, request-id/logging middleware and error mapping.""" +from __future__ import annotations + +import asyncio +import contextlib +import hashlib +import json +import logging +import random +import re +import time +import uuid +from typing import Any + +from starlette.applications import Starlette +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.responses import JSONResponse, Response, StreamingResponse +from starlette.routing import Route +from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Send + +from opentelemetry import context as otel_context +from opentelemetry import trace + +from . import attachments, authhdr, cursor, docs, passwords, repo, telemetry, validation +from .config import Settings +from .db import Database +from .errors import BASIC_CHALLENGE, ApiError, Conflict, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable +from .sessions import SessionStore, build_store +from .storage import ObjectMissing, Storage +from .timefmt import rfc3339 + +log = logging.getLogger("messenger") +access_log = logging.getLogger("messenger.access") + +REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}") + + +# -------------------------------------------------------------------------- +# Responses +# -------------------------------------------------------------------------- +def error_response(request_id: str, status: int, code: str, message: str, headers: dict[str, str] | None = None) -> JSONResponse: + body = {"error": {"code": code, "message": message, "request_id": request_id}} + return JSONResponse(body, status_code=status, headers={"X-Request-Id": request_id, **(headers or {})}) + + +async def api_error_handler(request: Request, exc: Exception) -> JSONResponse: + assert isinstance(exc, ApiError) + return error_response(request.state.request_id, exc.status, exc.code, exc.message, exc.headers) + + +async def http_exception_handler(request: Request, exc: Exception) -> JSONResponse: + """Unknown routes and wrong methods also answer in the contract error format.""" + assert isinstance(exc, HTTPException) + if exc.status_code == 404: + return error_response(request.state.request_id, 404, "not_found", "Объект не найден") + if exc.status_code == 405: + return error_response(request.state.request_id, 405, "invalid_request", "Метод не поддерживается", exc.headers) + return error_response(request.state.request_id, exc.status_code, "invalid_request", "Неверный запрос") + + +# -------------------------------------------------------------------------- +# Middleware (pure ASGI, so it also covers 404/405 and unexpected exceptions) +# -------------------------------------------------------------------------- +class RequestContextMiddleware: + """Adds X-Request-Id and X-Instance-Id to EVERY response (errors, health and crash 500/503 + included), writes one access-log line, turns crashes into 500. + + Lab 6: this outermost middleware is also the HTTP SERVER span and the HTTP metrics. The span + continues the caller's W3C `traceparent` (extracted from the headers BEFORE the span starts, + so a client-supplied trace is continued, not replaced by a new root). The route TEMPLATE + (`/api/v1/chats/{chat_id}/messages`) is taken from the Starlette route that served the request, + never the raw path: it names the span and labels the metrics. /health/* gets metrics but no + span (HAProxy and Docker poll it every second; those traces would only bury the real ones). + Response header X-Trace-Id = the trace of this request (to find it in Grafana/Tempo).""" + + def __init__(self, app: ASGIApp, instance_id: str): + self.app = app + self.instance_id = instance_id.encode("ascii") + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + raw_headers = scope["headers"] + incoming = dict(raw_headers).get(b"x-request-id", b"").decode("latin-1") + request_id = incoming if REQUEST_ID_RE.fullmatch(incoming) else uuid.uuid4().hex + scope.setdefault("state", {})["request_id"] = request_id + method = scope["method"] if scope["method"] in KNOWN_METHODS else "_OTHER" + traced = not scope["path"].startswith("/health/") + span = (telemetry.TRACER.start_span(f"{method}", kind=telemetry.SpanKind.SERVER, + context=telemetry.extract_headers(raw_headers), + attributes={"http.request.method": method, "url.scheme": "http", + "messenger.request_id": request_id, + "service.instance.id": self.instance_id.decode("ascii")}) + if traced else None) + token = otel_context.attach(trace.set_span_in_context(span)) if span is not None else None + trace_header = None + if span is not None and span.get_span_context().is_valid: + trace_header = format(span.get_span_context().trace_id, "032x").encode("ascii") + status = 500 + started = False + begin = time.perf_counter() + telemetry.http_active.add(1, {"http.request.method": method}) + + async def send_with_id(message: AsgiMessage) -> None: + nonlocal status, started + if message["type"] == "http.response.start": + started = True + status = message["status"] + headers = [(k, v) for k, v in message.get("headers", []) + if k.lower() not in (b"x-request-id", b"x-instance-id", b"x-trace-id")] + headers.append((b"x-request-id", request_id.encode("latin-1"))) + headers.append((b"x-instance-id", self.instance_id)) + if trace_header is not None: + headers.append((b"x-trace-id", trace_header)) + message = {**message, "headers": headers} + await send(message) + + try: + await self.app(scope, receive, send_with_id) + except asyncio.CancelledError: + # uvicorn cancels requests still running when SHUTDOWN_TIMEOUT_SECONDS expires: + # answer 503 (retryable) instead of a generic 500, then let the cancellation proceed. + if not started: + status = 503 + response = error_response(request_id, 503, "unavailable", "Сервер завершает работу") + await response(scope, receive, send_with_id) + raise + except Exception as exc: + log.exception("unhandled_error", extra={"fields": {"request_id": request_id}}) + if span is not None: + span.record_exception(exc) # type + stack (code lines only), never request data + if not started: + status = 500 + response = error_response(request_id, 500, "internal_error", "Внутренняя ошибка сервера") + await response(scope, receive, send_with_id) + finally: + elapsed = time.perf_counter() - begin + route = route_template(scope) + attributes = {"http.request.method": method, "http.route": route, + "http.response.status_code": status, "http.response.status_class": f"{status // 100}xx"} + telemetry.http_duration.record(elapsed, attributes) + telemetry.http_active.add(-1, {"http.request.method": method}) + access_log.info("request", extra={"fields": { + "request_id": request_id, + "method": scope["method"], + "path": scope["path"], # ids only; query (cursor) and bodies are never logged + "route": route, + "status": status, + "instance_id": self.instance_id.decode("ascii"), + "duration_ms": round(elapsed * 1000, 3), + }}) + if span is not None: + span.update_name(f"{method} {route}") + span.set_attribute("http.route", route) + span.set_attribute("http.response.status_code", status) + if status >= 500: + telemetry.mark_error(span, str(status)) # 4xx is the client's problem: not an error of the server span + span.end() + otel_context.detach(token) + + +KNOWN_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}) + + +def route_template(scope: Scope) -> str: + """Template of the route that matched (set by the Starlette router), e.g. + /api/v1/chats/{chat_id}/messages. Unknown paths share ONE label value, so a scanner hitting + random URLs cannot create new metric series.""" + route = scope.get("route") + path = getattr(route, "path", None) + return path if isinstance(path, str) else "UNMATCHED" + + +# -------------------------------------------------------------------------- +# Request helpers +# -------------------------------------------------------------------------- +def db_of(request: Request) -> Database: + return request.app.state.db + + +def sessions_of(request: Request) -> SessionStore: + return request.app.state.sessions + + +def storage_of(request: Request) -> Storage: + return request.app.state.storage + + +def staging_of(request: Request) -> Storage: + return request.app.state.staging + + +async def authenticate(request: Request) -> str: + """User id of a valid Bearer session, otherwise 401. X-User-Id is ignored since lab 2. + + Store failures are 503 (Unavailable), never 401 and never anonymous access. + """ + token = authhdr.parse_bearer(request.headers.get("authorization")) + user_id = await sessions_of(request).user_id_for(token) + if user_id is None: + raise Unauthorized("Сессия недействительна, истекла или отозвана") + return user_id + + +def path_uuid(request: Request, name: str) -> str: + return validation.parse_uuid(request.path_params[name], name) + + +async def read_json(request: Request) -> dict[str, Any]: + content_type = request.headers.get("content-type", "") + media_type, _, params = content_type.partition(";") + if media_type.strip().lower() != "application/json": + raise InvalidRequest("Content-Type должен быть application/json") + charset = params.strip().lower() + if charset and charset.replace(" ", "") not in {"charset=utf-8", "charset=\"utf-8\""}: + raise InvalidRequest("Поддерживается только кодировка UTF-8") + limit: int = request.app.state.settings.max_body_bytes + declared = request.headers.get("content-length") + if declared is not None and declared.isdigit() and int(declared) > limit: + raise PayloadTooLarge() + chunks: list[bytes] = [] + size = 0 + async for chunk in request.stream(): + size += len(chunk) + if size > limit: + raise PayloadTooLarge() + chunks.append(chunk) + return validation.parse_json_object(b"".join(chunks)) + + +def page_params(request: Request) -> tuple[int, str | None]: + query = request.query_params.multi_items() + limit = validation.parse_limit(validation.single_query_param(query, "limit")) + raw_cursor = validation.single_query_param(query, "cursor") + if raw_cursor is not None and raw_cursor == "": + raise InvalidRequest("cursor не может быть пустым") + return limit, raw_cursor + + +async def reject_body(request: Request) -> None: + """POST /auth/sessions takes credentials only from the Basic header; any body is 400.""" + if request.headers.get("transfer-encoding") or request.headers.get("content-length", "0") != "0": + raise InvalidRequest("Вход принимает только заголовок Authorization: Basic, без тела") + async for chunk in request.stream(): + if chunk: + raise InvalidRequest("Вход принимает только заголовок Authorization: Basic, без тела") + + +def idempotency_key(request: Request) -> str: + values = request.headers.getlist("idempotency-key") + return validation.idempotency_key(values[0] if len(values) == 1 else None) + + +def request_fingerprint(text: str, attachment_ids: list[str]) -> bytes: + """SHA-256 of the canonical body: key order and an absent attachment_ids vs [] do not matter.""" + canonical = json.dumps({"attachment_ids": attachment_ids, "text": text}, + ensure_ascii=False, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).digest() + + +def ok(body: Any, status: int = 200) -> JSONResponse: + return JSONResponse(body, status_code=status) + + +# -------------------------------------------------------------------------- +# Handlers +# -------------------------------------------------------------------------- +async def live(request: Request) -> JSONResponse: + return ok({"status": "ok"}) + + +async def ready(request: Request) -> JSONResponse: + """200 only if the WHOLE mandatory synchronous path can be served: PostgreSQL, Valkey + (SESSION_STORE=valkey) and, since lab 4, the S3 bucket (upload/download of attachments) + answer. 503 while draining after SIGTERM. HAProxy routes to such replicas first.""" + if request.app.state.draining: + raise Unavailable("Сервер завершает работу") + db_ok, store_ok, s3_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping(), + storage_of(request).ping()) + if not db_ok: + raise Unavailable("PostgreSQL недоступен") + if not store_ok: + raise Unavailable("Хранилище сессий недоступно") + if not s3_ok: + raise Unavailable("Хранилище файлов (S3) недоступно") + return ok({"status": "ok"}) + + +async def ready_core(request: Request) -> JSONResponse: + """Not in the contract: readiness WITHOUT S3, for the load balancer's degraded mode only. + If S3 is down for every replica, /health/ready is 503 everywhere; HAProxy then routes to + replicas that are at least core-ready, so chats and messages keep working while every + attachment request answers 503 itself (see infra/haproxy/haproxy.cfg).""" + if request.app.state.draining: + raise Unavailable("Сервер завершает работу") + db_ok, store_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping()) + if not (db_ok and store_ok): + raise Unavailable("PostgreSQL или хранилище сессий недоступно") + return ok({"status": "ok"}) + + +async def register_user(request: Request) -> JSONResponse: + data = await read_json(request) + validation.check_fields(data, {"username", "display_name", "password"}) + username = validation.username_field(data) + display_name = validation.text_field(data, "display_name", 100) + password = validation.password_field(data) + password_hash = await passwords.hash_password(password) + user = await repo.create_user(db_of(request), username, display_name, password_hash) + log.info("user_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}}) + return ok(user.to_json(), 201) + + +async def create_session(request: Request) -> JSONResponse: + """Login: only `Authorization: Basic`; wrong user and wrong password give the same 401.""" + username, password = authhdr.parse_basic(request.headers.get("authorization")) + await reject_body(request) + found = await repo.get_credentials(db_of(request), username) + user, stored_hash = found if found else (None, None) + if not await passwords.verify_password(stored_hash, password) or user is None: + log.info("login_failed", extra={"fields": {"request_id": request.state.request_id}}) + raise Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE) + ttl = request.app.state.settings.session_ttl_seconds + token, expires_at = await sessions_of(request).create(user.id, ttl) + log.info("session_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}}) + return ok({"token": token, "token_type": "Bearer", "expires_at": rfc3339(expires_at), "user": user.to_json()}, 201) + + +async def revoke_session(request: Request) -> Response: + token = authhdr.parse_bearer(request.headers.get("authorization")) + if not await sessions_of(request).revoke(token): + raise Unauthorized("Сессия недействительна, истекла или отозвана") + log.info("session_revoked", extra={"fields": {"request_id": request.state.request_id}}) + return Response(status_code=204) + + +async def me(request: Request) -> JSONResponse: + user_id = await authenticate(request) + user = await repo.get_user(db_of(request), user_id) + if user is None: + raise Unauthorized("Сессия недействительна, истекла или отозвана") + return ok(user.to_json()) + + +async def create_chat(request: Request) -> JSONResponse: + user_id = await authenticate(request) + data = await read_json(request) + validation.check_fields(data, {"title", "member_ids"}) + title = validation.text_field(data, "title", 100) + member_ids = validation.member_ids_field(data) + chat = await repo.create_chat(db_of(request), user_id, title, member_ids) + log.info("chat_created", extra={"fields": {"request_id": request.state.request_id, "chat_id": chat.id, "members": len(member_ids)}}) + return ok(chat.to_json(), 201) + + +async def list_chats(request: Request) -> JSONResponse: + user_id = await authenticate(request) + limit, raw_cursor = page_params(request) + after = cursor.decode(raw_cursor, cursor.CHATS, user_id) if raw_cursor else None + items, has_more = await repo.list_chats(db_of(request), user_id, after, limit) + next_cursor = cursor.encode(cursor.CHATS, user_id, items[-1].key) if has_more else None + return ok({"items": [c.to_json() for c in items], "next_cursor": next_cursor}) + + +async def get_chat(request: Request) -> JSONResponse: + user_id = await authenticate(request) + chat_id = path_uuid(request, "chat_id") + return ok((await repo.get_chat(db_of(request), user_id, chat_id)).to_json()) + + +def parse_message(data: dict[str, Any]) -> tuple[str, list[str]]: + """`text` is required and a string (also with attachments); `attachment_ids`, if present, an + array of 0-10 unique UUIDs. "" or whitespace-only text is allowed only with attachments.""" + validation.check_fields(data, {"text"}, frozenset({"attachment_ids"})) + attachment_ids = validation.attachment_ids_field(data) + text = validation.text_field(data, "text", 4000, min_len=0 if attachment_ids else 1, + allow_blank=bool(attachment_ids)) + return text, attachment_ids + + +async def create_message(request: Request) -> JSONResponse: + """Order of answers for both write paths: 401 -> 400 bad chat id -> 404 outsider -> 400 key/body + -> 409 other body with the same key -> 201 (new or replayed). sender_id comes from the session.""" + user_id = await authenticate(request) + chat_id = path_uuid(request, "chat_id") + db = db_of(request) + settings = request.app.state.settings + await message_faults(request) + if settings.message_write_path == "multi": + await repo.ensure_member(db, user_id, chat_id) # outsiders get 404 before key/body are looked at + key = idempotency_key(request) + text, attachment_ids = parse_message(await read_json(request)) + result = await repo.post_message(db, user_id, chat_id, key, request_fingerprint(text, attachment_ids), text, + settings.idempotency_ttl_seconds, attachment_ids) + else: + try: + key = idempotency_key(request) + text, attachment_ids = parse_message(await read_json(request)) + except ApiError: + # Rare error path only: an outsider must still get 404, not a hint about the body. + await repo.ensure_member(db, user_id, chat_id) + raise + # Membership check, key claim, chat clock and message: one SQL call, one transaction. + result = await repo.post_message_single_call(db, user_id, chat_id, key, + request_fingerprint(text, attachment_ids), text, + settings.idempotency_ttl_seconds, attachment_ids) + if result.replayed: + log.info("idempotent_replay", extra={"fields": {"request_id": request.state.request_id, + "message_id": result.message.id}}) + return ok(result.message.to_json(), 201) + + +async def list_messages(request: Request) -> JSONResponse: + user_id = await authenticate(request) + chat_id = path_uuid(request, "chat_id") + db = db_of(request) + await repo.ensure_member(db, user_id, chat_id) # 404 for outsiders before cursor details leak + limit, raw_cursor = page_params(request) + after = cursor.decode(raw_cursor, cursor.MESSAGES, chat_id) if raw_cursor else None + items, has_more = await repo.list_messages(db, chat_id, after, limit) + next_cursor = cursor.encode(cursor.MESSAGES, chat_id, items[-1].key) if has_more else None + return ok({"items": [m.to_json() for m in items], "next_cursor": next_cursor}) + + +# ------------------------------------------------------------------ attachments (lab 4, lab 5) +async def message_faults(request: Request) -> None: + """Lab 6 experiments (API_FAULT_POINTS slow_handler / random_5xx / random_slow); no-op normally.""" + settings: Settings = request.app.state.settings + points = settings.fault_points + if not points: + return + if "random_5xx" in points and random.random() * 1000 < settings.fault_value("random_5xx", 10): + log.warning("fault_injected", extra={"fields": {"request_id": request.state.request_id, "point": "random_5xx"}}) + raise Unavailable("Внедрённый отказ: random_5xx") + if "random_slow" in points and random.random() * 1000 < settings.fault_value("random_slow", 10): + await asyncio.sleep(0.5) + if "slow_handler" in points: + await asyncio.sleep(settings.fault_value("slow_handler", 300) / 1000) + + +def fault(request: Request, point: str) -> None: + """Failure injection for the experiments (FAULT_POINTS of the api service, compose variable + API_FAULT_POINTS; empty in normal runs).""" + if point in request.app.state.settings.fault_points: + log.warning("fault_injected", extra={"fields": {"request_id": request.state.request_id, "point": point}}) + raise Unavailable("Внедрённый отказ: " + point) + + +async def upload_attachment(request: Request) -> JSONResponse: + """POST /chats/{chat_id}/attachments?filename=...: raw PNG/JPEG -> 202 queued (attachments.py).""" + settings: Settings = request.app.state.settings + reader = attachments.BodyReader(request) + slots: asyncio.Semaphore = request.app.state.upload_slots + acquired = False + try: + try: + user_id = await authenticate(request) + chat_id = path_uuid(request, "chat_id") + db = db_of(request) + await repo.ensure_member(db, user_id, chat_id) # outsiders: 404 before anything about the body + filename = validation.filename_param(validation.query_items(request.scope["query_string"])) + declared = attachments.declared_type(request) + length = attachments.declared_length(request, settings.max_upload_bytes) + try: + await asyncio.wait_for(slots.acquire(), settings.upload_queue_timeout_seconds) + except asyncio.TimeoutError: + raise attachments.Busy("Слишком много одновременных загрузок, повторите позже") from None + acquired = True + upload = await attachments.read_image(reader, settings, declared, request.app.state.verify_slots, length) + except ApiError: + # Early rejection: drop (not store) a bounded rest of the body so the client reads our error. + await reader.discard(settings.max_upload_bytes + (1 << 20), timeout=5.0) + raise + # The slot is held until the buffer is no longer needed (after the S3 PUT), so at most + # UPLOAD_CONCURRENCY bodies of this replica exist in memory at any moment. + return await store_upload(request, db, chat_id, user_id, filename, upload) + finally: + if acquired: + slots.release() + + +async def store_upload(request: Request, db: Database, chat_id: str, user_id: str, filename: str, + upload: attachments.Upload) -> JSONResponse: + """intent (pending) -> staging PUT -> queued + job + outbox -> 202 (docs/PIPELINE.md). + No resize here: the worker does it; a stopped worker only delays `ready`.""" + settings: Settings = request.app.state.settings + attachment_id = uuid.uuid4() + staging_key = attachments.new_staging_key() + await attachments.create_intent(db, attachment_id, chat_id, user_id, filename, upload.info, len(upload.data), + upload.sha256, staging_key) + await staging_of(request).put(staging_key, upload.data, upload.info.content_type, + {"attachment-id": str(attachment_id), "sha256": upload.sha256.hex()}) + fault(request, "after_s3_put") + attachment = await attachments.enqueue(db, attachment_id, settings) + if attachment is None: + raise Unavailable("Загрузка не завершена, повторите запрос") + fault(request, "after_enqueue_commit") + log.info("attachment_queued", extra={"fields": {"request_id": request.state.request_id, + "attachment_id": attachment.id, "chat_id": chat_id, + "size": attachment.size_bytes, "type": attachment.content_type, + "pipeline_version": settings.pipeline_version}}) + return ok(attachment.to_json(), 202) + + +async def get_attachment(request: Request) -> JSONResponse: + user_id = await authenticate(request) + attachment_id = path_uuid(request, "attachment_id") + return ok((await attachments.get_visible(db_of(request), user_id, attachment_id)).to_json()) + + +def content_disposition(filename: str) -> str: + """RFC 6266/5987: ASCII fallback + UTF-8 name; the stored name itself is never interpreted.""" + from urllib.parse import quote + fallback = "".join(c if 32 <= ord(c) < 127 and c not in '"\\%;' else "_" for c in filename) + return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(filename, safe='')}" + + +async def download_attachment(request: Request) -> Response: + """Original or variant bytes through the authorized API: no redirect, no public S3 URL. + queued/processing/failed -> 409 (not ready); a variant a ready attachment lacks -> 404. + Streamed from S3 in 64 KiB chunks (memory per download does not depend on the file size).""" + user_id = await authenticate(request) + attachment_id = path_uuid(request, "attachment_id") + query = validation.query_items(request.scope["query_string"]) + try: + variant = validation.variant_param(query) + except ApiError: + await attachments.get_visible(db_of(request), user_id, attachment_id) # 404 for outsiders first + raise + attachment = await attachments.get_visible(db_of(request), user_id, attachment_id) + if attachment.status != "ready": + raise Conflict("Обработка вложения не удалась" if attachment.status == "failed" else "Вложение ещё не готово") + if attachment.lost: + raise NotFound("Оригинал вложения утрачен") + if variant == "original": + key, size_expected, media_type, etag = (attachment.object_key, attachment.size_bytes, + attachment.content_type, attachment.sha256) + name = attachment.filename + else: + found = attachment.variant(variant) + if found is None: + raise NotFound("Такого варианта у вложения нет") + key, size_expected, media_type, etag = found.object_key, found.size_bytes, found.content_type, found.sha256 + stem = attachment.filename.rsplit(".", 1)[0] or "image" + name = stem + "-" + variant + (".webp" if media_type == "image/webp" else ".jpg") + try: + size, chunks = await storage_of(request).open_stream(key) + except ObjectMissing: + log.error("attachment_object_missing", extra={"fields": {"request_id": request.state.request_id, + "attachment_id": attachment.id, "variant": variant}}) + raise Unavailable("Файл вложения временно недоступен") from None + if size != size_expected: + log.error("attachment_size_mismatch", extra={"fields": {"request_id": request.state.request_id, + "attachment_id": attachment.id, "variant": variant}}) + await chunks.aclose() + raise Unavailable("Файл вложения временно недоступен") + headers = { + "Content-Length": str(size), + "Content-Disposition": content_disposition(name), + "X-Content-Type-Options": "nosniff", + "Cache-Control": "private, no-store", + "ETag": '"' + etag + '"', + } + return StreamingResponse(chunks, media_type=media_type, headers=headers) + + +def create_app(settings: Settings | None = None) -> Starlette: + settings = settings or Settings.from_env() + db = Database(settings) + sessions = build_store(settings, db) + storage = Storage(settings) # final bucket: Read + staging = Storage(settings, bucket=settings.s3_staging_bucket) # staging bucket: Write (+ janitor DELETE) + + async def purge_loop() -> None: + """Housekeeping: expired Idempotency-Key rows (older than IDEMPOTENCY_TTL_SECONDS).""" + while True: + await asyncio.sleep(600) + try: + deleted = await repo.purge_idempotency_keys(db, settings.idempotency_ttl_seconds) + if deleted: + log.info("idempotency_keys_purged", extra={"fields": {"deleted": deleted}}) + except ApiError: + pass # database unavailable right now; next round + + async def janitor_loop(every: float) -> None: + """Cleanup of intents of failed uploads older than PENDING_GRACE_SECONDS (attachments.py). + Every replica runs it; the advisory lock lets one round run at a time.""" + while True: + await asyncio.sleep(every * (0.5 + random.random())) + try: + removed = await attachments.clean_stale_pending(db, staging, settings.pending_grace_seconds) + if removed: + log.info("stale_uploads_removed", extra={"fields": {"count": removed}}) + except ApiError: + pass # PostgreSQL or S3 unavailable right now; the rows stay pending for the next round + + stats_log = logging.getLogger("messenger.stats") + + async def stats_loop(every: float) -> None: + """Experiments only: DB pool saturation (waiting requests, wait time) and process CPU.""" + cpu = time.process_time() + db.pool.pop_stats() + while True: + await asyncio.sleep(every) + stats = db.pool.pop_stats() + now_cpu = time.process_time() + stats_log.info("pool_stats", extra={"fields": { + "interval_s": every, "cpu_s": round(now_cpu - cpu, 4), + **{k: stats.get(k, 0) for k in ("pool_size", "pool_available", "requests_waiting", "requests_num", + "requests_queued", "requests_wait_ms", "usage_ms", "requests_errors")}}}) + cpu = now_cpu + + @contextlib.asynccontextmanager + async def lifespan(app: Starlette): + passwords.configure(settings.hash_concurrency) + telemetry.observe_pool(db.pool, db.name) + await db.open() + await storage.open() + await staging.open() + log.info("dependencies_configured", extra={"fields": { + "session_store": sessions.name, "session_ttl_s": settings.session_ttl_seconds, + "db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds, + "instance_id": settings.instance_id, "drain_s": settings.drain_seconds, + "message_write_path": settings.message_write_path, "s3_bucket": settings.s3_bucket, + "s3_staging_bucket": settings.s3_staging_bucket, "pipeline_version": settings.pipeline_version, + "upload_concurrency": settings.upload_concurrency, "verify_concurrency": settings.image_verify_concurrency, + "pending_grace_s": settings.pending_grace_seconds, + "fault_points": sorted(settings.fault_points)}}) + tasks = [asyncio.create_task(purge_loop())] + if settings.janitor_interval_seconds > 0: + tasks.append(asyncio.create_task(janitor_loop(settings.janitor_interval_seconds))) + if settings.stats_log_seconds > 0: + tasks.append(asyncio.create_task(stats_loop(settings.stats_log_seconds))) + try: + yield + finally: + for task in tasks: + task.cancel() + await sessions.close() + await staging.close() + await storage.close() + await db.close() + + routes = [ + Route("/health/live", live, methods=["GET"]), + Route("/health/ready", ready, methods=["GET"]), + Route("/health/ready/core", ready_core, methods=["GET"]), + Route("/api/v1/users", register_user, methods=["POST"]), + Route("/api/v1/users/me", me, methods=["GET"]), + Route("/api/v1/auth/sessions", create_session, methods=["POST"]), + Route("/api/v1/auth/sessions/current", revoke_session, methods=["DELETE"]), + Route("/api/v1/chats", create_chat, methods=["POST"]), + Route("/api/v1/chats", list_chats, methods=["GET"]), + Route("/api/v1/chats/{chat_id}", get_chat, methods=["GET"]), + Route("/api/v1/chats/{chat_id}/messages", create_message, methods=["POST"]), + Route("/api/v1/chats/{chat_id}/messages", list_messages, methods=["GET"]), + Route("/api/v1/chats/{chat_id}/attachments", upload_attachment, methods=["POST"]), + Route("/api/v1/attachments/{attachment_id}", get_attachment, methods=["GET"]), + Route("/api/v1/attachments/{attachment_id}/content", download_attachment, methods=["GET"]), + ] + if settings.docs_enabled: # Swagger UI for manual experiments, not part of the contract + routes += [ + Route("/docs", docs.swagger_page, methods=["GET"]), + Route("/openapi.json", docs.openapi_json, methods=["GET"]), + ] + app = Starlette( + routes=routes, + exception_handlers={ApiError: api_error_handler, HTTPException: http_exception_handler}, + lifespan=lifespan, + ) + app.add_middleware(RequestContextMiddleware, instance_id=settings.instance_id) + app.state.settings = settings + app.state.db = db + app.state.sessions = sessions + app.state.storage = storage + app.state.staging = staging + app.state.upload_slots = asyncio.Semaphore(settings.upload_concurrency) + app.state.verify_slots = asyncio.Semaphore(settings.image_verify_concurrency) + app.state.draining = False + return app diff --git a/src/messenger/attachments.py b/src/messenger/attachments.py new file mode 100644 index 0000000..74e5775 --- /dev/null +++ b/src/messenger/attachments.py @@ -0,0 +1,339 @@ +"""Attachments: metadata in PostgreSQL, bytes in private S3 buckets (lab 4), processed +asynchronously by the worker (lab 5, docs/PIPELINE.md). + +Upload (POST /chats/{id}/attachments, raw PNG/JPEG body), in this order: + + auth -> membership (404) -> filename / Content-Type / Content-Length (400/415/413) + -> upload slot (at most UPLOAD_CONCURRENCY bodies per replica, else 503 + Retry-After) + -> body in chunks: size limit, read deadline, format + pixel count from the first bytes + -> full integrity check (images.verify) -> SHA-256 / size known (415 is decided HERE) + -> INSERT row status='pending' with a fresh random staging key, COMMIT (intent) + -> PUT the original into the STAGING bucket (Content-MD5) + -> ONE transaction: status 'pending' -> 'queued' + jobs row + outbox row, COMMIT + -> 202 queued. + +What is durable at 202: the complete, verified original in the staging bucket (S3 confirmed the +PUT and its MD5), the metadata row, the job and the outbox row that makes the relay publish it. +A crash of the API after the answer loses nothing; a broker that is down only delays the publish. + +Failures between the steps (docs/PIPELINE.md, failure windows): +* before the intent COMMIT: nothing was written; +* after the intent, before/while PUT, or between PUT and the job COMMIT (FAULT_POINTS=after_s3_put): + a 'pending' row (+ maybe the staging object), invisible to everybody (404). The client got 503 + and may retry (a new attachment). The janitor deletes the staging object - idempotent - and then + the row once it is older than PENDING_GRACE_SECONDS, deciding under the row lock; +* after the job COMMIT, answer lost (FAULT_POINTS=after_enqueue_commit): a correct queued + attachment the client does not know; the worker processes it as usual. +""" +from __future__ import annotations + +import asyncio +import datetime as dt +import hashlib +import logging +import secrets +import uuid +from dataclasses import dataclass + +import psycopg +from psycopg import errors as pg_errors +from starlette.requests import Request + +from . import images, jobs +from .config import Settings +from .db import Database +from .errors import ApiError, InvalidRequest, NotFound, PayloadTooLarge, Unavailable, UnsupportedMediaType +from .storage import STAGING_PREFIX, Storage +from .timefmt import rfc3339 + +log = logging.getLogger("messenger.attachments") + +JANITOR_LOCK_ID = 2026_04 # advisory lock: one janitor round at a time across all replicas + + +@dataclass(frozen=True, slots=True) +class Variant: + name: str + content_type: str + size_bytes: int + width: int + height: int + sha256: str + object_key: str + + def to_json(self) -> dict: + return {"name": self.name, "content_type": self.content_type, "size_bytes": self.size_bytes, + "width": self.width, "height": self.height, "sha256": self.sha256} + + +@dataclass(frozen=True, slots=True) +class Attachment: + id: str + chat_id: str + owner_id: str + filename: str + content_type: str + size_bytes: int + sha256: str + object_key: str | None # published original in the final bucket (None until the worker publishes it) + status: str + created_at: dt.datetime + updated_at: dt.datetime + lost: bool = False + error_code: str | None = None + published_version: int | None = None + variants: tuple[Variant, ...] = () + + def to_json(self) -> dict: + """Public representation: no object keys, no buckets, no job internals.""" + return {"id": self.id, "chat_id": self.chat_id, "owner_id": self.owner_id, "filename": self.filename, + "content_type": self.content_type, "size_bytes": self.size_bytes, "sha256": self.sha256, + "status": self.status, "variants": [v.to_json() for v in self.variants] if self.status == "ready" else [], + "error_code": self.error_code if self.status == "failed" else None, + "created_at": rfc3339(self.created_at), "updated_at": rfc3339(self.updated_at)} + + def variant(self, name: str) -> Variant | None: + return next((v for v in self.variants if v.name == name), None) + + +COLUMNS = ("a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.object_key, " + "a.status, a.created_at, a.updated_at, a.lost_at IS NOT NULL, a.error_code, a.published_version") + + +def _attachment(row, variants: tuple[Variant, ...] = ()) -> Attachment: + return Attachment(str(row[0]), str(row[1]), str(row[2]), row[3], row[4], row[5], bytes(row[6]).hex(), row[7], + row[8], row[9], row[10], row[11], row[12], row[13], variants) + + +def new_staging_key() -> str: + """Server-generated, 128 random bits, unrelated to the attachment id and the filename.""" + return STAGING_PREFIX + secrets.token_hex(16) + + +# ------------------------------------------------------------------ SQL +async def create_intent(db: Database, attachment_id: uuid.UUID, chat_id: str, owner_id: str, filename: str, + info: images.ImageInfo, size: int, sha256: bytes, staging_key: str) -> None: + async def work(conn: psycopg.AsyncConnection) -> None: + await conn.execute( + "INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, " + "width, height, staging_key, staging_state, status) " + "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'present', 'pending')", + (attachment_id, chat_id, owner_id, filename, info.content_type, size, sha256, info.width, info.height, + staging_key)) + try: + await db.run(work, transaction=False) + except pg_errors.ForeignKeyViolation: + raise NotFound("Чат не найден") from None + + +async def enqueue(db: Database, attachment_id: uuid.UUID, settings: Settings) -> Attachment | None: + """pending -> queued + job + outbox row in ONE transaction (the durable handoff before 202). + None if the row is no longer pending (the janitor removed a stale intent).""" + async def work(conn: psycopg.AsyncConnection) -> Attachment | None: + cur = await conn.execute( + "UPDATE attachments a SET status = 'queued', updated_at = clock_timestamp() " + f"WHERE a.id = %s AND a.status = 'pending' RETURNING {COLUMNS}", (attachment_id,)) + row = await cur.fetchone() + if row is None: + return None + await jobs.create_job(conn, attachment_id, settings.pipeline_version, "upload", settings.job_max_attempts, + "api:" + settings.instance_id) + return _attachment(row) + return await db.run(work) + + +async def get_visible(db: Database, user_id: str, attachment_id: str) -> Attachment: + """An attachment of a chat the user is a member of, in any state but the invisible intent + 'pending'; anything else is 404 (unknown, foreign chat, unfinished upload) - existence of + foreign objects is never revealed. A ready attachment comes with its published variants.""" + async def work(conn: psycopg.AsyncConnection) -> Attachment: + cur = await conn.execute( + f"SELECT {COLUMNS} FROM attachments a " + "JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = %s " + "WHERE a.id = %s AND a.status <> 'pending'", (user_id, attachment_id)) + row = await cur.fetchone() + if row is None: + raise NotFound("Вложение не найдено") + variants: tuple[Variant, ...] = () + if row[8] == "ready": + cur = await conn.execute( + "SELECT name, content_type, size_bytes, width, height, sha256, object_key FROM attachment_variants " + "WHERE attachment_id = %s AND pipeline_version = %s " + "ORDER BY array_position(ARRAY['thumbnail', 'crop', 'optimized'], name)", (row[0], row[13])) + variants = tuple(Variant(r[0], r[1], r[2], r[3], r[4], bytes(r[5]).hex(), r[6]) for r in await cur.fetchall()) + return _attachment(row, variants) + # REPEATABLE READ is not needed: the variant rows of a published version never change. + return await db.run(work) + + +async def clean_stale_pending(db: Database, staging: Storage, grace_seconds: int, batch: int = 20) -> int: + """Janitor round: remove intents of uploads that never got their job (no 202 was sent). + + Under FOR UPDATE: an upload that is (impossibly) still running would block on the row in + enqueue() and then find it gone (-> 503). Order: staging object first (idempotent), row second; + a crash in between leaves the pending row and the next round repeats. Only status='pending' + rows older than the grace period are touched: queued/processing/ready/failed never. + """ + async def work(conn: psycopg.AsyncConnection) -> int: + cur = await conn.execute("SELECT pg_try_advisory_xact_lock(%s)", (JANITOR_LOCK_ID,)) + if not (await cur.fetchone())[0]: + return 0 + cur = await conn.execute( + "SELECT id, staging_key FROM attachments WHERE status = 'pending' " + "AND created_at < clock_timestamp() - make_interval(secs => %s) " + "ORDER BY created_at LIMIT %s FOR UPDATE SKIP LOCKED", (grace_seconds, batch)) + rows = await cur.fetchall() + if not rows: + return 0 + await asyncio.gather(*(staging.delete(key) for _, key in rows)) + await conn.execute("DELETE FROM attachments WHERE id = ANY(%s) AND status = 'pending'", + ([r[0] for r in rows],)) + return len(rows) + return await db.run(work, deadline=staging.timeout + 5) + + +# ------------------------------------------------------------------ request body +class Busy(Unavailable): + """All upload slots of this replica are taken: retry shortly (no body was read).""" + + @property + def headers(self) -> dict[str, str]: + return {"Retry-After": "1"} + + +@dataclass +class Upload: + data: bytearray + info: images.ImageInfo + sha256: bytes + + +class BodyReader: + """Reads the raw ASGI body ourselves (not request.stream()), so we always know how much of it + is consumed and can discard the rest after an early rejection.""" + + def __init__(self, request: Request): + self.receive = request.receive + self.done = False + + async def chunk(self, timeout: float) -> bytes | None: + if self.done: + return None + message = await asyncio.wait_for(self.receive(), timeout) + if message["type"] == "http.disconnect": + self.done = True + raise InvalidRequest("Клиент прервал загрузку") + if not message.get("more_body", False): + self.done = True + return message.get("body", b"") + + async def discard(self, limit: int, timeout: float) -> None: + """After an early 4xx: read and DROP up to `limit` more bytes, so an ordinary client that + writes the whole body before reading the answer still gets our JSON error instead of a + connection reset. Nothing is kept in memory; beyond the limit the connection is dropped.""" + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + seen = 0 + try: + while not self.done and seen <= limit: + remaining = deadline - loop.time() + if remaining <= 0: + return + seen += len(await self.chunk(remaining) or b"") + except (ApiError, asyncio.TimeoutError): + return + + +def declared_type(request: Request) -> str: + """Content-Type of the upload must be image/png or image/jpeg (parameters ignored).""" + media_type = request.headers.get("content-type", "").partition(";")[0].strip().lower() + if media_type not in (images.PNG, images.JPEG): + raise UnsupportedMediaType("Content-Type должен быть image/png или image/jpeg") + return media_type + + +def declared_length(request: Request, limit: int) -> int | None: + raw = request.headers.get("content-length") + if raw is None: + return None # chunked transfer: the limit is enforced while reading + if not raw.isdigit(): + raise InvalidRequest("Неверный Content-Length") + length = int(raw) + if length > limit: + raise PayloadTooLarge(f"Файл больше {limit} байт") + if length == 0: + raise InvalidRequest("Тело запроса пустое: нужны байты изображения") + return length + + +async def read_image(reader: BodyReader, settings: Settings, declared: str, verify_slots: asyncio.Semaphore, + length: int | None) -> Upload: + """Body -> verified image. Memory: ONE buffer of at most MAX_UPLOAD_BYTES per upload - exactly + Content-Length bytes allocated once when the length is declared (no growth, no final copy); + it is passed as is to the checks and to the S3 PUT. The format and the pixel count are known + after the first bytes, so a picture that is too big or not a PNG/JPEG is rejected without + reading/decoding the rest.""" + loop = asyncio.get_running_loop() + deadline = loop.time() + settings.upload_read_timeout_seconds + limit = settings.max_upload_bytes + buffer = bytearray(length) if length else bytearray() + view = memoryview(buffer) if length else None + filled = 0 + digest = hashlib.sha256() + info: images.ImageInfo | None = None + while True: + remaining = deadline - loop.time() + if remaining <= 0: + raise InvalidRequest("Тело запроса не получено вовремя") + try: + chunk = await reader.chunk(remaining) + except asyncio.TimeoutError: + raise InvalidRequest("Тело запроса не получено вовремя") from None + if chunk is None: + break + if filled + len(chunk) > (length or limit): + raise PayloadTooLarge(f"Файл больше {limit} байт") + if view is not None: + view[filled:filled + len(chunk)] = chunk + else: + buffer += chunk + filled += len(chunk) + digest.update(chunk) + if info is None and filled: + info = _sniff(view[:filled] if view is not None else buffer, settings, declared) + if view is not None: + view.release() + if not filled: + raise InvalidRequest("Тело запроса пустое: нужны байты изображения") + if length and filled != length: + raise InvalidRequest("Тело запроса короче Content-Length") + if info is None: + raise UnsupportedMediaType("Файл не является корректным изображением PNG или JPEG") + try: + async with verify_slots: + await images.verify(buffer, info, timeout=settings.image_verify_timeout_seconds, + jpeg_max_memory_mb=settings.jpeg_max_memory_mb) + except images.ImageError as exc: + raise _image_error(exc) from None + except asyncio.TimeoutError: + raise UnsupportedMediaType("Изображение не удалось проверить за отведённое время") from None + except (images.VerifierUnavailable, MemoryError): + log.warning("image_verifier_unavailable", extra={"fields": {"type": info.content_type, "size": filled}}) + raise Busy("Не хватило ресурсов для проверки изображения, повторите позже") from None + return Upload(buffer, info, digest.digest()) + + +def _sniff(buffer: bytearray, settings: Settings, declared: str) -> images.ImageInfo | None: + try: + info = images.sniff(buffer, settings.max_image_pixels) + except images.ImageError as exc: + raise _image_error(exc) from None + if info is not None and info.content_type != declared: + # "MIME spoofing": the header says PNG, the bytes are JPEG (or vice versa). + raise UnsupportedMediaType("Содержимое не совпадает с Content-Type") + return info + + +def _image_error(exc: images.ImageError) -> ApiError: + return PayloadTooLarge(exc.message) if exc.status == 413 else UnsupportedMediaType(exc.message) + diff --git a/src/messenger/audit.py b/src/messenger/audit.py new file mode 100644 index 0000000..a555817 --- /dev/null +++ b/src/messenger/audit.py @@ -0,0 +1,190 @@ +"""Track 2: read-only checker of the pipeline invariants: `python -m messenger.audit` +(compose service `auditor`, profile tools; `make audit`). + +Read-only by construction: every database transaction is `READ ONLY` (PostgreSQL refuses any +write), and the S3 key pair of the auditor has Read + List only. Output: one JSON report; exit 1 +if any invariant is violated. + +Invariants (docs/PIPELINE.md): + I1 no lost work - a queued/processing attachment has an active job; an active job has an + outbox row (published or due) - nothing waits for a message that nobody sends. + I2 one effect - per (attachment, pipeline_version) either no variant rows or exactly the + three variants, all written by ONE successful attempt of a job of that version. + I3 published data - every published object (original, variants) exists with the stored size + (--verify-checksums: and the stored SHA-256). + I4 monotonic - published_version = the highest version with a succeeded job; a ready + attachment is never queued/processing again (published_version stays set). + I5 source kept - an active job whose original is not published still has its staging copy + (state present AND the object exists in the staging bucket). + I6 no stray data - every object in the buckets is referenced: published, staging of a live row, + or planned by an attempt whose objects were not cleaned yet. An object of an + already cleaned attempt is reported as `leaked_object` (written by a stalled + attempt after its cleanup: garbage, never a loss). + I7 attempts - a succeeded job has exactly one succeeded attempt; at most one running attempt + per job, and it is the lease holder. +""" +from __future__ import annotations + +import argparse +import asyncio +import hashlib +import json +import sys + +from .config import ConfigError, Settings +from .db import Database +from .errors import Unavailable +from .pipeline import VARIANT_NAMES +from .storage import ObjectMissing, SENTINEL_KEY, Storage + + +async def rows(db: Database, sql: str, params=()) -> list[tuple]: + async def work(conn): + await conn.execute("SET TRANSACTION READ ONLY") + cur = await conn.execute(sql, params) + return await cur.fetchall() + return await db.run(work, deadline=db.deadline) + + +async def list_all(storage: Storage, prefix: str) -> dict[str, int]: + found, after = {}, None + while True: + page, more = await storage.list_page(prefix, after, 1000) + for item in page: + found[item.key] = item.size + if not more or not page: + return found + after = page[-1].key + + +async def audit(settings: Settings, verify: bool) -> dict: + db = Database(settings, name="messenger-audit") + final = Storage(settings) + staging = Storage(settings, bucket=settings.s3_staging_bucket) + await db.open() + await final.open() + await staging.open() + violations: list[dict] = [] + notes: list[dict] = [] + + def bad(kind: str, **detail) -> None: + violations.append({"invariant": kind, **{k: str(v) for k, v in detail.items()}}) + + try: + # I1: queued/processing attachment without an active job; active job without outbox row. + for (aid,) in await rows(db, "SELECT a.id FROM attachments a WHERE a.status IN ('queued', 'processing') " + "AND NOT EXISTS (SELECT 1 FROM jobs j WHERE j.attachment_id = a.id " + "AND j.state IN ('queued', 'processing'))"): + bad("I1_no_active_job", attachment_id=aid) + for (jid,) in await rows(db, "SELECT j.id FROM jobs j WHERE j.state = 'queued' AND NOT EXISTS " + "(SELECT 1 FROM outbox o WHERE o.job_id = j.id)"): + bad("I1_queued_without_outbox", job_id=jid) + + # I2: exactly three variants per published version, one successful attempt of that version. + for aid, version, names, tokens in await rows( + db, "SELECT attachment_id, pipeline_version, array_agg(name ORDER BY name), " + "array_agg(DISTINCT attempt_token) FROM attachment_variants GROUP BY 1, 2"): + if sorted(names) != sorted(VARIANT_NAMES): + bad("I2_variant_set", attachment_id=aid, version=version, names=names) + if len(tokens) != 1: + bad("I2_mixed_attempts", attachment_id=aid, version=version, attempts=len(tokens)) + for aid, version, outcome, jversion in await rows( + db, "SELECT v.attachment_id, v.pipeline_version, ja.outcome, j.pipeline_version " + "FROM attachment_variants v JOIN job_attempts ja ON ja.token = v.attempt_token " + "JOIN jobs j ON j.id = ja.job_id WHERE ja.outcome <> 'succeeded' OR j.pipeline_version " + "<> v.pipeline_version OR j.attachment_id <> v.attachment_id"): + bad("I2_variant_from_unsuccessful_attempt", attachment_id=aid, version=version, outcome=outcome) + + # I4: published_version = highest succeeded version; ready <=> published. + for aid, status, published, best in await rows( + db, "SELECT a.id, a.status, a.published_version, (SELECT max(j.pipeline_version) FROM jobs j " + "WHERE j.attachment_id = a.id AND j.state = 'succeeded') FROM attachments a " + "WHERE a.published_version IS DISTINCT FROM (SELECT max(j.pipeline_version) FROM jobs j " + "WHERE j.attachment_id = a.id AND j.state = 'succeeded') " + "OR (a.published_version IS NOT NULL AND a.status <> 'ready')"): + bad("I4_published_version", attachment_id=aid, status=status, published=published, best_succeeded=best) + + # I7: attempts. + for (jid,) in await rows(db, "SELECT j.id FROM jobs j WHERE j.state = 'succeeded' AND (SELECT count(*) " + "FROM job_attempts a WHERE a.job_id = j.id AND a.outcome = 'succeeded') <> 1"): + bad("I7_succeeded_attempts", job_id=jid) + for jid, token in await rows(db, "SELECT a.job_id, a.token FROM job_attempts a JOIN jobs j ON j.id = a.job_id " + "WHERE a.outcome = 'running' AND j.lease_token IS DISTINCT FROM a.token"): + bad("I7_running_not_holder", job_id=jid, token=token) + + # I3 + I5 + I6: storage. + published = {k: (s, h) for k, s, h in await rows( + db, "SELECT object_key, size_bytes, sha256 FROM attachment_variants UNION ALL " + "SELECT object_key, size_bytes, sha256 FROM attachments WHERE object_key IS NOT NULL")} + staging_live = {k: (s, st, status) for k, s, st, status in await rows( + db, "SELECT staging_key, size_bytes, staging_state, status FROM attachments WHERE staging_key IS NOT NULL")} + planned_open, planned_cleaned = set(), set() + for keys, cleaned in await rows(db, "SELECT planned_keys, objects_cleaned_at IS NOT NULL FROM job_attempts"): + (planned_cleaned if cleaned else planned_open).update(keys) + final_objects = await list_all(final, "") + staging_objects = await list_all(staging, "") + for key, (size, sha) in published.items(): + if key not in final_objects: + bad("I3_published_missing", key=key) + elif final_objects[key] != size: + bad("I3_published_size", key=key, stored=size, actual=final_objects[key]) + elif verify: + data = await final.read_all(key, limit=settings.max_upload_bytes) + if hashlib.sha256(data).digest() != bytes(sha): + bad("I3_published_checksum", key=key) + for key, (size, state, status) in staging_live.items(): + # 'pending' may lack its object (the PUT failed: the janitor removes the row); accepted + # work (queued/processing) must have it. + active = status in ("queued", "processing") + if state == "present" and key not in staging_objects and active: + bad("I5_staging_missing", key=key, status=status) + for (aid,) in await rows(db, "SELECT a.id FROM attachments a WHERE a.status IN ('queued', 'processing') " + "AND a.object_key IS NULL AND a.staging_state <> 'present'"): + bad("I5_active_without_source", attachment_id=aid) + for key in final_objects: + if key == SENTINEL_KEY or key in published or key in planned_open: + continue + if key in planned_cleaned: + notes.append({"kind": "leaked_object", "key": key}) + else: + bad("I6_unknown_final_object", key=key) + for key in staging_objects: + if key == SENTINEL_KEY: + continue + row = staging_live.get(key) + if row is None: + bad("I6_unknown_staging_object", key=key) + elif row[1] == "deleted": + notes.append({"kind": "staging_marked_deleted_still_present", "key": key}) + counts = dict(await rows(db, "SELECT status, count(*) FROM attachments GROUP BY status")) + jobs = dict(await rows(db, "SELECT state, count(*) FROM jobs GROUP BY state")) + return {"ok": not violations, "violations": violations, "notes": notes, + "attachments": counts, "jobs": jobs, + "objects": {"final": len(final_objects), "staging": len(staging_objects), + "published": len(published), "checksums_verified": verify}} + finally: + await staging.close() + await final.close() + await db.close() + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(prog="audit", description="Read-only check of the pipeline invariants") + p.add_argument("--verify-checksums", action="store_true", help="read every published object and compare SHA-256") + args = p.parse_args(argv) + try: + settings = Settings.from_env() + except ConfigError as exc: + print(f"configuration error: {exc}", file=sys.stderr) + return 2 + try: + report = asyncio.run(audit(settings, args.verify_checksums)) + except (Unavailable, ObjectMissing) as exc: + print(json.dumps({"ok": False, "error": "store_unavailable", "detail": type(exc).__name__})) + return 1 + print(json.dumps(report, ensure_ascii=False, indent=1, default=str)) + return 0 if report["ok"] else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/messenger/authhdr.py b/src/messenger/authhdr.py new file mode 100644 index 0000000..f849b02 --- /dev/null +++ b/src/messenger/authhdr.py @@ -0,0 +1,48 @@ +"""Parsing of the Authorization header. Any malformed value is 401, never 500. + +Basic (RFC 7617) is accepted only by POST /auth/sessions; everything else needs +Bearer. Basic is an encoding, not encryption: plain HTTP is acceptable only for the +local synthetic lab stand (lab 7 adds TLS). +""" +from __future__ import annotations + +import base64 +import binascii +import re + +from .errors import BASIC_CHALLENGE, BEARER_CHALLENGE, Unauthorized +from .validation import USERNAME_RE + +B64_RE = re.compile(r"[A-Za-z0-9+/]+={0,2}") +TOKEN_RE = re.compile(r"[A-Za-z0-9_-]{32,128}") # token_urlsafe(32) gives 43 characters + + +def _split(header: str | None) -> tuple[str, str]: + if not header: + return "", "" + scheme, _, value = header.strip().partition(" ") + return scheme.lower(), value.strip() + + +def parse_basic(header: str | None) -> tuple[str, str]: + """(username, password) from `Basic base64(username:password)`; the password may contain ':'.""" + invalid = Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE) + scheme, value = _split(header) + if scheme != "basic" or B64_RE.fullmatch(value) is None or len(value) > 1024: + raise invalid + try: + decoded = base64.b64decode(value, validate=True).decode("utf-8") + except (binascii.Error, ValueError, UnicodeDecodeError): + raise invalid from None + username, sep, password = decoded.partition(":") # split at the FIRST colon + if not sep or USERNAME_RE.fullmatch(username) is None or not password: + raise invalid + return username, password + + +def parse_bearer(header: str | None) -> str: + scheme, value = _split(header) + if scheme != "bearer" or TOKEN_RE.fullmatch(value) is None: + # Missing header, Basic on a business endpoint, garbage token: one answer. + raise Unauthorized("Требуется действительная Bearer-сессия", challenge=BEARER_CHALLENGE) + return value diff --git a/src/messenger/broker.py b/src/messenger/broker.py new file mode 100644 index 0000000..524d3c7 --- /dev/null +++ b/src/messenger/broker.py @@ -0,0 +1,93 @@ +"""RabbitMQ (AMQP 0-9-1) for the attachment jobs: topology names and the message format. + +Topology (declared by the broker itself from its definitions file at boot, infra/rabbitmq and +scripts/init_secrets.py; the relay and the worker have NO configure permission and declare nothing): + + exchange messenger.jobs direct, durable + queue messenger.attachment-jobs quorum (Raft log on disk), bound with routing key + attachment.process.v1; x-delivery-limit and dead-lettering to + exchange messenger.jobs.dlx fanout -> queue messenger.attachment-jobs.dlq (quorum) + +Publisher side (relay): persistent message, `mandatory` (an unroutable message is returned, not +silently dropped), channel in confirm mode - `publish()` returns only after the broker has +written the message to the quorum log (publisher confirm). Consumer side (worker): manual ack +after the durable effect, prefetch = WORKER_CONCURRENCY. + +The message carries IDs and service fields only (contracts/jobs.schema.json): no bytes, no URL, +no S3 key, no filename, no credentials. The worker takes every trusted detail from PostgreSQL. +""" +from __future__ import annotations + +import datetime as dt +import json +import re +import uuid + +EXCHANGE = "messenger.jobs" +QUEUE = "messenger.attachment-jobs" +DLX = "messenger.jobs.dlx" +DLQ = "messenger.attachment-jobs.dlq" +ROUTING_KEY = "attachment.process.v1" +JOB_TYPE = "attachment.process.v1" +MAX_MESSAGE_BYTES = 4096 + +REQUIRED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"} +OPTIONAL = {"traceparent", "tracestate"} +TRACEPARENT_RE = re.compile(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}") +DATETIME_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z") + + +class BadMessage(ValueError): + """Not a valid job message (schema v1): dead-lettered, never processed.""" + + +def rfc3339(value: dt.datetime) -> str: + return value.astimezone(dt.timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") + + +def encode(job_id: str, attachment_id: str, pipeline_version: int, attempt: int, created_at: dt.datetime, + trace_context: dict[str, str] | None = None) -> bytes: + """Lab 6: `trace_context` = {"traceparent", "tracestate"} of the relay's PRODUCER span (the same + values also go into the AMQP headers; the worker reads the body fields, the schema's carrier).""" + body = {"schema_version": 1, "job_id": job_id, "type": JOB_TYPE, "attachment_id": attachment_id, + "pipeline_version": pipeline_version, "attempt": attempt, "created_at": rfc3339(created_at)} + for key in ("traceparent", "tracestate"): + value = (trace_context or {}).get(key) + if value: + body[key] = value + return json.dumps(body, separators=(",", ":")).encode() + + +def decode(raw: bytes) -> dict: + """Strict check against contracts/jobs.schema.json (additionalProperties: false).""" + if len(raw) > MAX_MESSAGE_BYTES: + raise BadMessage("too large") + try: + body = json.loads(raw) + except (ValueError, UnicodeError): + raise BadMessage("not JSON") from None + if not isinstance(body, dict): + raise BadMessage("not an object") + keys = set(body) + if not REQUIRED <= keys or keys - REQUIRED - OPTIONAL: + raise BadMessage("wrong fields") + if body["schema_version"] != 1 or isinstance(body["schema_version"], bool) or body["type"] != JOB_TYPE: + raise BadMessage("unsupported schema/type") + for name in ("job_id", "attachment_id"): + if not isinstance(body[name], str): + raise BadMessage(name) + try: + uuid.UUID(body[name]) + except ValueError: + raise BadMessage(name) from None + for name in ("pipeline_version", "attempt"): + value = body[name] + if not isinstance(value, int) or isinstance(value, bool) or value < 1: + raise BadMessage(name) + if not isinstance(body["created_at"], str) or not DATETIME_RE.fullmatch(body["created_at"]): + raise BadMessage("created_at") + if "traceparent" in body and not (isinstance(body["traceparent"], str) and TRACEPARENT_RE.fullmatch(body["traceparent"])): + raise BadMessage("traceparent") + if "tracestate" in body and not (isinstance(body["tracestate"], str) and len(body["tracestate"]) <= 512): + raise BadMessage("tracestate") + return body diff --git a/src/messenger/config.py b/src/messenger/config.py new file mode 100644 index 0000000..b93802e --- /dev/null +++ b/src/messenger/config.py @@ -0,0 +1,348 @@ +"""Runtime configuration read from environment variables (12-factor style). + +Non-secret settings have safe defaults. Connection strings with passwords are +read from files (`DATABASE_URL_FILE`, `CACHE_URL_FILE` → Docker secrets in +/run/secrets), so they never appear in `docker inspect`, compose files or logs. +Invalid values stop the process at startup with a clear message. +""" +from __future__ import annotations + +import os +import re +import socket +from dataclasses import dataclass, field +from pathlib import Path + + +class ConfigError(ValueError): + pass + + +INSTANCE_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}") + + +def _instance_id() -> str: + """X-Instance-Id of this process: INSTANCE_ID or the container hostname. + + Docker sets the hostname of a container to its short container ID, so the value + is unique per replica, stable for the life of the process and maps 1:1 to a real + container (`docker inspect`), which scripts/stop-one.sh relies on. + """ + value = os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname() + if INSTANCE_ID_RE.fullmatch(value) is None: + raise ConfigError("INSTANCE_ID must match [A-Za-z0-9._-]{1,64}") + return value + + +def _int(name: str, default: int, low: int, high: int) -> int: + raw = os.environ.get(name) + if raw is None or raw.strip() == "": + return default + try: + value = int(raw.strip()) + except ValueError: + raise ConfigError(f"{name} must be an integer, got {raw!r}") from None + if not low <= value <= high: + raise ConfigError(f"{name} must be in [{low}, {high}], got {value}") + return value + + +def _float(name: str, default: float, low: float, high: float) -> float: + raw = os.environ.get(name) + if raw is None or raw.strip() == "": + return default + try: + value = float(raw.strip()) + except ValueError: + raise ConfigError(f"{name} must be a number, got {raw!r}") from None + if not low <= value <= high: + raise ConfigError(f"{name} must be in [{low}, {high}], got {value}") + return value + + +def _bool(name: str, default: bool) -> bool: + raw = os.environ.get(name, "").strip().lower() + if raw == "": + return default + if raw not in {"true", "false", "1", "0"}: + raise ConfigError(f"{name} must be true/false, got {raw!r}") + return raw in {"true", "1"} + + +def _choice(name: str, default: str, allowed: set[str]) -> str: + value = os.environ.get(name, "").strip().lower() or default + if value not in allowed: + raise ConfigError(f"{name} must be one of {sorted(allowed)}, got {value!r}") + return value + + +def _secret(name: str, required: bool) -> str: + """Value of _FILE (preferred, Docker secret) or (local runs/tests).""" + path = os.environ.get(f"{name}_FILE", "").strip() + if path: + try: + value = Path(path).read_text(encoding="utf-8").strip() + except OSError as exc: + # The message names the file, never its content. + raise ConfigError(f"{name}_FILE={path} cannot be read: {exc.strerror}") from None + else: + value = os.environ.get(name, "").strip() + if required and not value: + raise ConfigError(f"{name}_FILE (or {name}) must be set") + return value + + +@dataclass(frozen=True) +class Settings: + host: str + port: int + env: str + log_level: str + shutdown_timeout: float + max_body_bytes: int + docs_enabled: bool = True + database_url: str = "" + session_store: str = "postgres" + cache_url: str = "" + session_ttl_seconds: int = 3600 + db_pool_min: int = 1 + db_pool_max: int = 10 + db_timeout_seconds: float = 3.0 + cache_timeout_seconds: float = 0.5 + hash_concurrency: int = 2 + instance_id: str = "local" + drain_seconds: float = 0.0 + idempotency_ttl_seconds: int = 86400 + stats_log_seconds: float = 0.0 + message_write_path: str = "function" + # Lab 4: private S3 bucket and attachment limits (see storage.py, attachments.py). + s3_endpoint: str = "http://s3:8333" + s3_region: str = "us-east-1" + s3_bucket: str = "messenger-attachments" + s3_access_key_id: str = "" + s3_secret_access_key: str = "" + s3_timeout_seconds: float = 3.0 + s3_connect_timeout_seconds: float = 1.0 + s3_max_connections: int = 20 + max_upload_bytes: int = 10 * 1024 * 1024 + max_image_pixels: int = 40_000_000 + upload_concurrency: int = 4 + upload_queue_timeout_seconds: float = 5.0 + upload_read_timeout_seconds: float = 30.0 + image_verify_timeout_seconds: float = 10.0 + image_verify_concurrency: int = 1 + jpeg_max_memory_mb: int = 256 + pending_grace_seconds: int = 900 + janitor_interval_seconds: float = 60.0 + # Lab 5: staging bucket (API writes, worker reads) and the asynchronous pipeline (jobs_settings()). + s3_staging_bucket: str = "messenger-staging" + broker_url: str = "" + pipeline_version: int = 1 + job_max_attempts: int = 5 + job_timeout_seconds: float = 60.0 + job_lease_seconds: float = 30.0 + job_retry_base_seconds: float = 2.0 + job_retry_max_seconds: float = 60.0 + worker_concurrency: int = 2 + worker_shutdown_seconds: float = 20.0 + image_max_memory_mb: int = 768 + staging_retention_seconds: int = 86400 + orphan_grace_seconds: int = 600 + cleanup_interval_seconds: float = 30.0 + relay_poll_seconds: float = 0.5 + relay_batch: int = 50 + queued_republish_seconds: float = 300.0 + fault_points: frozenset[str] = frozenset() + fault_values: dict[str, int] = field(default_factory=dict) + + def fault_value(self, point: str, default: int = 0) -> int: + return self.fault_values.get(point, default) + + @property + def db_statement_timeout_ms(self) -> int: + # The server stops a statement a bit before the client-side deadline fires. + return max(100, int(self.db_timeout_seconds * 1000) - 500) + + @classmethod + def from_env(cls, *, s3_credentials: bool = True) -> "Settings": + """s3_credentials=False: processes without S3 access (relay, jobctl).""" + log_level = os.environ.get("LOG_LEVEL", "info").strip().lower() or "info" + if log_level not in {"debug", "info", "warning", "error"}: + raise ConfigError(f"LOG_LEVEL must be debug/info/warning/error, got {log_level!r}") + session_store = os.environ.get("SESSION_STORE", "postgres").strip().lower() or "postgres" + if session_store == "redis": + session_store = "valkey" # same protocol; the course allows Redis OR Valkey + if session_store not in {"postgres", "valkey"}: + raise ConfigError(f"SESSION_STORE must be postgres or valkey, got {session_store!r}") + db_pool_min = _int("DB_POOL_MIN", 1, 0, 50) + db_pool_max = _int("DB_POOL_MAX", 10, 1, 100) + if db_pool_min > db_pool_max: + raise ConfigError("DB_POOL_MIN must not exceed DB_POOL_MAX") + return cls( + host=os.environ.get("APP_HOST", "0.0.0.0").strip() or "0.0.0.0", + port=_int("APP_PORT", 8080, 1, 65535), + env=os.environ.get("APP_ENV", "lab").strip() or "lab", + log_level=log_level, + # DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS must stay below compose stop_grace_period. + shutdown_timeout=_float("SHUTDOWN_TIMEOUT_SECONDS", 8.0, 0.0, 30.0), + max_body_bytes=_int("MAX_BODY_BYTES", 64 * 1024, 1024, 1024 * 1024), + docs_enabled=_bool("DOCS_ENABLED", True), + database_url=_secret("DATABASE_URL", required=True), + session_store=session_store, + cache_url=_secret("CACHE_URL", required=session_store == "valkey"), + # Contract name. Minimum 1 s so the expiry test can use 2 s. + session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600, 1, 30 * 24 * 3600), + db_pool_min=db_pool_min, + db_pool_max=db_pool_max, + db_timeout_seconds=_float("DB_TIMEOUT_SECONDS", 3.0, 0.5, 30.0), + cache_timeout_seconds=_float("CACHE_TIMEOUT_SECONDS", 0.5, 0.05, 10.0), + hash_concurrency=_int("PASSWORD_HASH_CONCURRENCY", 2, 1, 16), + instance_id=_instance_id(), + # After SIGTERM: readiness is 503 but requests are still served for this long, + # so the load balancer stops routing here before the listener closes. + drain_seconds=_float("DRAIN_SECONDS", 0.0, 0.0, 10.0), + # Contract: a replay within 24 h returns the original result. + idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 86400, 30 * 24 * 3600), + # Experiments (bench/track1): log DB pool counters and process CPU every N s; 0 = off. + stats_log_seconds=_float("STATS_LOG_SECONDS", 0.0, 0.0, 60.0), + # Track 1: `function` = one SQL call per send (migration 0003), `multi` = the previous + # multi-statement transaction; both have identical semantics (A/B on one image). + message_write_path=_choice("MESSAGE_WRITE_PATH", "function", {"function", "multi"}), + **s3_settings(credentials_required=s3_credentials), + **jobs_settings(broker_required=False), + ) + + +# Contract limits (contracts/README.md): configurable DOWN for experiments, never above them. +CONTRACT_MAX_UPLOAD_BYTES = 10 * 1024 * 1024 +CONTRACT_MAX_IMAGE_PIXELS = 40_000_000 +# Failure points for the experiments only (FAULT_POINTS of ONE service, compose variables +# API_/RELAY_/WORKER_FAULT_POINTS); empty in normal runs. `name` or `name=`. +FAULT_POINTS = { + # API, upload: between the staging PUT and the job COMMIT / after the job COMMIT, before 202. + "after_s3_put", "after_enqueue_commit", + # Relay: crash after the broker confirmed a publish but before outbox.published_at is + # committed; publish every message twice; publish a batch in reverse order. + "crash_after_publish", "duplicate_publish", "reverse_order", + # Worker: crash after the claim (before any side effect), after the S3 writes (before the + # result COMMIT), after the result COMMIT (before the ack); transient failure of the first N + # attempts; permanent failure; slow processing (N s, lease kept alive) of every job or only of + # pipeline version `slow_pipeline`; hang: stop the heartbeat and sleep N s inside processing. + "crash_after_claim", "crash_after_s3_write", "crash_after_commit", "transient_error", "permanent_error", + "slow", "slow_pipeline", "hang", + # Worker cleanup: pause N s after reading the candidates, before locking/deleting them. + "pause_cleanup", + # Lab 6 (API, POST /chats/{chat_id}/messages only): slow handler code (N ms of work outside the + # database: the trace shows a long server span WITHOUT a long child span - incident 2 contrast); + # rare server errors (N per mille answered 503) and rare slow requests (N per mille + 500 ms) + # for track 1 (what sampling keeps of rare events). + "slow_handler", "random_5xx", "random_slow", +} + + +def _faults() -> tuple[frozenset[str], dict[str, int]]: + names, values = set(), {} + for item in os.environ.get("FAULT_POINTS", "").split(","): + name, _, raw = item.strip().partition("=") + if not name: + continue + if name not in FAULT_POINTS: + raise ConfigError(f"FAULT_POINTS may contain only {sorted(FAULT_POINTS)}") + if raw: + if not raw.isdigit(): + raise ConfigError(f"FAULT_POINTS value of {name} must be an integer") + values[name] = int(raw) + names.add(name) + return frozenset(names), values + + +def _bucket(name: str, default: str) -> str: + bucket = os.environ.get(name, default).strip() or default + if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket): + raise ConfigError(f"{name} is not a valid bucket name: {bucket!r}") + return bucket + + +def s3_settings(*, credentials_required: bool = True) -> dict: + """S3 part of Settings; also used by the bootstrap CLI with its own keys.""" + faults, fault_values = _faults() + endpoint = os.environ.get("S3_ENDPOINT", "http://s3:8333").strip() or "http://s3:8333" + if not re.fullmatch(r"https?://[A-Za-z0-9.\-]+(:[0-9]{1,5})?/?", endpoint): + raise ConfigError(f"S3_ENDPOINT must be http(s)://host[:port], got {endpoint!r}") + bucket = _bucket("S3_BUCKET", "messenger-attachments") + staging = _bucket("S3_STAGING_BUCKET", "messenger-staging") + if staging == bucket: + raise ConfigError("S3_STAGING_BUCKET must differ from S3_BUCKET") + return dict( + s3_endpoint=endpoint, + s3_region=os.environ.get("S3_REGION", "us-east-1").strip() or "us-east-1", + s3_bucket=bucket, + s3_staging_bucket=staging, + s3_access_key_id=_secret("S3_ACCESS_KEY_ID", required=credentials_required), + s3_secret_access_key=_secret("S3_SECRET_ACCESS_KEY", required=credentials_required), + s3_timeout_seconds=_float("S3_TIMEOUT_SECONDS", 3.0, 0.2, 30.0), + s3_connect_timeout_seconds=_float("S3_CONNECT_TIMEOUT_SECONDS", 1.0, 0.1, 10.0), + s3_max_connections=_int("S3_MAX_CONNECTIONS", 20, 1, 200), + max_upload_bytes=_int("MAX_UPLOAD_BYTES", CONTRACT_MAX_UPLOAD_BYTES, 1024, CONTRACT_MAX_UPLOAD_BYTES), + max_image_pixels=_int("MAX_IMAGE_PIXELS", CONTRACT_MAX_IMAGE_PIXELS, 1, CONTRACT_MAX_IMAGE_PIXELS), + # At most this many request bodies of one replica are buffered/checked at once (RAM bound: + # UPLOAD_CONCURRENCY x MAX_UPLOAD_BYTES); further uploads wait, then get 503. + upload_concurrency=_int("UPLOAD_CONCURRENCY", 4, 1, 64), + upload_queue_timeout_seconds=_float("UPLOAD_QUEUE_TIMEOUT_SECONDS", 5.0, 0.0, 60.0), + upload_read_timeout_seconds=_float("UPLOAD_READ_TIMEOUT_SECONDS", 30.0, 1.0, 300.0), + image_verify_timeout_seconds=_float("IMAGE_VERIFY_TIMEOUT_SECONDS", 10.0, 1.0, 120.0), + # Full checks running at once per replica: a strict JPEG decode of a 40 Mpx progressive + # file needs up to ~120-240 MB of coefficient buffers (capped by JPEG_MAX_MEMORY_MB). + image_verify_concurrency=_int("IMAGE_VERIFY_CONCURRENCY", 1, 1, 16), + jpeg_max_memory_mb=_int("JPEG_MAX_MEMORY_MB", 256, 16, 2048), + # An intent row still `pending` after this long belongs to a failed upload: the janitor + # deletes its object and the row. Far above the longest possible upload (~45 s). + pending_grace_seconds=_int("PENDING_GRACE_SECONDS", 900, 1, 7 * 24 * 3600), + janitor_interval_seconds=_float("JANITOR_INTERVAL_SECONDS", 60.0, 0.0, 3600.0), + fault_points=faults, + fault_values=fault_values, + ) + + +def jobs_settings(*, broker_required: bool) -> dict: + """Lab 5 pipeline: retries, lease, worker limits, cleanup, relay (docs/PIPELINE.md).""" + from .pipeline import PIPELINES # local import: pipeline.py imports nothing from here + timeout = _float("JOB_TIMEOUT_SECONDS", 60.0, 1.0, 600.0) + lease = _float("JOB_LEASE_SECONDS", 30.0, 2.0, 600.0) + base = _float("JOB_RETRY_BASE_SECONDS", 2.0, 0.0, 600.0) + cap = _float("JOB_RETRY_MAX_SECONDS", 60.0, 0.0, 3600.0) + if base > cap: + raise ConfigError("JOB_RETRY_BASE_SECONDS must not exceed JOB_RETRY_MAX_SECONDS") + orphan_grace = _int("ORPHAN_GRACE_SECONDS", 600, 1, 7 * 24 * 3600) + version = _int("PIPELINE_VERSION", 1, 1, 1000) + if version not in PIPELINES: + raise ConfigError(f"PIPELINE_VERSION must be one of {sorted(PIPELINES)}") + return dict( + broker_url=_secret("BROKER_URL", required=broker_required), + # Pipeline version of the jobs created by new uploads (track 2: versioned pipeline). + pipeline_version=version, + # Managed attempts (claims) per job before failed/retry_exhausted. + job_max_attempts=_int("JOB_MAX_ATTEMPTS", 5, 1, 100), + # Hard limit of ONE attempt: the image child process is killed, the lease is no longer renewed. + job_timeout_seconds=timeout, + # Lease of a claimed job, renewed by the heartbeat every lease/3 while the attempt runs. + job_lease_seconds=lease, + # Backoff of transient failures: full jitter, uniform(0, min(max, base * 2^(attempt-1))). + job_retry_base_seconds=base, + job_retry_max_seconds=cap, + # Jobs processed at once by ONE worker process = RabbitMQ prefetch (basic.qos). + worker_concurrency=_int("WORKER_CONCURRENCY", 2, 1, 32), + worker_shutdown_seconds=_float("WORKER_SHUTDOWN_SECONDS", 20.0, 0.0, 120.0), + # Address-space limit (RLIMIT_AS) of the child process that decodes/encodes ONE image. + image_max_memory_mb=_int("IMAGE_MAX_MEMORY_MB", 768, 128, 8192), + # Staging copy of a FAILED attachment is kept this long for a replay, then deleted. + staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400, 0, 30 * 24 * 3600), + # Objects of attempts that did not publish are deleted once the attempt ended this long ago. + orphan_grace_seconds=orphan_grace, + cleanup_interval_seconds=_float("CLEANUP_INTERVAL_SECONDS", 30.0, 0.0, 3600.0), + relay_poll_seconds=_float("RELAY_POLL_SECONDS", 0.5, 0.05, 60.0), + relay_batch=_int("RELAY_BATCH", 50, 1, 1000), + # A queued job whose message has not led to a claim for this long is published again + # (message lost in the broker, dead-lettered, purged): no accepted job waits forever. + queued_republish_seconds=_float("QUEUED_REPUBLISH_SECONDS", 300.0, 5.0, 86400.0), + ) diff --git a/src/messenger/cursor.py b/src/messenger/cursor.py new file mode 100644 index 0000000..8e2d5ee --- /dev/null +++ b/src/messenger/cursor.py @@ -0,0 +1,56 @@ +"""Opaque keyset cursors. + +A cursor encodes the sort key `(created_at, id)` of the last item on the page +plus the resource it belongs to, e.g. `v1|m|||`, +packed in URL-safe base64. The client treats it as an opaque string; the server +rejects cursors of another chat/user (400) and any non-canonical encoding. +""" +from __future__ import annotations + +import base64 +import re + +from .errors import InvalidRequest +from .validation import UUID_RE + +B64_RE = re.compile(r"[A-Za-z0-9_-]{1,512}") +TS_RE = re.compile(r"[0-9]{1,19}") + +# Latest instant both Python datetime and PostgreSQL accept: 9999-12-31T23:59:59.999999Z. +MAX_TS_US = 253402300799999999 + +MESSAGES = "m" +CHATS = "c" + +SortKey = tuple[int, str] + + +def encode(scope: str, owner_id: str, key: SortKey) -> str: + ts, item_id = key + raw = f"v1|{scope}|{owner_id}|{ts}|{item_id}".encode("ascii") + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii") + + +def decode(cursor: str, scope: str, owner_id: str) -> SortKey: + """Return the sort key stored in the cursor or raise InvalidRequest.""" + bad = InvalidRequest("Неверный cursor") + if B64_RE.fullmatch(cursor) is None: + raise bad + try: + raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)).decode("ascii") + except (ValueError, UnicodeDecodeError): + raise bad from None + parts = raw.split("|") + if len(parts) != 5 or parts[0] != "v1": + raise bad + _, got_scope, got_owner, ts, item_id = parts + if TS_RE.fullmatch(ts) is None or UUID_RE.fullmatch(item_id) is None or item_id != item_id.lower(): + raise bad + key = (int(ts), item_id) + if key[0] > MAX_TS_US: + raise bad # out-of-range time must be 400, not an overflow (500) in datetime/SQL + if encode(got_scope, got_owner, key) != cursor: + raise bad # only the canonical form produced by the server is accepted + if got_scope != scope or got_owner != owner_id: + raise InvalidRequest("cursor относится к другому ресурсу") + return key diff --git a/src/messenger/db.py b/src/messenger/db.py new file mode 100644 index 0000000..98c3c7b --- /dev/null +++ b/src/messenger/db.py @@ -0,0 +1,171 @@ +"""PostgreSQL access: a bounded connection pool and a hard deadline for every unit of work. + +Three independent limits keep a request from hanging when the database misbehaves: + +* pool `timeout` — waiting for a free connection (pool exhausted); +* server `statement_timeout` / `lock_timeout` — PostgreSQL itself cancels a slow + statement or a statement stuck behind a lock; +* client deadline — covers what the server cannot report, e.g. a + paused/frozen PostgreSQL container or a dead network. + +The client deadline needs care. Every unit of work runs as its own task; at the deadline +the REQUEST stops waiting and gets 503 at once, but the task is NOT cancelled: cancelling a +psycopg query makes psycopg send a cancel request, and libpq starts that connection +(PQcancelStart) synchronously in the event-loop thread, resolving the host name first. +When the API has lost its network to PostgreSQL (lab 3 review scenario: `docker network +disconnect`), that blocked the WHOLE replica, /health/live included, for ~1 minute. +The abandoned task instead ends by itself, bounded by: + +* TCP keepalives + `tcp_user_timeout` (= the deadline): a dead peer or a vanished network + breaks the socket within seconds, the connection is discarded by the pool; +* `statement_timeout` / `lock_timeout` on a live but slow server; +* a frozen (paused) server keeps the connection until it resumes; meanwhile new work waits + at most the pool timeout and gets 503. + +Any failure becomes 503 `unavailable` — never 401, never a hang. +""" +from __future__ import annotations + +import asyncio +import logging +import sys +import time +from collections.abc import Awaitable, Callable +from typing import TypeVar + +import psycopg +from psycopg_pool import AsyncConnectionPool, PoolTimeout + +from . import telemetry +from .config import Settings +from .errors import Unavailable + +log = logging.getLogger("messenger.db") + +T = TypeVar("T") +Work = Callable[[psycopg.AsyncConnection], Awaitable[T]] + +# Errors that mean "the database is unavailable right now", not "the request is wrong". +# QueryCanceled (statement_timeout), LockNotAvailable (lock_timeout) and AdminShutdown +# (server restart) are subclasses of OperationalError. +UNAVAILABLE_ERRORS = (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout, TimeoutError) + + +def _forget(task: asyncio.Task) -> None: + """Done-callback for abandoned tasks: retrieve the result so nothing is logged as 'never retrieved'.""" + if not task.cancelled(): + task.exception() + + +class Database: + def __init__(self, settings: Settings, name: str = "messenger-api"): + self.name = name + self.deadline = settings.db_timeout_seconds + options = ( + f"-c statement_timeout={settings.db_statement_timeout_ms} " + f"-c lock_timeout={max(100, settings.db_statement_timeout_ms // 2)} " + "-c idle_in_transaction_session_timeout=10000" + ) + self.pool = AsyncConnectionPool( + conninfo=settings.database_url, + min_size=settings.db_pool_min, + max_size=settings.db_pool_max, + timeout=settings.db_timeout_seconds, # max wait for a free connection + open=False, + name=name, + check=AsyncConnectionPool.check_connection, # drop connections broken by a DB restart + kwargs={ + "options": options, + "connect_timeout": max(1, int(settings.db_timeout_seconds)), + "application_name": name, # visible in pg_stat_activity: api / relay / worker + # Autocommit connections: a single statement (post_message function, ping) is its + # own transaction with ONE round trip; multi-statement work uses an explicit + # conn.transaction() (BEGIN ... COMMIT), see run(). + "autocommit": True, + # Detect a dead peer / lost network without any cancel request (see module doc). + "keepalives": 1, + "keepalives_idle": 5, + "keepalives_interval": 1, + "keepalives_count": 3, + "tcp_user_timeout": int(settings.db_timeout_seconds * 1000), + }, + ) + + async def open(self) -> None: + # wait=False: the API starts (liveness 200) even if PostgreSQL is not up yet; + # readiness stays 503 until the database answers. + await self.pool.open(wait=False) + + async def close(self) -> None: + await self.pool.close(timeout=2) + + async def run(self, work: Work[T], deadline: float | None = None, *, transaction: bool = True, + op: str | None = None) -> T: + """Run `work(conn)` in one transaction (COMMIT on success, ROLLBACK on any exception). + transaction=False: `work` issues exactly ONE statement, which autocommit makes atomic. + + Domain errors raised by `work` (NotFound, Conflict, ...) propagate unchanged; + database unavailability and the deadline become Unavailable (503). + + Lab 6: one CLIENT span `db ` per unit of work (only inside a traced request/job: no + root spans from background loops) with the pool wait as attribute + `db.client.connection.wait_time_ms`, plus the metrics db.client.operation.duration and + db.client.connection.wait_time. `op` defaults to the calling function's name (a fixed + set of code names, low cardinality); SQL text and parameters are never recorded. + """ + op = op or sys._getframe(1).f_code.co_name + parent_recording = telemetry.trace.get_current_span().is_recording() + + async def unit() -> T: + begin = time.perf_counter() + span = (telemetry.TRACER.start_span(f"db {op}", kind=telemetry.SpanKind.CLIENT, attributes={ + "db.system.name": "postgresql", "db.operation.name": op, "db.client.connection.pool.name": self.name}) + if parent_recording else None) + outcome = "error" + try: + async with self.pool.connection() as conn: + waited = time.perf_counter() - begin + telemetry.db_wait.record(waited, {"db.client.connection.pool.name": self.name}) + if span is not None: + span.set_attribute("db.client.connection.wait_time_ms", round(waited * 1000, 3)) + if not transaction: + result = await work(conn) + else: + async with conn.transaction(): + result = await work(conn) + outcome = "ok" + return result + except UNAVAILABLE_ERRORS as exc: + if span is not None: + telemetry.mark_error(span, type(exc).__name__) + raise + except Exception: + outcome = "domain" # NotFound/Conflict...: an answer, not a database failure + raise + finally: + telemetry.db_duration.record(time.perf_counter() - begin, { + "db.system.name": "postgresql", "db.operation.name": op, "outcome": outcome, + "db.client.connection.pool.name": self.name}) + if span is not None: + span.end() + + task = asyncio.ensure_future(unit()) # copies the context: the span's parent is the caller's span + try: + return await asyncio.wait_for(asyncio.shield(task), deadline or self.deadline) + except UNAVAILABLE_ERRORS as exc: + log.warning("database_unavailable", extra={"fields": {"error": type(exc).__name__, "op": op}}) + raise Unavailable("База данных временно недоступна") from None + finally: + if not task.done(): + # Deadline or cancelled request: stop waiting now. The task is left to finish + # on its own (no task.cancel(): that would trigger psycopg's blocking cancel). + task.add_done_callback(_forget) + + async def ping(self, timeout: float = 1.0) -> bool: + async def select_one(conn: psycopg.AsyncConnection) -> None: + await conn.execute("SELECT 1") + try: + await self.run(select_one, deadline=timeout, transaction=False, op="ping") + return True + except Unavailable: + return False diff --git a/src/messenger/docs.py b/src/messenger/docs.py new file mode 100644 index 0000000..cb2ea46 --- /dev/null +++ b/src/messenger/docs.py @@ -0,0 +1,57 @@ +"""Swagger UI for manual experiments: http://127.0.0.1:8080/docs + +The page shows the course contract contracts/openapi.json as is (it is not +generated from our code). Only `servers` is replaced with "/" so that the +"Try it out" requests go to the same host the page was opened from. +Swagger UI itself (JS/CSS) is loaded by the browser from the jsDelivr CDN. +Disable with DOCS_ENABLED=false. +""" +from __future__ import annotations + +import json +from functools import lru_cache +from pathlib import Path + +from starlette.requests import Request +from starlette.responses import HTMLResponse, JSONResponse + +SPEC_PATH = Path(__file__).resolve().parents[2] / "contracts" / "openapi.json" +SWAGGER_UI = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.33.0" + +PAGE = f""" + + + + Messenger lab1 — Swagger UI + + + +
+ + + + +""" + + +@lru_cache(maxsize=1) +def _spec() -> dict: + spec = json.loads(SPEC_PATH.read_text(encoding="utf-8")) + spec["servers"] = [{"url": "/", "description": "этот сервер"}] + return spec + + +async def swagger_page(request: Request) -> HTMLResponse: + return HTMLResponse(PAGE) + + +async def openapi_json(request: Request) -> JSONResponse: + return JSONResponse(_spec()) diff --git a/src/messenger/errors.py b/src/messenger/errors.py new file mode 100644 index 0000000..fa3ce51 --- /dev/null +++ b/src/messenger/errors.py @@ -0,0 +1,71 @@ +"""Domain errors mapped 1:1 to the contract error codes (contracts/README.md).""" +from __future__ import annotations + +BEARER_CHALLENGE = 'Bearer realm="messenger"' +BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' + + +class ApiError(Exception): + status = 500 + code = "internal_error" + default_message = "Внутренняя ошибка сервера" + + def __init__(self, message: str | None = None): + self.message = message or self.default_message + super().__init__(self.message) + + @property + def headers(self) -> dict[str, str]: + return {} + + +class InvalidRequest(ApiError): + status = 400 + code = "invalid_request" + default_message = "Неверный запрос" + + +class Unauthorized(ApiError): + """401 with the challenge of the scheme the endpoint expects (RFC 7235).""" + + status = 401 + code = "unauthorized" + default_message = "Требуется действительная сессия" + + def __init__(self, message: str | None = None, challenge: str = BEARER_CHALLENGE): + super().__init__(message) + self.challenge = challenge + + @property + def headers(self) -> dict[str, str]: + return {"WWW-Authenticate": self.challenge} + + +class NotFound(ApiError): + status = 404 + code = "not_found" + default_message = "Объект не найден" + + +class Conflict(ApiError): + status = 409 + code = "conflict" + default_message = "Конфликт" + + +class PayloadTooLarge(ApiError): + status = 413 + code = "payload_too_large" + default_message = "Тело запроса слишком большое" + + +class UnsupportedMediaType(ApiError): + status = 415 + code = "unsupported_media_type" + default_message = "Неподдерживаемый тип содержимого" + + +class Unavailable(ApiError): + status = 503 + code = "unavailable" + default_message = "Сервис временно недоступен" diff --git a/src/messenger/healthcheck.py b/src/messenger/healthcheck.py new file mode 100644 index 0000000..37b0040 --- /dev/null +++ b/src/messenger/healthcheck.py @@ -0,0 +1,31 @@ +"""Docker HEALTHCHECK probe without curl/wget in the image: `python -m messenger.healthcheck`. + + (no arguments) API: GET /health/ready on the local port + --file /tmp/heartbeat --max-age 30 relay/worker: the main loop wrote its heartbeat recently + (it writes it only while its database/broker work) +""" +from __future__ import annotations + +import os +import sys +import time +import urllib.request + + +def main(argv: list[str]) -> int: + if len(argv) == 4 and argv[0] == "--file" and argv[2] == "--max-age": + try: + with open(argv[1], encoding="ascii") as f: + return 0 if time.time() - float(f.read().strip()) <= float(argv[3]) else 1 + except (OSError, ValueError): + return 1 + port = os.environ.get("APP_PORT", "8080").strip() or "8080" + try: + with urllib.request.urlopen(f"http://127.0.0.1:{port}/health/ready", timeout=2) as response: + return 0 if response.status == 200 else 1 + except Exception: + return 1 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/src/messenger/images.py b/src/messenger/images.py new file mode 100644 index 0000000..7169c0c --- /dev/null +++ b/src/messenger/images.py @@ -0,0 +1,328 @@ +"""Content checks of uploaded images (lab 4): what the bytes ARE, not what the client says. + +Two stages, both with bounded memory and both BEFORE anything is stored: + +1. `sniff(head)` — runs on the first bytes while the body is still arriving. Recognises + PNG/JPEG by the signature and reads the dimensions from the header (PNG IHDR, JPEG SOFn). + A foreign format is rejected (415) and a picture with more than MAX_IMAGE_PIXELS pixels + (413) before the rest of the body is read and long before any pixel is decoded. +2. `verify(data, info)` — full integrity check of the complete file, run in a worker thread: + * PNG: our own streaming validator. Every chunk CRC is checked, the IDAT zlib stream is + inflated in 1 MiB steps and DISCARDED (no raster in memory), its size must be exactly + height x (1 + row bytes) (Adam7 per pass), every row filter byte must be 0..4, IEND + must close the file. A truncated file, a broken IDAT or extra/missing pixel data fail. + Pillow is not used for PNG: it would allocate the whole raster (40 Mpx RGBA = 160 MB). + * JPEG: libjpeg-turbo `djpeg -strict` decodes the whole entropy-coded data at 1/8 scale + (DCT scaling: the output raster is 64 times smaller) in a child process; any decoder + warning is fatal, so a truncated file or a file without scan data after SOS fails. + +Every problem of the CONTENT is an ImageError carrying the HTTP status (415 or 413); +nothing here may turn user input into a 500. +""" +from __future__ import annotations + +import asyncio +import os +import shutil +import struct +import zlib +from dataclasses import dataclass + +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" +JPEG_SOI = b"\xff\xd8\xff" + +PNG = "image/png" +JPEG = "image/jpeg" + +# Bits per pixel channel count by PNG colour type, and the bit depths allowed for it. +PNG_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4} +PNG_DEPTHS = {0: {1, 2, 4, 8, 16}, 2: {8, 16}, 3: {1, 2, 4, 8}, 4: {8, 16}, 6: {8, 16}} +# Adam7 passes: (x start, y start, x step, y step). +ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)) +# JPEG start-of-frame markers that carry the frame size (not DHT C4, JPG C8, DAC CC). +JPEG_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} +# Standalone markers without a length field. +JPEG_STANDALONE = {0x01, *range(0xD0, 0xD8)} + +DJPEG = shutil.which("djpeg") or "djpeg" # libjpeg-turbo-progs, installed in the Dockerfile +INPUT_STEP = 1 << 16 # compressed bytes handed to zlib at once +INFLATE_STEP = 1 << 20 # bytes of raw PNG data produced per zlib call +MAX_DIMENSION = 2**31 - 1 + + +class ImageError(Exception): + """The uploaded bytes are not an acceptable image. `status`: 415 (format/corrupt) or 413.""" + + def __init__(self, status: int, message: str): + super().__init__(message) + self.status = status + self.message = message + + +class VerifierUnavailable(Exception): + """The checker itself could not run to the end (resources): the API answers 503, retryable.""" + + +def unsupported(message: str ="Файл не является корректным изображением PNG или JPEG") -> ImageError: + return ImageError(415, message) + + +@dataclass(frozen=True, slots=True) +class ImageInfo: + content_type: str + width: int + height: int + + +def detect(head: bytes) -> str | None: + """Format by signature; None while fewer bytes than a signature have arrived.""" + if head[:8] == PNG_SIGNATURE: + return PNG + if head[:3] == JPEG_SOI: + return JPEG + probe = min(len(head), 8) + if PNG_SIGNATURE.startswith(head[:probe]) or JPEG_SOI.startswith(head[:min(probe, 3)]): + return None + raise unsupported() + + +def sniff(head: bytes, max_pixels: int) -> ImageInfo | None: + """Format and size from the beginning of the file, or None if more bytes are needed. + + Raises ImageError: 415 for a foreign/broken header, 413 for too many pixels.""" + kind = detect(head) + if kind is None: + return None + info = _png_header(head) if kind == PNG else _jpeg_header(head) + if info is None: + return None + if info.width * info.height > max_pixels: + raise ImageError(413, f"Изображение больше {max_pixels} пикселей") + return info + + +def _png_header(head: bytes) -> ImageInfo | None: + if len(head) < 33: + return None + length, ctype = struct.unpack(">I4s", head[8:16]) + if ctype != b"IHDR" or length != 13: + raise unsupported() + if zlib.crc32(head[12:29]) != struct.unpack(">I", head[29:33])[0]: + raise unsupported() + width, height, depth, color, compression, filtering, interlace = struct.unpack(">IIBBBBB", head[16:29]) + if not (1 <= width <= MAX_DIMENSION and 1 <= height <= MAX_DIMENSION): + raise unsupported() + if color not in PNG_DEPTHS or depth not in PNG_DEPTHS[color] or compression or filtering or interlace > 1: + raise unsupported() + return ImageInfo(PNG, width, height) + + +def _jpeg_header(head: bytes) -> ImageInfo | None: + """Walk the marker segments up to the first SOFn. None = the SOF has not arrived yet.""" + i = 2 + n = len(head) + while True: + if i >= n: + return None + if head[i] != 0xFF: + raise unsupported() + while i < n and head[i] == 0xFF: # fill bytes + i += 1 + if i >= n: + return None + marker = head[i] + i += 1 + if marker in JPEG_STANDALONE: + continue + if marker in (0xD8, 0xD9, 0xDA, 0x00): + # Second SOI, EOI or scan data before any frame header: not a usable JPEG. + raise unsupported() + if i + 2 > n: + return None + length = struct.unpack(">H", head[i:i + 2])[0] + if length < 2: + raise unsupported() + if marker in JPEG_SOF: + if i + 7 > n: + return None + if length < 8: + raise unsupported() + height, width = struct.unpack(">HH", head[i + 3:i + 7]) + if width == 0 or height == 0: # height 0 = DNL-defined height: not supported + raise unsupported() + return ImageInfo(JPEG, width, height) + i += length + + +# ------------------------------------------------------------------ full verification +async def verify(data: bytes | bytearray | memoryview, info: ImageInfo, *, timeout: float = 10.0, + jpeg_max_memory_mb: int = 256) -> None: + """Complete integrity check of the whole file. PNG: our validator in a worker thread (zlib + releases the GIL); JPEG: a strict libjpeg decoder in a child process.""" + if info.content_type == PNG: + await asyncio.wait_for(asyncio.to_thread(verify_png, data), timeout) + else: + await verify_jpeg(data, timeout, jpeg_max_memory_mb) + + +def _png_segments(width: int, height: int, depth: int, color: int, interlace: int) -> list[tuple[int, int]]: + """(byte count, row stride) of every pass of the raw (filtered) image data.""" + bpp = PNG_CHANNELS[color] * depth + passes = ADAM7 if interlace else ((0, 0, 1, 1),) + segments = [] + for xs, ys, dx, dy in passes: + pw = (width - xs + dx - 1) // dx if width > xs else 0 + ph = (height - ys + dy - 1) // dy if height > ys else 0 + if pw and ph: + stride = 1 + (pw * bpp + 7) // 8 + segments.append((ph * stride, stride)) + return segments + + +class _RawChecker: + """Counts inflated bytes against the expected size and checks the filter byte of every row + using C-speed slicing (`piece[first::stride]`), so even 40 000 000 one-pixel rows are fast.""" + + VALID_FILTERS = bytes(range(5)) + + def __init__(self, segments: list[tuple[int, int]]): + self.segments = segments + self.index = 0 # current pass + self.offset = 0 # bytes already seen inside the current pass + self.expected = sum(size for size, _ in segments) + self.total = 0 + + def feed(self, piece: bytes) -> None: + self.total += len(piece) + if self.total > self.expected: + raise unsupported() + pos = 0 + while pos < len(piece): + size, stride = self.segments[self.index] + take = min(size - self.offset, len(piece) - pos) + part = piece[pos:pos + take] + first = (-self.offset) % stride + if part[first::stride].translate(None, self.VALID_FILTERS): + raise unsupported() + self.offset += take + pos += take + if self.offset == size: + self.index += 1 + self.offset = 0 + + +def verify_png(data: bytes | bytearray | memoryview) -> None: + view = memoryview(data) + if bytes(view[:8]) != PNG_SIGNATURE: + raise unsupported() + pos = 8 + n = len(view) + checker: _RawChecker | None = None + inflater = zlib.decompressobj() + color = None + seen_plte = seen_idat = idat_done = False + first = True + while True: + if pos + 12 > n: + raise unsupported() # truncated: no room for another chunk header + CRC + length, ctype = struct.unpack(">I4s", view[pos:pos + 8]) + if length > n - pos - 12: + raise unsupported() + body = view[pos + 8:pos + 8 + length] + crc = struct.unpack(">I", view[pos + 8 + length:pos + 12 + length])[0] + if zlib.crc32(body, zlib.crc32(ctype)) != crc: + raise unsupported() + pos += 12 + length + if not all(65 <= c <= 90 or 97 <= c <= 122 for c in ctype): + raise unsupported() + if first: + if ctype != b"IHDR" or length != 13: + raise unsupported() + width, height, depth, color, compression, filtering, interlace = struct.unpack(">IIBBBBB", body) + if (not (1 <= width <= MAX_DIMENSION and 1 <= height <= MAX_DIMENSION) or color not in PNG_DEPTHS + or depth not in PNG_DEPTHS[color] or compression or filtering or interlace > 1): + raise unsupported() + checker = _RawChecker(_png_segments(width, height, depth, color, interlace)) + first = False + continue + assert checker is not None + if ctype == b"IHDR": + raise unsupported() + if ctype == b"PLTE": + if seen_plte or seen_idat or color in (0, 4) or length % 3 or not 3 <= length <= 768: + raise unsupported() + seen_plte = True + elif ctype == b"IDAT": + if idat_done: + raise unsupported() # IDAT chunks must be consecutive + if color == 3 and not seen_plte: + raise unsupported() + seen_idat = True + _inflate(inflater, body, checker) + elif ctype == b"IEND": + if length != 0 or not seen_idat: + raise unsupported() + if pos != n: + raise unsupported() # bytes after IEND (polyglot files) are not accepted + break + elif not 97 <= ctype[0] <= 122: + raise unsupported() # unknown CRITICAL chunk: a decoder could not show the image + if ctype != b"IDAT" and seen_idat: + idat_done = True + # The zlib stream must end exactly with the last pixel row, without trailing data. + if not inflater.eof or inflater.unused_data or checker.total != checker.expected: + raise unsupported() + + +def _inflate(inflater, body: memoryview, checker: _RawChecker) -> None: + if inflater.eof: + if len(body): + raise unsupported() # data after the end of the zlib stream + return + # Input is fed in small slices: zlib's `unconsumed_tail` is a COPY of the unread input, so + # feeding the whole 10 MiB IDAT at once would copy the rest of it after every output step. + try: + for start in range(0, len(body), INPUT_STEP): + pending: bytes | memoryview = body[start:start + INPUT_STEP] + while pending: + if inflater.eof: + raise unsupported() # data after the end of the zlib stream + checker.feed(inflater.decompress(pending, INFLATE_STEP)) + pending = inflater.unconsumed_tail + if inflater.eof and inflater.unused_data: + raise unsupported() + except zlib.error: + raise unsupported() from None + + +async def verify_jpeg(data: bytes | bytearray | memoryview, timeout: float, max_memory_mb: int) -> None: + """Decode the WHOLE file with the reference decoder (libjpeg-turbo `djpeg`) in strict mode. + + `-strict` turns every libjpeg warning into a failure: "premature end of data segment" + (scan data missing or cut before EOI), "premature end of JPEG file", corrupt Huffman data. + Pillow cannot be used for this: it ignores libjpeg warnings and returns a grey picture for + a JPEG whose scan data is missing. `-scale 1/8` decodes every block but writes a 64x + smaller raster to /dev/null; `-maxmemory` caps libjpeg's working memory (coefficient + buffers of progressive files); the separate process is killed at the deadline. + """ + process = await asyncio.create_subprocess_exec( + DJPEG, "-strict", "-scale", "1/8", "-maxmemory", str(max_memory_mb * 1024), "-outfile", os.devnull, + stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE) + stderr = b"" + try: + _, stderr = await asyncio.wait_for(process.communicate(data), timeout) + except (asyncio.TimeoutError, asyncio.CancelledError): + process.kill() + await process.wait() + raise + except (BrokenPipeError, ConnectionResetError): + await process.wait() # djpeg stopped reading: the file is already known to be broken + if process.returncode is not None and process.returncode < 0: + # Killed by a signal (the cgroup OOM killer under memory pressure): a problem of the + # SERVER, not of the file - never report it as 415. + raise VerifierUnavailable() + if process.returncode != 0: + if b"Insufficient memory" in (stderr or b""): + # A valid but extremely memory-hungry file (progressive, 4:4:4, ~40 Mpx): a limit, not corruption. + raise ImageError(413, "Изображение слишком велико для обработки") + raise unsupported() diff --git a/src/messenger/imaging.py b/src/messenger/imaging.py new file mode 100644 index 0000000..2bf15cc --- /dev/null +++ b/src/messenger/imaging.py @@ -0,0 +1,208 @@ +"""Variants of ONE image, built in a separate child process with hard limits (lab 5 worker). + + parent (worker): await render(data, content_type, version, ...) -> list[Rendered] + child: python -m messenger.imaging --type image/png --pipeline 1 ... + stdin: original bytes; stdout: one JSON header line + variant bytes + +Why a child process per image: +* memory: RLIMIT_AS (IMAGE_MAX_MEMORY_MB) caps the address space of the decoder; a picture that + needs more fails with MemoryError -> `image_too_large` (permanent), the worker keeps running; +* time: the parent kills the child at JOB_TIMEOUT_SECONDS (C code of Pillow cannot be + interrupted inside a thread) -> `processing_timeout` (transient, bounded by JOB_MAX_ATTEMPTS); +* pixels: the size is read from the header and checked against MAX_IMAGE_PIXELS BEFORE the + pixels are decoded (`Image.open` is lazy). +A crash of the decoder (signal) is a transient `processing_killed`: the next attempt may run +with less memory pressure; JOB_MAX_ATTEMPTS bounds it. + +Geometry and encoder settings: pipeline.py. Alpha is handled in premultiplied form (RGBa) while +resizing, so transparent pixels do not bleed their colour into the edges; for JPEG the result is +then composited onto white. +""" +from __future__ import annotations + +import argparse +import asyncio +import hashlib +import io +import json +import sys +import warnings +from dataclasses import dataclass + +from .pipeline import CONTENT_TYPES, CROP_SIDE, OPTIMIZED_BOX, PIPELINES, THUMBNAIL_BOX, center_square, fit + +EXIT_INVALID = 3 # the bytes are not a decodable PNG/JPEG +EXIT_TOO_LARGE = 4 # pixel limit or memory limit +HEADER_LIMIT = 4096 + + +class ProcessingError(Exception): + """Outcome of an attempt that did not produce variants. `permanent`: another attempt with the + same input cannot succeed (job -> failed at once); otherwise retry with backoff.""" + + def __init__(self, code: str, permanent: bool): + super().__init__(code) + self.code = code + self.permanent = permanent + + +@dataclass(frozen=True, slots=True) +class Rendered: + name: str + content_type: str + width: int + height: int + data: bytes + + @property + def sha256(self) -> bytes: + return hashlib.sha256(self.data).digest() + + +# ------------------------------------------------------------------ parent side +async def render(data: bytes, content_type: str, pipeline_version: int, *, max_pixels: int, timeout: float, + memory_mb: int) -> list[Rendered]: + process = await asyncio.create_subprocess_exec( + sys.executable, "-m", "messenger.imaging", "--type", content_type, "--pipeline", str(pipeline_version), + "--max-pixels", str(max_pixels), "--memory-mb", str(memory_mb), + stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + try: + out, _ = await asyncio.wait_for(process.communicate(data), timeout) + except asyncio.TimeoutError: + process.kill() + await process.wait() + raise ProcessingError("processing_timeout", permanent=False) from None + except asyncio.CancelledError: + process.kill() + await process.wait() + raise + code = process.returncode + if code == EXIT_INVALID: + raise ProcessingError("invalid_image", permanent=True) + if code == EXIT_TOO_LARGE: + raise ProcessingError("image_too_large", permanent=True) + if code is None or code < 0: + raise ProcessingError("processing_killed", permanent=False) # OOM killer or another signal + if code != 0: + raise ProcessingError("processing_failed", permanent=False) + return parse_output(out) + + +def parse_output(out: bytes) -> list[Rendered]: + newline = out.find(b"\n", 0, HEADER_LIMIT) + if newline < 0: + raise ProcessingError("processing_failed", permanent=False) + header = json.loads(out[:newline]) + pos = newline + 1 + result = [] + for item in header["variants"]: + size = int(item["size"]) + result.append(Rendered(item["name"], item["content_type"], int(item["width"]), int(item["height"]), + out[pos:pos + size])) + pos += size + if pos != len(out) or [r.name for r in result] != list(CONTENT_TYPES): + raise ProcessingError("processing_failed", permanent=False) + return result + + +# ------------------------------------------------------------------ child side +def build(data: bytes, content_type: str, pipeline_version: int, max_pixels: int) -> list[Rendered]: + """Decode once, build every variant. Raises the Pillow/OS errors of a bad file.""" + from PIL import Image, ImageOps + + pipeline = PIPELINES[pipeline_version] + warnings.simplefilter("ignore", Image.DecompressionBombWarning) # our own pixel limit below + Image.MAX_IMAGE_PIXELS = max_pixels + expected = {"image/png": "PNG", "image/jpeg": "JPEG"}[content_type] + img = Image.open(io.BytesIO(data), formats=[expected]) # header only: nothing decoded yet + width, height = img.size + if width * height > max_pixels: + raise TooLarge() + if expected == "JPEG": + # DCT scaling: decode a big JPEG directly at 1/2..1/8 of its size, never below what the + # largest variant needs (the box stays square, so EXIF rotation does not matter). + img.draft("RGB", (OPTIMIZED_BOX, OPTIMIZED_BOX)) + img.load() + img = ImageOps.exif_transpose(img) # orientation goes into the pixels, the tag is dropped + img = _normalize(img) + alpha = img.mode == "RGBA" + base = img.convert("RGBa") if alpha else img # premultiplied alpha for resampling + del img + + def finish(im, *, flatten: bool): + if alpha: + im = im.convert("RGBA") + if flatten: + white = Image.new("RGB", im.size, (255, 255, 255)) + white.paste(im, mask=im.getchannel("A")) + im = white + im.info = {} # no EXIF/XMP/ICC/comments of the source in a variant + return im + + def resized(im, size): + return im if im.size == size else im.resize(size, Image.Resampling.LANCZOS, reducing_gap=3.0) + + thumbnail = finish(resized(base, fit(*base.size, THUMBNAIL_BOX)), flatten=True) + crop = finish(resized(base.crop(center_square(*base.size)), (CROP_SIDE, CROP_SIDE)), flatten=True) + optimized = finish(resized(base, fit(*base.size, OPTIMIZED_BOX)), flatten=False) + out = [] + for name, im in (("thumbnail", thumbnail), ("crop", crop), ("optimized", optimized)): + buf = io.BytesIO() + if CONTENT_TYPES[name] == "image/jpeg": + im.save(buf, "JPEG", quality=pipeline.jpeg_quality, optimize=True, subsampling=2, progressive=False) + else: + im.save(buf, "WEBP", quality=pipeline.webp_quality, method=pipeline.webp_method, exif=b"", + icc_profile="", xmp=b"") + out.append(Rendered(name, CONTENT_TYPES[name], im.width, im.height, buf.getvalue())) + return out + + +class TooLarge(Exception): + pass + + +def _normalize(img): + """Any PNG/JPEG mode -> RGB, or RGBA when the image has transparency.""" + if img.mode.startswith("I;16") or img.mode == "I": + # 16-bit grey: scale 0..65535 to 0..255 (a plain convert("L") would clip to white). + img = img.convert("I").point(lambda v: v * (1 / 257)).convert("L") + has_alpha = img.mode in ("RGBA", "LA", "PA", "La", "RGBa") or "transparency" in img.info + return img.convert("RGBA" if has_alpha else "RGB") if img.mode != ("RGBA" if has_alpha else "RGB") else img + + +def child_main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--type", required=True, choices=["image/png", "image/jpeg"]) + parser.add_argument("--pipeline", type=int, required=True, choices=sorted(PIPELINES)) + parser.add_argument("--max-pixels", type=int, required=True) + parser.add_argument("--memory-mb", type=int, required=True) + args = parser.parse_args(argv) + try: + import resource + limit = args.memory_mb * 1024 * 1024 + resource.setrlimit(resource.RLIMIT_AS, (limit, limit)) + except (ImportError, ValueError, OSError): + pass # not Linux (unit tests on Windows): the container memory limit still applies + data = sys.stdin.buffer.read() + try: + variants = build(data, args.type, args.pipeline, args.max_pixels) + except (TooLarge, MemoryError): + return EXIT_TOO_LARGE + except Exception as exc: # noqa: BLE001 - every decoder error of the CONTENT is "invalid image" + from PIL import Image + if isinstance(exc, Image.DecompressionBombError): + return EXIT_TOO_LARGE + if isinstance(exc, (OSError, SyntaxError, ValueError, EOFError, KeyError, IndexError, TypeError)): + return EXIT_INVALID + raise + header = {"variants": [{"name": v.name, "content_type": v.content_type, "width": v.width, "height": v.height, + "size": len(v.data)} for v in variants]} + sys.stdout.buffer.write(json.dumps(header).encode() + b"\n") + for v in variants: + sys.stdout.buffer.write(v.data) + sys.stdout.buffer.flush() + return 0 + + +if __name__ == "__main__": + sys.exit(child_main()) diff --git a/src/messenger/jobctl.py b/src/messenger/jobctl.py new file mode 100644 index 0000000..a037e19 --- /dev/null +++ b/src/messenger/jobctl.py @@ -0,0 +1,220 @@ +"""Operator CLI for attachment jobs: `python -m messenger.jobctl ...` (compose service `jobctl`). + + list-failed [--limit N] failed registry (view failed_jobs), newest first + show attachment state, its jobs, attempts and audit events + stats jobs by state, outbox backlog + replay --operator NAME --reason TEXT + failed -> queued: a NEW job (kind=replay, replay_of = the failed job) with a fresh attempt + budget. Refused (exit 3, nothing changed) unless the attachment is failed AND its source + still exists (staging copy present or original published). "Repeat" never means + "run a finished job again": a ready attachment is refused (already_ready). + reprocess --pipeline N --operator NAME --reason TEXT + Track 2: build a NEWER pipeline version of a READY attachment from its published original. + Refused unless ready, N known, N > published version and no job of version >= N active. + A not-yet-ready upload is refused: its only source is the staging copy that belongs to the + running job, and its result would race with the first publication. + +Every decision is taken under the attachments row lock, the same lock the cleanup takes before it +marks a staging copy `deleting`: either the replay sees the copy and the cleanup then skips the +row (no longer failed), or the cleanup marked it first and the replay refuses (source_missing). +Output: one JSON document on stdout, without secrets or file names. +""" +from __future__ import annotations + +import argparse +import asyncio +import json +import re +import sys +import uuid + +from . import jobs +from .config import ConfigError, Settings +from .db import Database +from .errors import Unavailable +from .pipeline import PIPELINES + +OPERATOR_RE = re.compile(r"[A-Za-z0-9._-]{1,64}") +EXIT_REFUSED = 3 + + +class Refused(Exception): + pass + + +def operator(value: str) -> str: + if not OPERATOR_RE.fullmatch(value): + raise argparse.ArgumentTypeError("operator must match [A-Za-z0-9._-]{1,64}") + return value + + +def reason(value: str) -> str: + value = value.strip() + if not 1 <= len(value) <= 200 or any(ord(ch) < 32 for ch in value): + raise argparse.ArgumentTypeError("reason: 1-200 printable characters") + return value + + +def attachment_id(value: str) -> str: + try: + return str(uuid.UUID(value)) + except ValueError: + raise argparse.ArgumentTypeError("not a UUID") from None + + +async def lock_attachment(conn, attachment: str): + cur = await conn.execute( + "SELECT status, staging_state, object_key IS NOT NULL, published_version FROM attachments " + "WHERE id = %s FOR UPDATE", (attachment,)) + row = await cur.fetchone() + if row is None or row[0] == "pending": + raise Refused("not_found") + return row + + +async def replay(conn, args, settings: Settings) -> dict: + status, staging_state, has_original, _ = await lock_attachment(conn, args.attachment_id) + if status == "ready": + raise Refused("already_ready") + if status != "failed": + raise Refused("not_failed:" + status) + if not has_original and staging_state != "present": + raise Refused("source_missing") # staging removed by the retention cleanup + cur = await conn.execute( + "SELECT id, pipeline_version FROM jobs WHERE attachment_id = %s AND state = 'failed' " + "ORDER BY finished_at DESC LIMIT 1", (args.attachment_id,)) + last = await cur.fetchone() + if last is None: + raise Refused("no_failed_job") + cur = await conn.execute("SELECT 1 FROM jobs WHERE attachment_id = %s AND state IN ('queued', 'processing')", + (args.attachment_id,)) + if await cur.fetchone(): + raise Refused("active_job") + await conn.execute( + "UPDATE attachments SET status = 'queued', error_code = NULL, failed_at = NULL, updated_at = clock_timestamp() " + "WHERE id = %s", (args.attachment_id,)) + actor = "jobctl:" + args.operator + await jobs.event(conn, last[0], "replay_requested", actor, reason=args.reason) + job_id = await jobs.create_job(conn, args.attachment_id, last[1], "replay", settings.job_max_attempts, actor, + replay_of=last[0], reason=args.reason) + return {"result": "queued", "job_id": str(job_id), "replay_of": str(last[0]), "pipeline_version": last[1]} + + +async def reprocess(conn, args, settings: Settings) -> dict: + status, _, _, published = await lock_attachment(conn, args.attachment_id) + if args.pipeline not in PIPELINES: + raise Refused("unknown_pipeline") + if status != "ready": + raise Refused("not_ready:" + status) + if args.pipeline <= published: + raise Refused("not_newer") + cur = await conn.execute( + "SELECT max(pipeline_version) FROM jobs WHERE attachment_id = %s AND state IN ('queued', 'processing')", + (args.attachment_id,)) + (active,) = await cur.fetchone() + if active is not None and active >= args.pipeline: + raise Refused("newer_or_same_active") + job_id = await jobs.create_job(conn, args.attachment_id, args.pipeline, "reprocess", settings.job_max_attempts, + "jobctl:" + args.operator, reason=args.reason) + return {"result": "queued", "job_id": str(job_id), "pipeline_version": args.pipeline, + "published_version": published} + + +async def list_failed(conn, args, settings: Settings) -> dict: + cur = await conn.execute( + "SELECT job_id, attachment_id, pipeline_version, kind, attempt, max_attempts, error_code, finished_at, " + "attachment_status, staging_state FROM failed_jobs ORDER BY finished_at DESC LIMIT %s", (args.limit,)) + cols = [d.name for d in cur.description] + return {"failed": [dict(zip(cols, r)) for r in await cur.fetchall()]} + + +async def show(conn, args, settings: Settings) -> dict: + cur = await conn.execute( + "SELECT status, error_code, published_version, staging_state, object_key IS NOT NULL AS original_published, " + "updated_at FROM attachments WHERE id = %s", (args.attachment_id,)) + row = await cur.fetchone() + if row is None: + raise Refused("not_found") + attachment = dict(zip([d.name for d in cur.description], row)) + + async def rows(sql: str) -> list[dict]: + c = await conn.execute(sql, (args.attachment_id,)) + names = [d.name for d in c.description] + return [dict(zip(names, r)) for r in await c.fetchall()] + + return { + "attachment": attachment, + "jobs": await rows("SELECT id, pipeline_version, kind, state, attempt, max_attempts, error_code, replay_of, " + "created_at, finished_at FROM jobs WHERE attachment_id = %s ORDER BY created_at"), + "attempts": await rows("SELECT a.job_id, a.attempt, a.token, a.worker, a.source, a.outcome, a.error_code, " + "a.started_at, a.finished_at, a.objects_cleaned_at FROM job_attempts a " + "JOIN jobs j ON j.id = a.job_id WHERE j.attachment_id = %s ORDER BY a.started_at"), + "variants": await rows("SELECT pipeline_version, name, content_type, size_bytes, width, height, " + "encode(sha256, 'hex') AS sha256 FROM attachment_variants WHERE attachment_id = %s " + "ORDER BY pipeline_version, name"), + "events": await rows("SELECT e.job_id, e.at, e.event, e.attempt, e.actor, e.error_code, e.detail " + "FROM job_events e JOIN jobs j ON j.id = e.job_id WHERE j.attachment_id = %s " + "ORDER BY e.id"), + } + + +async def stats(conn, args, settings: Settings) -> dict: + cur = await conn.execute("SELECT state, count(*) FROM jobs GROUP BY state ORDER BY state") + by_state = {r[0]: r[1] for r in await cur.fetchall()} + cur = await conn.execute("SELECT count(*), count(*) FILTER (WHERE available_at <= clock_timestamp()) " + "FROM outbox WHERE published_at IS NULL") + pending, due = await cur.fetchone() + return {"jobs": by_state, "outbox_unpublished": pending, "outbox_due": due} + + +COMMANDS = {"replay": replay, "reprocess": reprocess, "list-failed": list_failed, "show": show, "stats": stats} + + +def arguments(argv: list[str] | None) -> argparse.Namespace: + p = argparse.ArgumentParser(prog="jobctl", description="Attachment jobs: failed registry, replay, reprocess") + sub = p.add_subparsers(dest="command", required=True) + for name in ("replay", "reprocess"): + s = sub.add_parser(name) + s.add_argument("attachment_id", type=attachment_id) + if name == "reprocess": + s.add_argument("--pipeline", type=int, required=True) + s.add_argument("--operator", type=operator, required=True) + s.add_argument("--reason", type=reason, required=True) + s = sub.add_parser("list-failed") + s.add_argument("--limit", type=int, default=50) + s = sub.add_parser("show") + s.add_argument("attachment_id", type=attachment_id) + sub.add_parser("stats") + return p.parse_args(argv) + + +async def run(args: argparse.Namespace) -> int: + settings = Settings.from_env(s3_credentials=False) + db = Database(settings, name="messenger-jobctl") + await db.open() + try: + writes = args.command in ("replay", "reprocess") + result = await db.run(lambda c: COMMANDS[args.command](c, args, settings), deadline=10) + print(json.dumps(result, ensure_ascii=False, indent=1, default=str)) + return 0 if not writes or result.get("result") == "queued" else 1 + except Refused as exc: + print(json.dumps({"result": "refused", "reason": str(exc)})) + return EXIT_REFUSED + except Unavailable: + print(json.dumps({"result": "error", "reason": "database_unavailable"})) + return 1 + finally: + await db.close() + + +def main(argv: list[str] | None = None) -> int: + args = arguments(argv) + try: + return asyncio.run(run(args)) + except ConfigError as exc: + print(f"configuration error: {exc}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/messenger/jobs.py b/src/messenger/jobs.py new file mode 100644 index 0000000..374109e --- /dev/null +++ b/src/messenger/jobs.py @@ -0,0 +1,428 @@ +"""State machine of attachment jobs in PostgreSQL (lab 5). Every transition is ONE transaction. + +Lock order, everywhere both rows are locked: the jobs row FIRST, then the attachments row +(claim, complete, retry, lease expiry). Replay/reprocess/cleanup lock only the attachments row +and insert NEW job rows. So two transitions never wait on each other in opposite order. + +Fencing: a claim gives the attempt a fresh random `lease_token`. Every later write of that attempt +(heartbeat, result, retry) is conditional on `jobs.lease_token = ` under the jobs row +lock. When the lease expires, the reaper clears the token; from then on the old attempt - even if +its process is still alive (paused, slow) - can neither publish nor schedule anything, and the +objects it wrote under its own keys are garbage for the cleanup. + +Monotonic publication: a result of pipeline version V is published only if V is greater than the +published version of the attachment; otherwise the job ends as `superseded` and nothing visible +changes. `ready` never goes back to queued/processing. +""" +from __future__ import annotations + +import datetime as dt +import json +import random +import uuid +from dataclasses import dataclass + +import psycopg + +from . import telemetry +from .pipeline import VARIANT_NAMES +from .storage import attempt_key + +ACTIVE = ("queued", "processing") + + +def backoff_delay(attempt: int, base: float, cap: float, rnd=random.random) -> float: + """Full jitter (AWS Architecture Blog, "Exponential Backoff And Jitter"): uniform in + [0, min(cap, base * 2^(attempt-1))]. Spreads the retries of many jobs that failed together.""" + return rnd() * min(cap, base * (2 ** max(0, attempt - 1))) + + +async def event(conn: psycopg.AsyncConnection, job_id, name: str, actor: str, *, attempt: int | None = None, + error_code: str | None = None, **detail) -> None: + await conn.execute( + "INSERT INTO job_events (job_id, event, attempt, actor, error_code, detail) VALUES (%s, %s, %s, %s, %s, %s)", + (job_id, name, attempt, actor, error_code, json.dumps(detail, default=str))) + + +async def create_job(conn: psycopg.AsyncConnection, attachment_id, pipeline_version: int, kind: str, + max_attempts: int, actor: str, *, replay_of=None, **detail) -> uuid.UUID: + """jobs row + its first outbox row + audit, in the CALLER's transaction. + Lab 6: the current W3C trace context (the upload request) is stored with the job: every + message of this job is published as a child of it (migrations/0006_observability.sql).""" + job_id = uuid.uuid4() + carrier = telemetry.inject() + await conn.execute( + "INSERT INTO jobs (id, attachment_id, pipeline_version, kind, replay_of, max_attempts, traceparent, tracestate) " + "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", + (job_id, attachment_id, pipeline_version, kind, replay_of, max_attempts, + carrier.get("traceparent"), carrier.get("tracestate"))) + await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, 1)", (job_id,)) + await event(conn, job_id, "created", actor, kind=kind, pipeline_version=pipeline_version, + replay_of=str(replay_of) if replay_of else None, **detail) + return job_id + + +# ------------------------------------------------------------------ relay +@dataclass(frozen=True, slots=True) +class Due: + outbox_id: int + job_id: str + attachment_id: str + pipeline_version: int + attempt: int + created_at: dt.datetime + job_state: str + traceparent: str | None = None + tracestate: str | None = None + kind: str = "upload" + + +async def due_outbox(conn: psycopg.AsyncConnection, batch: int) -> list[Due]: + """Due, unpublished outbox rows, locked for this relay pass (SKIP LOCKED: several relays + never publish the same row at the same time - a crash may still publish it twice).""" + cur = await conn.execute( + "SELECT o.id, o.job_id, j.attachment_id, j.pipeline_version, o.attempt, j.created_at, j.state, " + "j.traceparent, j.tracestate, j.kind " + "FROM outbox o JOIN jobs j ON j.id = o.job_id " + "WHERE o.published_at IS NULL AND o.available_at <= clock_timestamp() " + "ORDER BY o.available_at, o.id LIMIT %s FOR UPDATE OF o SKIP LOCKED", (batch,)) + return [Due(r[0], str(r[1]), str(r[2]), r[3], r[4], r[5], r[6], r[7], r[8], r[9]) for r in await cur.fetchall()] + + +async def mark_published(conn: psycopg.AsyncConnection, ids: list[int]) -> None: + if ids: + await conn.execute("UPDATE outbox SET published_at = clock_timestamp() WHERE id = ANY(%s)", (ids,)) + + +async def count_publish_failure(conn: psycopg.AsyncConnection, ids: list[int]) -> None: + if ids: + await conn.execute("UPDATE outbox SET publish_failures = publish_failures + 1 WHERE id = ANY(%s)", (ids,)) + + +async def expire_leases(conn: psycopg.AsyncConnection, actor: str, limit: int = 50) -> int: + """Reaper: processing jobs whose lease ran out (the worker died, hung or lost its database). + The attempt is abandoned; the job goes back to queued with a new outbox row, or to failed + `retry_exhausted` when it used all its attempts.""" + cur = await conn.execute( + "SELECT id, attempt, max_attempts, lease_token, attachment_id FROM jobs " + "WHERE state = 'processing' AND lease_until < clock_timestamp() " + "ORDER BY lease_until LIMIT %s FOR UPDATE SKIP LOCKED", (limit,)) + rows = await cur.fetchall() + for job_id, attempt, max_attempts, token, attachment_id in rows: + await conn.execute( + "UPDATE job_attempts SET outcome = 'abandoned', error_code = 'lease_expired', finished_at = clock_timestamp() " + "WHERE token = %s AND outcome = 'running'", (token,)) + if attempt >= max_attempts: + await _fail(conn, job_id, attachment_id, "retry_exhausted", actor, attempt, cause="lease_expired") + else: + await conn.execute( + "UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, " + "available_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (job_id,)) + await conn.execute( + "UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() " + "WHERE id = %s AND status = 'processing'", (attachment_id,)) + await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (job_id, attempt + 1)) + await event(conn, job_id, "lease_expired", actor, attempt=attempt) + return len(rows) + + +async def republish_stale(conn: psycopg.AsyncConnection, older_than: float, actor: str, limit: int = 50) -> int: + """Lost-message guard: a queued, due job that has had no unpublished outbox row and no + publish for `older_than` seconds gets a new outbox row (its message was lost by the broker, + dead-lettered after too many redeliveries, or the queue was purged).""" + cur = await conn.execute( + "SELECT j.id, j.attempt FROM jobs j " + "WHERE j.state = 'queued' AND j.available_at < clock_timestamp() - make_interval(secs => %s) " + "AND j.updated_at < clock_timestamp() - make_interval(secs => %s) " + "AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.id AND (o.published_at IS NULL " + " OR o.published_at > clock_timestamp() - make_interval(secs => %s))) " + "ORDER BY j.updated_at LIMIT %s FOR UPDATE OF j SKIP LOCKED", (older_than, older_than, older_than, limit)) + rows = await cur.fetchall() + for job_id, attempt in rows: + await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (job_id, attempt + 1)) + await event(conn, job_id, "republished", actor, attempt=attempt) + return len(rows) + + +async def queue_stats(conn: psycopg.AsyncConnection) -> dict: + """Backlog for the gauges (relay, every few seconds): two aggregates over partial indexes.""" + cur = await conn.execute( + "SELECT count(*) FILTER (WHERE state = 'queued'), count(*) FILTER (WHERE state = 'processing'), " + "COALESCE(EXTRACT(EPOCH FROM clock_timestamp() - min(created_at)), 0)::float8 " + "FROM jobs WHERE state IN ('queued', 'processing')") + queued, processing, oldest = await cur.fetchone() + cur = await conn.execute( + "SELECT count(*) FILTER (WHERE available_at <= clock_timestamp()), " + "count(*) FILTER (WHERE available_at > clock_timestamp()), " + "COALESCE(EXTRACT(EPOCH FROM clock_timestamp() - min(available_at) " + " FILTER (WHERE available_at <= clock_timestamp())), 0)::float8 " + "FROM outbox WHERE published_at IS NULL") + due, delayed, outbox_age = await cur.fetchone() + return {"queued": queued, "processing": processing, "oldest_age": float(oldest), + "outbox_due": due, "outbox_delayed": delayed, "outbox_oldest_due_age": float(outbox_age)} + + +async def purge_outbox(conn: psycopg.AsyncConnection, keep_seconds: int = 7 * 86400) -> int: + cur = await conn.execute( + "DELETE FROM outbox WHERE id IN (SELECT id FROM outbox WHERE published_at < clock_timestamp() " + "- make_interval(secs => %s) LIMIT 1000)", (keep_seconds,)) + return cur.rowcount + + +# ------------------------------------------------------------------ worker +@dataclass(frozen=True, slots=True) +class Claim: + job_id: str + attachment_id: str + pipeline_version: int + attempt: int + max_attempts: int + token: str + source: str # staging | original + source_key: str + content_type: str + size_bytes: int + sha256: bytes + write_original: bool # the original is not published yet: this attempt publishes it too + kind: str = "upload" # upload | replay | reprocess | migrate + accepted_at: dt.datetime | None = None # jobs.created_at = the durable acceptance (202) of an upload + + def key(self, name: str) -> str: + return attempt_key(self.attachment_id, self.token, name) + + +@dataclass(frozen=True, slots=True) +class Noop: + reason: str # finished | leased | not_due | superseded | unknown_job + + +async def claim(conn: psycopg.AsyncConnection, job_id: str, worker: str, lease_seconds: float) -> Claim | Noop: + cur = await conn.execute( + "SELECT state, attempt, max_attempts, available_at > clock_timestamp(), attachment_id, pipeline_version, " + "kind, created_at FROM jobs WHERE id = %s FOR UPDATE", (job_id,)) + row = await cur.fetchone() + if row is None: + return Noop("unknown_job") + state, attempt, max_attempts, not_due, attachment_id, version, kind, accepted_at = row + if state not in ACTIVE: + return Noop("finished") # duplicate/redelivery of a finished job: ack, nothing else + if state == "processing": + return Noop("leased") # another attempt holds the lease; the reaper handles its death + if not_due: + return Noop("not_due") # backoff not over: the outbox publishes it at available_at + cur = await conn.execute( + "SELECT status, published_version, object_key, staging_key, staging_state, content_type, size_bytes, sha256 " + "FROM attachments WHERE id = %s FOR UPDATE", (attachment_id,)) + status, published, object_key, staging_key, staging_state, content_type, size, sha = await cur.fetchone() + actor = "worker:" + worker + if published is not None and published >= version: + # A newer (or the same) version is already published: this job can only be stale. + await _finish(conn, job_id, "superseded", None) + await event(conn, job_id, "superseded", actor, attempt=attempt, published_version=published) + return Noop("superseded") + if object_key is not None: + source, source_key = "original", object_key + elif staging_state == "present": + source, source_key = "staging", staging_key + else: + # Cannot happen while the CHECK attachments_active_has_source holds; fail visibly anyway. + await _fail(conn, job_id, attachment_id, "source_missing", actor, attempt) + return Noop("finished") + token = uuid.uuid4().hex + attempt += 1 + write_original = object_key is None + names = (("original",) if write_original else ()) + VARIANT_NAMES + planned = [attempt_key(str(attachment_id), token, n) for n in names] + await conn.execute( + "UPDATE jobs SET state = 'processing', attempt = %s, lease_token = %s, lease_owner = %s, " + "lease_until = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE id = %s", + (attempt, token, worker, lease_seconds, job_id)) + await conn.execute( + "INSERT INTO job_attempts (token, job_id, attempt, worker, source, planned_keys) VALUES (%s, %s, %s, %s, %s, %s)", + (token, job_id, attempt, worker, source, planned)) + await conn.execute( + "UPDATE attachments SET status = 'processing', updated_at = clock_timestamp() WHERE id = %s AND status = 'queued'", + (attachment_id,)) + await event(conn, job_id, "claimed", actor, attempt=attempt, source=source, token=token) + return Claim(str(job_id), str(attachment_id), version, attempt, max_attempts, token, source, source_key, + content_type, size, bytes(sha), write_original, kind, accepted_at) + + +async def heartbeat(conn: psycopg.AsyncConnection, claim: Claim, lease_seconds: float) -> bool: + """Extend the lease; False = the lease was lost (expired and taken over): stop the attempt.""" + cur = await conn.execute( + "UPDATE jobs SET lease_until = clock_timestamp() + make_interval(secs => %s) " + "WHERE id = %s AND state = 'processing' AND lease_token = %s", (lease_seconds, claim.job_id, claim.token)) + return cur.rowcount == 1 + + +async def _holds_lease(conn: psycopg.AsyncConnection, claim: Claim) -> bool: + cur = await conn.execute("SELECT state = 'processing' AND lease_token = %s FROM jobs WHERE id = %s FOR UPDATE", + (claim.token, claim.job_id)) + row = await cur.fetchone() + return bool(row and row[0]) + + +async def complete(conn: psycopg.AsyncConnection, claim: Claim, variants, worker: str) -> str: + """Publish the result of an attempt atomically: variant rows + attachment ready + job succeeded. + Returns succeeded | superseded | fenced (this attempt lost its lease: nothing written).""" + actor = "worker:" + worker + if not await _holds_lease(conn, claim): + return "fenced" + cur = await conn.execute("SELECT published_version FROM attachments WHERE id = %s FOR UPDATE", (claim.attachment_id,)) + (published,) = await cur.fetchone() + if published is not None and published >= claim.pipeline_version: + await _end_attempt(conn, claim, "superseded", None) + await _finish(conn, claim.job_id, "superseded", None) + await event(conn, claim.job_id, "superseded", actor, attempt=claim.attempt, published_version=published) + return "superseded" + for v in variants: + await conn.execute( + "INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, " + "size_bytes, width, height, sha256, attempt_token) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", + (claim.attachment_id, claim.pipeline_version, v.name, claim.key(v.name), v.content_type, len(v.data), + v.width, v.height, v.sha256, claim.token)) + await conn.execute( + "UPDATE attachments SET status = 'ready', published_version = %s, error_code = NULL, failed_at = NULL, " + "object_key = COALESCE(object_key, %s), updated_at = clock_timestamp() WHERE id = %s", + (claim.pipeline_version, claim.key("original") if claim.write_original else None, claim.attachment_id)) + await _end_attempt(conn, claim, "succeeded", None) + await _finish(conn, claim.job_id, "succeeded", None) + await event(conn, claim.job_id, "succeeded", actor, attempt=claim.attempt, pipeline_version=claim.pipeline_version) + return "succeeded" + + +async def retry_or_fail(conn: psycopg.AsyncConnection, claim: Claim, code: str, permanent: bool, worker: str, + base: float, cap: float) -> tuple[str, float]: + """After a failed attempt: permanent error or no attempts left -> failed (failed registry); + otherwise queued again after a jittered backoff. Returns (outcome, delay seconds).""" + actor = "worker:" + worker + if not await _holds_lease(conn, claim): + return "fenced", 0.0 + if permanent or claim.attempt >= claim.max_attempts: + final = code if permanent else "retry_exhausted" + await _end_attempt(conn, claim, "failed", code) + await _fail(conn, claim.job_id, claim.attachment_id, final, actor, claim.attempt, cause=code) + return "failed", 0.0 + delay = backoff_delay(claim.attempt, base, cap) + await _end_attempt(conn, claim, "retry", code) + await conn.execute( + "UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, error_code = %s, " + "available_at = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE id = %s", + (code, delay, claim.job_id)) + await conn.execute( + "UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = %s AND status = 'processing'", + (claim.attachment_id,)) + await conn.execute( + "INSERT INTO outbox (job_id, attempt, available_at) " + "VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s))", (claim.job_id, claim.attempt + 1, delay)) + await event(conn, claim.job_id, "retry_scheduled", actor, attempt=claim.attempt, error_code=code, + delay_s=round(delay, 3)) + return "retry", delay + + +async def release(conn: psycopg.AsyncConnection, claim: Claim, worker: str) -> str: + """Graceful stop of a worker with an attempt still running: give the job back at once + (without waiting for the lease to expire). The claim already counted as an attempt.""" + if not await _holds_lease(conn, claim): + return "fenced" + await _end_attempt(conn, claim, "abandoned", "worker_shutdown") + if claim.attempt >= claim.max_attempts: + await _fail(conn, claim.job_id, claim.attachment_id, "retry_exhausted", "worker:" + worker, claim.attempt, + cause="worker_shutdown") + return "failed" + await conn.execute( + "UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, " + "available_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (claim.job_id,)) + await conn.execute( + "UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = %s AND status = 'processing'", + (claim.attachment_id,)) + await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (claim.job_id, claim.attempt + 1)) + await event(conn, claim.job_id, "released", "worker:" + worker, attempt=claim.attempt) + return "released" + + +async def _end_attempt(conn: psycopg.AsyncConnection, claim: Claim, outcome: str, code: str | None) -> None: + await conn.execute( + "UPDATE job_attempts SET outcome = %s, error_code = %s, finished_at = clock_timestamp() " + "WHERE token = %s AND outcome = 'running'", (outcome, code, claim.token)) + + +async def _finish(conn: psycopg.AsyncConnection, job_id, state: str, code: str | None) -> None: + await conn.execute( + "UPDATE jobs SET state = %s, error_code = %s, lease_token = NULL, lease_owner = NULL, lease_until = NULL, " + "finished_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (state, code, job_id)) + + +async def _fail(conn: psycopg.AsyncConnection, job_id, attachment_id, code: str, actor: str, attempt: int, + **detail) -> None: + """Job -> failed (registry). The attachment becomes failed only if it is not ready: a failed + reprocess of a newer version leaves the published result in place.""" + await _finish(conn, job_id, "failed", code) + await conn.execute( + "UPDATE attachments SET status = 'failed', error_code = %s, failed_at = clock_timestamp(), " + "updated_at = clock_timestamp() WHERE id = %s AND status IN ('queued', 'processing')", (code, attachment_id)) + await event(conn, job_id, "failed", actor, attempt=attempt, error_code=code, **detail) + + +# ------------------------------------------------------------------ cleanup (worker) +async def staging_to_delete(conn: psycopg.AsyncConnection, retention_seconds: int, limit: int = 50) -> list[str]: + """Candidates only (no lock): ready attachments (staging no longer needed) and failed ones + older than the retention. The decision is re-checked under the row lock in mark_staging_deleting.""" + cur = await conn.execute( + "SELECT id FROM attachments WHERE staging_state IN ('present', 'deleting') AND (status = 'ready' OR " + "(status = 'failed' AND failed_at < clock_timestamp() - make_interval(secs => %s))) " + "ORDER BY updated_at LIMIT %s", (retention_seconds, limit)) + return [str(r[0]) for r in await cur.fetchall()] + + +async def mark_staging_deleting(conn: psycopg.AsyncConnection, attachment_id: str, retention_seconds: int) -> str | None: + """Under the attachment row lock, decide AGAIN from the committed state and mark the staging copy + `deleting` BEFORE the S3 DELETE. A replay that committed in between made the row queued, so it + no longer matches; a replay that comes later sees `deleting` and refuses. Queued/processing + rows never match (and the CHECK attachments_active_has_source forbids it anyway).""" + cur = await conn.execute( + "UPDATE attachments SET staging_state = 'deleting' " # internal state: updated_at stays (public field) + "WHERE id = %s AND staging_state IN ('present', 'deleting') AND (status = 'ready' OR (status = 'failed' " + "AND failed_at < clock_timestamp() - make_interval(secs => %s) AND NOT EXISTS (SELECT 1 FROM jobs j " + "WHERE j.attachment_id = attachments.id AND j.state IN ('queued', 'processing')))) RETURNING staging_key", + (attachment_id, retention_seconds)) + row = await cur.fetchone() + return row[0] if row else None + + +async def mark_staging_deleted(conn: psycopg.AsyncConnection, attachment_id: str) -> None: + await conn.execute( + "UPDATE attachments SET staging_state = 'deleted' WHERE id = %s AND staging_state = 'deleting'", (attachment_id,)) + + +async def attempts_to_clean(conn: psycopg.AsyncConnection, grace_seconds: int, limit: int = 50) -> list[str]: + cur = await conn.execute( + "SELECT token FROM job_attempts WHERE outcome IN ('retry', 'failed', 'abandoned', 'superseded') " + "AND objects_cleaned_at IS NULL AND finished_at < clock_timestamp() - make_interval(secs => %s) " + "ORDER BY finished_at LIMIT %s", (grace_seconds, limit)) + return [r[0].hex for r in await cur.fetchall()] + + +async def lock_attempt_for_cleanup(conn: psycopg.AsyncConnection, token: str) -> list[str] | None: + """Keys of an attempt that can never publish: it ended without success, it is not the lease + holder of its job (tokens are never reused) and nothing published references its keys.""" + cur = await conn.execute( + "SELECT ja.planned_keys FROM job_attempts ja JOIN jobs j ON j.id = ja.job_id " + "WHERE ja.token = %s AND ja.objects_cleaned_at IS NULL " + "AND ja.outcome IN ('retry', 'failed', 'abandoned', 'superseded') " + "AND j.lease_token IS DISTINCT FROM ja.token FOR UPDATE OF ja", (token,)) + row = await cur.fetchone() + if row is None: + return None + keys = list(row[0]) + cur = await conn.execute( + "SELECT EXISTS (SELECT 1 FROM attachment_variants WHERE object_key = ANY(%s)) " + "OR EXISTS (SELECT 1 FROM attachments WHERE object_key = ANY(%s))", (keys, keys)) + if (await cur.fetchone())[0]: + return None # published: never delete (would be a bug elsewhere; logged by the caller) + return keys + + +async def mark_attempt_cleaned(conn: psycopg.AsyncConnection, token: str) -> None: + await conn.execute("UPDATE job_attempts SET objects_cleaned_at = clock_timestamp() WHERE token = %s", (token,)) diff --git a/src/messenger/logging_setup.py b/src/messenger/logging_setup.py new file mode 100644 index 0000000..b06640c --- /dev/null +++ b/src/messenger/logging_setup.py @@ -0,0 +1,44 @@ +"""JSON-lines logging to stdout. Logs never contain message texts or request bodies. + +Lab 6: every line written inside an active span carries its trace_id/span_id (the same ids the +OTLP copy of the record has in Loki), so `docker compose logs` can be joined with Tempo too.""" +from __future__ import annotations + +import datetime as dt +import json +import logging +import sys + +from . import telemetry + + +class JsonFormatter(logging.Formatter): + def format(self, record: logging.LogRecord) -> str: + entry = { + "ts": dt.datetime.fromtimestamp(record.created, dt.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"), + "level": record.levelname.lower(), + "logger": record.name, + "event": record.getMessage(), + } + ids = telemetry.current_ids() + if ids: + entry["trace_id"], entry["span_id"] = ids + fields = getattr(record, "fields", None) + if fields: + entry.update(fields) + if record.exc_info: + # Stack traces go only to the server log, never to the HTTP client. + entry["exception"] = self.formatException(record.exc_info) + return json.dumps(entry, ensure_ascii=False) + + +def configure(level: str) -> None: + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(JsonFormatter()) + root = logging.getLogger() + root.handlers[:] = [handler] + root.setLevel(level.upper()) + # uvicorn's own access log is disabled; our middleware writes one line per request. + for name in ("uvicorn", "uvicorn.error"): + logging.getLogger(name).handlers[:] = [] + logging.getLogger(name).propagate = True diff --git a/src/messenger/migrate.py b/src/messenger/migrate.py new file mode 100644 index 0000000..10b18e9 --- /dev/null +++ b/src/messenger/migrate.py @@ -0,0 +1,76 @@ +"""Versioned SQL migrations: `python -m messenger.migrate` (compose service `migrate`). + +* Files `migrations/NNNN_name.sql` are applied in name order, each in its own + transaction together with its row in `schema_migrations` (DDL is transactional + in PostgreSQL, so a failed migration leaves nothing behind). +* Re-running is safe: applied versions are skipped, so data is never duplicated. +* The SHA-256 of every applied file is stored; if an applied file was edited later, + the run stops instead of silently diverging from the real schema. +* `pg_advisory_lock` serialises concurrent runs (two API replicas starting at once). +""" +from __future__ import annotations + +import hashlib +import sys +import time +from pathlib import Path + +import psycopg + +from .config import ConfigError, _secret + +MIGRATIONS_DIR = Path(__file__).resolve().parents[2] / "migrations" +LOCK_ID = 2026_02 # arbitrary application-wide advisory lock id + + +def say(text: str) -> None: + print(f"migrate: {text}", flush=True) + + +def connect(url: str, wait_seconds: float = 60) -> psycopg.Connection: + deadline = time.monotonic() + wait_seconds + while True: + try: + return psycopg.connect(url, autocommit=True, connect_timeout=3, application_name="messenger-migrate") + except psycopg.OperationalError as exc: + if time.monotonic() > deadline: + raise SystemExit(f"migrate: database is not reachable: {type(exc).__name__}") from None + time.sleep(1) + + +def main() -> int: + try: + url = _secret("DATABASE_URL", required=True) + except ConfigError as exc: + print(f"configuration error: {exc}", file=sys.stderr) + return 2 + files = sorted(MIGRATIONS_DIR.glob("*.sql")) + with connect(url) as conn: + conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,)) + try: + conn.execute( + "CREATE TABLE IF NOT EXISTS schema_migrations (" + " version text PRIMARY KEY, checksum text NOT NULL," + " applied_at timestamptz NOT NULL DEFAULT now())") + applied = dict(conn.execute("SELECT version, checksum FROM schema_migrations").fetchall()) + for path in files: + version, sql = path.stem, path.read_bytes() + checksum = hashlib.sha256(sql).hexdigest() + if version in applied: + if applied[version] != checksum: + say(f"{version}: file changed after it was applied; create a new migration instead") + return 1 + say(f"{version}: already applied, skipped") + continue + with conn.transaction(): + conn.execute(sql.decode("utf-8")) + conn.execute("INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)", (version, checksum)) + say(f"{version}: applied") + finally: + conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,)) + say(f"done, {len(files)} migration file(s) checked") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/messenger/passwords.py b/src/messenger/passwords.py new file mode 100644 index 0000000..a1fc35a --- /dev/null +++ b/src/messenger/passwords.py @@ -0,0 +1,53 @@ +"""Password hashing with Argon2id (memory-hard password KDF; also mandatory in lab 7). + +* Parameters follow the OWASP minimum for Argon2id: m=19 MiB, t=2, p=1. Unlike bcrypt + there is no 72-byte limit, so any 12-128 code point UTF-8 password is hashed whole. +* Hashing takes tens of milliseconds of CPU and 19 MiB of RAM. It runs in a worker + thread (argon2-cffi releases the GIL), so the event loop keeps serving other + requests, and a semaphore caps parallel hashes (memory/CPU DoS protection). +* An unknown username is checked against a dummy hash, so "no such user" and + "wrong password" take the same time and return the same 401. +""" +from __future__ import annotations + +import asyncio + +from argon2 import PasswordHasher +from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError + +_hasher = PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1, hash_len=32, salt_len=16) +_semaphore: asyncio.Semaphore | None = None +_dummy_hash: str | None = None + + +def configure(concurrency: int) -> None: + global _semaphore + _semaphore = asyncio.Semaphore(concurrency) + + +async def _run(func, *args): + if _semaphore is None: + configure(2) + async with _semaphore: + return await asyncio.to_thread(func, *args) + + +async def hash_password(password: str) -> str: + return await _run(_hasher.hash, password) + + +def _verify(stored_hash: str, password: str) -> bool: + try: + return _hasher.verify(stored_hash, password) + except (VerifyMismatchError, VerificationError, InvalidHashError): + return False + + +async def verify_password(stored_hash: str | None, password: str) -> bool: + global _dummy_hash + if stored_hash is None: + if _dummy_hash is None: + _dummy_hash = await hash_password("dummy-password-for-timing") + await _run(_verify, _dummy_hash, password) + return False + return await _run(_verify, stored_hash, password) diff --git a/src/messenger/pipeline.py b/src/messenger/pipeline.py new file mode 100644 index 0000000..9534ac5 --- /dev/null +++ b/src/messenger/pipeline.py @@ -0,0 +1,63 @@ +"""Versioned image pipeline (lab 5): WHAT the worker builds for one attachment. Pure definitions, +no I/O; the pixels are produced by imaging.py in a child process. + +Every pipeline version builds the same three variants with the geometry of the contract; versions +differ only in encoder parameters, so the published version is visible in the bytes (sha256): + + thumbnail JPEG, fits into 256x256, keeps the aspect ratio, never upscales, floor rounding + (minimum 1 px), EXIF orientation applied, alpha composited onto white; + crop JPEG, centred square 128x128 (small images ARE upscaled, the contract allows it); + optimized WebP, fits into 1280x1280, never upscales, alpha kept. + +Metadata: nothing of the source is copied into a variant - no EXIF (orientation is applied to +the pixels instead), no XMP, no ICC profile, no comments (the pixels are treated as sRGB). +The original is published byte for byte and keeps everything. + +Track 2: the version of a job is fixed when the job is created (PIPELINE_VERSION for uploads, +`jobctl reprocess --pipeline N` later). A result is published only if its version is greater +than the published one, so an old job can never overwrite a newer result. +""" +from __future__ import annotations + +from dataclasses import dataclass + +THUMBNAIL_BOX = 256 +CROP_SIDE = 128 +OPTIMIZED_BOX = 1280 +VARIANT_NAMES = ("thumbnail", "crop", "optimized") +CONTENT_TYPES = {"thumbnail": "image/jpeg", "crop": "image/jpeg", "optimized": "image/webp"} + + +@dataclass(frozen=True, slots=True) +class Pipeline: + version: int + jpeg_quality: int # thumbnail and crop: baseline JPEG, 4:2:0, optimized Huffman tables + webp_quality: int # optimized: lossy WebP + webp_method: int # 0 (fast) .. 6 (slow, smaller) + + +PIPELINES = { + 1: Pipeline(1, jpeg_quality=85, webp_quality=80, webp_method=4), + # Versions 2 and 3 exist for the track 2 experiments (reprocess, reorder, stale jobs): + # different encoder settings -> different bytes, identical geometry. + 2: Pipeline(2, jpeg_quality=80, webp_quality=75, webp_method=4), + 3: Pipeline(3, jpeg_quality=90, webp_quality=85, webp_method=5), +} + + +def fit(width: int, height: int, box: int) -> tuple[int, int]: + """Size inside box x box keeping the aspect ratio, never upscaling, rounded DOWN, >= 1 px. + Integer arithmetic: 320x200 -> 256x160 exactly, 1x1000 -> 1x256 (0.256 -> 1 px minimum).""" + if width <= box and height <= box: + return width, height + if width >= height: + return box, max(1, height * box // width) + return max(1, width * box // height), box + + +def center_square(width: int, height: int) -> tuple[int, int, int, int]: + """Crop box (left, top, right, bottom) of the centred square with side min(width, height).""" + side = min(width, height) + left = (width - side) // 2 + top = (height - side) // 2 + return left, top, left + side, top + side diff --git a/src/messenger/relay.py b/src/messenger/relay.py new file mode 100644 index 0000000..cd397c6 --- /dev/null +++ b/src/messenger/relay.py @@ -0,0 +1,235 @@ +"""Outbox relay: `python -m messenger.relay` (compose service `relay`, one process). + + loop: SELECT due outbox rows FOR UPDATE SKIP LOCKED + -> publish each job message to RabbitMQ, wait for the publisher CONFIRM + -> UPDATE outbox SET published_at -> COMMIT + every few seconds: reaper (expired leases -> queued/failed), lost-message guard. + +Why an outbox: the API commits the job and the outbox row in ONE PostgreSQL transaction and never +talks to the broker. A crash between COMMIT and publish leaves the row unpublished; the relay +publishes it when it (or the broker) is back - nobody re-creates a job by hand. While the broker +is down, uploads still get 202 and the rows wait in the outbox. + +A crash after the confirm but before the COMMIT of published_at publishes the row once more after +the restart: the queue then holds a duplicate. That is at-least-once delivery; the worker turns +the duplicate into a no-op (jobs.claim). The relay never deletes or rewrites jobs. + +Lab 6: every publish is a PRODUCER span `messenger.jobs publish` (publish + wait for the confirm), +child of the trace context stored with the job (the upload request). The producer's context goes +into the message body (`traceparent`/`tracestate`, contracts/jobs.schema.json) and the AMQP +headers. The relay is also the source of the queue gauges: every MAINTENANCE_SECONDS it counts +unfinished jobs and due outbox rows in PostgreSQL (the source of truth of the backlog, including +jobs waiting for a retry, which the broker queue does not hold). +""" +from __future__ import annotations + +import asyncio +import logging +import sys +import time + +import aio_pika +from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractExchange + +from . import __version__, broker, jobs, logging_setup, service, telemetry +from .config import ConfigError, Settings +from .db import Database +from .errors import Unavailable + +log = logging.getLogger("messenger.relay") +ACTOR = "relay" +MAINTENANCE_SECONDS = 5.0 +PURGE_SECONDS = 600.0 + + +class Relay: + def __init__(self, settings: Settings): + self.settings = settings + self.db = Database(settings, name="messenger-relay") + self.connection: AbstractConnection | None = None + self.channel: AbstractChannel | None = None + self.exchange: AbstractExchange | None = None + self.lost: asyncio.Event | None = None + self.queue_stats: dict | None = None # last jobs.queue_stats (None: unknown -> no data points) + + def connected(self) -> bool: + return (self.connection is not None and self.lost is not None and not self.lost.is_set() + and self.channel is not None and not self.channel.is_closed) + + async def connect(self) -> None: + self.connection = await aio_pika.connect( + self.settings.broker_url, timeout=5, + client_properties={"connection_name": "relay@" + self.settings.instance_id}) + self.lost = service.watch_connection(self.connection) + # Confirm mode: every publish() waits for basic.ack of the broker (message in the quorum log). + self.channel = await self.connection.channel(publisher_confirms=True, on_return_raises=True) + # No declare: the topology belongs to the broker definitions; the relay may only write. + self.exchange = await self.channel.get_exchange(broker.EXCHANGE, ensure=False) + log.info("broker_connected", extra={"fields": {"exchange": broker.EXCHANGE}}) + + async def disconnect(self) -> None: + if self.connection is not None: + try: + await self.connection.close() + except Exception: # noqa: BLE001 - already broken + pass + self.connection = self.channel = self.exchange = self.lost = None + + async def publish_due(self) -> int: + settings = self.settings + exchange = self.exchange + + async def work(conn) -> list[jobs.Due]: + rows = await jobs.due_outbox(conn, settings.relay_batch) + if "reverse_order" in settings.fault_points: + rows.reverse() + # Rows of jobs that are no longer queued (finished meanwhile) need no message. + sendable = [r for r in rows if r.job_state == "queued"] + copies = 2 if "duplicate_publish" in settings.fault_points else 1 + for row in sendable: + with telemetry.TRACER.start_as_current_span( + f"{broker.EXCHANGE} publish", kind=telemetry.SpanKind.PRODUCER, + context=telemetry.extract(row.traceparent, row.tracestate), + record_exception=False, set_status_on_exception=False, + attributes={"messaging.system": "rabbitmq", "messaging.operation.type": "send", + "messaging.operation.name": "publish", + "messaging.destination.name": broker.EXCHANGE, + "messaging.rabbitmq.destination.routing_key": broker.ROUTING_KEY, + "messaging.message.id": f"{row.job_id}:{row.outbox_id}", + "messenger.job.id": row.job_id, "messenger.job.attempt": row.attempt, + "messenger.job.kind": row.kind}) as span: + carrier = telemetry.inject() # = this producer span + message = aio_pika.Message( + broker.encode(row.job_id, row.attachment_id, row.pipeline_version, row.attempt, + row.created_at, carrier), + delivery_mode=aio_pika.DeliveryMode.PERSISTENT, content_type="application/json", + message_id=f"{row.job_id}:{row.outbox_id}", type=broker.JOB_TYPE, headers=dict(carrier)) + try: + for _ in range(copies): + await exchange.publish(message, routing_key=broker.ROUTING_KEY, mandatory=True, timeout=5) + except BaseException as exc: + telemetry.mark_error(span, type(exc).__name__) + raise + for row in sendable: + # Confirmed by the broker, outbox not marked yet: the window "after publish, before + # the confirm is recorded". The crash rolls this transaction back. + await service.crash_once(settings, self.db, "crash_after_publish", row.job_id, ACTOR, + outbox_id=row.outbox_id) + await jobs.mark_published(conn, [r.outbox_id for r in rows]) + return sendable + + sent = await self.db.run(work, deadline=10 + 5 * settings.relay_batch) + for row in sent: + log.info("job_published", extra={"fields": {"job_id": row.job_id, "attempt": row.attempt, + "outbox_id": row.outbox_id}}) + return len(sent) + + async def maintenance(self) -> None: + try: + self.queue_stats = await self.db.run(jobs.queue_stats, op="queue_stats") + except Unavailable: + self.queue_stats = None # unknown backlog: the gauges report nothing (not a stale value) + raise + expired = await self.db.run(lambda c: jobs.expire_leases(c, ACTOR)) + republished = await self.db.run(lambda c: jobs.republish_stale(c, self.settings.queued_republish_seconds, ACTOR)) + if expired or republished: + log.info("maintenance", extra={"fields": {"leases_expired": expired, "republished": republished}}) + + def register_metrics(self) -> None: + queue = {"messaging.destination.name": broker.QUEUE} + + def depth(): + st = self.queue_stats + return [] if st is None else [(st["queued"], {**queue, "state": "queued"}), + (st["processing"], {**queue, "state": "processing"})] + + def oldest(): + st = self.queue_stats + return [] if st is None else [(st["oldest_age"], queue)] + + def outbox(): + st = self.queue_stats + return [] if st is None else [(st["outbox_due"], {"state": "due"}), + (st["outbox_delayed"], {"state": "delayed"})] + + def outbox_age(): + st = self.queue_stats + return [] if st is None else [(st["outbox_oldest_due_age"], {})] + + telemetry.observe("messenger.queue.depth", "{job}", + "Unfinished jobs (PostgreSQL) by state: queued (incl. waiting for a retry) / processing", depth) + telemetry.observe("messenger.queue.oldest_age", "s", + "Age of the oldest unfinished job: now - its durable acceptance (jobs.created_at)", oldest) + telemetry.observe("messenger.outbox.pending", "{message}", + "Unpublished outbox rows: due now / delayed (retry backoff)", outbox) + telemetry.observe("messenger.outbox.oldest_age", "s", + "How long the oldest DUE outbox row waits for its publish (broker down -> grows)", outbox_age) + telemetry.observe_pool(self.db.pool, self.db.name) + + async def run(self) -> int: + stop = service.stop_event() + self.register_metrics() + await self.db.open() + next_maintenance = next_purge = 0.0 + failures = 0 + try: + while not stop.is_set(): + healthy = True + now = time.monotonic() + try: + if now >= next_maintenance: + await self.maintenance() + next_maintenance = now + MAINTENANCE_SECONDS + if now >= next_purge: + purged = await self.db.run(jobs.purge_outbox) + next_purge = now + PURGE_SECONDS + if purged: + log.info("outbox_purged", extra={"fields": {"rows": purged}}) + except Unavailable: + healthy = False + try: + if not self.connected(): + await self.disconnect() + await self.connect() + sent = await self.publish_due() + failures = 0 + except Unavailable: + healthy, sent = False, 0 + except Exception as exc: # noqa: BLE001 - every broker/channel error, never a crash + # Broker down/unreachable, channel closed, message returned/nacked: nothing marked, + # the rows stay in the outbox (transaction rolled back) and are published later. + failures += 1 + healthy, sent = False, 0 + log.warning("publish_failed", extra={"fields": {"error": type(exc).__name__, "failures": failures}}) + await self.disconnect() + if healthy: + service.beat() + if not sent: + await service.sleep_or_stop(stop, min(5.0, self.settings.relay_poll_seconds * (2 ** min(failures, 3)))) + finally: + await self.disconnect() + await self.db.close() + log.info("relay_stopped") + return 0 + + +def main() -> int: + try: + settings = Settings.from_env(s3_credentials=False) + if not settings.broker_url: + raise ConfigError("BROKER_URL_FILE (or BROKER_URL) must be set") + except ConfigError as exc: + print(f"configuration error: {exc}", file=sys.stderr) + return 2 + logging_setup.configure(settings.log_level) + telemetry.setup("messenger-relay", settings.instance_id, __version__) + log.info("relay_starting", extra={"fields": {"instance_id": settings.instance_id, + "fault_points": sorted(settings.fault_points)}}) + try: + return asyncio.run(Relay(settings).run()) + finally: + telemetry.shutdown() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/messenger/repo.py b/src/messenger/repo.py new file mode 100644 index 0000000..5ab8bbc --- /dev/null +++ b/src/messenger/repo.py @@ -0,0 +1,373 @@ +"""SQL for users, chats and messages. All statements are parameterised (%s placeholders): +values travel separately from the SQL text, so input can never change the query. + +Free text is stored as UTF-8 BYTEA (PostgreSQL TEXT cannot hold U+0000), so it is +encoded on the way in and decoded on the way out. See docs/DATA_MODEL.md. +""" +from __future__ import annotations + +import datetime as dt +import uuid +from dataclasses import dataclass + +import psycopg +from psycopg import errors as pg_errors + +from .cursor import SortKey +from .db import Database +from .errors import Conflict, InvalidRequest, NotFound, Unavailable +from .timefmt import from_us, rfc3339, to_us + + +def _b(text: str) -> bytes: + return text.encode("utf-8") + + +def _s(raw: bytes | memoryview) -> str: + return bytes(raw).decode("utf-8") + + +@dataclass(slots=True, frozen=True) +class User: + id: str + username: str + display_name: str + created_at: dt.datetime + + def to_json(self) -> dict: + return {"id": self.id, "username": self.username, "display_name": self.display_name, + "created_at": rfc3339(self.created_at)} + + +@dataclass(slots=True, frozen=True) +class Chat: + id: str + title: str + member_ids: tuple[str, ...] + created_at: dt.datetime + + @property + def key(self) -> SortKey: + return (to_us(self.created_at), self.id) + + def to_json(self) -> dict: + return {"id": self.id, "title": self.title, "member_ids": list(self.member_ids), + "created_at": rfc3339(self.created_at)} + + +@dataclass(slots=True, frozen=True) +class Message: + id: str + chat_id: str + sender_id: str + text: str + created_at: dt.datetime + attachment_ids: tuple[str, ...] = () + + @property + def key(self) -> SortKey: + return (to_us(self.created_at), self.id) + + def to_json(self) -> dict: + return {"id": self.id, "chat_id": self.chat_id, "sender_id": self.sender_id, "text": self.text, + "created_at": rfc3339(self.created_at), "attachment_ids": list(self.attachment_ids)} + + +def _user(row) -> User: + return User(str(row[0]), row[1], _s(row[2]), row[3]) + + +# ------------------------------------------------------------------ users +async def create_user(db: Database, username: str, display_name: str, password_hash: str) -> User: + async def work(conn: psycopg.AsyncConnection) -> User: + cur = await conn.execute( + "INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s) " + "RETURNING id, username, display_name, created_at", + (uuid.uuid4(), username, _b(display_name), password_hash)) + return _user(await cur.fetchone()) + try: + return await db.run(work) + except pg_errors.UniqueViolation: + # Two concurrent registrations: the unique index lets exactly one INSERT commit. + raise Conflict("Имя пользователя уже занято") from None + + +async def get_user(db: Database, user_id: str) -> User | None: + async def work(conn: psycopg.AsyncConnection) -> User | None: + cur = await conn.execute( + "SELECT id, username, display_name, created_at FROM users WHERE id = %s", (user_id,)) + row = await cur.fetchone() + return _user(row) if row else None + return await db.run(work) + + +async def get_credentials(db: Database, username: str) -> tuple[User, str] | None: + async def work(conn: psycopg.AsyncConnection) -> tuple[User, str] | None: + cur = await conn.execute( + "SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s", + (username,)) + row = await cur.fetchone() + return (_user(row), row[4]) if row else None + return await db.run(work) + + +# ------------------------------------------------------------------ chats +async def create_chat(db: Database, creator_id: str, title: str, member_ids: list[str]) -> Chat: + """Atomic: the chat row and all memberships commit together or not at all. + + The chat is inserted FIRST; an unknown member then fails the membership INSERT + with a foreign-key violation and the whole transaction (chat row included) is + rolled back. student-tests check that nothing is left behind. + """ + if creator_id not in member_ids: + raise InvalidRequest("member_ids должен включать текущего пользователя") + chat_id = uuid.uuid4() + + async def work(conn: psycopg.AsyncConnection) -> dt.datetime: + cur = await conn.execute( + "INSERT INTO chats (id, title, created_by) VALUES (%s, %s, %s) RETURNING created_at", + (chat_id, _b(title), creator_id)) + (created_at,) = await cur.fetchone() + await conn.execute( + "INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) " + "SELECT %s, m.user_id, m.ord - 1, %s " + "FROM unnest(%s::uuid[]) WITH ORDINALITY AS m(user_id, ord)", + (chat_id, created_at, member_ids)) + return created_at + try: + created_at = await db.run(work) + except pg_errors.ForeignKeyViolation: + raise InvalidRequest("member_ids содержит несуществующих пользователей") from None + return Chat(str(chat_id), title, tuple(member_ids), created_at) + + +async def _load_chats(conn: psycopg.AsyncConnection, rows) -> list[Chat]: + if not rows: + return [] + ids = [r[0] for r in rows] + cur = await conn.execute( + "SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY(%s) ORDER BY chat_id, position", (ids,)) + members: dict[uuid.UUID, list[str]] = {i: [] for i in ids} + for chat_id, user_id in await cur.fetchall(): + members[chat_id].append(str(user_id)) + return [Chat(str(r[0]), _s(r[1]), tuple(members[r[0]]), r[2]) for r in rows] + + +async def get_chat(db: Database, user_id: str, chat_id: str) -> Chat: + """The chat if the user is a member; a missing chat and a foreign chat are both 404.""" + async def work(conn: psycopg.AsyncConnection) -> Chat: + cur = await conn.execute( + "SELECT c.id, c.title, c.created_at FROM chats c " + "JOIN chat_members m ON m.chat_id = c.id AND m.user_id = %s WHERE c.id = %s", + (user_id, chat_id)) + row = await cur.fetchone() + if row is None: + raise NotFound("Чат не найден") + return (await _load_chats(conn, [row]))[0] + return await db.run(work) + + +async def _check_member(conn: psycopg.AsyncConnection, user_id: str, chat_id: str) -> None: + cur = await conn.execute( + "SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user_id)) + if await cur.fetchone() is None: + raise NotFound("Чат не найден") + + +async def ensure_member(db: Database, user_id: str, chat_id: str) -> None: + async def work(conn: psycopg.AsyncConnection) -> None: + await _check_member(conn, user_id, chat_id) + await db.run(work) + + +async def list_chats(db: Database, user_id: str, after: SortKey | None, limit: int) -> tuple[list[Chat], bool]: + async def work(conn: psycopg.AsyncConnection) -> tuple[list[Chat], bool]: + if after is None: + cur = await conn.execute( + "SELECT c.id, c.title, c.created_at FROM chat_members m JOIN chats c ON c.id = m.chat_id " + "WHERE m.user_id = %s ORDER BY m.chat_created_at, m.chat_id LIMIT %s", + (user_id, limit + 1)) + else: + cur = await conn.execute( + "SELECT c.id, c.title, c.created_at FROM chat_members m JOIN chats c ON c.id = m.chat_id " + "WHERE m.user_id = %s AND (m.chat_created_at, m.chat_id) > (%s, %s) " + "ORDER BY m.chat_created_at, m.chat_id LIMIT %s", + (user_id, from_us(after[0]), after[1], limit + 1)) + rows = await cur.fetchall() + return await _load_chats(conn, rows[:limit]), len(rows) > limit + return await db.run(work) + + +# ------------------------------------------------------------------ messages +@dataclass(slots=True, frozen=True) +class PostResult: + message: Message + replayed: bool # True: the key was already used with this body, nothing new was written + + +async def _insert_message(conn: psycopg.AsyncConnection, message_id: uuid.UUID, user_id: str, chat_id: str, + text: str, attachment_ids: list[str]) -> dt.datetime: + """Insert with a per-chat strictly increasing timestamp. + + `UPDATE chats ... RETURNING` locks the chat row until COMMIT, so writers of one + chat are serialised: a message with a smaller created_at can never commit after + a message with a bigger one, and a reader paging by cursor cannot skip it. + """ + cur = await conn.execute( + "UPDATE chats SET last_message_at = greatest(clock_timestamp(), " + "last_message_at + interval '1 microsecond') WHERE id = %s RETURNING last_message_at", + (chat_id,)) + (created_at,) = await cur.fetchone() + await conn.execute( + "INSERT INTO messages (id, chat_id, sender_id, text, created_at, attachment_ids) " + "VALUES (%s, %s, %s, %s, %s, %s::uuid[])", + (message_id, chat_id, user_id, _b(text), created_at, attachment_ids)) + if attachment_ids: + await conn.execute( + "INSERT INTO message_attachments (message_id, position, attachment_id) " + "SELECT %s, a.ord - 1, a.id FROM unnest(%s::uuid[]) WITH ORDINALITY AS a(id, ord)", + (message_id, attachment_ids)) + return created_at + + +# Attachments a message may reference (lab 5): of THIS chat and not the invisible 'pending' intent +# (else 404); queued/processing/ready are usable, failed or quarantined -> 409. +# FOR SHARE keeps a concurrent transition to failed from slipping in before COMMIT. +CHECK_ATTACHMENTS = ( + "SELECT count(*), count(*) FILTER (WHERE a.lost_at IS NULL AND a.status <> 'failed') FROM (" + "SELECT lost_at, status FROM attachments WHERE id = ANY(%s::uuid[]) AND chat_id = %s AND status <> 'pending' " + "FOR SHARE) a") + + +async def _check_attachments(conn: psycopg.AsyncConnection, chat_id: str, attachment_ids: list[str]) -> str: + if not attachment_ids: + return "ok" + cur = await conn.execute(CHECK_ATTACHMENTS, (attachment_ids, chat_id)) + found, usable = await cur.fetchone() + if found != len(attachment_ids): + return "attachment_not_found" + return "ok" if usable == found else "attachment_conflict" + + +def _attachment_error(status: str) -> None: + if status == "attachment_not_found": + raise NotFound("Вложение не найдено") + if status == "attachment_conflict": + raise Conflict("Вложение недоступно и не может быть прикреплено") + + +# Claim the key. A row of a concurrent transaction that is not committed yet makes this +# INSERT wait on the unique index until that transaction ends: after COMMIT it is a conflict +# (the key is taken), after ROLLBACK the INSERT goes through. A key older than the TTL is +# re-used as if it were new (ON CONFLICT ... DO UPDATE ... WHERE expired). +CLAIM_KEY = ( + "INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id) " + "VALUES (%s, %s, %s, %s, %s) " + "ON CONFLICT (user_id, chat_id, key) DO UPDATE SET " + "request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp() " + "WHERE idempotency_keys.created_at < clock_timestamp() - make_interval(secs => %s) " + "RETURNING 1") +STORED_RESULT = ( + "SELECT k.request_hash, m.id, m.text, m.created_at, m.attachment_ids FROM idempotency_keys k " + "JOIN messages m ON m.id = k.message_id " + "WHERE k.user_id = %s AND k.chat_id = %s AND k.key = %s") + + +async def post_message(db: Database, user_id: str, chat_id: str, key: str, request_hash: bytes, text: str, + ttl_seconds: int, attachment_ids: list[str] = ()) -> PostResult: + """Idempotent send: the key, the message and the stored result commit in ONE transaction. + + * first request -> key row + message + chat clock, all or nothing (no "pending" key is + ever left behind: a crash or 5xx rolls everything back and the client may retry); + * same key, same body (any replica, also concurrently) -> the stored Message, 201, replayed; + * same key, other body -> 409; the membership check comes first, so outsiders always get 404; + * attachments (lab 4) are checked before the key is claimed (same order as post_message_v3). + """ + message_id = uuid.uuid4() + attachment_ids = list(attachment_ids) + + async def work(conn: psycopg.AsyncConnection) -> PostResult: + await _check_member(conn, user_id, chat_id) + check = await _check_attachments(conn, chat_id, attachment_ids) + if check == "ok": + cur = await conn.execute(CLAIM_KEY, (user_id, chat_id, key, request_hash, message_id, ttl_seconds)) + if await cur.fetchone() is not None: + created_at = await _insert_message(conn, message_id, user_id, chat_id, text, attachment_ids) + return PostResult(Message(str(message_id), chat_id, user_id, text, created_at, + tuple(attachment_ids)), False) + cur = await conn.execute(STORED_RESULT, (user_id, chat_id, key)) + row = await cur.fetchone() + if row is None: + _attachment_error(check) + # The key row vanished between the two statements (expired-key cleanup): retryable. + raise Unavailable("Повторите запрос с тем же Idempotency-Key") + if bytes(row[0]) != request_hash: + raise Conflict("Idempotency-Key уже использован с другим сообщением") + return PostResult(Message(str(row[1]), chat_id, user_id, _s(row[2]), row[3], + tuple(str(a) for a in row[4])), True) + return await db.run(work) + + +POST_MESSAGE_CALL = ("SELECT o_status, o_id, o_text, o_created_at, o_attachments " + "FROM post_message_v3(%s, %s, %s, %s, %s, %s, %s, %s::uuid[])") + + +async def post_message_single_call(db: Database, user_id: str, chat_id: str, key: str, request_hash: bytes, + text: str, ttl_seconds: int, attachment_ids: list[str] = ()) -> PostResult: + """Same contract as post_message, ONE round trip: SQL function post_message_v3 (migration 0005 = + 0003 + attachment_ids) in autocommit mode, i.e. the call is the whole transaction.""" + message_id = uuid.uuid4() + + async def work(conn: psycopg.AsyncConnection) -> tuple: + cur = await conn.execute(POST_MESSAGE_CALL, (user_id, chat_id, key, request_hash, message_id, _b(text), + ttl_seconds, list(attachment_ids))) + return await cur.fetchone() + status, stored_id, stored_text, created_at, stored_attachments = await db.run(work, transaction=False) + if status == "not_found": + raise NotFound("Чат не найден") + _attachment_error(status) + if status == "conflict": + raise Conflict("Idempotency-Key уже использован с другим сообщением") + if status == "retry": + raise Unavailable("Повторите запрос с тем же Idempotency-Key") + return PostResult(Message(str(stored_id), chat_id, user_id, _s(stored_text), created_at, + tuple(str(a) for a in stored_attachments)), status == "replayed") + + +async def purge_idempotency_keys(db: Database, ttl_seconds: int, batch: int = 5000) -> int: + """Delete expired keys in bounded batches; one replica at a time (advisory xact lock).""" + async def work(conn: psycopg.AsyncConnection) -> int: + cur = await conn.execute("SELECT pg_try_advisory_xact_lock(%s)", (2026_03,)) + if not (await cur.fetchone())[0]: + return 0 + cur = await conn.execute( + "DELETE FROM idempotency_keys WHERE ctid = ANY(ARRAY(" + "SELECT ctid FROM idempotency_keys " + "WHERE created_at < clock_timestamp() - make_interval(secs => %s) LIMIT %s))", + (ttl_seconds, batch)) + return cur.rowcount + return await db.run(work) + + +# Two statements instead of one with "(%s IS NULL OR ...)": with a generic plan the OR +# would push the cursor into a Filter and late pages would scan the whole prefix. +# attachment_ids is a column of the message row (migration 0004): still one index range scan. +HISTORY_FIRST = ( + "SELECT id, sender_id, text, created_at, attachment_ids FROM messages " + "WHERE chat_id = %s ORDER BY created_at, id LIMIT %s") +HISTORY_AFTER = ( + "SELECT id, sender_id, text, created_at, attachment_ids FROM messages " + "WHERE chat_id = %s AND (created_at, id) > (%s, %s) ORDER BY created_at, id LIMIT %s") + + +async def list_messages(db: Database, chat_id: str, after: SortKey | None, limit: int) -> tuple[list[Message], bool]: + async def work(conn: psycopg.AsyncConnection) -> list: + if after is None: + cur = await conn.execute(HISTORY_FIRST, (chat_id, limit + 1)) + else: + cur = await conn.execute(HISTORY_AFTER, (chat_id, from_us(after[0]), after[1], limit + 1)) + return await cur.fetchall() + rows = await db.run(work) + items = [Message(str(r[0]), chat_id, str(r[1]), _s(r[2]), r[3], tuple(str(a) for a in r[4])) + for r in rows[:limit]] + return items, len(rows) > limit diff --git a/src/messenger/s3_bootstrap.py b/src/messenger/s3_bootstrap.py new file mode 100644 index 0000000..d7f2e65 --- /dev/null +++ b/src/messenger/s3_bootstrap.py @@ -0,0 +1,182 @@ +"""One-shot S3 bootstrap: `python -m messenger.s3_bootstrap` (compose service `s3-init`). + +Idempotent, safe to run on every `docker compose up`: + +1. waits until the S3 endpoint answers; +2. creates the final bucket (S3_BUCKET) and the staging bucket (S3_STAGING_BUCKET) with the ADMIN + key pair if they do not exist yet (existing buckets and their objects are left untouched); +3. writes the sentinel object `health/sentinel` into the final bucket (the API readiness HEADs it); +4. proves the access model and FAILS the stand (exit 1) if it is wrong: + * anonymous (unsigned) GET of an object and anonymous LIST are refused on both buckets; + * api: writes staging, reads final; cannot read staging, write final, list or create buckets, + nor read another bucket (a canary bucket created here for this check); + * worker: reads and writes both buckets; cannot list or create buckets; + * auditor: reads and lists both buckets; cannot write. +Only file names and verdicts are printed, never key values. +""" +from __future__ import annotations + +import asyncio +import os +import sys +import time +import urllib.error +import urllib.request + +from botocore.exceptions import ClientError + +from .config import ConfigError, Settings, _secret, s3_settings +from .errors import Unavailable +from .storage import SENTINEL_KEY, Storage + + +def say(text: str) -> None: + print(f"s3-bootstrap: {text}", flush=True) + + +def anonymous_status(url: str) -> int: + """HTTP status of an UNSIGNED request (what anyone on the network could do).""" + try: + with urllib.request.urlopen(url, timeout=3) as response: + return response.status + except urllib.error.HTTPError as exc: + return exc.code + + +async def error_code(coro) -> str: + """S3 error code of a call that is expected to be refused ('' if it succeeded).""" + try: + await coro + return "" + except ClientError as exc: + return str(exc.response.get("Error", {}).get("Code", "error")) + + +def settings_with(keys: tuple[str, str]) -> Settings: + base = s3_settings(credentials_required=False) + base.update(s3_access_key_id=keys[0], s3_secret_access_key=keys[1]) + return Settings(host="", port=0, env="lab", log_level="info", shutdown_timeout=0, max_body_bytes=1024, **base) + + +def pair(prefix: str) -> tuple[str, str]: + return _secret(f"{prefix}ACCESS_KEY_ID", True), _secret(f"{prefix}SECRET_ACCESS_KEY", True) + + +async def ensure_bucket(admin_s3: Storage, bucket: str) -> bool: + code = await error_code(admin_s3.client.head_bucket(Bucket=bucket)) + if code == "": + say(f"bucket {bucket}: exists, kept as is") + return True + if code in ("404", "NoSuchBucket", "NotFound"): + code = await error_code(admin_s3.client.create_bucket(Bucket=bucket)) + if code not in ("", "BucketAlreadyOwnedByYou", "BucketAlreadyExists"): + say(f"bucket {bucket}: create failed ({code})") + return False + say(f"bucket {bucket}: created") + return True + say(f"bucket {bucket}: head failed ({code})") + return False + + +async def run() -> int: + settings = settings_with(pair("S3_ADMIN_")) + final, staging = settings.s3_bucket, settings.s3_staging_bucket + admin_s3 = Storage(settings) + clients = {"api": Storage(settings_with(pair("S3_"))), "worker": Storage(settings_with(pair("S3_WORKER_"))), + "auditor": Storage(settings_with(pair("S3_AUDITOR_")))} + for s in (admin_s3, *clients.values()): + await s.open() + try: + deadline = time.monotonic() + 60 + while True: + try: + await admin_s3._call("list_buckets", admin_s3.client.list_buckets()) + break + except Unavailable: + if time.monotonic() > deadline: + say("S3 endpoint does not answer within 60 s") + return 1 + await asyncio.sleep(1) + for bucket in (final, staging): + if not await ensure_bucket(admin_s3, bucket): + return 1 + await admin_s3.put(SENTINEL_KEY, b"ok\n", "text/plain", {}) + await admin_s3.client.put_object(Bucket=staging, Key=SENTINEL_KEY, Body=b"ok\n") + say(f"sentinel {SENTINEL_KEY}: written") + canary = final + "-canary" + if await error_code(admin_s3.client.head_bucket(Bucket=canary)): + await admin_s3.client.create_bucket(Bucket=canary) + await admin_s3.client.put_object(Bucket=canary, Key="canary", Body=b"secret of another bucket") + + failures = [] + base = settings.s3_endpoint.rstrip("/") + for bucket in (final, staging): + for what, url in ((f"anonymous GET object of {bucket}", f"{base}/{bucket}/{SENTINEL_KEY}"), + (f"anonymous LIST of {bucket}", f"{base}/{bucket}?list-type=2")): + status = anonymous_status(url) + verdict = "refused" if status in (401, 403) else "ALLOWED" + say(f"{what}: HTTP {status} -> {verdict}") + if verdict != "refused": + failures.append(what) + + probe = "health/bootstrap-probe" + + def c(who: str): + return clients[who].client + + # (what, coroutine, allowed?) - every refusal must be a real AccessDenied, not an outage. + checks = [ + ("api: write staging", c("api").put_object(Bucket=staging, Key=probe, Body=b"p"), True), + ("api: delete staging (janitor)", c("api").delete_object(Bucket=staging, Key=probe), True), + ("api: read staging", c("api").head_object(Bucket=staging, Key=SENTINEL_KEY), False), + ("api: read final", c("api").head_object(Bucket=final, Key=SENTINEL_KEY), True), + ("api: write final", c("api").put_object(Bucket=final, Key=probe, Body=b"p"), False), + ("api: list final", c("api").list_objects_v2(Bucket=final, MaxKeys=1), False), + ("api: list staging", c("api").list_objects_v2(Bucket=staging, MaxKeys=1), False), + ("api: create bucket", c("api").create_bucket(Bucket=final + "-x"), False), + ("api: read another bucket", c("api").head_object(Bucket=canary, Key="canary"), False), + ("worker: read staging", c("worker").head_object(Bucket=staging, Key=SENTINEL_KEY), True), + ("worker: write final", c("worker").put_object(Bucket=final, Key=probe, Body=b"p"), True), + ("worker: delete final", c("worker").delete_object(Bucket=final, Key=probe), True), + ("worker: write staging", c("worker").put_object(Bucket=staging, Key=probe, Body=b"p"), True), + ("worker: delete staging", c("worker").delete_object(Bucket=staging, Key=probe), True), + ("worker: list final", c("worker").list_objects_v2(Bucket=final, MaxKeys=1), False), + ("worker: create bucket", c("worker").create_bucket(Bucket=final + "-x"), False), + ("worker: read another bucket", c("worker").head_object(Bucket=canary, Key="canary"), False), + ("auditor: list final", c("auditor").list_objects_v2(Bucket=final, MaxKeys=1), True), + ("auditor: list staging", c("auditor").list_objects_v2(Bucket=staging, MaxKeys=1), True), + ("auditor: read final", c("auditor").head_object(Bucket=final, Key=SENTINEL_KEY), True), + ("auditor: write final", c("auditor").put_object(Bucket=final, Key=probe, Body=b"p"), False), + ("auditor: delete staging", c("auditor").delete_object(Bucket=staging, Key=SENTINEL_KEY), False), + ] + for what, coro, allowed in checks: + code = await error_code(coro) + ok = (code == "") == allowed and code in ("", "AccessDenied", "403") + say(f"{what}: {'allowed' if code == '' else 'refused (' + code + ')'} -> {'OK' if ok else 'WRONG'}") + if not ok: + failures.append(what) + visible = [b["Name"] for b in (await c("api").list_buckets()).get("Buckets", [])] + say(f"api: buckets visible in ListBuckets: {visible} -> {'OK' if canary not in visible else 'WRONG'}") + if canary in visible: + failures.append("api sees another bucket") + if failures: + say("access model is WRONG: " + ", ".join(failures)) + return 1 + say("done: private buckets, least-privilege keys verified") + return 0 + finally: + for s in (admin_s3, *clients.values()): + await s.close() + + +def main() -> int: + try: + return asyncio.run(run()) + except ConfigError as exc: + print(f"configuration error: {exc}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + os.environ.setdefault("PYTHONUNBUFFERED", "1") + sys.exit(main()) diff --git a/src/messenger/service.py b/src/messenger/service.py new file mode 100644 index 0000000..0df62f6 --- /dev/null +++ b/src/messenger/service.py @@ -0,0 +1,76 @@ +"""Common runtime of the background processes (relay, worker): signals, heartbeat file for the +Docker healthcheck, failure injection that fires once per job and leaves an audit row.""" +from __future__ import annotations + +import asyncio +import logging +import os +import signal +import time +from pathlib import Path + +from . import jobs +from .config import Settings +from .db import Database + +log = logging.getLogger("messenger.service") + +HEARTBEAT_FILE = Path(os.environ.get("HEARTBEAT_FILE", "/tmp/heartbeat")) +CRASH_EXIT_CODE = 70 # os._exit: no cleanup, no ack, no COMMIT - like SIGKILL in the middle of work + + +def beat() -> None: + """Healthcheck input: `python -m messenger.healthcheck --file /tmp/heartbeat --max-age 30`.""" + try: + HEARTBEAT_FILE.write_text(str(time.time()), encoding="ascii") + except OSError: + pass + + +def watch_connection(connection) -> asyncio.Event: + """Event set when an AMQP connection is closed by ANY side. aio-pika's `is_closed` does not turn + True when the broker drops the connection (found by the broker-restart test: the worker kept + "running" without a consumer), so the close callback is the signal to reconnect.""" + lost = asyncio.Event() + connection.close_callbacks.add(lambda *_: lost.set()) + return lost + + +def stop_event() -> asyncio.Event: + stop = asyncio.Event() + loop = asyncio.get_running_loop() + for sig in (signal.SIGTERM, signal.SIGINT): + try: + loop.add_signal_handler(sig, stop.set) + except (NotImplementedError, RuntimeError): + pass # Windows unit tests: no signal handlers + return stop + + +async def sleep_or_stop(stop: asyncio.Event, seconds: float) -> None: + try: + await asyncio.wait_for(stop.wait(), seconds) + except asyncio.TimeoutError: + pass + + +async def crash_once(settings: Settings, db: Database, point: str, job_id: str, actor: str, **detail) -> None: + """Experiments only (FAULT_POINTS): kill THIS process at `point`, once per job (and per `detail`), + across restarts and replicas. The decision is an audit row committed before the crash, so the + restarted process (or another replica) continues normally and the evidence stays in job_events.""" + if point not in settings.fault_points: + return + + async def record(conn) -> bool: + cur = await conn.execute( + "SELECT 1 FROM job_events WHERE job_id = %s AND event = 'fault_injected' AND detail->>'point' = %s " + "AND detail @> %s::jsonb", (job_id, point, jobs.json.dumps({k: str(v) for k, v in detail.items()}))) + if await cur.fetchone(): + return False + await jobs.event(conn, job_id, "fault_injected", actor, point=point, **{k: str(v) for k, v in detail.items()}) + return True + + if await db.run(record): + log.warning("fault_injected_crash", extra={"fields": {"point": point, "job_id": job_id, **detail}}) + logging.shutdown() + os._exit(CRASH_EXIT_CODE) diff --git a/src/messenger/sessions.py b/src/messenger/sessions.py new file mode 100644 index 0000000..53736e4 --- /dev/null +++ b/src/messenger/sessions.py @@ -0,0 +1,160 @@ +"""Server-side sessions behind an opaque Bearer token. + +* Token: `secrets.token_urlsafe(32)` = 256 random bits. Only SHA-256(token) is + stored, so a leaked database/AOF does not contain usable tokens. A fast hash is + enough for a 256-bit random value; passwords need a slow KDF (passwords.py). +* Expiry is absolute: `expires_at = login time + SESSION_TTL_SECONDS`. Every lookup + compares it with the current time, and a restart never extends it. + +Two interchangeable stores (SESSION_STORE): + +* `valkey` (compose default): the ONLY copy of a session is a Valkey key with + `PXAT expires_at`, persisted by AOF with `appendfsync always`. There is no second + copy (no cache over PostgreSQL), so a logout cannot be "forgotten" and a revoked + token cannot come back after Valkey fails and recovers. If Valkey is unreachable + a session cannot be checked: protected requests and logout get 503, never access. +* `postgres`: table `sessions` (migrations/0001_init.sql). +""" +from __future__ import annotations + +import asyncio +import datetime as dt +import hashlib +import json +import logging +import secrets +from typing import Protocol + +from redis import exceptions as redis_errors +from redis.asyncio import Redis +from redis.backoff import NoBackoff +from redis.retry import Retry + +from .config import Settings +from .db import Database +from .errors import Unavailable +from .timefmt import UTC, from_us, to_us + +log = logging.getLogger("messenger.sessions") + + +def new_token() -> str: + return secrets.token_urlsafe(32) + + +def token_hash(token: str) -> bytes: + return hashlib.sha256(token.encode("ascii")).digest() + + +def now() -> dt.datetime: + return dt.datetime.now(UTC) + + +class SessionStore(Protocol): + name: str + + async def create(self, user_id: str, ttl_seconds: int) -> tuple[str, dt.datetime]: ... + async def user_id_for(self, token: str) -> str | None: ... + async def revoke(self, token: str) -> bool: ... + async def ping(self) -> bool: ... + async def close(self) -> None: ... + + +class PostgresSessionStore: + name = "postgres" + + def __init__(self, db: Database): + self.db = db + + async def create(self, user_id: str, ttl_seconds: int) -> tuple[str, dt.datetime]: + token = new_token() + expires_at = now() + dt.timedelta(seconds=ttl_seconds) + + async def work(conn) -> None: + await conn.execute( + "INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s)", + (token_hash(token), user_id, expires_at)) + # Housekeeping: drop this user's expired sessions (bounded by the user's own rows). + await conn.execute("DELETE FROM sessions WHERE user_id = %s AND expires_at <= %s", (user_id, now())) + await self.db.run(work) + return token, expires_at + + async def user_id_for(self, token: str) -> str | None: + async def work(conn): + cur = await conn.execute( + "SELECT user_id FROM sessions WHERE token_hash = %s AND expires_at > %s", (token_hash(token), now())) + return await cur.fetchone() + row = await self.db.run(work) + return str(row[0]) if row else None + + async def revoke(self, token: str) -> bool: + async def work(conn) -> bool: + cur = await conn.execute( + "DELETE FROM sessions WHERE token_hash = %s AND expires_at > %s", (token_hash(token), now())) + return cur.rowcount == 1 + return await self.db.run(work) + + async def ping(self) -> bool: + return True # covered by the database readiness check + + async def close(self) -> None: + return None + + +class ValkeySessionStore: + name = "valkey" + PREFIX = "session:" + + def __init__(self, settings: Settings): + self.timeout = settings.cache_timeout_seconds + self.client = Redis.from_url( + settings.cache_url, + socket_timeout=self.timeout, + socket_connect_timeout=self.timeout, + retry=Retry(NoBackoff(), 0), # no hidden retries: a failure is reported at once + decode_responses=False, + ) + + def _key(self, token: str) -> str: + return self.PREFIX + token_hash(token).hex() + + async def _call(self, coro): + try: + async with asyncio.timeout(self.timeout * 2): + return await coro + except (redis_errors.ConnectionError, redis_errors.TimeoutError, TimeoutError, OSError) as exc: + log.warning("session_store_unavailable", extra={"fields": {"error": type(exc).__name__}}) + raise Unavailable("Хранилище сессий временно недоступно") from None + + async def create(self, user_id: str, ttl_seconds: int) -> tuple[str, dt.datetime]: + token = new_token() + expires_at = now() + dt.timedelta(seconds=ttl_seconds) + value = json.dumps({"user_id": user_id, "expires_at_us": to_us(expires_at)}).encode() + # PXAT = absolute expiry time: survives restarts (AOF) without being extended. + await self._call(self.client.set(self._key(token), value, pxat=to_us(expires_at) // 1000)) + return token, expires_at + + async def user_id_for(self, token: str) -> str | None: + raw = await self._call(self.client.get(self._key(token))) + if raw is None: + return None + data = json.loads(raw) + if from_us(data["expires_at_us"]) <= now(): + return None # do not rely only on Valkey's lazy expiry + return data["user_id"] + + async def revoke(self, token: str) -> bool: + return await self._call(self.client.delete(self._key(token))) == 1 + + async def ping(self) -> bool: + try: + return bool(await self._call(self.client.ping())) + except Unavailable: + return False + + async def close(self) -> None: + await self.client.aclose() + + +def build_store(settings: Settings, db: Database) -> SessionStore: + return ValkeySessionStore(settings) if settings.session_store == "valkey" else PostgresSessionStore(db) diff --git a/src/messenger/storage.py b/src/messenger/storage.py new file mode 100644 index 0000000..9c891d7 --- /dev/null +++ b/src/messenger/storage.py @@ -0,0 +1,211 @@ +"""Private S3 bucket (SeaweedFS in compose) through aiobotocore, with a hard deadline per call. + +* Credentials: the API's OWN key pair (S3_ACCESS_KEY_ID_FILE / S3_SECRET_ACCESS_KEY_FILE -> + Docker secrets). SeaweedFS grants it only Read + Write on this one bucket: no List, no + Admin (cannot create/delete buckets or read other buckets). The admin pair is given only + to the S3 server and the one-shot bootstrap (infra/seaweedfs, messenger.s3_bootstrap). +* Deadlines: botocore connect/read timeouts AND an asyncio deadline around every call, so a + paused or unreachable S3 costs at most S3_TIMEOUT_SECONDS, then 503 `unavailable`. Unlike a + libpq query (db.py), an aiohttp request can be cancelled safely, so the call is cancelled. +* ONE retry inside botocore (total_max_attempts=2), within the same asyncio deadline: after S3 + restarts, pooled keep-alive connections to the old process are dead and the first request on + such a connection fails although S3 is up again (found by test_s3_outage_..._stop on a clean + clone). Every call here is idempotent PER KEY (PUT of the same bytes to the same server-chosen + key, GET, HEAD, DELETE), so repeating it cannot create a second attachment. +* Checksums: Content-MD5 is sent with every PUT, so S3 rejects bytes damaged on the way. + botocore's newer default (aws-chunked CRC32 trailers) is switched off ("when_required"): + plain, widely supported S3 requests. +""" +from __future__ import annotations + +import asyncio +import base64 +import contextlib +import hashlib +import logging +from collections.abc import AsyncIterator +from dataclasses import dataclass + +from aiobotocore.config import AioConfig +from aiobotocore.session import get_session +from botocore.exceptions import BotoCoreError, ClientError + +from . import telemetry +from .config import Settings +from .errors import Unavailable + +log = logging.getLogger("messenger.storage") + +MISSING_CODES = {"NoSuchKey", "404", "NotFound"} + + +class ObjectMissing(Exception): + """The key does not exist in the bucket (definitive answer of S3, not an outage).""" + + +@dataclass(frozen=True, slots=True) +class ObjectHead: + size: int + content_type: str + metadata: dict[str, str] + last_modified_ts: float # POSIX seconds + + +@dataclass(frozen=True, slots=True) +class ListedObject: + key: str + size: int + last_modified_ts: float # POSIX seconds + + +class Storage: + def __init__(self, settings: Settings, *, access_key: str | None = None, secret_key: str | None = None, + bucket: str | None = None): + # Lab 5: one client per bucket - the final bucket (S3_BUCKET) or the staging bucket. + self.bucket = bucket or settings.s3_bucket + self.timeout = settings.s3_timeout_seconds + self._endpoint = settings.s3_endpoint + self._region = settings.s3_region + self._access_key = access_key or settings.s3_access_key_id + self._secret_key = secret_key or settings.s3_secret_access_key + self._config = AioConfig( + connect_timeout=settings.s3_connect_timeout_seconds, + read_timeout=settings.s3_timeout_seconds, + retries={"total_max_attempts": 2, "mode": "standard"}, + s3={"addressing_style": "path"}, + signature_version="s3v4", + request_checksum_calculation="when_required", + response_checksum_validation="when_required", + max_pool_connections=settings.s3_max_connections, + ) + self._stack: contextlib.AsyncExitStack | None = None + self._client = None + + async def open(self) -> None: + self._stack = contextlib.AsyncExitStack() + session = get_session() + self._client = await self._stack.enter_async_context(session.create_client( + "s3", endpoint_url=self._endpoint, region_name=self._region, + aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key, config=self._config)) + + async def close(self) -> None: + if self._stack is not None: + await self._stack.aclose() + self._stack = None + + @property + def client(self): + assert self._client is not None, "Storage.open() was not called" + return self._client + + async def _call(self, what: str, coro, deadline: float | None = None): + """Await one S3 call under the deadline; outages become Unavailable (503). + + Lab 6: a CLIENT span `s3 ` (bucket name only - never the object key, which would let a + reader of the traces fetch objects, and never a signed URL) inside a traced request/job. + Body chunks of a download (`get_body`) get no span of their own: they belong to `s3 get` + timing-wise, and a 10 MiB file would otherwise produce 160 spans.""" + span = None + if what not in ("get_body", "ping") and telemetry.trace.get_current_span().is_recording(): + span = telemetry.TRACER.start_span(f"s3 {what}", kind=telemetry.SpanKind.CLIENT, attributes={ + "rpc.system": "aws-api", "rpc.service": "S3", "rpc.method": what, "aws.s3.bucket": self.bucket}) + try: + return await asyncio.wait_for(coro, deadline or self.timeout) + except ClientError as exc: + code = str(exc.response.get("Error", {}).get("Code", "")) + if code in MISSING_CODES: + if span is not None: + span.set_attribute("messenger.s3.result", "missing") + raise ObjectMissing() from None + log.warning("s3_error", extra={"fields": {"op": what, "code": code}}) + if span is not None: + telemetry.mark_error(span, code or "ClientError") + raise Unavailable("Хранилище файлов временно недоступно") from None + except (asyncio.TimeoutError, BotoCoreError, OSError) as exc: + log.warning("s3_unavailable", extra={"fields": {"op": what, "error": type(exc).__name__}}) + if span is not None: + telemetry.mark_error(span, type(exc).__name__) + raise Unavailable("Хранилище файлов временно недоступно") from None + finally: + if span is not None: + span.end() + + async def put(self, key: str, data: bytes | bytearray, content_type: str, metadata: dict[str, str]) -> None: + md5 = base64.b64encode(hashlib.md5(data, usedforsecurity=False).digest()).decode("ascii") + # Time budget grows with the size: 10 MiB over a local network takes well under a second. + deadline = self.timeout + len(data) / (8 * 1024 * 1024) + await self._call("put", self.client.put_object( + Bucket=self.bucket, Key=key, Body=data, ContentType=content_type, ContentLength=len(data), + ContentMD5=md5, Metadata=metadata), deadline) + + async def head(self, key: str) -> ObjectHead: + response = await self._call("head", self.client.head_object(Bucket=self.bucket, Key=key)) + return ObjectHead(int(response["ContentLength"]), response.get("ContentType", ""), + dict(response.get("Metadata", {})), response["LastModified"].timestamp()) + + async def open_stream(self, key: str) -> tuple[int, AsyncIterator[bytes]]: + """Start a GET: (Content-Length, async iterator of chunks). The headers arrive under the + deadline; every chunk read afterwards has its own deadline (a stalled S3 aborts the + download instead of hanging the connection).""" + response = await self._call("get", self.client.get_object(Bucket=self.bucket, Key=key)) + body = response["Body"] + size = int(response["ContentLength"]) + + async def chunks() -> AsyncIterator[bytes]: + try: + while True: + chunk = await self._call("get_body", body.read(64 * 1024)) + if not chunk: + return + yield chunk + finally: + body.close() + return size, chunks() + + async def read_all(self, key: str, limit: int) -> bytes: + """Whole object (worker source, audit checksums); refuses objects above `limit`. + Lab 6: span `s3 download` covers headers AND body (the `s3 get` child: headers only).""" + with telemetry.child_span("s3 download", {"aws.s3.bucket": self.bucket}) as span: + size, chunks = await self.open_stream(key) + if size > limit: + raise Unavailable("Объект больше допустимого размера") + parts = [chunk async for chunk in chunks] + if span is not None: + span.set_attribute("messenger.s3.size_bytes", size) + return b"".join(parts) + + async def delete(self, key: str) -> None: + """Idempotent: deleting a missing key is a success in S3.""" + await self._call("delete", self.client.delete_object(Bucket=self.bucket, Key=key)) + + async def list_page(self, prefix: str, start_after: str | None, page_size: int) -> tuple[list[ListedObject], bool]: + """One ListObjectsV2 page in key order (needs the List permission: reconciler only).""" + params = {"Bucket": self.bucket, "Prefix": prefix, "MaxKeys": page_size} + if start_after: + params["StartAfter"] = start_after + response = await self._call("list", self.client.list_objects_v2(**params)) + items = [ListedObject(o["Key"], int(o["Size"]), o["LastModified"].timestamp()) + for o in response.get("Contents", [])] + return items, bool(response.get("IsTruncated")) + + async def ping(self, timeout: float = 1.0) -> bool: + """Readiness: HEAD of the sentinel object written by the bootstrap. Proves that S3 + answers, the bucket exists and the API credentials are accepted (Read permission).""" + try: + await self._call("ping", self.client.head_object(Bucket=self.bucket, Key=SENTINEL_KEY), timeout) + return True + except (Unavailable, ObjectMissing): + return False + + +SENTINEL_KEY = "health/sentinel" +# Lab 4 originals: o/ in the final bucket (still readable). +OBJECT_PREFIX = "o/" +# Lab 5: s/ in the STAGING bucket (written by the API before 202) and +# a/// in the final bucket +# (written by the worker; the token makes every attempt write its own keys). +STAGING_PREFIX = "s/" + + +def attempt_key(attachment_id: str, token: str, name: str) -> str: + return f"a/{attachment_id}/{token}/{name}" diff --git a/src/messenger/telemetry.py b/src/messenger/telemetry.py new file mode 100644 index 0000000..bdb7b2b --- /dev/null +++ b/src/messenger/telemetry.py @@ -0,0 +1,364 @@ +"""Lab 6: OpenTelemetry for the API, the relay and the worker (one module, three processes). + + process --OTLP/HTTP protobuf--> otel-collector --> Prometheus (metrics) / Loki (logs) / Tempo (traces) + +What is set up here (docs/OBSERVABILITY.md has the full signal map): + +* Resource: service.name (messenger-api / messenger-relay / messenger-worker), service.version, + service.instance.id (= X-Instance-Id / container hostname), deployment.environment.name=lab + (from OTEL_RESOURCE_ATTRIBUTES). +* Traces: TracerProvider + BatchSpanProcessor (bounded in-memory queue, OTEL_BSP_* variables) + + OTLP exporter. The sampler comes from OTEL_TRACES_SAMPLER / OTEL_TRACES_SAMPLER_ARG + (default parentbased_always_on). Propagation: W3C traceparent/tracestate. +* Metrics: MeterProvider + PeriodicExportingMetricReader (OTEL_METRIC_EXPORT_INTERVAL, ms). + Histogram bucket boundaries are set per instrument (explicit_bucket_boundaries_advisory): + the default OTel boundaries (0, 5, 10, 25 ... 10000) were made for milliseconds and would + put every request of a few ms into one bucket when the unit is seconds. +* Logs: our own small logging.Handler on the `messenger` logger tree -> LoggerProvider + + BatchLogRecordProcessor + OTLP exporter. Each record carries the active trace_id/span_id. + Only the `messenger.*` loggers are exported: the SDK's own warnings ("failed to export") + go to stdout only, so an unavailable Collector cannot cause a feedback loop. + +OTEL_SDK_DISABLED=true (track 1 "telemetry off") installs nothing: the API calls below become +no-ops (non-recording spans, no-op instruments) and only the stdout JSON log remains. + +Nothing exported here may contain secrets or user content: no Authorization header, session +token, password, message text, image bytes, S3 key, signed URL or query string (cursor, +filename). Metric attributes are low-cardinality only (method, route TEMPLATE, status code, +operation, outcome) - never user_id/chat_id/message_id/attachment_id/request_id. +""" +from __future__ import annotations + +import contextlib +import logging +import os +from collections.abc import Iterable, Sequence + +from opentelemetry import context as otel_context +from opentelemetry import metrics, propagate, trace +from opentelemetry.metrics import CallbackOptions, Observation +from opentelemetry.trace import SpanKind, Status, StatusCode + +log = logging.getLogger("messenger.telemetry") + +TRACER = trace.get_tracer("messenger") +METER = metrics.get_meter("messenger") + +# Bucket boundaries, seconds. Dense where our latencies are (1 ms .. 1 s), still covering the +# timeouts (DB 3 s, S3 3 s, job 60 s) so a p99 near a limit is not clamped to the last bucket. +HTTP_BUCKETS = (0.001, 0.0025, 0.005, 0.0075, 0.01, 0.015, 0.025, 0.05, 0.075, 0.1, 0.15, 0.25, 0.5, + 0.75, 1.0, 1.5, 2.5, 5.0, 10.0) +DB_BUCKETS = (0.0005, 0.001, 0.0025, 0.005, 0.0075, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0) +JOB_BUCKETS = (0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0, 20.0, 30.0, 60.0) +READY_BUCKETS = (0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0, 20.0, 30.0, 60.0, 120.0, 300.0, 600.0) + +_state = {"enabled": False, "providers": []} + + +def enabled() -> bool: + return _state["enabled"] + + +def sdk_disabled() -> bool: + return os.environ.get("OTEL_SDK_DISABLED", "false").strip().lower() == "true" + + +# ----------------------------------------------------------------------------- setup +def setup(service_name: str, instance_id: str, version: str) -> None: + """Install the SDK providers for this process (once, before the work starts).""" + if sdk_disabled(): + log.info("telemetry_disabled", extra={"fields": {"reason": "OTEL_SDK_DISABLED"}}) + return + from opentelemetry._logs import set_logger_provider + 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 + 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 + + # Explicit attributes win over OTEL_RESOURCE_ATTRIBUTES / OTEL_SERVICE_NAME. + resource = Resource.create({"service.name": service_name, "service.version": version, + "service.instance.id": instance_id}) + tracer_provider = TracerProvider(resource=resource) # sampler from OTEL_TRACES_SAMPLER + tracer_provider.add_span_processor(SpanCounter()) + tracer_provider.add_span_processor(BatchSpanProcessor(CountingSpanExporter(OTLPSpanExporter()))) + trace.set_tracer_provider(tracer_provider) + + reader = PeriodicExportingMetricReader(OTLPMetricExporter()) # interval from OTEL_METRIC_EXPORT_INTERVAL + meter_provider = MeterProvider(resource=resource, metric_readers=[reader]) + metrics.set_meter_provider(meter_provider) + + logger_provider = LoggerProvider(resource=resource) + logger_provider.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter())) + set_logger_provider(logger_provider) + logging.getLogger("messenger").addHandler(OtlpLogHandler(logger_provider)) + + _state["enabled"] = True + _state["providers"] = [tracer_provider, meter_provider, logger_provider] + _register_process_metrics() + log.info("telemetry_enabled", extra={"fields": { + "service": service_name, "endpoint": os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", ""), + "sampler": os.environ.get("OTEL_TRACES_SAMPLER", "parentbased_always_on"), + "sampler_arg": os.environ.get("OTEL_TRACES_SAMPLER_ARG", "")}}) + + +def shutdown() -> None: + """Flush what is buffered (bounded by the exporters' timeouts) at process exit.""" + for provider in _state["providers"]: + try: + provider.shutdown() + except Exception: # noqa: BLE001 - the Collector may be gone; never block the exit on it + pass + _state["providers"] = [] + + +# ----------------------------------------------------------------------------- logs +_SEVERITY = ((logging.CRITICAL, 21), (logging.ERROR, 17), (logging.WARNING, 13), (logging.INFO, 9), (logging.DEBUG, 5)) + + +def _attr(value): + if value is None or isinstance(value, (str, bool, int, float)): + return value + if isinstance(value, (list, tuple, set, frozenset)): + return [str(v) for v in value] + return str(value) + + +def is_probe_noise(record: logging.LogRecord, fields: dict) -> bool: + """A SUCCESSFUL /health/* access line is not exported (HAProxy and Docker probe every replica + every 1-2 s: ~3 lines/s of noise per replica in Loki). It stays in stdout; a failed probe + (503: dependency down, draining) is exported like any other line.""" + route = fields.get("route") + return (record.name == "messenger.access" and isinstance(route, str) and route.startswith("/health/") + and isinstance(fields.get("status"), int) and fields["status"] < 400) + + +class OtlpLogHandler(logging.Handler): + """logging -> OTLP log records. Body and attribute `event` = the event name (our log message is + always a short event id such as `request` or `job_done`); the structured `fields` become + attributes. trace_id/span_id come from the current context (the active span).""" + + def __init__(self, provider) -> None: + super().__init__() + self._logger = provider.get_logger("messenger") + + def emit(self, record: logging.LogRecord) -> None: + try: + from opentelemetry._logs import SeverityNumber + fields = getattr(record, "fields", None) or {} + if is_probe_noise(record, fields): + return + event = record.getMessage() + attributes = {"event": event, "logger.name": record.name} + for key, value in fields.items(): + value = _attr(value) + if value is not None: + attributes[key] = value + if record.exc_info and record.exc_info[0] is not None: + attributes["exception.type"] = record.exc_info[0].__name__ + number = next(n for level, n in _SEVERITY if record.levelno >= level) if record.levelno >= logging.DEBUG else 1 + self._logger.emit(timestamp=int(record.created * 1e9), context=otel_context.get_current(), + severity_number=SeverityNumber(number), severity_text=record.levelname, + body=event, attributes=attributes, event_name=event) + except Exception: # noqa: BLE001 + self.handleError(record) + + +def current_ids() -> tuple[str, str] | None: + """(trace_id, span_id) of the active span as hex, for the stdout JSON log.""" + ctx = trace.get_current_span().get_span_context() + if not ctx.is_valid: + return None + return format(ctx.trace_id, "032x"), format(ctx.span_id, "016x") + + +# ----------------------------------------------------------------------------- context +def inject() -> dict[str, str]: + """W3C carrier of the CURRENT context: {"traceparent": ..., "tracestate": ...} (may be empty).""" + carrier: dict[str, str] = {} + propagate.inject(carrier) + return {k: v for k, v in carrier.items() if k in ("traceparent", "tracestate")} + + +def extract(traceparent: str | None, tracestate: str | None = None): + carrier = {} + if traceparent: + carrier["traceparent"] = traceparent + if tracestate: + carrier["tracestate"] = tracestate + return propagate.extract(carrier) + + +def extract_headers(headers: Iterable[tuple[bytes, bytes]]): + """Context from the raw ASGI headers (only traceparent/tracestate are read).""" + carrier = {} + for key, value in headers: + name = key.decode("latin-1").lower() + if name in ("traceparent", "tracestate"): + carrier[name] = value.decode("latin-1") + return propagate.extract(carrier) + + +@contextlib.contextmanager +def child_span(name: str, attributes: dict | None = None, kind: SpanKind = SpanKind.INTERNAL): + """Current span for the block - only inside an already traced request/job (else yields None). + An exception leaving the block marks the span as error (type only).""" + if not trace.get_current_span().is_recording(): + yield None + return + with TRACER.start_as_current_span(name, kind=kind, attributes=attributes or {}, + record_exception=False, set_status_on_exception=False) as span: + try: + yield span + except BaseException as exc: + if not isinstance(exc, (GeneratorExit,)): + mark_error(span, type(exc).__name__) + raise + + +def mark_error(span, code: str) -> None: + span.set_status(Status(StatusCode.ERROR, code)) + span.set_attribute("error.type", code) + + +# ----------------------------------------------------------------------------- instruments +http_duration = METER.create_histogram( + "http.server.request.duration", unit="s", + description="Duration of HTTP server requests (whole ASGI call, until the last body byte)", + explicit_bucket_boundaries_advisory=HTTP_BUCKETS) +http_active = METER.create_up_down_counter( + "http.server.active_requests", unit="{request}", description="HTTP requests being served now") +db_duration = METER.create_histogram( + "db.client.operation.duration", unit="s", + description="One unit of database work (pool wait + statements + COMMIT)", + explicit_bucket_boundaries_advisory=DB_BUCKETS) +db_wait = METER.create_histogram( + "db.client.connection.wait_time", unit="s", description="Time waiting for a free pool connection", + explicit_bucket_boundaries_advisory=DB_BUCKETS) +jobs_processed = METER.create_counter( + "messenger.jobs.processed", unit="{job}", + description="Job deliveries handled by the worker, by outcome (succeeded, retry, failed, noop_*, ...)") +job_duration = METER.create_histogram( + "messenger.job.duration", unit="s", description="Handling of one job delivery by the worker", + explicit_bucket_boundaries_advisory=JOB_BUCKETS) +time_to_ready = METER.create_histogram( + "messenger.attachment.time_to_ready", unit="s", + description="From the durable acceptance (202, job COMMIT) to the COMMIT of status ready", + explicit_bucket_boundaries_advisory=READY_BUCKETS) +worker_busy = METER.create_up_down_counter( + "messenger.worker.busy", unit="{job}", description="Job attempts being processed now") +spans_ended = METER.create_counter( + "messenger.telemetry.spans.ended", unit="{span}", description="Recorded (sampled) spans finished in this process") +spans_exported = METER.create_counter( + "messenger.telemetry.spans.exported", unit="{span}", + description="Spans handed to the OTLP exporter, by result (success / failure)") + + +def observe(name: str, unit: str, description: str, callback) -> None: + """Asynchronous gauge; `callback()` returns [(value, attributes), ...]. Callbacks run in the + metric reader thread, so they only read values the process already has in memory.""" + def wrapped(options: CallbackOptions) -> Iterable[Observation]: + try: + return [Observation(v, a) for v, a in callback()] + except Exception: # noqa: BLE001 - a broken gauge must not break the export of the others + return [] + METER.create_observable_gauge(name, callbacks=[wrapped], unit=unit, description=description) + + +def observe_pool(pool, pool_name: str) -> None: + """db.client.connection.* (semantic conventions) from psycopg_pool's counters.""" + def connections(): + stats = pool.get_stats() + size, idle = stats.get("pool_size", 0), stats.get("pool_available", 0) + return [(idle, {"db.client.connection.pool.name": pool_name, "db.client.connection.state": "idle"}), + (max(0, size - idle), {"db.client.connection.pool.name": pool_name, "db.client.connection.state": "used"})] + observe("db.client.connection.count", "{connection}", "Open pool connections by state", connections) + observe("db.client.connection.max", "{connection}", "Pool max_size", + lambda: [(pool.max_size, {"db.client.connection.pool.name": pool_name})]) + observe("db.client.connection.pending_requests", "{request}", "Requests waiting for a pool connection", + lambda: [(pool.get_stats().get("requests_waiting", 0), {"db.client.connection.pool.name": pool_name})]) + + +# ----------------------------------------------------------------------------- spans accounting +try: + from opentelemetry.sdk.trace import SpanProcessor as _SpanProcessor +except ImportError: # pragma: no cover - the SDK is a locked dependency + _SpanProcessor = object + + +class SpanCounter(_SpanProcessor): + """SpanProcessor counting the spans this process records (track 1: losses on the way).""" + + def on_end(self, span) -> None: + spans_ended.add(1) + + +class CountingSpanExporter: + """Wraps the OTLP span exporter: counts spans exported / failed (Collector unreachable).""" + + def __init__(self, inner) -> None: + self.inner = inner + + def export(self, spans: Sequence): + from opentelemetry.sdk.trace.export import SpanExportResult + result = self.inner.export(spans) + spans_exported.add(len(spans), {"result": "success" if result == SpanExportResult.SUCCESS else "failure"}) + return result + + def shutdown(self) -> None: + self.inner.shutdown() + + def force_flush(self, timeout_millis: int = 30000) -> bool: + return self.inner.force_flush(timeout_millis) + + +# ----------------------------------------------------------------------------- CPU / RAM +def _read(path: str) -> str | None: + try: + with open(path, encoding="ascii") as f: + return f.read() + except OSError: + return None + + +def _register_process_metrics() -> None: + """Container (cgroup v2) and process CPU/RAM. The container values include the worker's image + child processes; Docker's own `docker stats` reads the same cgroup files.""" + def container_cpu(): + stat = _read("/sys/fs/cgroup/cpu.stat") + if not stat: + return [] + for line in stat.splitlines(): + if line.startswith("usage_usec "): + return [(int(line.split()[1]) / 1e6, {})] + return [] + + def container_memory(): + value = _read("/sys/fs/cgroup/memory.current") + return [(int(value), {})] if value else [] + + def container_memory_limit(): + value = _read("/sys/fs/cgroup/memory.max") + return [(int(value), {})] if value and value.strip().isdigit() else [] + + def process_memory(): + statm = _read("/proc/self/statm") + return [(int(statm.split()[1]) * os.sysconf("SC_PAGE_SIZE"), {})] if statm else [] + + def cpu_counter(options: CallbackOptions): + return [Observation(v, a) for v, a in container_cpu()] + + METER.create_observable_counter("container.cpu.time", callbacks=[cpu_counter], unit="s", + description="CPU time of the whole container (cgroup cpu.stat usage_usec)") + observe("container.memory.usage", "By", "Memory of the container (cgroup memory.current)", container_memory) + observe("container.memory.limit", "By", "Memory limit of the container (cgroup memory.max)", container_memory_limit) + observe("process.memory.usage", "By", "Resident memory of the main process", process_memory) + + +__all__ = ["TRACER", "SpanKind", "StatusCode", "setup", "shutdown", "enabled", "inject", "extract", + "extract_headers", "current_ids", "mark_error", "child_span", "observe", "observe_pool"] diff --git a/src/messenger/timefmt.py b/src/messenger/timefmt.py new file mode 100644 index 0000000..9c33b12 --- /dev/null +++ b/src/messenger/timefmt.py @@ -0,0 +1,22 @@ +"""Conversions between PostgreSQL timestamptz values, cursor integers and RFC 3339 strings.""" +from __future__ import annotations + +import datetime as dt + +UTC = dt.timezone.utc +_EPOCH = dt.datetime(1970, 1, 1, tzinfo=UTC) + + +def to_us(value: dt.datetime) -> int: + """Microseconds since the Unix epoch (exact: timestamptz has microsecond precision).""" + delta = value - _EPOCH + return (delta.days * 86_400 + delta.seconds) * 1_000_000 + delta.microseconds + + +def from_us(us: int) -> dt.datetime: + return _EPOCH + dt.timedelta(microseconds=us) + + +def rfc3339(value: dt.datetime) -> str: + """RFC 3339 UTC with fixed microsecond precision, e.g. 2026-10-12T12:00:00.000001Z.""" + return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ") diff --git a/src/messenger/validation.py b/src/messenger/validation.py new file mode 100644 index 0000000..bd62fc4 --- /dev/null +++ b/src/messenger/validation.py @@ -0,0 +1,195 @@ +"""Strict request validation according to contracts/openapi.json + contracts/README.md. + +Written by hand instead of a schema library so that every rule is visible: +extra fields, wrong JSON types, whitespace-only strings and lengths counted in +Unicode code points all produce 400 invalid_request. +""" +from __future__ import annotations + +import json +import re +import unicodedata +from typing import Any +from urllib.parse import parse_qsl + +from .errors import InvalidRequest + +USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}") +# Canonical textual UUID (8-4-4-4-12 hex). Case-insensitive, normalised to lower case. +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}") +LIMIT_RE = re.compile(r"[0-9]{1,3}") +# Idempotency-Key (contract, lab 3): ASCII [A-Za-z0-9._:-]{1,128}. +IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}") +SURROGATES_RE = re.compile("[\ud800-\udfff]") + +DEFAULT_LIMIT = 50 +MAX_LIMIT = 100 + + +def _reject_constant(name: str) -> Any: + # Python's json accepts NaN/Infinity, which are not valid JSON. + raise ValueError(f"invalid JSON constant {name}") + + +def _unique_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + # {"text":"a","text":"b"} is ambiguous (which one is meant?) -> 400, not "last one wins". + result = dict(pairs) + if len(result) != len(pairs): + raise ValueError("duplicate key in JSON object") + return result + + +def parse_json_object(body: bytes) -> dict[str, Any]: + """Decode a UTF-8 JSON object or raise InvalidRequest (malformed JSON -> 400).""" + try: + text = body.decode("utf-8") + value = json.loads(text, parse_constant=_reject_constant, object_pairs_hook=_unique_keys) + except (UnicodeDecodeError, ValueError): + raise InvalidRequest("Тело запроса должно быть корректным JSON в UTF-8") from None + if not isinstance(value, dict): + raise InvalidRequest("Тело запроса должно быть JSON-объектом") + return value + + +def check_fields(data: dict[str, Any], required: set[str], optional: frozenset[str] = frozenset()) -> None: + extra = set(data) - required - optional + if extra: + raise InvalidRequest("Неизвестные поля: " + ", ".join(sorted(extra))) + missing = required - set(data) + if missing: + raise InvalidRequest("Отсутствуют обязательные поля: " + ", ".join(sorted(missing))) + + +def text_field(data: dict[str, Any], name: str, max_len: int, *, min_len: int = 1, allow_blank: bool = False) -> str: + value = data[name] + if not isinstance(value, str): + raise InvalidRequest(f"Поле {name} должно быть строкой") + if SURROGATES_RE.search(value): + # "\ud800" escapes decode to lone surrogates that cannot be encoded as UTF-8. + raise InvalidRequest(f"Поле {name} содержит недопустимые символы") + # len() of a Python str is the number of Unicode code points, as the contract requires. + if not min_len <= len(value) <= max_len: + raise InvalidRequest(f"Длина поля {name} должна быть от {min_len} до {max_len} символов") + if value.strip() == "" and not allow_blank: + raise InvalidRequest(f"Поле {name} не может состоять только из пробелов") + return value + + +def username_field(data: dict[str, Any]) -> str: + value = data["username"] + if not isinstance(value, str) or USERNAME_RE.fullmatch(value) is None: + raise InvalidRequest("username должен соответствовать [a-z0-9_]{3,32}") + return value + + +def password_field(data: dict[str, Any]) -> str: + """12-128 Unicode code points, not whitespace-only; any other character (':' too) is allowed.""" + value = data["password"] + if not isinstance(value, str): + raise InvalidRequest("Поле password должно быть строкой") + if SURROGATES_RE.search(value): + raise InvalidRequest("Поле password содержит недопустимые символы") + if not 12 <= len(value) <= 128: + raise InvalidRequest("Длина пароля должна быть от 12 до 128 символов") + if value.strip() == "": + raise InvalidRequest("Пароль не может состоять только из пробелов") + return value + + +def parse_uuid(value: Any, what: str = "UUID") -> str: + if not isinstance(value, str) or UUID_RE.fullmatch(value) is None: + raise InvalidRequest(f"Неверный {what}") + return value.lower() + + +def member_ids_field(data: dict[str, Any]) -> list[str]: + value = data["member_ids"] + if not isinstance(value, list): + raise InvalidRequest("member_ids должен быть массивом") + if not 1 <= len(value) <= 100: + raise InvalidRequest("member_ids должен содержать от 1 до 100 элементов") + ids = [parse_uuid(item, "UUID участника") for item in value] + if len(set(ids)) != len(ids): + raise InvalidRequest("member_ids содержит дубликаты") + return ids + + +def attachment_ids_field(data: dict[str, Any]) -> list[str]: + """Optional `attachment_ids` (lab 4+): absent and [] are the same message (contracts/README.md); + null or any other non-array type is 400.""" + value = data.get("attachment_ids", []) + if not isinstance(value, list): + raise InvalidRequest("attachment_ids должен быть массивом") + if len(value) > 10: + raise InvalidRequest("attachment_ids содержит больше 10 элементов") + ids = [parse_uuid(item, "UUID вложения") for item in value] + if len(set(ids)) != len(ids): + raise InvalidRequest("attachment_ids содержит дубликаты") + return ids + + +def idempotency_key(raw: str | None) -> str: + if raw is None or IDEMPOTENCY_KEY_RE.fullmatch(raw) is None: + raise InvalidRequest("Заголовок Idempotency-Key обязателен: [A-Za-z0-9._:-]{1,128}") + return raw + + +def single_query_param(query: list[tuple[str, str]], name: str) -> str | None: + values = [v for k, v in query if k == name] + if len(values) > 1: + raise InvalidRequest(f"Параметр {name} указан несколько раз") + return values[0] if values else None + + +def parse_limit(raw: str | None) -> int: + if raw is None: + return DEFAULT_LIMIT + if LIMIT_RE.fullmatch(raw) is None or not 1 <= int(raw) <= MAX_LIMIT: + raise InvalidRequest(f"limit должен быть целым числом от 1 до {MAX_LIMIT}") + return int(raw) + + +# Lab 4: the display name of an attachment. Never used as a path or an S3 key, but it is shown +# to other users, so characters that change how a name LOOKS are refused: control characters +# (C0, DEL, C1 such as U+0085), line/paragraph separators, unpaired surrogates and bidi controls +# ("photognp.exe" would display as "photoexe.png"). +BIDI_CONTROLS = frozenset("\u061c\u200e\u200f\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069") +FORBIDDEN_CATEGORIES = frozenset({"Cc", "Cs", "Zl", "Zp"}) + + +def query_items(raw: bytes) -> list[tuple[str, str]]: + """Strict query parsing: percent-encoded UTF-8 only (Starlette would replace bad bytes by U+FFFD).""" + try: + return parse_qsl(raw.decode("ascii"), keep_blank_values=True, encoding="utf-8", errors="strict") + except (UnicodeDecodeError, ValueError): + raise InvalidRequest("Параметры запроса должны быть в UTF-8 с percent-encoding") from None + + +def filename_param(query: list[tuple[str, str]]) -> str: + value = single_query_param(query, "filename") + if value is None: + raise InvalidRequest("Параметр filename обязателен") + if not 1 <= len(value) <= 255: + raise InvalidRequest("Длина filename должна быть от 1 до 255 символов") + if value.strip() == "" or value in {".", ".."}: + raise InvalidRequest("filename не может состоять только из пробелов или точек") + if "/" in value or "\\" in value: + raise InvalidRequest("filename не может содержать / или \\") + for char in value: + if unicodedata.category(char) in FORBIDDEN_CATEGORIES or char in BIDI_CONTROLS: + raise InvalidRequest("filename содержит управляющие символы") + return value + + +ATTACHMENT_VARIANTS = ("original", "thumbnail", "crop", "optimized") + + +def variant_param(query: list[tuple[str, str]]) -> str: + """`variant` of GET /attachments/{id}/content: original (default) or a lab 5 variant name. + Any other value is 400; a known name that a ready attachment lacks is 404 (handler).""" + value = single_query_param(query, "variant") + if value is None: + return "original" + if value in ATTACHMENT_VARIANTS: + return value + raise InvalidRequest("variant должен быть original, thumbnail, crop или optimized") diff --git a/src/messenger/worker.py b/src/messenger/worker.py new file mode 100644 index 0000000..63e691e --- /dev/null +++ b/src/messenger/worker.py @@ -0,0 +1,403 @@ +"""Image worker: `python -m messenger.worker` (compose service `worker`, separate from the API). + +One delivery of a job message: + + decode + validate (schema v1; invalid -> reject -> dead-letter queue) + -> CLAIM in PostgreSQL (jobs.claim): finished/leased/not due/stale -> no-op, ack + -> lease heartbeat every JOB_LEASE_SECONDS/3 while the attempt runs + -> read the source (staging copy or published original), check size + SHA-256 against the DB + -> variants in a child process (imaging.py: pixel, memory and time limits) + -> PUT the original (first publication) and the variants under keys of THIS attempt + -> ONE transaction: variants + attachment ready, fenced by the lease token (jobs.complete) + -> ack -> delete the staging copy (marked in the DB first, then S3). + +The ack comes only after the durable effect (the COMMIT). A crash anywhere before it makes +RabbitMQ deliver the message again; the job row then says what is left to do. Failures: a +permanent one (invalid_image, image_too_large, source_missing/corrupt) fails the job at once, a +transient one (S3 down, timeout, killed decoder) is retried with backoff via the outbox, at most +JOB_MAX_ATTEMPTS claims in total. + +Concurrency: RabbitMQ prefetch = WORKER_CONCURRENCY unacked messages per worker, and at most +WORKER_CONCURRENCY image child processes. Graceful stop (SIGTERM): stop consuming, let running +attempts finish for WORKER_SHUTDOWN_SECONDS, give the rest back (jobs.release). + +The worker also runs the cleanup of the pipeline objects (staging copies that are no longer +needed, objects of attempts that never published) - always decided under a row lock. + +Lab 6: one delivery = one CONSUMER span `messenger.attachment-jobs process`, child of the relay's +PRODUCER span (context from the message's `traceparent`), so the upload, its publish, every +attempt and its DB/S3 steps are one trace. Metrics: messenger.jobs.processed (by outcome), +messenger.job.duration, messenger.attachment.time_to_ready (uploads: 202 -> ready COMMIT), +messenger.worker.busy / messenger.worker.capacity, db.client.connection.* of the worker pool. +""" +from __future__ import annotations + +import asyncio +import hashlib +import logging +import sys +import time + +import aio_pika +from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractIncomingMessage, AbstractQueue + +from . import __version__, broker, imaging, jobs, logging_setup, service, telemetry +from .config import ConfigError, Settings +from .db import Database +from .errors import Unavailable +from .imaging import ProcessingError +from .storage import ObjectMissing, Storage + +log = logging.getLogger("messenger.worker") + + +class Worker: + def __init__(self, settings: Settings): + self.settings = settings + self.name = settings.instance_id + self.actor = "worker:" + self.name + self.db = Database(settings, name="messenger-worker") + self.staging = Storage(settings, bucket=settings.s3_staging_bucket) + self.final = Storage(settings) + self.slots = asyncio.Semaphore(settings.worker_concurrency) + self.tasks: set[asyncio.Task] = set() + self.connection: AbstractConnection | None = None + self.channel: AbstractChannel | None = None + self.queue: AbstractQueue | None = None + self.consumer_tag: str | None = None + self.lost: asyncio.Event | None = None + + def connected(self) -> bool: + return (self.connection is not None and self.lost is not None and not self.lost.is_set() + and self.channel is not None and not self.channel.is_closed) + + # ---------------------------------------------------------------- broker + async def connect(self) -> None: + self.connection = await aio_pika.connect( + self.settings.broker_url, timeout=5, + client_properties={"connection_name": "worker@" + self.name}) + self.lost = service.watch_connection(self.connection) + self.channel = await self.connection.channel() + # Prefetch: the broker keeps at most this many unacked messages in flight to this worker. + await self.channel.set_qos(prefetch_count=self.settings.worker_concurrency) + self.queue = await self.channel.get_queue(broker.QUEUE, ensure=False) + self.consumer_tag = await self.queue.consume(self.on_message, no_ack=False) + log.info("consuming", extra={"fields": {"queue": broker.QUEUE, "prefetch": self.settings.worker_concurrency}}) + + async def disconnect(self) -> None: + if self.connection is not None: + try: + await self.connection.close() + except Exception: # noqa: BLE001 - already broken + pass + self.connection = self.channel = self.queue = self.lost = None + self.consumer_tag = None + + async def on_message(self, message: AbstractIncomingMessage) -> None: + task = asyncio.create_task(self.deliver(message)) + self.tasks.add(task) + task.add_done_callback(self.tasks.discard) + + @staticmethod + async def settle(action) -> None: + """ack/nack/reject; the channel may be gone (broker restart): then the broker requeues the + message by itself and the redelivery is a no-op.""" + try: + await action + except Exception as exc: # noqa: BLE001 + log.warning("settle_failed", extra={"fields": {"error": type(exc).__name__}}) + + async def deliver(self, message: AbstractIncomingMessage) -> None: + begin = time.perf_counter() + try: + body = broker.decode(message.body) + except broker.BadMessage as exc: + log.error("bad_message", extra={"fields": {"reason": str(exc), "message_id": message.message_id}}) + self.count("rejected", begin) + await self.settle(message.reject(requeue=False)) # -> messenger.attachment-jobs.dlq + return + with telemetry.TRACER.start_as_current_span( + f"{broker.QUEUE} process", kind=telemetry.SpanKind.CONSUMER, + context=telemetry.extract(body.get("traceparent"), body.get("tracestate")), + record_exception=False, set_status_on_exception=False, + attributes={"messaging.system": "rabbitmq", "messaging.operation.type": "process", + "messaging.destination.name": broker.QUEUE, + "messaging.message.id": message.message_id or "", + "messaging.rabbitmq.message.redelivered": bool(message.redelivered), + "messenger.job.id": body["job_id"], "messenger.job.message_attempt": body["attempt"], + "messenger.attachment.id": body["attachment_id"], + "messenger.pipeline.version": body["pipeline_version"], + "service.instance.id": self.name}) as span: + try: + async with self.slots: + telemetry.worker_busy.add(1) + try: + outcome = await self.process(body["job_id"]) + finally: + telemetry.worker_busy.add(-1) + except Unavailable: + # PostgreSQL (or S3 during a DB step) unavailable: nothing decided. Back to the queue + # after a pause; a claim that did happen is protected by its lease. + log.warning("job_deferred", extra={"fields": {"job_id": body["job_id"]}}) + telemetry.mark_error(span, "deferred") + span.set_attribute("messenger.job.outcome", "deferred") + self.count("deferred", begin) + await asyncio.sleep(2) + await self.settle(message.nack(requeue=True)) + return + except asyncio.CancelledError: + # Shutdown: back to the queue. If the job was claimed it has been released (new outbox + # row), and one of the two deliveries becomes a no-op. + span.set_attribute("messenger.job.outcome", "cancelled") + self.count("cancelled", begin) + await self.settle(asyncio.shield(message.nack(requeue=True))) + raise + span.set_attribute("messenger.job.outcome", outcome) + if outcome in ("failed", "retry", "fenced"): + telemetry.mark_error(span, outcome) + self.count(outcome, begin) + log.info("job_done", extra={"fields": {"job_id": body["job_id"], "outcome": outcome, + "message_attempt": body["attempt"], + "redelivered": message.redelivered}}) + await self.settle(message.ack()) + + @staticmethod + def count(outcome: str, begin: float) -> None: + """messenger.jobs.processed + messenger.job.duration of one delivery (outcome: a fixed set: + succeeded, retry, failed, fenced, superseded, released, deferred, cancelled, rejected, noop_*).""" + attributes = {"messenger.job.type": broker.JOB_TYPE, "outcome": outcome} + telemetry.jobs_processed.add(1, attributes) + telemetry.job_duration.record(time.perf_counter() - begin, attributes) + + # ---------------------------------------------------------------- one attempt + async def process(self, job_id: str) -> str: + settings = self.settings + claim = await self.db.run(lambda c: jobs.claim(c, job_id, self.name, settings.job_lease_seconds), + op="jobs.claim") + if isinstance(claim, jobs.Noop): + return "noop_" + claim.reason + span = telemetry.trace.get_current_span() + span.set_attribute("messenger.job.attempt", claim.attempt) + span.set_attribute("messenger.job.kind", claim.kind) + span.set_attribute("messenger.job.source", claim.source) + await service.crash_once(settings, self.db, "crash_after_claim", job_id, self.actor) + lost = asyncio.Event() + work = asyncio.create_task(self.attempt(claim)) + beat = asyncio.create_task(self.heartbeat(claim, work, lost)) + try: + variants = await work + except asyncio.CancelledError: + if lost.is_set() and not asyncio.current_task().cancelling(): + return "fenced" # lease taken over: this attempt may write nothing more + outcome = await asyncio.shield(self.db.run(lambda c: jobs.release(c, claim, self.name), op="jobs.release")) + log.info("job_released", extra={"fields": {"job_id": job_id, "outcome": outcome}}) + raise + except ProcessingError as exc: + return await self.failed(claim, exc.code, exc.permanent) + except Unavailable: + return await self.failed(claim, "storage_unavailable", False) + finally: + beat.cancel() + await service.crash_once(settings, self.db, "crash_after_s3_write", job_id, self.actor) + outcome = await self.db.run(lambda c: jobs.complete(c, claim, variants, self.name), op="jobs.complete") + if outcome == "succeeded" and claim.kind == "upload" and claim.accepted_at is not None: + # Lab 6 SLI "time to ready": durable acceptance (job COMMIT before the 202) -> ready COMMIT. + telemetry.time_to_ready.record(max(0.0, time.time() - claim.accepted_at.timestamp()), + {"messenger.job.kind": claim.kind}) + await service.crash_once(settings, self.db, "crash_after_commit", job_id, self.actor) + if outcome == "succeeded": + await self.delete_staging(claim.attachment_id) + return outcome + + async def failed(self, claim: jobs.Claim, code: str, permanent: bool) -> str: + s = self.settings + outcome, delay = await self.db.run( + lambda c: jobs.retry_or_fail(c, claim, code, permanent, self.name, s.job_retry_base_seconds, + s.job_retry_max_seconds), op="jobs.retry_or_fail") + telemetry.trace.get_current_span().set_attribute("messenger.job.error_code", code) + log.info("attempt_failed", extra={"fields": {"job_id": claim.job_id, "attempt": claim.attempt, "code": code, + "permanent": permanent, "outcome": outcome, + "delay_s": round(delay, 3)}}) + return outcome + + async def heartbeat(self, claim: jobs.Claim, work: asyncio.Task, lost: asyncio.Event) -> None: + """Renew the lease while the attempt is alive and within JOB_TIMEOUT_SECONDS. A hung attempt + stops being renewed, so the reaper can hand the job to another worker; if the lease turns out + to be lost, the attempt is cancelled (its result would be fenced anyway).""" + s = self.settings + if "hang" in s.fault_points: + return # experiment: a hung worker that no longer heartbeats + started = time.monotonic() + while True: + await asyncio.sleep(s.job_lease_seconds / 3) + if time.monotonic() - started > s.job_timeout_seconds: + return + try: + alive = await self.db.run(lambda c: jobs.heartbeat(c, claim, s.job_lease_seconds), op="jobs.heartbeat") + except Unavailable: + continue # the lease may expire meanwhile; the fence protects the result + if not alive: + log.warning("lease_lost", extra={"fields": {"job_id": claim.job_id, "attempt": claim.attempt}}) + lost.set() + work.cancel() + return + + async def attempt(self, claim: jobs.Claim) -> list[imaging.Rendered]: + s = self.settings + if "hang" in s.fault_points: + await asyncio.sleep(s.fault_value("hang", 3600)) # stuck outside of the time limit + try: + return await asyncio.wait_for(self.build(claim), s.job_timeout_seconds) + except asyncio.TimeoutError: + raise ProcessingError("processing_timeout", permanent=False) from None + + async def build(self, claim: jobs.Claim) -> list[imaging.Rendered]: + s = self.settings + started = time.monotonic() + if claim.size_bytes > s.max_upload_bytes: + raise ProcessingError("image_too_large", permanent=True) + source = self.staging if claim.source == "staging" else self.final + try: + data = await source.read_all(claim.source_key, limit=s.max_upload_bytes) + except ObjectMissing: + raise ProcessingError("source_missing", permanent=True) from None + if len(data) != claim.size_bytes or hashlib.sha256(data).digest() != claim.sha256: + raise ProcessingError("source_corrupt", permanent=True) + self.injected(claim) + if "slow" in s.fault_points and s.fault_value("slow_pipeline", claim.pipeline_version) == claim.pipeline_version: + await asyncio.sleep(s.fault_value("slow", 10)) + remaining = max(1.0, s.job_timeout_seconds - (time.monotonic() - started)) + with telemetry.child_span("image render", {"messenger.image.content_type": claim.content_type, + "messenger.image.size_bytes": claim.size_bytes}) as span: + variants = await imaging.render(data, claim.content_type, claim.pipeline_version, + max_pixels=s.max_image_pixels, timeout=remaining, + memory_mb=s.image_max_memory_mb) + if span is not None: + span.set_attribute("messenger.image.variants", [v.name for v in variants]) + meta = {"attachment-id": claim.attachment_id, "pipeline-version": str(claim.pipeline_version)} + puts = [self.final.put(claim.key(v.name), v.data, v.content_type, meta) for v in variants] + if claim.write_original: + puts.append(self.final.put(claim.key("original"), data, claim.content_type, + {**meta, "sha256": claim.sha256.hex()})) + await asyncio.gather(*puts) + return variants + + def injected(self, claim: jobs.Claim) -> None: + s = self.settings + if "permanent_error" in s.fault_points: + raise ProcessingError("invalid_image", permanent=True) + if "transient_error" in s.fault_points and claim.attempt <= s.fault_value("transient_error", 1000): + raise ProcessingError("injected_transient", permanent=False) + + # ---------------------------------------------------------------- cleanup + async def delete_staging(self, attachment_id: str) -> None: + """Mark `deleting` under the row lock (re-checked there), then S3 DELETE, then `deleted`.""" + try: + key = await self.db.run( + lambda c: jobs.mark_staging_deleting(c, attachment_id, self.settings.staging_retention_seconds)) + if key is None: + return + await self.staging.delete(key) + await self.db.run(lambda c: jobs.mark_staging_deleted(c, attachment_id)) + log.info("staging_deleted", extra={"fields": {"attachment_id": attachment_id}}) + except Unavailable: + pass # stays present/deleting; the next cleanup pass repeats (DELETE is idempotent) + + async def cleanup(self) -> None: + s = self.settings + ids = await self.db.run(lambda c: jobs.staging_to_delete(c, s.staging_retention_seconds)) + tokens = await self.db.run(lambda c: jobs.attempts_to_clean(c, s.orphan_grace_seconds)) + if "pause_cleanup" in s.fault_points and (ids or tokens): + # Experiment: the race "cleanup read its candidates -> replay commits -> cleanup goes on". + log.warning("cleanup_paused", extra={"fields": {"attachments": ids, "attempts": tokens}}) + await asyncio.sleep(s.fault_value("pause_cleanup", 10)) + for attachment_id in ids: + await self.delete_staging(attachment_id) + for token in tokens: + keys = await self.db.run(lambda c: jobs.lock_attempt_for_cleanup(c, token)) + if keys is None: + continue + await asyncio.gather(*(self.final.delete(k) for k in keys)) + await self.db.run(lambda c: jobs.mark_attempt_cleaned(c, token)) + log.info("attempt_objects_deleted", extra={"fields": {"token": token, "objects": len(keys)}}) + + async def cleanup_loop(self, stop: asyncio.Event) -> None: + while not stop.is_set() and self.settings.cleanup_interval_seconds > 0: + await service.sleep_or_stop(stop, self.settings.cleanup_interval_seconds) + try: + await self.cleanup() + except Unavailable: + pass + + # ---------------------------------------------------------------- lifecycle + async def run(self) -> int: + stop = service.stop_event() + telemetry.observe("messenger.worker.capacity", "{job}", "WORKER_CONCURRENCY: attempts one worker runs at once", + lambda: [(self.settings.worker_concurrency, {})]) + telemetry.observe_pool(self.db.pool, self.db.name) + await self.db.open() + await self.staging.open() + await self.final.open() + cleaner = asyncio.create_task(self.cleanup_loop(stop)) + try: + while not stop.is_set(): + if not self.connected(): + await self.disconnect() + try: + await self.connect() + except Exception as exc: # noqa: BLE001 - broker down: retry in 2 s, never crash + log.warning("broker_unavailable", extra={"fields": {"error": type(exc).__name__}}) + await self.disconnect() + if self.connected(): + service.beat() # healthy only while a consumer is really attached + await service.sleep_or_stop(stop, 2.0) + await self.shutdown() + finally: + cleaner.cancel() + await self.disconnect() + await self.final.close() + await self.staging.close() + await self.db.close() + log.info("worker_stopped") + return 0 + + async def shutdown(self) -> None: + """Stop consuming; running attempts get WORKER_SHUTDOWN_SECONDS, the rest is released.""" + if self.queue is not None and self.consumer_tag is not None: + try: + await self.queue.cancel(self.consumer_tag) + except Exception: # noqa: BLE001 + pass + pending = set(self.tasks) + log.info("worker_draining", extra={"fields": {"in_flight": len(pending)}}) + if pending: + _, pending = await asyncio.wait(pending, timeout=self.settings.worker_shutdown_seconds) + for task in pending: + task.cancel() + if pending: + await asyncio.wait(pending, timeout=10) + + +def main() -> int: + try: + settings = Settings.from_env() + if not settings.broker_url: + raise ConfigError("BROKER_URL_FILE (or BROKER_URL) must be set") + except ConfigError as exc: + print(f"configuration error: {exc}", file=sys.stderr) + return 2 + logging_setup.configure(settings.log_level) + telemetry.setup("messenger-worker", settings.instance_id, __version__) + log.info("worker_starting", extra={"fields": { + "instance_id": settings.instance_id, "concurrency": settings.worker_concurrency, + "max_attempts": settings.job_max_attempts, "timeout_s": settings.job_timeout_seconds, + "lease_s": settings.job_lease_seconds, "memory_mb": settings.image_max_memory_mb, + "fault_points": sorted(settings.fault_points)}}) + try: + return asyncio.run(Worker(settings).run()) + finally: + telemetry.shutdown() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/student-tests/conftest.py b/student-tests/conftest.py new file mode 100644 index 0000000..daf4abe --- /dev/null +++ b/student-tests/conftest.py @@ -0,0 +1,439 @@ +"""Shared helpers for the student tests. + +* `unit/` — pure functions (validation, cursor, auth headers, Argon2id); no services. +* `test_*` in this folder — marker `stack`: black-box HTTP against the running compose + stand THROUGH THE LOAD BALANCER (BASE_URL, default http://127.0.0.1:8080) plus + `docker compose` for database checks (psql inside the postgres container), the HAProxy + runtime state (scripts/lbctl.py) and failure injection. Every failure test restores the + stopped/paused service or replica in `finally` and waits until HAProxy sees all replicas UP. + + python -m pytest student-tests # everything (stand must be up) + python -m pytest student-tests -m "not stack" # unit only +""" +from __future__ import annotations + +import base64 +import contextlib +import json +import os +import subprocess +import sys +import time +import uuid +from pathlib import Path +from urllib.parse import quote + +import httpx2 as httpx +import pytest +from jsonschema import Draft202012Validator + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) +sys.path.insert(0, str(ROOT / "scripts")) +import lbctl # noqa: E402 + +SPEC = json.loads((ROOT / "contracts" / "openapi.json").read_text(encoding="utf-8")) +BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") +PASSWORD = "Test-password-Ω-12345" # synthetic; 12+ code points, non-ASCII on purpose +REPLICAS = int(os.environ.get("API_REPLICAS", "2")) # replicas the stand normally runs + + +def pytest_configure(config): + config.addinivalue_line("markers", "stack: needs the running compose stand (docker compose up -d --wait)") + + +def schema_errors(value, name: str) -> list[str]: + """Validate against components/schemas/ of the course contract (JSON Schema 2020-12).""" + schema = {"$ref": f"#/components/schemas/{name}", "components": SPEC["components"]} + validator = Draft202012Validator(schema, format_checker=Draft202012Validator.FORMAT_CHECKER) + return [e.message for e in validator.iter_errors(value)] + + +def basic(username: str, password: str) -> str: + return "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode() + + +# ------------------------------------------------------------------ docker / psql +def compose(*args: str, check: bool = True, timeout: float = 120, stdin: str | None = None) -> subprocess.CompletedProcess: + return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, + encoding="utf-8", check=check, timeout=timeout, input=stdin) + + +def psql(sql: str) -> str: + """Run SQL inside the postgres container (no DB port is published) and return unaligned output.""" + result = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", + "-At", "-v", "ON_ERROR_STOP=1", "-c", sql) + return result.stdout.strip() + + +def wait_ready(timeout: float = 90) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + if httpx.get(BASE_URL + "/health/ready", timeout=2).status_code == 200: + return + except httpx.HTTPError: + pass + time.sleep(0.3) + raise AssertionError("stand did not become ready") + + +def wait_healthy(*services: str, timeout: float = 120) -> None: + """Poll Docker health until EVERY container of every service is healthy again. `compose up + --wait` is not used: it gives up at once on a container marked unhealthy while paused.""" + deadline = time.monotonic() + timeout + pending = set(services) + while pending and time.monotonic() < deadline: + for service in list(pending): + ids = compose("ps", "-q", service, check=False).stdout.split() + if ids: + states = subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", *ids], + capture_output=True, text=True).stdout.split() + if states and all(state == "healthy" for state in states): + pending.discard(service) + time.sleep(0.5) + assert not pending, f"not healthy: {pending}" + + +def wait_stand(replicas: int = REPLICAS) -> None: + """Readiness through the LB AND every replica back in HAProxy rotation.""" + wait_ready() + lbctl.wait_up(replicas, timeout=90) + + +def restart_services(*services: str) -> None: + compose("restart", *services) + wait_healthy(*services) + wait_stand() + + +@contextlib.contextmanager +def service_down(service: str, how: str = "stop"): + """Stop or pause a compose service; ALWAYS bring it back and wait for readiness.""" + assert how in {"stop", "pause"} + compose(how, service) + try: + yield + finally: + compose("unpause" if how == "pause" else "start", service) + wait_healthy(service) + wait_stand() + + +def recreate(service: str, env: dict, scale: int | None = None) -> None: + """`docker compose up` of ONE service with the given environment (no dependency restarts).""" + cmd = ["docker", "compose", "up", "-d", "--no-deps", "--wait", service] + if scale is not None: + cmd[4:4] = ["--scale", f"{service}={scale}"] + subprocess.run(cmd, cwd=ROOT, env=env, capture_output=True, text=True, check=True, timeout=180) + + +@contextlib.contextmanager +def service_with_env(service: str, scale: int | None = None, **overrides: str): + """Recreate a service (api, relay, worker) with environment overrides (e.g. FAULT_POINTS of the + worker = WORKER_FAULT_POINTS), then ALWAYS recreate it with the normal configuration.""" + clean = {k: v for k, v in os.environ.items() if k not in overrides} + recreate(service, {**os.environ, **overrides}, scale) + if service == "api": + wait_stand() + try: + yield + finally: + recreate(service, clean, 1 if scale is not None and service != "api" else None) + wait_healthy(service) + if service == "api": + wait_stand() + + +def api_with_env(**overrides: str): + return service_with_env("api", **overrides) + + +def running_replicas() -> list[dict]: + return [r for r in lbctl.replicas() if r["state"] == "running"] + + +@contextlib.contextmanager +def replica_stopped(replica: dict, mode: str = "stop"): + """Stop ONE api container (stop = SIGTERM + drain, kill = SIGKILL); ALWAYS start it again + and wait until HAProxy has every replica UP.""" + assert mode in {"stop", "kill"} + subprocess.run(["docker", "stop", "--time", "15" if mode == "stop" else "0", replica["id"]], + capture_output=True, text=True, check=True, timeout=60) + try: + yield + finally: + subprocess.run(["docker", "start", replica["id"]], capture_output=True, text=True, check=True, timeout=60) + wait_healthy("api") + wait_stand() + + +def api_env(name: str) -> str: + """Current value of an environment variable inside the running api container.""" + return compose("exec", "-T", "api", "printenv", name).stdout.strip() + + +# ------------------------------------------------------------------ HTTP +class Api: + """HTTP helper that checks the invariants every response must satisfy.""" + + def __init__(self, base_url: str = BASE_URL): + self.client = httpx.Client(base_url=base_url, timeout=15) + + def call(self, method: str, path: str, expected: int | tuple[int, ...], *, token: str | None = None, + json_body=None, raw: bytes | None = None, headers: dict | None = None, schema: str | None = None, + lb_error_ok: bool = False): + """lb_error_ok: a 502/503/504 generated by HAProxy itself (no API replica answered) is + accepted without X-Instance-Id; every response of an API replica must carry it.""" + h = dict(headers or {}) + if token is not None: + h["Authorization"] = "Bearer " + token + if json_body is not None: + raw = json.dumps(json_body, ensure_ascii=False).encode("utf-8") + h.setdefault("Content-Type", "application/json") + response = self.client.request(method, path, content=raw, headers=h) + allowed = (expected,) if isinstance(expected, int) else expected + assert response.status_code in allowed, (method, path, response.status_code, response.text[:300]) + request_id = response.headers.get("x-request-id") + assert request_id, "every response must carry X-Request-Id" + if not response.headers.get("x-instance-id"): + assert lb_error_ok and response.status_code in (502, 503, 504), \ + ("missing X-Instance-Id", method, path, response.status_code) + if response.status_code >= 400: + body = response.json() + assert schema_errors(body, "Error") == [], response.text + assert body["error"]["request_id"] == request_id + assert "Traceback" not in response.text and "psycopg" not in response.text + if response.status_code == 401: + challenge = "basic" if path == "/api/v1/auth/sessions" else "bearer" + assert response.headers.get("www-authenticate", "").lower().startswith(challenge) + elif schema: + assert schema_errors(response.json(), schema) == [], response.text + return response + + def register(self, label: str = "u", *, password: str = PASSWORD, display_name: str | None = None) -> dict: + username = f"{label}_{uuid.uuid4().hex[:12]}"[:32] + body = {"username": username, "display_name": display_name or f"Студент {label}", "password": password} + user = self.call("POST", "/api/v1/users", 201, json_body=body, schema="User").json() + return {"id": user["id"], "user": user, "username": username, "password": password} + + def login(self, actor: dict) -> str: + session = self.call("POST", "/api/v1/auth/sessions", 201, + headers={"Authorization": basic(actor["username"], actor["password"])}, + schema="Session").json() + assert session["user"] == actor["user"] and session["token_type"] == "Bearer" + return session["token"] + + def user(self, label: str = "u", **kwargs) -> dict: + actor = self.register(label, **kwargs) + actor["token"] = self.login(actor) + return actor + + def chat(self, owner: dict, *members: dict, title: str = "Тестовый чат") -> dict: + ids = [owner["id"], *(m["id"] for m in members)] + return self.call("POST", "/api/v1/chats", 201, token=owner["token"], + json_body={"title": title, "member_ids": ids}, schema="Chat").json() + + def post_message(self, actor: dict, chat: dict, body, expected=201, *, key: str | None = None, + raw: bytes | None = None, headers: dict | None = None, **kwargs): + """POST a message with an Idempotency-Key (a fresh one unless `key` is given).""" + h = {"Idempotency-Key": key or uuid.uuid4().hex, **(headers or {})} + if raw is not None: + h.setdefault("Content-Type", "application/json") + return self.call("POST", f"/api/v1/chats/{chat['id']}/messages", expected, token=actor["token"], + json_body=body if raw is None else None, raw=raw, headers=h, + schema="Message" if expected == 201 else None, **kwargs) + + def send(self, actor: dict, chat: dict, text: str, key: str | None = None) -> dict: + return self.post_message(actor, chat, {"text": text}, key=key).json() + + def upload(self, actor: dict, chat: dict, data, expected=202, *, content_type: str | None = "image/png", + filename: str | None = "photo.png", query: str | None = None, headers: dict | None = None): + """POST raw bytes to /chats/{id}/attachments. `query` replaces the whole query string + (to send hand-made percent-encoding); `data` may be bytes or an iterator (chunked).""" + h = dict(headers or {}) + if content_type is not None: + h["Content-Type"] = content_type + if query is None: + query = "" if filename is None else "filename=" + quote(filename, safe="") + path = f"/api/v1/chats/{chat['id']}/attachments" + (f"?{query}" if query else "") + if isinstance(data, (bytes, bytearray)): + return self.call("POST", path, expected, token=actor["token"], raw=bytes(data), headers=h, + schema="Attachment" if expected == 202 else None) + h["Authorization"] = "Bearer " + actor["token"] + response = self.client.post(path, content=data, headers=h) + assert response.status_code == expected, (response.status_code, response.text[:300]) + return response + + def attachment(self, actor: dict, attachment_id: str, expected=200) -> dict: + return self.call("GET", f"/api/v1/attachments/{attachment_id}", expected, token=actor["token"], + schema="Attachment" if expected == 200 else None).json() + + def wait_status(self, actor: dict, attachment_id: str, *statuses: str, timeout: float = 60) -> dict: + """Poll the metadata until the status is one of `statuses` (default: a final one).""" + wanted = statuses or ("ready", "failed") + deadline = time.monotonic() + timeout + while True: + att = self.attachment(actor, attachment_id) + if att["status"] in wanted: + return att + assert time.monotonic() < deadline, f"attachment stayed {att['status']}, wanted {wanted}" + time.sleep(0.3) + + def content(self, actor: dict, attachment_id: str, variant: str | None = None, expected=200): + query = f"?variant={variant}" if variant else "" + return self.call("GET", f"/api/v1/attachments/{attachment_id}/content{query}", expected, token=actor["token"]) + + def history(self, actor: dict, chat: dict, limit: int) -> tuple[list[dict], int]: + """Walk all pages; returns (items, number_of_pages).""" + items, pages, cursor = [], 0, None + while True: + query = f"?limit={limit}" + (f"&cursor={cursor}" if cursor else "") + page = self.call("GET", f"/api/v1/chats/{chat['id']}/messages{query}", 200, + token=actor["token"], schema="MessagePage").json() + pages += 1 + items.extend(page["items"]) + cursor = page["next_cursor"] + if cursor is None: + return items, pages + assert len(page["items"]) == limit, "a non-final page must be full" + assert len(items) < 100_000, "cursor loop" + + +def _stand_is_up() -> bool: + try: + return httpx.get(BASE_URL + "/health/ready", timeout=3).status_code == 200 + except httpx.HTTPError: + return False + + +def pytest_collection_modifyitems(config, items): + if any("stack" in item.keywords for item in items) and not _stand_is_up(): + skip = pytest.mark.skip(reason=f"stand is not running at {BASE_URL}: docker compose up -d --wait") + for item in items: + if "stack" in item.keywords: + item.add_marker(skip) + + +@pytest.fixture(scope="session") +def api() -> Api: + return Api() + + +def run_hook(name: str, timeout: float = 180, **env: str) -> subprocess.CompletedProcess: + """Run scripts/ (a POSIX sh hook); on Windows through Git Bash like the .cmd wrappers.""" + script = str(ROOT / "scripts" / name) + if os.name == "nt": + command = [os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe"), script] + else: + command = [script] + return subprocess.run(command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", check=True, + timeout=timeout, env={**os.environ, **env}) + + +def s3_exec(body: str, bucket: str = "final", service: str = "worker", stdin: str | None = None) -> str: + """Run `body` (async Python, `s` = messenger.storage.Storage of the final or the staging bucket) + INSIDE a container that holds S3 credentials: `worker` (Read+Write both buckets, no List) or + `auditor` (Read+List, no Write). The S3 port is not published on the host; this is how the + tests look into the buckets and inject faults.""" + script = ("import asyncio, base64, json, sys\n" + "from messenger.config import Settings, s3_settings\n" + "from messenger.storage import Storage, ObjectMissing\n" + "async def main():\n" + " st = Settings(host='', port=0, env='lab', log_level='info', shutdown_timeout=0, max_body_bytes=1024, **s3_settings())\n" + f" s = Storage(st, bucket=st.s3_staging_bucket if {bucket == 'staging'} else None)\n" + " await s.open()\n" + " try:\n" + "".join(" " + line + "\n" for line in body.splitlines()) + + " finally:\n" + " await s.close()\n" + "asyncio.run(main())\n") + if service == "auditor": + cmd = ["run", "--rm", "--no-deps", "-T", "--entrypoint", "python", service, "-c", script] + else: + cmd = ["exec", "-T", service, "python", "-c", script] + return compose(*cmd, timeout=120, stdin=stdin).stdout.strip() + + +def s3_put(key: str, data: bytes, bucket: str = "final") -> None: + """Write raw bytes under `key` (base64 over stdin: Windows limits command lines to 32 KiB).""" + s3_exec(f"await s.put({key!r}, base64.b64decode(sys.stdin.read()), 'image/png', {{}})", bucket, + stdin=base64.b64encode(data).decode()) + + +def s3_delete(key: str, bucket: str = "final") -> None: + s3_exec(f"await s.delete({key!r})", bucket) + + +def s3_size(key: str, bucket: str = "final") -> int | None: + out = s3_exec(f"try:\n print((await s.head({key!r})).size)\nexcept ObjectMissing:\n print(-1)", bucket) + size = int(out.splitlines()[-1]) + return None if size < 0 else size + + +def s3_keys(prefix: str, bucket: str = "final") -> set[str]: + """Every object key under `prefix` (needs List: runs with the auditor's key pair).""" + out = s3_exec("keys, after = [], None\n" + "while True:\n" + f" page, more = await s.list_page({prefix!r}, after, 1000)\n" + " keys += [o.key for o in page]\n" + " if not more or not page:\n" + " break\n" + " after = page[-1].key\n" + "print(json.dumps(keys))", bucket, service="auditor") + return set(json.loads(out.splitlines()[-1])) + + +def jobctl(*args: str, expect_code: int = 0) -> dict: + """Operator CLI (compose service jobctl, profile tools); returns its JSON output.""" + result = compose("run", "--rm", "--no-deps", "-T", "jobctl", *args, check=False, timeout=120) + assert result.returncode == expect_code, (result.returncode, result.stdout[-1000:], result.stderr[-1000:]) + return json.loads(result.stdout) + + +def audit(*args: str) -> dict: + """Read-only invariant checker (compose service auditor); asserts that it found no violation.""" + result = compose("run", "--rm", "--no-deps", "-T", "auditor", *args, check=False, timeout=300) + report = json.loads(result.stdout) + assert result.returncode == 0 and report["ok"], json.dumps(report.get("violations"), ensure_ascii=False)[:3000] + return report + + +def job_rows(attachment_id: str) -> list[dict]: + out = psql("SELECT coalesce(json_agg(json_build_object('id', id, 'state', state, 'attempt', attempt, 'kind', kind, " + "'pipeline_version', pipeline_version, 'error_code', error_code) ORDER BY created_at), '[]') " + "FROM jobs WHERE attachment_id = '%s'" % attachment_id) + return json.loads(out) + + +def events_of(attachment_id: str) -> list[dict]: + out = psql("SELECT coalesce(json_agg(json_build_object('event', e.event, 'attempt', e.attempt, 'actor', e.actor, " + "'error_code', e.error_code, 'detail', e.detail, 'at', e.at) ORDER BY e.id), '[]') " + "FROM job_events e JOIN jobs j ON j.id = e.job_id WHERE j.attachment_id = '%s'" % attachment_id) + return json.loads(out) + + +def queue_depth(queue: str = "messenger.attachment-jobs") -> int: + out = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "messages").stdout + for line in out.splitlines(): + name, _, count = line.partition("\t") + if name == queue: + return int(count) + raise AssertionError("queue not found: " + queue) + + +def attachment_row(attachment_id: str) -> dict | None: + out = psql("SELECT json_build_object('status', status, 'object_key', object_key, 'size', size_bytes, " + "'lost_reason', lost_reason, 'staging_key', staging_key, 'staging_state', staging_state, " + "'published_version', published_version, 'error_code', error_code) " + "FROM attachments WHERE id = '%s'" % attachment_id) + return json.loads(out) if out else None + + +def probe_inside(replica: dict, path: str) -> int: + """HTTP status of `path` asked inside the replica container itself (bypassing the LB).""" + code = ("import urllib.request as u, urllib.error as e\n" + "try: print(u.urlopen('http://127.0.0.1:8080%s', timeout=3).status)\n" + "except e.HTTPError as x: print(x.code)") % path + out = subprocess.run(["docker", "exec", replica["id"], "python", "-c", code], capture_output=True, text=True, + timeout=30).stdout.strip() + return int(out or 0) diff --git a/student-tests/imagegen.py b/student-tests/imagegen.py new file mode 100644 index 0000000..1f03da4 --- /dev/null +++ b/student-tests/imagegen.py @@ -0,0 +1,117 @@ +"""Synthetic images for the lab 4 tests: valid PNG/JPEG of any size, and the broken files the +reviewer used against other solutions (truncated, corrupted IDAT with a valid CRC, JPEG without +scan data, decompression-bomb headers, MIME spoofing). Nothing big is stored in Git: every file +is generated in memory.""" +from __future__ import annotations + +import io +import os +import struct +import zlib + +from PIL import Image + +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" + + +def chunk(ctype: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + ctype + data + struct.pack(">I", zlib.crc32(ctype + data)) + + +def ihdr(width: int, height: int, depth: int = 8, color: int = 2, interlace: int = 0) -> bytes: + return chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace)) + + +def png(width: int = 64, height: int = 48, mode: str = "RGB", noise: bool = False, **save) -> bytes: + if noise: + channels = len(mode) + image = Image.frombytes(mode, (width, height), os.urandom(width * height * channels)) + else: + image = Image.new(mode, (width, height), (40, 120, 200) if mode == "RGB" else 128) + out = io.BytesIO() + image.save(out, "PNG", **save) + return out.getvalue() + + +def png_of_size(target: int) -> bytes: + """A valid PNG of (about, at most) `target` bytes: random pixels do not compress.""" + side = int((target / 3) ** 0.5) + data = png(side, side, noise=True, compress_level=1) + while len(data) > target: + side -= 8 + data = png(side, side, noise=True, compress_level=1) + return data + + +def png_exactly(size: int) -> bytes: + """A valid PNG of EXACTLY `size` bytes: noise image + an ancillary padding chunk.""" + base = png_of_size(size - 64) + pad = size - len(base) - 12 + assert pad >= 0 + return base[:-12] + chunk(b"tEXt", b"pad\x00" + b"x" * (pad - 4)) + base[-12:] + + +def jpeg(width: int = 64, height: int = 48, progressive: bool = False, noise: bool = False, quality: int = 85) -> bytes: + if noise: + image = Image.frombytes("RGB", (width, height), os.urandom(width * height * 3)) + else: + image = Image.new("RGB", (width, height), (200, 30, 30)) + out = io.BytesIO() + image.save(out, "JPEG", progressive=progressive, quality=quality) + return out.getvalue() + + +# ------------------------------------------------------------------ broken files +def png_corrupt_idat() -> bytes: + """Valid signature, IHDR and CRCs; the IDAT payload is 86 bytes of garbage (reviewer's case).""" + return PNG_SIGNATURE + ihdr(20, 20) + chunk(b"IDAT", bytes(range(86))) + chunk(b"IEND", b"") + + +def png_short_pixels() -> bytes: + """A complete, CRC-correct PNG whose zlib stream holds fewer rows than the header promises.""" + raw = b"".join(b"\x00" + bytes(60) for _ in range(19)) + return PNG_SIGNATURE + ihdr(20, 20) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"") + + +def png_bomb_header(width: int = 20000, height: int = 10000) -> bytes: + """Header of a huge picture: must be refused (413) from the first 33 bytes.""" + raw_row = b"\x00" + bytes(width * 3) + body = zlib.compress(raw_row * 4, 9) # a few rows only: the decoder must never get that far + return PNG_SIGNATURE + ihdr(width, height) + chunk(b"IDAT", body) + chunk(b"IEND", b"") + + +def jpeg_without_scan_data() -> bytes: + data = jpeg(128, 96) + sos = data.index(b"\xff\xda") + length = struct.unpack(">H", data[sos + 2:sos + 4])[0] + return data[:sos + 2 + length] + b"\xff\xd9" + + +def jpeg_bomb_header() -> bytes: + """SOF0 announcing 20000 x 20000 = 400 Mpx.""" + return (b"\xff\xd8\xff\xc0\x00\x11\x08" + struct.pack(">HH", 20000, 20000) + + b"\x03\x01\x22\x00\x02\x11\x01\x03\x11\x01" + b"\xff\xd9") + + +# ------------------------------------------------------------------ cases the reviewer used in lab 4/5 PRs +def png_bad_filter(filter_byte: int) -> bytes: + """PNG 1x1 RGB, correct CRCs and zlib stream, but the row filter byte is not 0..4.""" + raw = bytes([filter_byte]) + b"\x00\x00\x00" + return PNG_SIGNATURE + ihdr(1, 1) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"") + + +def png_idat_not_zlib() -> bytes: + """Correct PNG structure, IDAT = b'not-a-zlib-stream' with a recomputed CRC.""" + return PNG_SIGNATURE + ihdr(64, 64) + chunk(b"IDAT", b"not-a-zlib-stream") + chunk(b"IEND", b"") + + +# SOI, SOF0 1x1 grey, SOS, EOI: no tables, no scan data (27 bytes). +JPEG_27_BYTES = bytes.fromhex("ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9") + + +def jpeg_sos_unknown_component() -> bytes: + """A valid JPEG whose first SOS component id (byte sos+5) is 250, absent from SOF.""" + data = bytearray(jpeg(64, 48)) + sos = data.index(b"\xff\xda") + data[sos + 5] = 250 + return bytes(data) diff --git a/student-tests/test_api.py b/student-tests/test_api.py new file mode 100644 index 0000000..13fc2d2 --- /dev/null +++ b/student-tests/test_api.py @@ -0,0 +1,344 @@ +"""Contract behaviour over real HTTP (stand must be running). Lab 1 checks moved to Bearer + new lab 2 auth.""" +from __future__ import annotations + +import base64 +import uuid + +import pytest + +from conftest import PASSWORD, basic + +pytestmark = pytest.mark.stack + + +def key(item: dict) -> tuple[str, int]: + return item["created_at"], uuid.UUID(item["id"]).int + + +# ================================================================== registration & login +def test_register_never_returns_password_and_login_returns_bearer(api): + actor = api.register("alice", display_name="Алиса 👩‍💻") + assert set(actor["user"]) == {"id", "username", "display_name", "created_at"} + session = api.call("POST", "/api/v1/auth/sessions", 201, + headers={"Authorization": basic(actor["username"], PASSWORD)}, schema="Session").json() + assert session["token_type"] == "Bearer" and len(session["token"]) >= 43 + assert actor["username"] not in session["token"] and actor["id"] not in session["token"] + assert api.call("GET", "/api/v1/users/me", 200, token=session["token"], schema="User").json() == actor["user"] + + +def test_duplicate_username_is_409(api): + actor = api.register("dup") + body = {"username": actor["username"], "display_name": "Другой", "password": PASSWORD} + assert api.call("POST", "/api/v1/users", 409, json_body=body).json()["error"]["code"] == "conflict" + + +@pytest.mark.parametrize("password", ["short-11ch", " " * 12, " \t \n " * 3, "я" * 129]) +def test_bad_password_on_registration_is_400(api, password): + body = {"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "x", "password": password} + api.call("POST", "/api/v1/users", 400, json_body=body) + + +@pytest.mark.parametrize("password", ["я" * 128, "with:colons:inside", "Twelve chars"]) +def test_edge_passwords_register_and_login(api, password): + actor = api.user("edge", password=password) + api.call("GET", "/api/v1/users/me", 200, token=actor["token"]) + + +def test_wrong_password_and_unknown_user_give_the_same_401(api): + actor = api.register("victim") + wrong = api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(actor["username"], "Wrong-password-1")}) + unknown = api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("nobody_" + uuid.uuid4().hex[:8], PASSWORD)}) + assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"] + assert wrong.headers["www-authenticate"] == 'Basic realm="messenger", charset="UTF-8"' + + +@pytest.mark.parametrize("header", ["Basic é", "Basic !!!", "Basic " + base64.b64encode(b"no_colon").decode(), + "Basic " + base64.b64encode(b"\xff\xfe:x").decode(), "Bearer " + "a" * 43, ""]) +def test_malformed_basic_is_401_not_500(api, header): + # Raw UTF-8 bytes, as curl would send them (httpx refuses non-ASCII str headers). + api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": header.encode("utf-8")} if header else {}) + + +def test_logout_revokes_only_this_token(api): + actor = api.user("logout") + second = api.login(actor) + api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=actor["token"]) + api.call("GET", "/api/v1/users/me", 401, token=actor["token"]) + api.call("DELETE", "/api/v1/auth/sessions/current", 401, token=actor["token"]) + api.call("GET", "/api/v1/users/me", 200, token=second) # other session of the same user survives + + +def test_x_user_id_basic_and_garbage_do_not_authenticate(api): + actor = api.user("hdr") + for headers in ({"X-User-Id": actor["id"]}, + {"Authorization": basic(actor["username"], PASSWORD)}, + {"Authorization": "Bearer " + "A" * 43}, + {"Authorization": "Bearer"}): + api.call("GET", "/api/v1/users/me", 401, headers=headers) + me = api.call("GET", "/api/v1/users/me", 200, token=actor["token"], headers={"X-User-Id": str(uuid.uuid4())}) + assert me.json()["id"] == actor["id"] + + +# ================================================================== validation / errors (from lab 1) +@pytest.mark.parametrize("raw", [b"{", b"", b"[]", b"null", b'{"username": "abc_def", "display_name": NaN, "password": "Twelve-chars"}', + b'{"username": "abc_def", "display_name": "x", "password": "Twelve-chars"}{"a": 1}', + b'{"username": "abc_def", "display_name": "\\ud800", "password": "Twelve-chars"}']) +def test_malformed_json_is_400(api, raw): + api.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"}) + + +@pytest.mark.parametrize("body", [ + {"username": "abc_def", "display_name": "x"}, # no password + {"username": "abc_def", "display_name": "x", "password": "Twelve-chars", "extra": 1}, + {"username": "Abc_def", "display_name": "x", "password": "Twelve-chars"}, + {"username": "abc_def", "display_name": " ", "password": "Twelve-chars"}, + {"username": "abc_def", "display_name": "x" * 101, "password": "Twelve-chars"}, + {"username": 5, "display_name": "x", "password": "Twelve-chars"}, +]) +def test_invalid_registration_fields_are_400(api, body): + api.call("POST", "/api/v1/users", 400, json_body=body) + + +def test_unicode_limits_are_code_points_and_nul_is_stored(api): + actor = api.user("uni", display_name="😀" * 100) + assert actor["user"]["display_name"] == "😀" * 100 + nul = api.user("nul", display_name="A\u0000B") + assert api.call("GET", "/api/v1/users/me", 200, token=nul["token"]).json()["display_name"] == "A\u0000B" + chat = api.chat(actor, title="T\u0000itle") + assert chat["title"] == "T\u0000itle" + assert api.send(actor, chat, "hello\u0000world")["text"] == "hello\u0000world" + assert api.send(actor, chat, "🙂" * 4000)["text"] == "🙂" * 4000 + api.post_message(actor, chat, {"text": "я" * 4001}, 400) + texts = [m["text"] for m in api.history(actor, chat, 100)[0]] + assert texts == ["hello\u0000world", "🙂" * 4000] + + +def test_oversized_body_and_wrong_content_type(api): + api.call("POST", "/api/v1/users", 413, json_body={"username": "big_body", "display_name": "x" * 70_000, "password": PASSWORD}) + api.call("POST", "/api/v1/users", 400, raw=b'{"username":"abc_def"}', headers={"Content-Type": "text/plain"}) + + +# ================================================================== chats & membership +def test_chat_validation(api): + alice, bob = api.user("alice"), api.user("bob") + for body in ({"title": "x", "member_ids": [alice["id"], bob["id"], bob["id"]]}, + {"title": "x", "member_ids": [alice["id"], str(uuid.uuid4())]}, + {"title": "x", "member_ids": [bob["id"]]}, + {"title": " ", "member_ids": [alice["id"]]}, + {"title": "x", "member_ids": [alice["id"], "bob"]}): + api.call("POST", "/api/v1/chats", 400, token=alice["token"], json_body=body) + + +def test_foreign_chat_is_indistinguishable_from_missing(api): + alice, bob, eve = api.user("alice"), api.user("bob"), api.user("eve") + chat = api.chat(alice, bob) + for chat_id in (chat["id"], str(uuid.uuid4())): + base = f"/api/v1/chats/{chat_id}" + errors = [api.call("GET", base, 404, token=eve["token"]).json(), + api.call("GET", base + "/messages", 404, token=eve["token"]).json(), + api.call("POST", base + "/messages", 404, token=eve["token"], json_body={"text": "чужое"}, headers={"Idempotency-Key": "k1"}).json(), + api.call("GET", base + "/messages?cursor=garbage", 404, token=eve["token"]).json()] + assert len({e["error"]["message"] for e in errors}) == 1 + api.call("GET", "/api/v1/chats/not-a-uuid", 401) + api.call("GET", "/api/v1/chats/not-a-uuid", 400, token=alice["token"]) + api.call("GET", "/api/v1/chats/NOT-A-UUID/messages", 400, token=alice["token"]) + + +def test_chat_list_order_pagination_and_isolation(api): + alice, bob, eve = api.user("alice"), api.user("bob"), api.user("eve") + created = [api.chat(alice, bob, title=f"Чат {i}") for i in range(5)] + api.chat(eve, title="Чат Евы") + walked, cursor = [], None + while True: + query = "?limit=2" + (f"&cursor={cursor}" if cursor else "") + page = api.call("GET", "/api/v1/chats" + query, 200, token=bob["token"], schema="ChatPage").json() + walked += page["items"] + cursor = page["next_cursor"] + if not cursor: + break + assert walked == created + first = api.call("GET", "/api/v1/chats?limit=1", 200, token=alice["token"]).json()["next_cursor"] + api.call("GET", f"/api/v1/chats?limit=1&cursor={first}", 400, token=bob["token"]) # cursor of another user + api.call("GET", "/api/v1/chats?limit=0", 400, token=bob["token"]) + + +# ================================================================== messages & keyset pagination +def test_history_pages_without_loss_or_duplicates(api): + alice, bob = api.user("alice"), api.user("bob") + chat = api.chat(alice, bob) + sent = [api.send(alice if i % 2 else bob, chat, f"сообщение {i}") for i in range(25)] + items, pages = api.history(bob, chat, 7) + assert pages == 4 and items == sent and items == sorted(items, key=key) + assert sent[0]["sender_id"] == bob["id"] and sent[1]["sender_id"] == alice["id"] + + +@pytest.mark.parametrize("query", ["limit=0", "limit=101", "limit=abc", "limit=1&limit=2", "cursor=", "cursor=garbage", + "cursor=djF8bXx4fDF8Mg", "cursor=" + base64.urlsafe_b64encode(b"v1|m|x|99999999999999999999|y").decode()]) +def test_bad_limit_or_cursor_is_400(api, query): + alice = api.user("alice") + chat = api.chat(alice) + api.call("GET", f"/api/v1/chats/{chat['id']}/messages?{query}", 400, token=alice["token"]) + + +def test_cursor_bound_to_chat(api): + alice = api.user("alice") + a, b = api.chat(alice, title="A"), api.chat(alice, title="B") + for chat in (a, b): + api.send(alice, chat, "1") + api.send(alice, chat, "2") + cursor = api.call("GET", f"/api/v1/chats/{a['id']}/messages?limit=1", 200, token=alice["token"]).json()["next_cursor"] + api.call("GET", f"/api/v1/chats/{b['id']}/messages?cursor={cursor}", 400, token=alice["token"]) + empty = api.chat(alice, title="Empty") + api.call("GET", f"/api/v1/chats/{empty['id']}/messages?cursor=garbage", 400, token=alice["token"]) + + +def test_read_after_write(api): + alice, bob = api.user("alice"), api.user("bob") + chat = api.chat(alice, bob) + for i in range(5): + message = api.send(alice, chat, f"m{i}") + last = api.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", 200, token=bob["token"]).json()["items"][-1] + assert last == message + + +# ================================================================== lab 3: inputs found by the reviewer in other PRs +def b64(raw: bytes) -> str: + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() + + +def bad_cursors(owner_id: str) -> list[str]: + """Wrong types/values inside the cursor, empty and whitespace cursors, out-of-range time.""" + good_uuid = str(uuid.uuid4()) + return ["", " ", "%20", "garbage", b64(b"[]"), b64(b"{}"), b64(b"123"), b64(b"false"), b64(b"null"), + b64(b'{"created_at":1,"id":1}'), b64(b'{"created_at":null,"id":"x"}'), + b64(f"v1|m|{owner_id}|1|1".encode()), b64(f"v1|c|{owner_id}|1|1".encode()), + b64(f"v1|m|{owner_id}|abc|{good_uuid}".encode()), b64(f"v1|m|{owner_id}|-1|{good_uuid}".encode()), + b64(f"v1|m|{owner_id}|9223372036854775807|{good_uuid}".encode()), + b64(f"v1|c|{owner_id}|9223372036854775807|{good_uuid}".encode()), + b64(f"v1|m|{owner_id}|1|{good_uuid.upper()}".encode()), b64(f"v2|m|{owner_id}|1|{good_uuid}".encode())] + + +def test_malformed_cursor_values_are_400_on_both_lists(api): + alice = api.user("cur") + chat = api.chat(alice) + for cursor in bad_cursors(chat["id"]) + bad_cursors(alice["id"]): + quoted = cursor if cursor in ("", "%20") else cursor.replace(" ", "%20") + for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"): + error = api.call("GET", f"{path}?cursor={quoted}", 400, token=alice["token"]).json() + assert error["error"]["code"] == "invalid_request", (path, cursor) + + +@pytest.mark.parametrize("raw", [b"\xff", b'{"text":"first","TEXT":"second"}', b'{"text":"a","text":"b"}', + b'{"text":123}', b'{"text":"valid"}}', b'{"text":"valid"}]', b'{"text":"x"} {}', + b'{"text":"x","sender_id":"11111111-1111-4111-8111-111111111111"}', + b'{"text":"x","attachment_ids":null}', b'{"text":"x","attachment_ids":["nope"]}', + b'{"text":" \n\t "}']) +def test_bad_message_body_is_400_and_nothing_is_stored(api, raw): + alice = api.user("body") + chat = api.chat(alice) + error = api.post_message(alice, chat, None, 400, raw=raw).json() + assert error["error"]["code"] == "invalid_request" + assert api.history(alice, chat, 100)[0] == [] + + +def test_ff_byte_body_on_registration_is_contract_error(api): + response = api.call("POST", "/api/v1/users", 400, raw=b"\xff", headers={"Content-Type": "application/json"}) + assert response.json()["error"]["request_id"] == response.headers["x-request-id"] + + +def test_text_is_stored_verbatim_and_length_counts_raw_text(api): + alice = api.user("verbatim") + chat = api.chat(alice) + padded = " строка\nс пробелами " + assert api.send(alice, chat, padded)["text"] == padded + api.post_message(alice, chat, {"text": " " + "a" * 4000}, 400) # 4001 code points before any trimming + assert [m["text"] for m in api.history(alice, chat, 100)[0]] == [padded] + + +def test_unknown_attachment_ids_are_404(api): + alice = api.user("att") + chat = api.chat(alice) + api.post_message(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())]}, 404) + api.post_message(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())] * 2}, 400) # duplicates + assert api.history(alice, chat, 100)[0] == [] + + +def test_member_ids_are_compared_as_uuids_not_strings(api): + alice, bob = api.user("case"), api.user("case") + api.call("POST", "/api/v1/chats", 400, token=alice["token"], + json_body={"title": "x", "member_ids": [alice["id"], alice["id"].upper()]}) + api.call("POST", "/api/v1/chats", 400, token=alice["token"], + json_body={"title": "x", "member_ids": [alice["id"], bob["id"]], "id": str(uuid.uuid4())}) + chat = api.call("POST", "/api/v1/chats", 201, token=alice["token"], + json_body={"title": "x", "member_ids": [alice["id"].upper(), bob["id"]]}, schema="Chat").json() + assert chat["member_ids"] == [alice["id"], bob["id"]] + + +@pytest.mark.parametrize("header", ["Bearer é", "Bearer .", "Bearer a b", "Bearer " + "é" * 43, "bearer\t" + "a" * 43]) +def test_non_ascii_or_garbage_bearer_is_401_not_500(api, header): + api.call("GET", "/api/v1/users/me", 401, headers={"Authorization": header.encode("utf-8")}) + + +def test_login_with_a_body_is_rejected(api): + actor = api.register("login_body") + auth = {"Authorization": basic(actor["username"], actor["password"])} + api.call("POST", "/api/v1/auth/sessions", 400, raw=b'{"extra":1}', headers={**auth, "Content-Type": "application/json"}) + api.call("POST", "/api/v1/auth/sessions", 400, raw=b"x", headers=auth) + api.call("POST", "/api/v1/auth/sessions", 201, headers=auth, schema="Session") + + +def test_password_range_is_12_to_128_code_points(api): + api.call("POST", "/api/v1/users", 400, json_body={"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "x", "password": "a"}) + actor = api.user("pw128", password="я:" * 64) + api.call("GET", "/api/v1/users/me", 200, token=actor["token"]) + + +def test_every_api_response_carries_instance_and_request_id(api): + """X-Instance-Id also on 404 of unknown routes, 405, 401, 400 and health (Api.call asserts it).""" + api.call("GET", "/health/live", 200) + api.call("GET", "/health/ready", 200) + api.call("GET", "/no/such/route", 404) + api.call("PUT", "/api/v1/users", 405) + api.call("GET", "/api/v1/users/me", 401) + response = api.call("GET", "/api/v1/users/me", 401, headers={"X-Request-Id": "client-supplied.id-1"}) + assert response.headers["x-request-id"] == "client-supplied.id-1" # one id from LB log to API log + + +@pytest.mark.parametrize("blank", [" ", "  ", "  \t "]) +def test_unicode_whitespace_only_strings_are_400(api, blank): + alice = api.user("blank") + chat = api.chat(alice) + api.call("POST", "/api/v1/users", 400, json_body={"username": "bl_" + uuid.uuid4().hex[:10], "display_name": blank, + "password": PASSWORD}) + api.call("POST", "/api/v1/chats", 400, token=alice["token"], json_body={"title": blank, "member_ids": [alice["id"]]}) + api.post_message(alice, chat, {"text": blank}, 400) + assert api.history(alice, chat, 100)[0] == [] + + +@pytest.mark.parametrize("raw", [b'{"username":"num_probe","display_name":"x","password":1e1000}', + '{"username":"ff_probe","display_name":"x","password":"12345678901'.encode() + b'\xff"}', + b'{"username":"num_probe","display_name":1,"password":"Twelve-chars-ok"}']) +def test_odd_registration_bodies_are_400_and_the_api_survives(api, raw): + api.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"}) + api.call("GET", "/health/ready", 200) + + +def test_more_than_100_members_is_400(api): + owner = api.user("big") + others = [api.register(f"m{i}")["id"] for i in range(100)] + api.call("POST", "/api/v1/chats", 400, token=owner["token"], json_body={"title": "x", "member_ids": [owner["id"], *others]}) + chat = api.call("POST", "/api/v1/chats", 201, token=owner["token"], + json_body={"title": "x", "member_ids": [owner["id"], *others[:99]]}, schema="Chat").json() + assert len(chat["member_ids"]) == 100 + + +def test_cursor_of_one_list_is_rejected_by_the_other(api): + alice = api.user("cross") + chats = [api.chat(alice, title=f"c{i}") for i in range(2)] + for _ in range(2): + api.send(alice, chats[0], "m") + message_cursor = api.call("GET", f"/api/v1/chats/{chats[0]['id']}/messages?limit=1", 200, + token=alice["token"]).json()["next_cursor"] + chat_cursor = api.call("GET", "/api/v1/chats?limit=1", 200, token=alice["token"]).json()["next_cursor"] + api.call("GET", f"/api/v1/chats?cursor={message_cursor}", 400, token=alice["token"]) + api.call("GET", f"/api/v1/chats/{chats[0]['id']}/messages?cursor={chat_cursor}", 400, token=alice["token"]) diff --git a/student-tests/test_attachments.py b/student-tests/test_attachments.py new file mode 100644 index 0000000..7bd6113 --- /dev/null +++ b/student-tests/test_attachments.py @@ -0,0 +1,291 @@ +"""Attachments through the load balancer (lab 4, levels 3 and 4; lab 5: upload is 202 queued and +the worker publishes the original + variants): upload/download, ACL, limits, content checks, +filename rules and messages with attachment_ids. + +Negative inputs include every case the reviewer used against other lab 4 solutions: corrupted +IDAT with valid CRCs, the first 33 bytes of the fixture, JPEG without scan data, a 20000x10000 +header (DecompressionBomb), exactly 10 MiB through the LB, C1 control U+0085 and a whitespace +filename, text=null / missing text / attachment_ids=null in a message; and the lab 4/5 review +cases: PNG row filter 5 and 0xff, IDAT that is not a zlib stream, the 27-byte JPEG without tables +and scan data, a JPEG whose SOS names a component missing from SOF - all 415 AT UPLOAD, never +202 followed by failed/invalid_image.""" +from __future__ import annotations + +import hashlib +import subprocess +import time +import uuid +from pathlib import Path + +import pytest + +import imagegen +from conftest import attachment_row, compose, s3_size + +pytestmark = pytest.mark.stack + +ROOT = Path(__file__).resolve().parents[1] +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() +MiB = 1024 * 1024 + + +@pytest.fixture() +def trio(api): + """alice + bob share a chat; eve is an outsider with her own chat.""" + alice, bob, eve = api.user("alice"), api.user("bob"), api.user("eve") + return alice, bob, eve, api.chat(alice, bob), api.chat(eve) + + +def content(api, actor, attachment_id, expected=200, query=""): + return api.call("GET", f"/api/v1/attachments/{attachment_id}/content{query}", expected, token=actor["token"]) + + +# ------------------------------------------------------------------ positive path +def test_png_and_jpeg_roundtrip_byte_for_byte(api, trio): + alice, bob, _, chat, _ = trio + jpg = imagegen.jpeg(321, 123, noise=True) + for data, ctype in ((SAMPLE, "image/png"), (jpg, "image/jpeg")): + att = api.upload(alice, chat, data, content_type=ctype, filename="кот 😺.bin").json() + assert att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None + assert att["chat_id"] == chat["id"] and att["owner_id"] == alice["id"] + assert att["size_bytes"] == len(data) and att["sha256"] == hashlib.sha256(data).hexdigest() + assert att["content_type"] == ctype and att["filename"] == "кот 😺.bin" + meta = api.wait_status(bob, att["id"], "ready") + assert {k: v for k, v in meta.items() if k not in ("status", "variants", "updated_at")} == \ + {k: v for k, v in att.items() if k not in ("status", "variants", "updated_at")} + assert [v["name"] for v in meta["variants"]] == ["thumbnail", "crop", "optimized"] + got = content(api, bob, att["id"]) + assert got.content == data and got.headers["content-type"] == ctype + assert got.headers["content-length"] == str(len(data)) + assert got.headers["x-content-type-options"] == "nosniff" + assert got.headers["content-disposition"].startswith("attachment;") + assert "location" not in got.headers # bytes through the API, never a redirect to S3 + + +def test_metadata_reveals_no_storage_details(api, trio): + alice, _, _, chat, _ = trio + att = api.upload(alice, chat, SAMPLE).json() + api.wait_status(alice, att["id"], "ready") + row = attachment_row(att["id"]) + assert row["status"] == "ready" and row["object_key"].startswith(f"a/{att['id']}/") + assert row["staging_key"].startswith("s/") + text = api.call("GET", f"/api/v1/attachments/{att['id']}", 200, token=alice["token"]).text + for secret in (row["object_key"], row["staging_key"], "messenger-attachments", "messenger-staging", "a/", "s3"): + assert secret not in text.lower(), secret + # The staging key is random: neither the id nor the filename is part of it. + assert att["id"].replace("-", "") not in row["staging_key"] and "photo" not in row["staging_key"] + assert s3_size(row["object_key"]) == len(SAMPLE) # the published original IS in the final bucket + + +def test_original_is_not_stored_on_api_containers(api, trio): + """The API keeps no file of the original: no recently written file of that size anywhere in + the replica's filesystem (the bytes live only in the bucket).""" + alice, _, _, chat, _ = trio + data = imagegen.png_of_size(300_000) + api.upload(alice, chat, data) + size = len(data) + for cid in compose("ps", "-q", "api").stdout.split(): + out = subprocess.run( + ["docker", "exec", cid, "sh", "-c", f"find / -xdev -type f -size {size}c -mmin -10 2>/dev/null | head"], + capture_output=True, text=True, timeout=60).stdout.strip() + assert out == "", out + + +# ------------------------------------------------------------------ access control +def test_outsider_and_unknown_get_404(api, trio): + alice, _, eve, chat, _ = trio + att = api.upload(alice, chat, SAMPLE).json() + for suffix in ("", "/content"): + api.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 404, token=eve["token"]) + api.call("GET", f"/api/v1/attachments/{uuid.uuid4()}{suffix}", 404, token=alice["token"]) + api.call("GET", f"/api/v1/attachments/not-a-uuid{suffix}", 400, token=alice["token"]) + api.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 401) + # Upload into a foreign chat: 404 before anything about the body is looked at. + api.upload(eve, chat, SAMPLE, 404) + api.upload(eve, chat, b"garbage", 404, content_type="text/plain") + + +def test_attachment_ids_are_checked_per_chat(api, trio): + alice, bob, eve, chat, eve_chat = trio + other = api.chat(alice) # alice's second chat + att_other = api.upload(alice, other, SAMPLE).json() + att_eve = api.upload(eve, eve_chat, SAMPLE).json() + # Alice is a member of both chats, but a file is bound to its chat. + api.post_message(alice, chat, {"text": "x", "attachment_ids": [att_other["id"]]}, 404) + api.post_message(alice, chat, {"text": "x", "attachment_ids": [att_eve["id"]]}, 404) + api.post_message(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())]}, 404) + # Eve cannot post into alice's chat even with her own file: membership first. + api.post_message(eve, chat, {"text": "x", "attachment_ids": [att_eve["id"]]}, 404) + # Any member may reference an attachment of the chat. + att = api.upload(alice, chat, SAMPLE).json() + msg = api.post_message(bob, chat, {"text": "", "attachment_ids": [att["id"]]}).json() + assert msg["attachment_ids"] == [att["id"]] and msg["sender_id"] == bob["id"] + + +# ------------------------------------------------------------------ messages with attachments +def test_message_with_attachments_and_history(api, trio): + alice, bob, _, chat, _ = trio + a1, a2 = (api.upload(alice, chat, SAMPLE).json()["id"] for _ in range(2)) + m1 = api.post_message(alice, chat, {"text": "", "attachment_ids": [a2, a1]}).json() + m2 = api.post_message(alice, chat, {"text": " ", "attachment_ids": [a1]}).json() # blank text + file: ok + m3 = api.post_message(alice, chat, {"text": "без файлов"}).json() + assert m1["attachment_ids"] == [a2, a1] and m1["text"] == "" + assert m2["text"] == " " and m3["attachment_ids"] == [] + items, _ = api.history(bob, chat, 2) + assert [m["attachment_ids"] for m in items] == [[a2, a1], [a1], []] + + +def test_idempotent_replay_with_attachments(api, trio): + alice, _, _, chat, _ = trio + a1, a2 = (api.upload(alice, chat, SAMPLE).json()["id"] for _ in range(2)) + key = uuid.uuid4().hex + first = api.post_message(alice, chat, {"text": "файлы", "attachment_ids": [a1, a2]}, key=key).json() + raw = ('{"attachment_ids":["%s","%s"],"text":"файлы"}' % (a1, a2)).encode() + assert api.post_message(alice, chat, None, raw=raw, key=key).json() == first # key order irrelevant + api.post_message(alice, chat, {"text": "файлы", "attachment_ids": [a2, a1]}, 409, key=key) # other body + api.post_message(alice, chat, {"text": "файлы"}, 409, key=key) + # A failed attachment check does not burn the key: the same key works with a valid body later. + key2 = uuid.uuid4().hex + api.post_message(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())]}, 404, key=key2) + api.post_message(alice, chat, {"text": "x", "attachment_ids": [a1]}, key=key2) + + +@pytest.mark.parametrize("raw", [ + b'{"attachment_ids":["%(a)s"]}', # text missing + b'{"text":null,"attachment_ids":["%(a)s"]}', # text null + b'{"text":1,"attachment_ids":["%(a)s"]}', + b'{"text":"x","attachment_ids":null}', # attachment_ids null + b'{"text":"x","attachment_ids":"%(a)s"}', + b'{"text":"x","attachment_ids":{}}', + b'{"text":"x","attachment_ids":["%(a)s","%(a)s"]}', # duplicates + b'{"text":"x","attachment_ids":["%(a)s",1]}', + b'{"text":"x","attachment_ids":["not-a-uuid"]}', + b'{"text":"","attachment_ids":[]}', # neither text nor files + b'{"text":" "}', + b'{"text":"x","attachment_ids":[],"sender_id":"%(a)s"}', +], ids=lambda raw: raw.decode()[:40]) +def test_message_body_validation(api, trio, raw): + alice, _, _, chat, _ = trio + a = api.upload(alice, chat, SAMPLE).json()["id"] + api.post_message(alice, chat, None, 400, raw=raw % {b"a": a.encode()}) + + +def test_at_most_ten_attachments(api, trio): + alice, _, _, chat, _ = trio + ids = [api.upload(alice, chat, imagegen.png(4, 4)).json()["id"] for _ in range(11)] + assert len(api.post_message(alice, chat, {"text": "", "attachment_ids": ids[:10]}).json()["attachment_ids"]) == 10 + api.post_message(alice, chat, {"text": "", "attachment_ids": ids}, 400) + + +# ------------------------------------------------------------------ limits +def test_size_limit_through_the_load_balancer(api, trio): + alice, bob, _, chat, _ = trio + exact = imagegen.png_exactly(10 * MiB) + assert len(exact) == 10 * MiB + att = api.upload(alice, chat, exact).json() # exactly the limit: accepted via LB + api.wait_status(bob, att["id"], "ready") + assert content(api, bob, att["id"]).content == exact + started = time.monotonic() + api.upload(alice, chat, exact + b"\x00", 413) # Content-Length over the limit + assert time.monotonic() - started < 5 + over = exact + bytes(1024) + + def chunks(): # no Content-Length: chunked body + for i in range(0, len(over), 256 * 1024): + yield over[i:i + 256 * 1024] + error = api.upload(alice, chat, chunks(), 413).json() + assert error["error"]["code"] == "payload_too_large" + + +def test_pixel_limit_before_decoding(api, trio): + alice, _, _, chat, _ = trio + for data, ctype in ((imagegen.png_bomb_header(), "image/png"), (imagegen.jpeg_bomb_header(), "image/jpeg"), + (imagegen.PNG_SIGNATURE + imagegen.ihdr(8001, 5000), "image/png")): + started = time.monotonic() + assert api.upload(alice, chat, data, 413, content_type=ctype).json()["error"]["code"] == "payload_too_large" + assert time.monotonic() - started < 2 # refused from the header, nothing decoded + + +def test_exactly_40_megapixels_is_accepted(api, trio): + alice, _, _, chat, _ = trio + data = imagegen.png(8000, 5000, compress_level=9) # 40 000 000 px, ~120 KB file + att = api.upload(alice, chat, data).json() + assert att["size_bytes"] == len(data) + # Lab 5: the worker processes the biggest allowed picture within its memory limit. + ready = api.wait_status(alice, att["id"], "ready", timeout=120) + assert {v["name"]: (v["width"], v["height"]) for v in ready["variants"]} == \ + {"thumbnail": (256, 160), "crop": (128, 128), "optimized": (1280, 800)} + + +# ------------------------------------------------------------------ content checks +BROKEN = { + "png: first 33 bytes of the fixture": (SAMPLE[:33], "image/png"), + "png: truncated": (SAMPLE[:-20], "image/png"), + "png: corrupt IDAT, valid CRC": (imagegen.png_corrupt_idat(), "image/png"), + "png: fewer rows than IHDR": (imagegen.png_short_pixels(), "image/png"), + "png: flipped byte": (SAMPLE[:700] + bytes([SAMPLE[700] ^ 0x5A]) + SAMPLE[701:], "image/png"), + "png: bytes after IEND": (SAMPLE + b"", "image/png"), + "jpeg: no scan data after SOS": (imagegen.jpeg_without_scan_data(), "image/jpeg"), + "jpeg: truncated": (imagegen.jpeg(400, 300, noise=True)[:5000], "image/jpeg"), + "review: png row filter 5": (imagegen.png_bad_filter(5), "image/png"), + "review: png row filter 0xff": (imagegen.png_bad_filter(0xFF), "image/png"), + "review: png IDAT not-a-zlib-stream": (imagegen.png_idat_not_zlib(), "image/png"), + "review: jpeg 27 bytes, no tables/scan": (imagegen.JPEG_27_BYTES, "image/jpeg"), + "review: jpeg SOS component not in SOF": (imagegen.jpeg_sos_unknown_component(), "image/jpeg"), + "mime: png bytes declared jpeg": (SAMPLE, "image/jpeg"), + "mime: jpeg bytes declared png": (imagegen.jpeg(), "image/png"), + "mime: gif declared png": (b"GIF89a" + bytes(100), "image/png"), + "mime: html declared png": (b"", "image/png"), + "type: text/plain": (SAMPLE, "text/plain"), + "type: octet-stream": (SAMPLE, "application/octet-stream"), + "type: multipart": (SAMPLE, "multipart/form-data; boundary=x"), + "type: missing": (SAMPLE, None), +} + + +@pytest.mark.parametrize("name", list(BROKEN)) +def test_bad_content_is_415(api, trio, name): + alice, _, _, chat, _ = trio + data, ctype = BROKEN[name] + error = api.upload(alice, chat, data, 415, content_type=ctype).json() + assert error["error"]["code"] == "unsupported_media_type" + + +def test_empty_body_is_400(api, trio): + alice, _, _, chat, _ = trio + api.upload(alice, chat, b"", 400) + + +# ------------------------------------------------------------------ filename +@pytest.mark.parametrize("query", [ + "", "filename=", "filename=%20%20%20", "filename=.", "filename=..", "filename=a%2Fb.png", "filename=a%5Cb.png", + "filename=a%00b.png", "filename=c1%C2%85.png", "filename=tab%09.png", "filename=photo%E2%80%AEgnp.exe", + "filename=%FF%FE.png", "filename=a.png&filename=b.png", "filename=" + "a" * 256, +], ids=lambda q: q[:40] or "missing") +def test_bad_filename_is_400(api, trio, query): + alice, _, _, chat, _ = trio + api.upload(alice, chat, SAMPLE, 400, query=query) + + +def test_unicode_filename_is_kept_and_safely_exposed(api, trio): + alice, _, _, chat, _ = trio + name = 'отчёт "Q3"; ok.png' + att = api.upload(alice, chat, SAMPLE, filename=name).json() + assert att["filename"] == name + api.wait_status(alice, att["id"], "ready") + disposition = content(api, alice, att["id"]).headers["content-disposition"] + assert '"' not in disposition.split('filename="')[1].split('";')[0] # quotes neutralised in the fallback + assert "filename*=UTF-8''" in disposition + + +# ------------------------------------------------------------------ variants +def test_variant_parameter(api, trio): + alice, _, eve, chat, _ = trio + att = api.upload(alice, chat, SAMPLE).json() + api.wait_status(alice, att["id"], "ready") + assert content(api, alice, att["id"], query="?variant=original").content == SAMPLE + assert content(api, alice, att["id"], query="?variant=thumbnail").headers["content-type"] == "image/jpeg" + content(api, alice, att["id"], 400, query="?variant=huge") + content(api, alice, att["id"], 400, query="?variant=thumbnail&variant=crop") + content(api, eve, att["id"], 404, query="?variant=thumbnail") # outsider: 404, nothing revealed + content(api, eve, att["id"], 404, query="?variant=huge") # outsider first, then the value diff --git a/student-tests/test_balancing.py b/student-tests/test_balancing.py new file mode 100644 index 0000000..6ee08bc --- /dev/null +++ b/student-tests/test_balancing.py @@ -0,0 +1,354 @@ +"""Load balancer, replicas and graceful shutdown (lab 3, levels 3 and 4). + +Each test that stops, kills, rescales or isolates a replica restores the stand in `finally` +and waits until HAProxy reports every replica UP again (conftest.wait_stand). +""" +from __future__ import annotations + +import contextlib +import json +import subprocess +import threading +import time +import uuid + +import httpx2 as httpx +import pytest + +from conftest import BASE_URL, REPLICAS, Api, compose, lbctl, probe_inside, psql, replica_stopped, run_hook, \ + running_replicas, wait_healthy, wait_stand + +pytestmark = pytest.mark.stack + + +def instances_seen(api: Api, token: str, requests: int = 40) -> list[str]: + return [api.call("GET", "/api/v1/users/me", 200, token=token).headers["x-instance-id"] for _ in range(requests)] + + +# ------------------------------------------------------------------ level 3: replicas, no affinity +def test_one_session_is_served_by_every_real_replica(api): + actor = api.user("rr") + seen = instances_seen(api, actor["token"]) + running = {r["hostname"] for r in running_replicas()} + assert len(running) == REPLICAS >= 2 + assert set(seen) == running, "X-Instance-Id values must be exactly the hostnames of the running containers" + # Round robin on ONE keep-alive client connection: consecutive requests switch replicas, + # so there is no sticky session hiding split state. + switches = sum(1 for a, b in zip(seen, seen[1:]) if a != b) + assert switches >= len(seen) // 2, seen + assert {s["instance_id"] for s in lbctl.lb_servers() if s["state"] == "UP"} == running + + +def test_write_on_one_replica_is_read_on_the_other(api): + alice, bob = api.user("rw"), api.user("rw") + chat = api.chat(alice, bob) + for i in range(10): + sent = api.post_message(alice, chat, {"text": f"m{i}"}) + read = api.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", 200, token=bob["token"]) + assert read.json()["items"][-1] == sent.json() + logout = api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=alice["token"]) + for _ in range(6): # the revocation is visible on every replica at once (shared Valkey) + r = api.call("GET", "/api/v1/users/me", 401, token=alice["token"]) + assert r.headers["x-instance-id"] + assert logout.headers["x-instance-id"] + + +# ------------------------------------------------------------------ readiness drives the LB +def hba_file() -> str: + return psql("SHOW hba_file") + + +@contextlib.contextmanager +def isolated_from_postgres(replica: dict): + """Make ONE replica unable to reach PostgreSQL (pg_hba reject for its IP + terminate its + connections), while it keeps running and answering /health/live. Always undone.""" + ip = replica["networks"]["data"] # PostgreSQL sees the replica's address on the data network + path = hba_file() + marker = "lab3-test-isolate" + compose("exec", "-T", "postgres", "sh", "-c", f"sed -i '1i host all all {ip}/32 reject # {marker}' {path}") + try: + psql("SELECT pg_reload_conf()") + psql(f"SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity WHERE client_addr = '{ip}'") + yield replica + finally: + compose("exec", "-T", "postgres", "sh", "-c", f"sed -i '/{marker}/d' {path}") + psql("SELECT pg_reload_conf()") + lbctl.wait_up(REPLICAS, timeout=15) # self-heals: no restart of the replica needed + wait_stand() + + +@contextlib.contextmanager +def disconnected_from_data_network(replica: dict): + """`docker network disconnect _data `: the replica keeps its edge link to the + LB but loses PostgreSQL AND Valkey. Always reconnected.""" + network = next(n for n in json.loads(subprocess.run( + ["docker", "inspect", "-f", "{{json .NetworkSettings.Networks}}", replica["id"]], + capture_output=True, text=True, check=True).stdout) if n.endswith("_data")) + subprocess.run(["docker", "network", "disconnect", network, replica["id"]], check=True, capture_output=True) + try: + yield + finally: + subprocess.run(["docker", "network", "connect", network, replica["id"]], check=True, capture_output=True) + lbctl.wait_up(REPLICAS, timeout=15) # self-heals: dead sockets are dropped (tcp_user_timeout) + wait_stand() + + +@pytest.mark.parametrize("how", ["pg_hba", "network"]) +@pytest.mark.parametrize("position", range(REPLICAS)) +def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position, how): + """The reviewers' scenarios: one API loses PostgreSQL (pg_hba reject) or its whole data + network (docker network disconnect) but keeps running. /health/live 200, /health/ready + 503 -> HAProxy must take it out; no business request may reach it.""" + replica = sorted(running_replicas(), key=lambda r: r["name"])[position] + actor = api.user("ready") + isolate = isolated_from_postgres if how == "pg_hba" else disconnected_from_data_network + with isolate(replica): + started = time.monotonic() + while replica["hostname"] in lbctl.up_instances(): + assert time.monotonic() - started < 5, "HAProxy did not mark the unready replica DOWN within 5 s" + time.sleep(0.1) + detected = time.monotonic() - started + for _ in range(3): # the process stays responsive (event loop never blocked) ... + started_probe = time.monotonic() + assert probe_inside(replica, "/health/live") == 200 + assert probe_inside(replica, "/health/ready") == 503 # ... but not ready + assert time.monotonic() - started_probe < 4.5, "replica froze while its dependencies were unreachable" + seen = instances_seen(api, actor["token"], 40) + assert replica["hostname"] not in seen and len(seen) == 40 + for i in range(20): # writes keep working, only through the ready replicas + assert api.register(f"r{i}")["id"] + print(f"{replica['name']} ({how}): unready replica out of rotation after {detected:.2f} s") + + +# ------------------------------------------------------------------ stopping replicas under traffic +class Traffic: + """Background writers/readers through the LB; uncertain POSTs are retried with the SAME key.""" + + def __init__(self, api: Api, workers: int = 4): + self.alice, self.bob = api.user("load"), api.user("load") + self.chat = api.chat(self.alice, self.bob) + self.workers = workers + self.stop = threading.Event() + self.lock = threading.Lock() + self.events: list[tuple[float, str, int, str | None]] = [] # (time, kind, status, instance) + self.confirmed: list[dict] = [] + self.threads = [threading.Thread(target=self.run, args=(i,), daemon=True) for i in range(workers)] + + def record(self, kind: str, status: int, instance: str | None) -> None: + with self.lock: + self.events.append((time.monotonic(), kind, status, instance)) + + def run(self, index: int) -> None: + client = httpx.Client(base_url=BASE_URL, timeout=3) + auth = {"Authorization": "Bearer " + self.alice["token"]} + n = 0 + key, text = uuid.uuid4().hex, f"w{index}-0" + while not self.stop.is_set(): + try: + r = client.post(f"/api/v1/chats/{self.chat['id']}/messages", json={"text": text}, + headers={**auth, "Idempotency-Key": key}) + self.record("POST", r.status_code, r.headers.get("x-instance-id")) + if r.status_code == 201: + with self.lock: + self.confirmed.append(r.json()) + n += 1 + key, text = uuid.uuid4().hex, f"w{index}-{n}" + # any other outcome: keep key and text, retry the same request + except httpx.HTTPError: + self.record("POST", 0, None) + try: + r = client.get(f"/api/v1/chats/{self.chat['id']}/messages?limit=5", headers=auth) + self.record("GET", r.status_code, r.headers.get("x-instance-id")) + except httpx.HTTPError: + self.record("GET", 0, None) + time.sleep(0.02) + client.close() + + def __enter__(self) -> "Traffic": + for t in self.threads: + t.start() + time.sleep(1.0) + return self + + def __exit__(self, *exc) -> None: + self.stop.set() + for t in self.threads: + t.join(timeout=10) + + def failures(self, since: float = 0.0) -> list[tuple]: + return [e for e in self.events if e[0] >= since and e[2] not in (200, 201)] + + def check_history(self, api: Api) -> None: + history = api.history(self.bob, self.chat, 100)[0] + ids, texts = [m["id"] for m in history], [m["text"] for m in history] + assert len(ids) == len(set(ids)) and len(texts) == len(set(texts)), "duplicate after retry" + assert {m["id"] for m in self.confirmed} <= set(ids), "a confirmed message was lost" + + +@pytest.mark.parametrize("position", range(REPLICAS)) +def test_graceful_stop_of_each_replica_loses_no_request(api, position): + """SIGTERM -> readiness 503 -> HAProxy DOWN -> drain -> exit 0: not one failed request.""" + replica = sorted(running_replicas(), key=lambda r: r["name"])[position] + with Traffic(api) as traffic: + started = time.monotonic() + with replica_stopped(replica, "stop"): + stopped_after = time.monotonic() - started + time.sleep(3) + after = [e for e in traffic.events if e[0] > time.monotonic() - 2] + assert after and replica["hostname"] not in {e[3] for e in after} + time.sleep(1) + state = json.loads(subprocess.run(["docker", "inspect", replica["id"]], capture_output=True, text=True, + check=True).stdout)[0]["State"] + assert traffic.failures() == [], traffic.failures()[:10] + assert stopped_after < 15, "graceful stop must finish before stop_grace_period (no SIGKILL)" + assert state["Status"] == "running" # restored by replica_stopped + traffic.check_history(api) + print(f"{replica['name']}: stop took {stopped_after:.1f} s, {len(traffic.events)} requests, 0 failed") + + +@pytest.mark.parametrize("position", range(REPLICAS)) +def test_killed_replica_bounded_errors_recovery_and_no_duplicates(api, position): + """SIGKILL: requests in flight on that replica may fail (counted), new ones succeed within + 10 s, the killed replica gets nothing after detection, retries do not duplicate.""" + replica = sorted(running_replicas(), key=lambda r: r["name"])[position] + with Traffic(api) as traffic: + killed_at = time.monotonic() + with replica_stopped(replica, "kill"): + time.sleep(4) + failures = traffic.failures(killed_at) + last_failure = max((e[0] for e in failures), default=killed_at) - killed_at + post_ok = [e for e in traffic.events if e[0] > killed_at and e[1] == "POST" and e[2] == 201] + assert post_ok and post_ok[0][0] - killed_at <= 10, "writes did not recover within 10 s" + late = [e for e in traffic.events if e[0] > killed_at + 3.5] + assert late and replica["hostname"] not in {e[3] for e in late} + assert last_failure <= 10 + traffic.check_history(api) + print(f"{replica['name']}: killed; {len(failures)} failed of {len(traffic.events)}, last failure +{last_failure:.2f} s") + + +def test_graceful_shutdown_order_in_logs(api): + """Logs prove the order: drain_started -> (HAProxy marks DOWN) -> shutdown_requested -> exit 0.""" + replica = sorted(running_replicas(), key=lambda r: r["name"])[-1] + since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 1)) + with replica_stopped(replica, "stop"): + logs = subprocess.run(["docker", "logs", "--since", since, replica["id"]], capture_output=True, + text=True, encoding="utf-8").stdout + lb_logs = compose("logs", "--no-log-prefix", "--since", since, "lb").stdout + state = json.loads(subprocess.run(["docker", "inspect", replica["id"]], capture_output=True, text=True, + check=True).stdout)[0]["State"] + events = [json.loads(line) for line in logs.splitlines() if line.startswith("{")] + names = [e["event"] for e in events] + assert names.index("drain_started") < names.index("shutdown_requested") < names.index("stopped") + t = {e["event"]: e["ts"] for e in events} + assert t["drain_started"] < t["shutdown_requested"] + assert state["ExitCode"] == 0 and not state["OOMKilled"] + assert "is DOWN" in lb_logs and ("503" in lb_logs or "Connection refused" in lb_logs) + + +# ------------------------------------------------------------------ discovery: restart and scaling +def test_full_restart_lb_rediscovers_all_replicas(api): + actor = api.user("restart") + before = {r["hostname"]: r["started_at"] for r in running_replicas()} + run_hook("restart.sh") + wait_healthy("postgres", "valkey", "api") + wait_stand() + after = {r["hostname"]: r["started_at"] for r in running_replicas()} + assert set(after) == set(before) and all(after[h] != before[h] for h in after), "every replica restarted" + assert set(instances_seen(api, actor["token"])) == set(after) # same token, both replicas, no LB restart needed + + +def test_scale_up_and_down_is_picked_up_without_errors(api): + with Traffic(api, workers=2) as traffic: + try: + compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "--scale", f"api={REPLICAS + 1}", "api", + timeout=180) + lbctl.wait_up(REPLICAS + 1, timeout=30) + actor = api.user("scale") + assert len(set(instances_seen(api, actor["token"], 30))) == REPLICAS + 1 + finally: + compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "--scale", f"api={REPLICAS}", "api", + timeout=180) + wait_stand() + time.sleep(1) + assert traffic.failures() == [], traffic.failures()[:10] + traffic.check_history(api) + + +# ------------------------------------------------------------------ level 4: deployment policy +def test_compose_policy_limits_ports_secrets_images(): + config = json.loads(compose("config", "--format", "json").stdout) + services = config["services"] + # auditor and jobctl (profile "tools") are started on demand and not part of the running stand. + assert set(services) == {"postgres", "valkey", "s3", "broker", "migrate", "s3-init", "api", "lb", "relay", "worker", + # lab 6: observability + "otel-collector", "prometheus", "loki", "tempo", "grafana"} + for name, svc in services.items(): + limits = svc.get("deploy", {}).get("resources", {}).get("limits", {}) + assert limits.get("cpus") and limits.get("memory"), f"{name}: CPU/RAM limits" + assert "container_name" not in svc, f"{name}: container_name prevents scaling" + if name in ("api", "migrate"): + assert "build" in svc # built from this repository's source + elif name in ("s3-init", "relay", "worker"): + assert svc["image"] == services["api"]["image"] # the same locally built image + else: + assert "@sha256:" in svc["image"], f"{name}: image must be pinned by digest" + assert services["api"]["deploy"]["replicas"] >= 2 and not services["api"].get("ports") + published = {name: svc.get("ports", []) for name, svc in services.items() if svc.get("ports")} + # Published: the LB and (lab 6) the Grafana UI - both on loopback only. No OTLP/store/admin port. + assert set(published) == {"lb", "grafana"} + assert all(p["host_ip"] in ("127.0.0.1", "::1") for ports in published.values() for p in ports) + assert [p["target"] for p in published["grafana"]] == [3000, 3000] + secrets = {name: sorted(s["source"] for s in svc.get("secrets", [])) for name, svc in services.items()} + s3_keys = sorted(f"s3_{who}_{part}" for who in ("admin", "api", "worker", "auditor") + for part in ("access_key_id", "secret_access_key")) + assert secrets == {"postgres": ["postgres_password"], "valkey": ["valkey_password"], "s3": s3_keys, + "migrate": ["database_url"], "s3-init": s3_keys, "lb": [], + "broker": ["rabbitmq_users"], + # the API: its own S3 key pair only (no admin/worker keys, no broker credentials) + "api": ["cache_url", "database_url", "s3_api_access_key_id", "s3_api_secret_access_key"], + # relay: database + its broker user only; worker: + its own S3 key pair + "relay": ["broker_url_relay", "database_url"], + "worker": ["broker_url_worker", "database_url", "s3_worker_access_key_id", + "s3_worker_secret_access_key"], + # lab 6: the telemetry services get no application secret at all + "otel-collector": [], "prometheus": [], "loki": [], "tempo": [], + "grafana": ["grafana_admin_password"]} + volumes = {name: [v["source"] for v in svc.get("volumes", []) if v["type"] == "volume"] + for name, svc in services.items()} + assert volumes == {"postgres": ["pgdata"], "valkey": ["valkeydata"], "s3": ["s3data"], "migrate": [], + "s3-init": [], "api": [], "lb": [], "broker": ["rabbitmqdata"], "relay": [], "worker": [], + "otel-collector": [], "prometheus": ["promdata"], "loki": ["lokidata"], "tempo": ["tempodata"], + "grafana": ["grafanadata"]} + networks = {name: sorted(svc.get("networks", {})) for name, svc in services.items()} + assert networks == {"postgres": ["data"], "valkey": ["data"], "s3": ["storage"], "migrate": ["data"], + "s3-init": ["storage"], "api": ["data", "edge", "storage", "telemetry"], "broker": ["queue"], + "relay": ["data", "queue", "telemetry"], "worker": ["data", "queue", "storage", "telemetry"], + "lb": ["edge"], "otel-collector": ["telemetry"], "prometheus": ["telemetry"], + "loki": ["telemetry"], "tempo": ["telemetry"], "grafana": ["telemetry", "ui"]}, networks + # the LB cannot reach the stores; the API not the broker; telemetry stores cannot reach the app stores + for network in ("data", "storage", "queue", "telemetry"): + assert config["networks"][network].get("internal") is True, network + + +def test_running_containers_have_limits_and_no_bypass_ports(): + ids = compose("ps", "-q").stdout.split() + for item in json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, text=True, + check=True).stdout): + name = item["Name"] + assert item["HostConfig"]["NanoCpus"] > 0 and item["HostConfig"]["Memory"] > 0, name + bindings = item["HostConfig"]["PortBindings"] or {} + if "-lb-" in name or "-grafana-" in name: + assert all(b["HostIp"] in ("127.0.0.1", "::1") for v in bindings.values() for b in v) # loopback only + else: + assert not bindings, f"{name} publishes ports in bypass of the LB" + + +def test_migrations_ran_once_by_the_migrate_service(): + applied = psql("SELECT version FROM schema_migrations ORDER BY version").split() + assert applied == ["0001_init", "0002_idempotency_keys", "0003_post_message_function", "0004_attachments", + "0005_pipeline", "0006_observability"] + migrate = compose("ps", "-a", "--format", "json", "migrate").stdout + rows = [json.loads(line) for line in migrate.splitlines() if line.strip()] + assert rows and all(r["State"] == "exited" and r["ExitCode"] == 0 for r in rows) + api_logs = compose("logs", "--no-log-prefix", "api").stdout + assert "migrate:" not in api_logs and "schema_migrations" not in api_logs # replicas never migrate diff --git a/student-tests/test_consistency.py b/student-tests/test_consistency.py new file mode 100644 index 0000000..2ddab1d --- /dev/null +++ b/student-tests/test_consistency.py @@ -0,0 +1,125 @@ +"""Consistency of PostgreSQL and S3 around one upload (lab 4 level 4, lab 5 failure windows of the API). + +Lab 5 upload: intent row 'pending' -> staging PUT -> ONE transaction 'queued' + job + outbox -> 202. +Failures between the steps are injected with FAULT_POINTS of the api service (compose variable +API_FAULT_POINTS, empty in normal runs; the API raises 503 at that exact point, as if the process +or the network failed there): + +* after_s3_put "after staging, before the job is written": staging object exists, row + still pending, NO job and NO outbox row; the client got 503 -> invisible, + the janitor removes the staging object and the row after PENDING_GRACE_SECONDS; +* after_enqueue_commit job committed, the answer is lost (client got 503) -> nothing may be + deleted: the worker processes the job and the attachment becomes ready. + +Plus: an upload interrupted by the client and a stalled body leave nothing behind.""" +from __future__ import annotations + +import socket +import time +from pathlib import Path + +import pytest + +import imagegen +from conftest import api_with_env, attachment_row, psql, s3_size + +pytestmark = pytest.mark.stack + +ROOT = Path(__file__).resolve().parents[1] +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() + + +def rows_of_chat(chat_id: str) -> list[tuple[str, str, str]]: + out = psql(f"SELECT id || ' ' || status || ' ' || staging_key FROM attachments WHERE chat_id = '{chat_id}'") + return [tuple(line.split()) for line in out.splitlines() if line] + + +def jobs_of(attachment_id: str) -> tuple[int, int]: + """(jobs rows, outbox rows) of an attachment.""" + out = psql(f"SELECT (SELECT count(*) FROM jobs WHERE attachment_id = '{attachment_id}') || ' ' || " + f"(SELECT count(*) FROM outbox o JOIN jobs j ON j.id = o.job_id WHERE j.attachment_id = '{attachment_id}')") + jobs, outbox = out.split() + return int(jobs), int(outbox) + + +def wait_for(condition, timeout: float, what: str) -> None: + deadline = time.monotonic() + timeout + while not condition(): + assert time.monotonic() < deadline, what + time.sleep(0.5) + + +def raw_upload(token: str, chat_id: str, declared: int, body: bytes, *, wait_answer: float | None) -> bytes: + """Hand-made HTTP request: announce `declared` bytes, send only `body`, then either close the + socket (client gone) or keep it open and read the answer after `wait_answer` seconds.""" + sock = socket.create_connection(("127.0.0.1", 8080), timeout=30) + head = (f"POST /api/v1/chats/{chat_id}/attachments?filename=x.png HTTP/1.1\r\nHost: localhost\r\n" + f"Authorization: Bearer {token}\r\nContent-Type: image/png\r\nContent-Length: {declared}\r\n\r\n") + sock.sendall(head.encode() + body) + if wait_answer is None: + sock.close() + return b"" + time.sleep(wait_answer) + answer = sock.recv(65536) + sock.close() + return answer + + +def test_interrupted_and_stalled_uploads_leave_nothing(api): + alice = api.user("alice") + chat = api.chat(alice) + data = imagegen.png_of_size(2_000_000) + raw_upload(alice["token"], chat["id"], len(data), data[:300_000], wait_answer=None) # client disconnects + with api_with_env(UPLOAD_READ_TIMEOUT_SECONDS="2"): + answer = raw_upload(alice["token"], chat["id"], len(data), data[:300_000], wait_answer=5) # client stalls + assert answer.startswith(b"HTTP/1.1 400") and b"invalid_request" in answer, answer[:200] + assert b"x-instance-id" in answer.lower() + time.sleep(1) + assert rows_of_chat(chat["id"]) == [] # nothing was written: the body is checked before any write + + +def test_crash_after_staging_before_job_is_cleaned_by_janitor(api): + """Failure window 1 of contracts/attachment-states.md: the original is in staging, the job is + not written. No 202 was sent, so nothing was promised: the janitor removes the staging copy + (object first) and then the intent row; no job, no message ever existed.""" + alice = api.user("alice") + chat = api.chat(alice) + with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"): + assert api.upload(alice, chat, SAMPLE, 503).json()["error"]["code"] == "unavailable" + [(attachment_id, status, key)] = rows_of_chat(chat["id"]) + assert status == "pending" and s3_size(key, "staging") == len(SAMPLE) # the orphan-to-be exists + assert jobs_of(attachment_id) == (0, 0) # no job, no outbox row + api.call("GET", f"/api/v1/attachments/{attachment_id}", 404, token=alice["token"]) # invisible + api.post_message(alice, chat, {"text": "", "attachment_ids": [attachment_id]}, 404) # not attachable + wait_for(lambda: rows_of_chat(chat["id"]) == [], 30, "janitor did not remove the stale intent") + assert s3_size(key, "staging") is None # object removed first + # Normal configuration again: an upload in the same chat works and is not touched. + att = api.upload(alice, chat, SAMPLE).json() + assert api.wait_status(alice, att["id"], "ready")["status"] == "ready" + + +def test_lost_answer_after_job_commit_still_becomes_ready(api): + """The job COMMIT succeeded, the answer was lost (503). Nothing compensates in the request path + (the janitor only touches 'pending' rows); the worker processes the job as usual.""" + alice, bob = api.user("alice"), api.user("bob") + chat = api.chat(alice, bob) + with api_with_env(API_FAULT_POINTS="after_enqueue_commit", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"): + api.upload(alice, chat, SAMPLE, 503) + [(attachment_id, status, key)] = rows_of_chat(chat["id"]) + assert status in ("queued", "processing", "ready") and jobs_of(attachment_id)[0] == 1 + att = api.wait_status(bob, attachment_id, "ready") + time.sleep(4) # several janitor rounds + assert attachment_row(attachment_id)["status"] == "ready" + got = api.call("GET", f"/api/v1/attachments/{attachment_id}/content", 200, token=bob["token"]) + assert got.content == SAMPLE and att["sha256"] == __import__("hashlib").sha256(SAMPLE).hexdigest() + + +def test_fresh_pending_upload_is_not_touched_by_janitor(api): + """An intent younger than PENDING_GRACE_SECONDS is an upload in progress: never removed.""" + alice = api.user("alice") + chat = api.chat(alice) + with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="600", JANITOR_INTERVAL_SECONDS="1"): + api.upload(alice, chat, SAMPLE, 503) + time.sleep(4) + [(_, status, key)] = rows_of_chat(chat["id"]) + assert status == "pending" and s3_size(key, "staging") == len(SAMPLE) diff --git a/student-tests/test_db.py b/student-tests/test_db.py new file mode 100644 index 0000000..8f9b266 --- /dev/null +++ b/student-tests/test_db.py @@ -0,0 +1,119 @@ +"""Database-level guarantees, checked over HTTP and verified directly in PostgreSQL / Valkey.""" +from __future__ import annotations + +import threading +import time +import uuid + +import pytest + +from conftest import PASSWORD, Api, compose, psql + +pytestmark = pytest.mark.stack + + +def run_concurrently(workers: int, target) -> list: + barrier = threading.Barrier(workers) + results: list = [None] * workers + + def body(index: int) -> None: + local = Api() # one HTTP client (connection) per worker + barrier.wait() # all workers fire at the same moment + try: + results[index] = target(local, index) + except BaseException as exc: # noqa: BLE001 - reported by the test + results[index] = exc + + threads = [threading.Thread(target=body, args=(i,)) for i in range(workers)] + for t in threads: + t.start() + for t in threads: + t.join() + return results + + +def test_registration_race_exactly_one_201_and_seven_409(): + username = "race_" + uuid.uuid4().hex[:10] + + def register(client: Api, _index: int) -> int: + body = {"username": username, "display_name": "Гонка", "password": PASSWORD} + response = client.client.post("/api/v1/users", json=body) + return response.status_code + + statuses = run_concurrently(8, register) + # Real HTTP codes are compared: a timeout, 500 or exception fails the test instead of counting as 409. + assert sorted(statuses, key=str) == [201] + [409] * 7, statuses + assert psql(f"SELECT count(*) FROM users WHERE username = '{username}'") == "1" + + +def _ins_counter() -> int: + return int(psql("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'")) + + +def test_create_chat_rolls_back_after_the_chat_row_was_inserted(api): + """The chat INSERT runs first; the unknown member then breaks the membership INSERT (FK). + + Proof that the first INSERT really happened and was rolled back: PostgreSQL counts + attempted inserts in pg_stat_user_tables.n_tup_ins even for aborted transactions, + while the table contains no such chat and no new membership rows. + """ + alice = api.user("rollback") + title = "rollback-" + uuid.uuid4().hex + members_before = int(psql("SELECT count(*) FROM chat_members")) + attempts_before = _ins_counter() + error = api.call("POST", "/api/v1/chats", 400, token=alice["token"], + json_body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]}).json() + assert "несуществующих" in error["error"]["message"] + deadline = time.monotonic() + 20 # statistics are flushed by the API backend asynchronously + while _ins_counter() == attempts_before and time.monotonic() < deadline: + time.sleep(0.5) + assert _ins_counter() > attempts_before, "the chat INSERT was never attempted" + assert psql(f"SELECT count(*) FROM chats WHERE title = convert_to('{title}', 'UTF8')") == "0" + assert int(psql("SELECT count(*) FROM chat_members")) == members_before + + +def test_migrations_rerun_is_a_noop(): + users_before = psql("SELECT count(*) FROM users") + result = compose("run", "--rm", "--no-deps", "migrate") + assert "0001_init: already applied, skipped" in result.stdout + assert "0002_idempotency_keys: already applied, skipped" in result.stdout + assert "0003_post_message_function: already applied, skipped" in result.stdout + assert "0004_attachments: already applied, skipped" in result.stdout + assert "0005_pipeline: already applied, skipped" in result.stdout + assert "0006_observability: already applied, skipped" in result.stdout + assert psql("SELECT count(*) FROM schema_migrations") == "6" + assert psql("SELECT count(*) FROM users") == users_before + + +def test_100_messages_from_10_clients_keep_order_and_cursor_walk(api): + clients = [api.user(f"w{i}") for i in range(10)] + chat = api.chat(clients[0], *clients[1:]) + + def writer(client: Api, index: int) -> list[dict]: + return [client.send(clients[index], chat, f"c{index}-m{j}") for j in range(10)] + + results = run_concurrently(10, writer) + assert all(isinstance(r, list) for r in results), results + confirmed = [m for batch in results for m in batch] + history, pages = api.history(clients[5], chat, 7) + ids = [m["id"] for m in history] + assert len(confirmed) == 100 and len(history) == 100 and len(set(ids)) == 100 and pages == 15 + assert set(ids) == {m["id"] for m in confirmed} + keys = [(m["created_at"], uuid.UUID(m["id"]).int) for m in history] + assert all(a < b for a, b in zip(keys, keys[1:])), "history is not strictly ordered" + stamps = [m["created_at"] for m in history] + assert len(set(stamps)) == 100, "per-chat clock must give unique timestamps" + for i, client in enumerate(clients): + own = [m["text"] for m in history if m["sender_id"] == client["id"]] + assert own == [f"c{i}-m{j}" for j in range(10)] + + +def test_secrets_are_not_stored_in_plain_text(api): + actor = api.user("store") + stored = psql(f"SELECT password_hash FROM users WHERE id = '{actor['id']}'") + assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$") and PASSWORD not in stored + token_hex = actor["token"].encode().hex() + keys = compose("exec", "-T", "valkey", "sh", "-c", + 'REDISCLI_AUTH="$(cat /run/secrets/valkey_password)" valkey-cli --scan --pattern "session:*"').stdout.split() + assert keys and all(len(k) == len("session:") + 64 for k in keys) + assert not any(actor["token"] in k or token_hex in k for k in keys) diff --git a/student-tests/test_explain.py b/student-tests/test_explain.py new file mode 100644 index 0000000..a2503a5 --- /dev/null +++ b/student-tests/test_explain.py @@ -0,0 +1,35 @@ +"""The history index really bounds the work of a late page (>= 10 000 messages, generic plan).""" +from __future__ import annotations + +import re +import sys + +import pytest + +from conftest import ROOT + +pytestmark = pytest.mark.stack + +sys.path.insert(0, str(ROOT / "scripts")) +import explain_history # noqa: E402 + + +def section(text: str, number: int) -> str: + parts = re.split(r"^=== ", text, flags=re.M) + return next(p for p in parts if p.startswith(f"{number}.")) + + +def buffers(plan: str) -> int: + return int(re.search(r"Buffers: shared hit=(\d+)", plan).group(1)) + + +def test_late_page_uses_index_range_not_filter(): + text = explain_history.run() + assert "20000" in text # the target chat holds 20 000 messages + app_late = section(text, 2) + assert "Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3)))" in app_late + assert "Rows Removed by Filter" not in app_late and "Sort" not in app_late + rejected = section(text, 3) + assert "Rows Removed by Filter: 19950" in rejected + # The app query touches a handful of pages; the rejected variants touch the whole prefix. + assert buffers(app_late) <= 10 < buffers(rejected) and buffers(app_late) <= 10 < buffers(section(text, 4)) diff --git a/student-tests/test_failures.py b/student-tests/test_failures.py new file mode 100644 index 0000000..899d29b --- /dev/null +++ b/student-tests/test_failures.py @@ -0,0 +1,111 @@ +"""Dependency failures with a VALID session: bounded 503, never anonymous access, recovery afterwards. + +Every test stops/pauses a real container and restores it in `finally` (service_down). +Timing bounds: DB_TIMEOUT_SECONDS=3 (client deadline), CACHE_TIMEOUT_SECONDS=0.5. + +Lab 3: requests go through HAProxy. While the outage is being detected the replicas answer +503 themselves; once every replica fails /health/ready, HAProxy answers 503 in the same +contract format (without X-Instance-Id). Both are "unavailable"; never 200 and never 401 +for a valid token. Liveness/readiness of the processes are checked inside each container. +""" +from __future__ import annotations + +import subprocess +import time + +import pytest + +from conftest import ROOT, probe_inside, restart_services, running_replicas, service_down + +pytestmark = pytest.mark.stack + +DB_BOUND = 3.6 # DB_TIMEOUT_SECONDS + network/HTTP overhead +CACHE_BOUND = 1.6 # 2 x CACHE_TIMEOUT_SECONDS + overhead + + +def timed(api, *args, **kwargs): + started = time.monotonic() + response = api.call(*args, lb_error_ok=True, **kwargs) + return response, time.monotonic() - started + + +def processes_alive_but_not_ready() -> None: + for replica in running_replicas(): + assert probe_inside(replica, "/health/live") == 200 + assert probe_inside(replica, "/health/ready") == 503 + + +@pytest.fixture +def prepared(api): + alice, bob = api.user("alice"), api.user("bob") + chat = api.chat(alice, bob) + message = api.send(alice, chat, "до отказа") + return alice, bob, chat, message + + +def check_intact(api, alice, bob, chat, message): + """After recovery the SAME tokens work and confirmed data is unchanged.""" + assert api.call("GET", "/api/v1/users/me", 200, token=alice["token"]).json() == alice["user"] + items = api.call("GET", f"/api/v1/chats/{chat['id']}/messages", 200, token=bob["token"]).json()["items"] + assert items == [message] + + +@pytest.mark.parametrize("how", ["stop", "pause"]) +def test_valkey_failure(api, prepared, how): + alice, bob, chat, message = prepared + with service_down("valkey", how): + response, took = timed(api, "GET", "/api/v1/users/me", 503, token=alice["token"]) + assert response.json()["error"]["code"] == "unavailable" and took < CACHE_BOUND, took + api.call("GET", f"/api/v1/chats/{chat['id']}/messages", 503, token=bob["token"]) + api.call("GET", "/api/v1/users/me", (401, 503), lb_error_ok=True) # anonymous never gets access + api.call("GET", "/health/ready", 503, lb_error_ok=True) + processes_alive_but_not_ready() + check_intact(api, alice, bob, chat, message) + + +@pytest.mark.parametrize("how", ["stop", "pause"]) +def test_postgres_failure(api, prepared, how): + alice, bob, chat, message = prepared + with service_down("postgres", how): + for path in ("/api/v1/users/me", f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"): + response, took = timed(api, "GET", path, 503, token=alice["token"]) + assert response.json()["error"]["code"] == "unavailable", path + assert took < DB_BOUND, (path, took) # bounded even when PostgreSQL is frozen (pause) + api.call("GET", "/api/v1/users/me", (401, 503), lb_error_ok=True) # anonymous never gets access + api.call("GET", "/health/ready", 503, lb_error_ok=True) + processes_alive_but_not_ready() + check_intact(api, alice, bob, chat, message) + + +def test_locked_table_gives_bounded_503(api, prepared): + """A statement stuck behind a lock is stopped by lock_timeout, not after minutes.""" + alice, bob, chat, message = prepared + locker = subprocess.Popen( + ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c", + "BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(6); COMMIT;"], + cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + time.sleep(1.5) # let the lock be taken + response, took = timed(api, "GET", f"/api/v1/chats/{chat['id']}/messages", 503, token=bob["token"]) + assert response.json()["error"]["code"] == "unavailable" and took < DB_BOUND, took + assert response.headers.get("x-instance-id"), "a lock is the API's own 503, the replicas stay ready" + finally: + locker.wait(timeout=30) + check_intact(api, alice, bob, chat, message) + + +def test_logout_during_valkey_outage_is_never_lost(api, prepared): + """Valkey is the single source of truth for sessions, so a logout cannot be 'forgotten': + during the outage logout answers 503 (nothing revoked, the client knows it failed); + after recovery logout works, and the revocation survives a Valkey and API restart (AOF).""" + alice, bob, chat, message = prepared + with service_down("valkey", "stop"): + api.call("DELETE", "/api/v1/auth/sessions/current", 503, token=alice["token"], lb_error_ok=True) + api.call("GET", "/api/v1/users/me", 200, token=alice["token"]) # logout did not happen + api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=alice["token"]) + api.call("GET", "/api/v1/users/me", 401, token=alice["token"]) + restart_services("valkey", "api") + for _ in range(10): # repeated checks: the revoked token must never come back + api.call("GET", "/api/v1/users/me", 401, token=alice["token"]) + api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, token=alice["token"], json_body={"text": "x"}) + api.call("GET", "/api/v1/users/me", 200, token=bob["token"]) # other sessions survived the restart diff --git a/student-tests/test_idempotency.py b/student-tests/test_idempotency.py new file mode 100644 index 0000000..a1e2bcc --- /dev/null +++ b/student-tests/test_idempotency.py @@ -0,0 +1,281 @@ +"""Shared idempotency of POST /chats/{id}/messages (lab 3), through the load balancer. + +Strict assertions: exact HTTP codes for every request, identical bodies for replays, +the number of rows in PostgreSQL (messages AND idempotency_keys), and which replica +answered (X-Instance-Id). Fault injection (trigger, row lock, stopped replica) is always +undone in `finally`. +""" +from __future__ import annotations + +import subprocess +import threading +import time +import uuid + +import httpx2 as httpx +import pytest + +from conftest import BASE_URL, ROOT, Api, psql, replica_stopped, running_replicas + +pytestmark = pytest.mark.stack + + +def messages_in_db(chat: dict) -> int: + return int(psql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}'")) + + +def key_rows(actor: dict, key: str) -> int: + return int(psql(f"SELECT count(*) FROM idempotency_keys WHERE user_id = '{actor['id']}' AND key = '{key}'")) + + +@pytest.fixture +def pair(api): + alice, bob = api.user("alice"), api.user("bob") + return alice, bob, api.chat(alice, bob) + + +def test_replay_returns_the_same_201_and_message_from_every_replica(api, pair): + alice, bob, chat = pair + key = "replay-" + uuid.uuid4().hex + first = api.post_message(alice, chat, {"text": "один раз"}, key=key) + served = {first.headers["x-instance-id"]} + for _ in range(20): + again = api.post_message(alice, chat, {"text": "один раз"}, key=key) + assert again.status_code == 201 and again.json() == first.json() + served.add(again.headers["x-instance-id"]) + assert len(served) >= 2, "replays must be answered by different replicas, not a local cache" + assert api.history(bob, chat, 100)[0] == [first.json()] + assert messages_in_db(chat) == 1 and key_rows(alice, key) == 1 + + +def test_other_body_with_the_same_key_is_409_and_keeps_the_original(api, pair): + alice, bob, chat = pair + key = uuid.uuid4().hex + original = api.send(alice, chat, "оригинал", key=key) + for body in ({"text": "другой текст"}, {"text": "оригинал "}, {"text": "Оригинал"}): + assert api.post_message(alice, chat, body, 409, key=key).json()["error"]["code"] == "conflict" + assert api.send(alice, chat, "оригинал", key=key) == original + assert api.history(bob, chat, 100)[0] == [original] and key_rows(alice, key) == 1 + + +def test_key_order_and_missing_attachment_ids_are_the_same_body(api, pair): + alice, _, chat = pair + key = uuid.uuid4().hex + first = api.post_message(alice, chat, None, raw='{"text":"порядок"}'.encode(), key=key).json() + for raw in ('{"attachment_ids":[],"text":"порядок"}', '{"text":"порядок","attachment_ids":[]}', + '{ "text" : "\\u043f\\u043e\\u0440\\u044f\\u0434\\u043e\\u043a" }'): + assert api.post_message(alice, chat, None, raw=raw.encode(), key=key).json() == first + assert messages_in_db(chat) == 1 + + +@pytest.mark.parametrize("value", ["", "a" * 129, "ключ", "a b", "a/b", "a,b", "a\tb", "*"]) +def test_missing_or_invalid_key_is_400(api, pair, value): + alice, _, chat = pair + raw_value = value.encode("utf-8") + error = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"], + json_body={"text": "x"}, headers={"Idempotency-Key": raw_value} if value else {}).json() + assert error["error"]["code"] == "invalid_request" + assert messages_in_db(chat) == 0 + + +def test_repeated_key_header_is_400(pair): + alice, _, chat = pair + response = httpx.post(BASE_URL + f"/api/v1/chats/{chat['id']}/messages", json={"text": "x"}, timeout=10, + headers=[("Authorization", "Bearer " + alice["token"]), + ("Idempotency-Key", "one"), ("Idempotency-Key", "two")]) + assert response.status_code == 400 and response.headers["x-instance-id"] + assert messages_in_db(chat) == 0 + + +def test_longest_key_and_every_allowed_character(api, pair): + alice, _, chat = pair + for key in ("k" * 128, "A-Za-z0-9._:-" + uuid.uuid4().hex): + first = api.send(alice, chat, key[:20], key=key) + assert api.send(alice, chat, key[:20], key=key) == first + assert messages_in_db(chat) == 2 + + +def test_scope_is_user_plus_chat_plus_key(api, pair): + alice, bob, chat = pair + other = api.chat(alice, bob, title="второй") + key = "shared-key" + a1 = api.send(alice, chat, "текст", key=key) + b1 = api.send(bob, chat, "текст", key=key) # another user: independent + a2 = api.send(alice, other, "текст", key=key) # another chat: independent + assert len({a1["id"], b1["id"], a2["id"]}) == 3 + assert messages_in_db(chat) == 2 and messages_in_db(other) == 1 + + +def test_outsider_and_revoked_session_never_see_the_stored_result(api, pair): + alice, bob, chat = pair + eve = api.user("eve") + key = uuid.uuid4().hex + api.send(alice, chat, "секрет", key=key) + for _ in range(3): # a replay checks access again: always 404, never 409 or the stored message + assert api.post_message(eve, chat, {"text": "секрет"}, 404, key=key).json()["error"]["code"] == "not_found" + api.post_message(eve, chat, {"text": "другое"}, 404, key=key) + api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=alice["token"]) + api.post_message(alice, chat, {"text": "секрет"}, 401, key=key) # session checked again + assert messages_in_db(chat) == 1 + + +def fire_together(workers: int, request) -> list: + barrier = threading.Barrier(workers) + results: list = [None] * workers + + def body(index: int) -> None: + client = httpx.Client(base_url=BASE_URL, timeout=15) # own connection -> LB spreads them + barrier.wait() + try: + results[index] = request(client, index) + except BaseException as exc: # noqa: BLE001 - asserted by the test + results[index] = exc + finally: + client.close() + + threads = [threading.Thread(target=body, args=(i,)) for i in range(workers)] + for t in threads: + t.start() + for t in threads: + t.join() + return results + + +def test_concurrent_same_key_through_different_replicas_creates_exactly_one(pair): + alice, bob, chat = pair + key = "race-" + uuid.uuid4().hex + + def post(client: httpx.Client, _index: int): + r = client.post(f"/api/v1/chats/{chat['id']}/messages", json={"text": "гонка"}, + headers={"Authorization": "Bearer " + alice["token"], "Idempotency-Key": key}) + return r.status_code, r.headers.get("x-instance-id"), r.json() + + for _ in range(3): # three rounds: the first creates, later rounds replay concurrently + results = fire_together(24, post) + assert all(isinstance(r, tuple) for r in results), results + assert [r[0] for r in results] == [201] * 24, [r[0] for r in results] + assert len({str(r[2]) for r in results}) == 1, "every concurrent replay must return the same Message" + assert len({r[1] for r in results}) >= 2, "requests did not reach two replicas" + assert messages_in_db(chat) == 1 and key_rows(alice, key) == 1 + + +def test_concurrent_same_key_different_bodies_one_wins(pair): + alice, _, chat = pair + key = "conflict-" + uuid.uuid4().hex + + def post(client: httpx.Client, index: int): + r = client.post(f"/api/v1/chats/{chat['id']}/messages", json={"text": f"вариант {index % 2}"}, + headers={"Authorization": "Bearer " + alice["token"], "Idempotency-Key": key}) + return r.status_code, r.json() + + results = fire_together(20, post) + winners = [body for status, body in results if status == 201] + losers = [body for status, body in results if status == 409] + assert len(winners) + len(losers) == 20, results + assert winners and len({str(b) for b in winners}) == 1 + assert all(b["error"]["code"] == "conflict" for b in losers) + assert {b["text"] for b in winners} <= {"вариант 0", "вариант 1"} + assert len(losers) == sum(1 for i in range(20) if f"вариант {i % 2}" != winners[0]["text"]) + assert messages_in_db(chat) == 1 + + +def inserts_into_keys() -> int: + return int(psql("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'idempotency_keys'")) + + +def test_failure_after_the_key_insert_rolls_everything_back(api, pair): + """A trigger makes the MESSAGE insert fail AFTER the key row was inserted in the same + transaction. Expected: 500 for the client, no key row and no message left behind + (n_tup_ins proves the key INSERT really ran), and a retry with the same key succeeds.""" + alice, bob, chat = pair + marker = "boom-" + uuid.uuid4().hex + key = uuid.uuid4().hex + psql("CREATE OR REPLACE FUNCTION lab3_test_fail() RETURNS trigger LANGUAGE plpgsql AS $$ " + f"BEGIN IF NEW.text = convert_to('{marker}', 'UTF8') THEN RAISE EXCEPTION 'injected failure'; END IF; " + "RETURN NEW; END $$; " + "CREATE TRIGGER lab3_test_fail BEFORE INSERT ON messages FOR EACH ROW EXECUTE FUNCTION lab3_test_fail()") + try: + before = inserts_into_keys() + error = api.post_message(alice, chat, {"text": marker}, 500, key=key) + assert error.json()["error"]["code"] == "internal_error" and "injected" not in error.text + assert key_rows(alice, key) == 0 and messages_in_db(chat) == 0 + deadline = time.monotonic() + 20 # table statistics are flushed asynchronously + while inserts_into_keys() == before and time.monotonic() < deadline: + time.sleep(0.5) + assert inserts_into_keys() > before, "the key INSERT never ran before the failure" + finally: + psql("DROP TRIGGER IF EXISTS lab3_test_fail ON messages; DROP FUNCTION IF EXISTS lab3_test_fail()") + retried = api.send(alice, chat, marker, key=key) # transient failure was not recorded + assert api.send(alice, chat, marker, key=key) == retried + assert api.history(bob, chat, 100)[0] == [retried] and key_rows(alice, key) == 1 + + +def lock_chat_row(chat: dict, seconds: float) -> subprocess.Popen: + sql = (f"BEGIN; SELECT 1 FROM chats WHERE id = '{chat['id']}' FOR UPDATE; " + f"SELECT pg_sleep({seconds}); COMMIT;") + return subprocess.Popen(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", + "messenger", "-c", sql], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def wait_lock_taken(chat: dict) -> None: + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + if psql("SELECT count(*) FROM pg_stat_activity WHERE query LIKE '%pg_sleep%' AND state = 'active' " + "AND pid <> pg_backend_pid()") != "0": + return + time.sleep(0.2) + raise AssertionError("the row lock was not taken") + + +def test_client_timeout_then_retry_with_the_same_key_gives_the_committed_message(api, pair): + """Uncertain outcome: the client gives up after 0.4 s, the server commits later (the row + lock is held 1 s < lock_timeout). The retry must return THAT message, not a second one.""" + alice, bob, chat = pair + key = uuid.uuid4().hex + locker = lock_chat_row(chat, 1.0) + try: + wait_lock_taken(chat) + with pytest.raises(httpx.TimeoutException): + httpx.post(BASE_URL + f"/api/v1/chats/{chat['id']}/messages", json={"text": "неопределённо"}, timeout=0.4, + headers={"Authorization": "Bearer " + alice["token"], "Idempotency-Key": key}) + finally: + locker.wait(timeout=30) + deadline = time.monotonic() + 10 + while messages_in_db(chat) == 0 and time.monotonic() < deadline: + time.sleep(0.2) + stored = psql(f"SELECT id FROM messages WHERE chat_id = '{chat['id']}'") + assert stored, "the server-side transaction was expected to commit after the lock was released" + retried = api.send(alice, chat, "неопределённо", key=key) + assert retried["id"] == stored and messages_in_db(chat) == 1 and key_rows(alice, key) == 1 + + +def test_lock_timeout_is_a_transient_503_that_is_not_recorded(api, pair): + """The row lock outlives lock_timeout: the API answers 503 within its deadline and stores + nothing; after the lock is gone the same key creates the message exactly once.""" + alice, bob, chat = pair + key = uuid.uuid4().hex + locker = lock_chat_row(chat, 4.0) + try: + wait_lock_taken(chat) + started = time.monotonic() + api.post_message(alice, chat, {"text": "после блокировки"}, 503, key=key) + assert time.monotonic() - started < 3.6 + assert key_rows(alice, key) == 0 and messages_in_db(chat) == 0 + finally: + locker.wait(timeout=30) + created = api.send(alice, chat, "после блокировки", key=key) + assert api.send(alice, chat, "после блокировки", key=key) == created + assert api.history(bob, chat, 100)[0] == [created] and key_rows(alice, key) == 1 + + +def test_replay_after_the_serving_replica_is_stopped(api, pair): + alice, bob, chat = pair + key = uuid.uuid4().hex + first = api.post_message(alice, chat, {"text": "до остановки"}, key=key) + served_by = first.headers["x-instance-id"] + replica = next(r for r in running_replicas() if r["hostname"] == served_by) + with replica_stopped(replica): + for _ in range(5): + again = Api().post_message(alice, chat, {"text": "до остановки"}, key=key) + assert again.json() == first.json() and again.headers["x-instance-id"] != served_by + assert messages_in_db(chat) == 1 diff --git a/student-tests/test_observability.py b/student-tests/test_observability.py new file mode 100644 index 0000000..65f9f91 --- /dev/null +++ b/student-tests/test_observability.py @@ -0,0 +1,184 @@ +"""Lab 6, against the running stand: what the stored observations really contain. + +* one upload with a client-chosen traceparent = ONE trace: API SERVER (continues it) -> relay + PRODUCER -> worker CONSUMER -> s3/db spans; with WORKER_FAULT_POINTS=transient_error=1 the + failed attempt AND the retry are in the same trace (two publishes, two consumer spans); +* log records of api and worker carry the trace_id and the X-Request-Id; +* metrics: exact counters (jobs processed by outcome, time to ready) moved for our work, and + no metric series has an id/raw path as a label value; +* nothing secret in Loki/Tempo: no password, token, message text of our requests. +Stores are read through Grafana's datasource proxy (scripts/obs.py). +""" +from __future__ import annotations + +import re +import secrets +import time + +import pytest + +import obs +from conftest import ROOT, service_with_env + +pytestmark = pytest.mark.stack + +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() +UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + + +def traced_upload(api, actor, chat): + trace_id, parent = secrets.token_hex(16), secrets.token_hex(8) + response = api.upload(actor, chat, SAMPLE, headers={"traceparent": f"00-{trace_id}-{parent}-01", + "X-Request-Id": "obs-" + secrets.token_hex(6)}) + assert response.headers["x-trace-id"] == trace_id + return trace_id, parent, response + + +def jobs_counter(outcome: str) -> float: + return obs.scalar(f'sum(messenger_jobs_processed_total{{outcome="{outcome}"}})', 0.0) + + +def test_upload_is_one_trace_api_relay_worker_s3_db(api): + owner = api.user("obs") + chat = api.chat(owner) + trace_id, parent, response = traced_upload(api, owner, chat) + att = api.wait_status(owner, response.json()["id"], "ready") + spans = obs.wait_trace(trace_id, lambda s: any(x["name"] == "db jobs.complete" for x in s), timeout=90) + ids = {s["span_id"]: s for s in spans} + server = [s for s in spans if s["kind"] == "SERVER"] + assert len(server) == 1 and server[0]["service"] == "messenger-api" + assert server[0]["parent_id"] == parent # continued, not replaced + assert server[0]["name"] == "POST /api/v1/chats/{chat_id}/attachments" + producer = [s for s in spans if s["kind"] == "PRODUCER"] + consumer = [s for s in spans if s["kind"] == "CONSUMER"] + assert len(producer) == 1 and producer[0]["service"] == "messenger-relay" + assert len(consumer) == 1 and consumer[0]["service"] == "messenger-worker" + assert consumer[0]["parent_id"] == producer[0]["span_id"] + assert producer[0]["parent_id"] == server[0]["span_id"] # context stored with the job = the upload request + assert any(s["name"] == "db enqueue" and s["parent_id"] == server[0]["span_id"] for s in spans) + assert consumer[0]["attrs"]["messenger.job.outcome"] == "succeeded" + assert consumer[0]["attrs"]["messenger.attachment.id"] == att["id"] + worker_children = {s["name"] for s in spans if s["parent_id"] == consumer[0]["span_id"]} + assert {"db jobs.claim", "s3 download", "image render", "s3 put", "db jobs.complete"} <= worker_children + puts = [s for s in spans if s["name"] == "s3 put" and s["parent_id"] == consumer[0]["span_id"]] + assert len(puts) == 4 # original + thumbnail + crop + optimized + for s in spans: # no object keys / urls in span attributes + assert not any(k in s["attrs"] for k in ("aws.s3.key", "url.full", "http.url", "db.query.text")) + + +def test_retry_is_visible_in_the_same_trace(): + """WORKER_FAULT_POINTS=transient_error=1: attempt 1 fails (transient), the job is retried via + the outbox; both publishes and both worker attempts belong to the upload's trace.""" + from conftest import Api + api = Api() + before_retry, before_ok = jobs_counter("retry"), jobs_counter("succeeded") + with service_with_env("worker", WORKER_FAULT_POINTS="transient_error=1", JOB_RETRY_BASE_SECONDS="1"): + owner = api.user("obsretry") + chat = api.chat(owner) + trace_id, _, response = traced_upload(api, owner, chat) + api.wait_status(owner, response.json()["id"], "ready", timeout=90) + spans = obs.wait_trace(trace_id, lambda s: sum(x["kind"] == "CONSUMER" for x in s) >= 2 + and any(x["name"] == "db jobs.complete" for x in s), timeout=90) + consumers = sorted((s for s in spans if s["kind"] == "CONSUMER"), key=lambda s: s["start"]) + producers = sorted((s for s in spans if s["kind"] == "PRODUCER"), key=lambda s: s["start"]) + assert len(producers) == 2 and len(consumers) == 2 + assert [p["attrs"]["messenger.job.attempt"] for p in producers] == [1, 2] or \ + [str(p["attrs"]["messenger.job.attempt"]) for p in producers] == ["1", "2"] + first, second = consumers + assert first["attrs"]["messenger.job.outcome"] == "retry" and first["status"] == "ERROR" + assert first["attrs"]["messenger.job.error_code"] == "injected_transient" + assert second["attrs"]["messenger.job.outcome"] == "succeeded" + assert {c["parent_id"] for c in consumers} == {p["span_id"] for p in producers} + time.sleep(12) # metric export 5 s + batch + push + assert jobs_counter("retry") >= before_retry + 1 + assert jobs_counter("succeeded") >= before_ok + 1 + + +def test_logs_of_api_and_worker_are_joined_by_trace_id(api): + owner = api.user("obslog") + chat = api.chat(owner) + trace_id, _, response = traced_upload(api, owner, chat) + request_id = response.headers["x-request-id"] + api.wait_status(owner, response.json()["id"], "ready") + deadline = time.monotonic() + 60 + records = [] + while time.monotonic() < deadline: + records = obs.trace_logs(trace_id, minutes=10) + if {"messenger-api", "messenger-worker"} <= {r["service"] for r in records} and \ + any(r["line"] == "job_done" for r in records): + break + time.sleep(2) + access = [r for r in records if r["service"] == "messenger-api" and r["line"] == "request"] + assert access and access[0]["metadata"]["request_id"] == request_id + assert access[0]["metadata"]["route"] == "/api/v1/chats/{chat_id}/attachments" + assert access[0]["metadata"]["severity_text"] == "INFO" + done = [r for r in records if r["service"] == "messenger-worker" and r["line"] == "job_done"] + assert done and done[0]["metadata"]["outcome"] == "succeeded" + for r in records: + assert len(r["metadata"]["span_id"]) == 16 and r["metadata"].get("trace_id") in (None, trace_id) + + +def test_no_ids_or_raw_paths_in_metric_labels(): + """Cardinality guard: no label VALUE of an application series looks like a UUID/hex id, and the + route label only holds templates.""" + series = obs.promql('count by (__name__) ({job=~"messenger-.+"})') + assert series, "no application metrics in Prometheus" + names = [s["metric"]["__name__"] for s in series] + for name in names: + for s in obs.promql(f'{name}{{job=~"messenger-.+"}}'): + for label, value in s["metric"].items(): + if label in ("instance",): # container hostname (one per replica) + continue + assert not UUID_RE.search(value), (name, label, value) + assert label not in ("user_id", "chat_id", "message_id", "attachment_id", "request_id", "url_path") + routes = {s["metric"]["http_route"] for s in obs.promql("count by (http_route) (http_server_request_duration_seconds_count)")} + assert routes and all(r == "UNMATCHED" or r.startswith("/") and not UUID_RE.search(r) for r in routes) + assert "/api/v1/chats/{chat_id}/messages" in routes + + +def test_no_secrets_or_message_text_in_logs_and_traces(api): + owner = api.user("obssecret") + chat = api.chat(owner) + text = "секретный-текст-" + secrets.token_hex(8) + response = api.post_message(owner, chat, {"text": text}) + trace_id = response.headers["x-trace-id"] + spans = obs.wait_trace(trace_id, lambda s: any(x["kind"] == "SERVER" for x in s), timeout=60) + time.sleep(3) + blobs = [str(spans), str(obs.trace_logs(trace_id, minutes=10)), + str(obs.logs(f'{{service_name="messenger-api"}} |= "{owner["username"]}"', minutes=10))] + for blob in blobs: + assert text not in blob + assert owner["token"] not in blob + assert owner["password"] not in blob + assert "Bearer " not in blob and "Basic " not in blob + + +def test_history_survives_restart_of_the_stores(api): + """Persistent volumes keep the history: a trace, its logs and a metric value recorded BEFORE a + restart of Tempo, Loki and Prometheus are still found after it.""" + from conftest import compose + owner = api.user("obshist") + chat = api.chat(owner) + trace_id, _, response = traced_upload(api, owner, chat) + api.wait_status(owner, response.json()["id"], "ready") + obs.wait_trace(trace_id, lambda s: any(x["kind"] == "CONSUMER" for x in s), timeout=90) + time.sleep(15) # metric pushes (5 s) and log batches are in + before = time.time() + value_before = obs.scalar('sum(messenger_jobs_processed_total{outcome="succeeded"})') + assert value_before and value_before >= 1 + compose("restart", "tempo", "loki", "prometheus", timeout=180) + deadline = time.monotonic() + 180 + while True: + try: + spans = obs.trace_spans(trace_id) + records = obs.trace_logs(trace_id, minutes=15) + old = obs.promql('sum(messenger_jobs_processed_total{outcome="succeeded"})', at=before) + if spans and records and old: + break + except Exception: # noqa: BLE001 - stores still starting + pass + assert time.monotonic() < deadline, "history not available after the restart" + time.sleep(3) + assert any(s["kind"] == "SERVER" for s in spans) and any(s["kind"] == "CONSUMER" for s in spans) + assert any(r["line"] == "job_done" for r in records) + assert float(old[0]["value"][1]) == value_before diff --git a/student-tests/test_pipeline_flow.py b/student-tests/test_pipeline_flow.py new file mode 100644 index 0000000..3d25e4f --- /dev/null +++ b/student-tests/test_pipeline_flow.py @@ -0,0 +1,504 @@ +"""Lab 5 pipeline against the running stand: 202 -> queued -> ready, variants by the contract, +the failure windows of contracts/attachment-states.md, retries, the failed registry and replay, +lease expiry of a hung worker, cleanup that never deletes accepted work. + +Failures are injected with the real mechanisms - docker stop/pause/restart of a service, and +FAULT_POINTS of ONE service recreated with an override (conftest.service_with_env) - and every +test restores the normal stand in `finally`. Each test checks exact HTTP codes AND the rows in +PostgreSQL AND the objects in S3, then the read-only invariant audit (I1-I7) of the whole stand.""" +from __future__ import annotations + +import hashlib +import io +import json +import subprocess +import time +import uuid +from pathlib import Path + +import pytest +from PIL import Image + +import imagegen +from conftest import (attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys, + s3_size, service_down, service_with_env, wait_healthy, wait_stand) + +pytestmark = pytest.mark.stack + +ROOT = Path(__file__).resolve().parents[1] +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() +FAST_LEASE = {"JOB_LEASE_SECONDS": "6"} # the reaper notices a dead attempt within ~11 s + + +@pytest.fixture() +def pair(api): + alice, bob = api.user("alice"), api.user("bob") + return alice, bob, api.chat(alice, bob) + + +def wait_for(condition, timeout: float, what: str): + deadline = time.monotonic() + timeout + while True: + value = condition() + if value: + return value + assert time.monotonic() < deadline, what + time.sleep(0.5) + + +def check_variants(api, actor, att: dict, source: bytes) -> dict[str, bytes]: + """Download every variant: real format and size decoded with Pillow, size/sha256 = metadata.""" + expected = {"thumbnail": ("image/jpeg", "JPEG"), "crop": ("image/jpeg", "JPEG"), "optimized": ("image/webp", "WEBP")} + assert [v["name"] for v in att["variants"]] == list(expected) + src = Image.open(io.BytesIO(source)) + w, h = src.size + out = {} + for v in att["variants"]: + got = api.content(actor, att["id"], v["name"]) + assert got.headers["content-type"] == expected[v["name"]][0] == v["content_type"] + assert len(got.content) == v["size_bytes"] and hashlib.sha256(got.content).hexdigest() == v["sha256"] + img = Image.open(io.BytesIO(got.content)) + assert img.format == expected[v["name"]][1] and img.size == (v["width"], v["height"]) + out[v["name"]] = got.content + def fit(box): + if w <= box and h <= box: + return w, h + return (box, max(1, h * box // w)) if w >= h else (max(1, w * box // h), box) + sizes = {v["name"]: (v["width"], v["height"]) for v in att["variants"]} + assert sizes == {"thumbnail": fit(256), "crop": (128, 128), "optimized": fit(1280)} + original = api.content(actor, att["id"]) + assert original.content == source # the original is published byte for byte + return out + + +def published_keys(attachment_id: str) -> list[str]: + return psql(f"SELECT object_key FROM attachment_variants WHERE attachment_id = '{attachment_id}' " + f"UNION ALL SELECT object_key FROM attachments WHERE id = '{attachment_id}' ORDER BY 1").split() + + +def attempts(attachment_id: str) -> list[dict]: + out = psql("SELECT coalesce(json_agg(json_build_object('attempt', a.attempt, 'outcome', a.outcome, " + "'error_code', a.error_code, 'token', a.token, 'cleaned', a.objects_cleaned_at IS NOT NULL, " + "'keys', a.planned_keys) ORDER BY a.started_at), '[]') FROM job_attempts a JOIN jobs j ON j.id = a.job_id " + f"WHERE j.attachment_id = '{attachment_id}'") + return json.loads(out) + + +def outbox_of(attachment_id: str) -> list[dict]: + out = psql("SELECT coalesce(json_agg(json_build_object('attempt', o.attempt, 'published', o.published_at IS NOT NULL) " + f"ORDER BY o.id), '[]') FROM outbox o JOIN jobs j ON j.id = o.job_id WHERE j.attachment_id = '{attachment_id}'") + return json.loads(out) + + +def names(events: list[dict]) -> list[str]: + return [e["event"] for e in events] + + +# ------------------------------------------------------------------ level 3: the happy path +def test_upload_is_202_queued_then_ready_with_contract_variants(api, pair): + alice, bob, chat = pair + data = imagegen.png(900, 600, noise=True) + response = api.upload(alice, chat, data) + assert response.status_code == 202 + att = response.json() + assert att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None + ready = api.wait_status(bob, att["id"], "ready") + assert ready["error_code"] is None and ready["sha256"] == hashlib.sha256(data).hexdigest() + check_variants(api, bob, ready, data) + row = attachment_row(att["id"]) + assert row["published_version"] == 1 and row["staging_state"] == "deleted" # staging cleaned after ready + assert s3_size(row["staging_key"], "staging") is None + [job] = job_rows(att["id"]) + assert job["state"] == "succeeded" and job["attempt"] == 1 and job["kind"] == "upload" + assert names(events_of(att["id"])) == ["created", "claimed", "succeeded"] + + +def test_queued_attachment_is_attachable_failed_is_not(api, pair): + alice, bob, chat = pair + with service_down("worker"): # stays queued + att = api.upload(alice, chat, SAMPLE).json() + msg = api.post_message(alice, chat, {"text": "", "attachment_ids": [att["id"]]}).json() + assert msg["attachment_ids"] == [att["id"]] + api.wait_status(alice, att["id"], "ready") + with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error"): + bad = api.upload(alice, chat, SAMPLE).json() + failed = api.wait_status(bob, bad["id"], "failed") + assert failed["error_code"] == "invalid_image" and failed["variants"] == [] + api.post_message(alice, chat, {"text": "", "attachment_ids": [bad["id"]]}, 409) + api.content(bob, bad["id"], expected=409) + api.content(bob, bad["id"], "thumbnail", expected=409) + + +def test_worker_stopped_upload_202_content_409_restart_api_and_broker_then_ready(api, pair): + """The defence scenario: worker stopped -> upload 202 -> content 409, other messages keep working + -> the message with the attachment is created -> API and broker restarted WITH volumes -> + the job is still in the queue -> worker started -> ready, thumbnail downloadable.""" + alice, bob, chat = pair + compose("stop", "worker") + try: + response = api.upload(alice, chat, SAMPLE) + att = response.json() + assert response.status_code == 202 and att["status"] == "queued" + for variant in (None, "thumbnail"): + assert api.content(bob, att["id"], variant, expected=409).json()["error"]["code"] == "conflict" + api.send(bob, chat, "текст работает без worker") + msg = api.post_message(alice, chat, {"text": "фото", "attachment_ids": [att["id"]]}).json() + wait_for(lambda: all(o["published"] for o in outbox_of(att["id"])), 15, "relay did not publish the job") + # rabbitmqctl counters are refreshed every ~5 s (statistics interval): wait, do not sample once. + wait_for(lambda: queue_depth() >= 1, 20, "no message in the queue") # durable message waits in the queue + compose("restart", "api", "broker") # volumes preserved + wait_healthy("api", "broker", "relay") + wait_stand() + wait_for(lambda: queue_depth() >= 1, 20, "the accepted job was lost by the broker restart") + assert api.attachment(bob, att["id"])["status"] == "queued" + finally: + compose("start", "worker") + wait_healthy("worker") + ready = api.wait_status(bob, att["id"], "ready") + check_variants(api, bob, ready, SAMPLE) + items, _ = api.history(bob, chat, 50) + assert any(m["id"] == msg["id"] and m["attachment_ids"] == [att["id"]] for m in items) + [job] = job_rows(att["id"]) + assert job["attempt"] == 1 # no duplicate work + + +# ------------------------------------------------------------------ failure windows +def test_broker_down_commit_to_publish_gap_is_closed_by_the_outbox(api, pair): + """Window "after COMMIT, before publish": the broker is down, the API still answers 202 (it never + talks to the broker), the outbox row stays unpublished. No manual action: when the broker is + back the relay publishes it and the worker finishes the job.""" + alice, bob, chat = pair + with service_down("broker"): + att = api.upload(alice, chat, SAMPLE).json() + assert att["status"] == "queued" + time.sleep(3) + assert outbox_of(att["id"]) == [{"attempt": 1, "published": False}] + api.send(alice, chat, "сообщения работают без брокера") + api.wait_status(bob, att["id"], "ready", timeout=90) + assert outbox_of(att["id"]) == [{"attempt": 1, "published": True}] + assert [j["attempt"] for j in job_rows(att["id"])] == [1] + + +def test_relay_down_job_waits_in_outbox_not_lost(api, pair): + alice, bob, chat = pair + with service_down("relay"): + att = api.upload(alice, chat, SAMPLE).json() + time.sleep(3) + assert outbox_of(att["id"]) == [{"attempt": 1, "published": False}] + assert api.attachment(bob, att["id"])["status"] == "queued" + api.wait_status(bob, att["id"], "ready") + + +def test_crash_after_publish_before_confirm_is_recorded_gives_a_harmless_duplicate(api, pair): + """Window "after publish, before confirm": the relay dies after the broker confirmed the message + but before outbox.published_at is committed. The restarted relay publishes it AGAIN; the + duplicate is a no-op (one claim, one set of variants).""" + alice, bob, chat = pair + with service_with_env("relay", RELAY_FAULT_POINTS="crash_after_publish"): + att = api.upload(alice, chat, SAMPLE).json() + api.wait_status(bob, att["id"], "ready", timeout=90) + wait_for(lambda: all(o["published"] for o in outbox_of(att["id"])), 30, "outbox not marked after restart") + events = events_of(att["id"]) + assert names(events).count("fault_injected") == 1 and names(events).count("claimed") == 1 + assert [j["attempt"] for j in job_rows(att["id"])] == [1] + assert len(published_keys(att["id"])) == 4 # original + 3 variants, once + + +def test_duplicate_and_reordered_deliveries_are_noops(api, pair): + alice, bob, chat = pair + with service_with_env("relay", RELAY_FAULT_POINTS="duplicate_publish,reverse_order"): + atts = [api.upload(alice, chat, imagegen.png(50 + i, 40)).json() for i in range(4)] + for att in atts: + api.wait_status(bob, att["id"], "ready") + time.sleep(2) # let the duplicates be consumed + for att in atts: + assert names(events_of(att["id"])) == ["created", "claimed", "succeeded"] + assert len(published_keys(att["id"])) == 4 + logs = compose("logs", "--no-log-prefix", "worker").stdout + assert '"noop_finished"' in logs or '"noop_leased"' in logs # duplicates were seen and acked + + +def test_worker_crash_before_side_effect_lease_expires_and_job_completes(api, pair): + """The worker dies right after the claim. The redelivered message finds a valid lease (no-op); + the reaper returns the job to queued when the lease expires; attempt 2 publishes.""" + alice, bob, chat = pair + with service_with_env("worker", WORKER_FAULT_POINTS="crash_after_claim", **FAST_LEASE): + att = api.upload(alice, chat, SAMPLE).json() + api.wait_status(bob, att["id"], "ready", timeout=90) + ev = names(events_of(att["id"])) + assert ev.count("fault_injected") == 1 and "lease_expired" in ev and ev[-1] == "succeeded" + tries = attempts(att["id"]) + assert [(a["attempt"], a["outcome"]) for a in tries] == [(1, "abandoned"), (2, "succeeded")] + assert tries[0]["keys"] and all(s3_size(k) is None for k in tries[0]["keys"]) # nothing written + + +def test_worker_crash_after_s3_write_before_commit_republishes_without_duplicates(api, pair): + """Window "after the S3 write, before the result COMMIT": objects of attempt 1 exist under ITS keys + but are never published; attempt 2 publishes its own; the cleanup deletes attempt 1's objects + after ORPHAN_GRACE_SECONDS (they can never become published: the token is fenced).""" + alice, bob, chat = pair + with service_with_env("worker", WORKER_FAULT_POINTS="crash_after_s3_write", ORPHAN_GRACE_SECONDS="2", + CLEANUP_INTERVAL_SECONDS="1", **FAST_LEASE): + att = api.upload(alice, chat, SAMPLE).json() + ready = api.wait_status(bob, att["id"], "ready", timeout=90) + first, second = attempts(att["id"]) + assert (first["outcome"], second["outcome"]) == ("abandoned", "succeeded") + assert set(published_keys(att["id"])) == set(second["keys"]) + wait_for(lambda: attempts(att["id"])[0]["cleaned"], 30, "orphans of attempt 1 not cleaned") + assert all(s3_size(k) is None for k in first["keys"]) + assert all(s3_size(k) is not None for k in second["keys"]) + assert s3_keys(f"a/{att['id']}/") == set(second["keys"]) # exactly one set of objects + check_variants(api, bob, ready, SAMPLE) + + +def test_worker_crash_after_commit_before_ack_redelivery_is_noop(api, pair): + """Window "after the result COMMIT, before the ack": the message comes back; the job is + succeeded -> ack without any work; the same result stays published.""" + alice, bob, chat = pair + with service_with_env("worker", WORKER_FAULT_POINTS="crash_after_commit"): + att = api.upload(alice, chat, SAMPLE).json() + ready = api.wait_status(bob, att["id"], "ready", timeout=60) + before = published_keys(att["id"]) + wait_healthy("worker") + wait_for(lambda: '"noop_finished"' in compose("logs", "--no-log-prefix", "worker").stdout, 30, + "the redelivered message was not acknowledged as a no-op") + ev = names(events_of(att["id"])) + assert ev == ["created", "claimed", "fault_injected", "succeeded"] or ev == ["created", "claimed", "succeeded", "fault_injected"] + assert published_keys(att["id"]) == before and [a["outcome"] for a in attempts(att["id"])] == ["succeeded"] + assert api.attachment(bob, att["id"]) == ready + + +# ------------------------------------------------------------------ retries and failures +def test_transient_errors_are_retried_with_jittered_backoff(api, pair): + alice, bob, chat = pair + with service_with_env("worker", WORKER_FAULT_POINTS="transient_error=2", JOB_RETRY_BASE_SECONDS="1", + JOB_RETRY_MAX_SECONDS="8"): + att = api.upload(alice, chat, SAMPLE).json() + api.wait_status(bob, att["id"], "ready", timeout=60) + events = events_of(att["id"]) + retries = [e for e in events if e["event"] == "retry_scheduled"] + assert [(e["attempt"], e["error_code"]) for e in retries] == [(1, "injected_transient"), (2, "injected_transient")] + for e in retries: + assert 0 <= e["detail"]["delay_s"] <= 1 * 2 ** (e["attempt"] - 1) # full jitter window + assert [(a["attempt"], a["outcome"]) for a in attempts(att["id"])] == [(1, "retry"), (2, "retry"), (3, "succeeded")] + assert [o["attempt"] for o in outbox_of(att["id"])] == [1, 2, 3] # every retry went through the outbox + + +def test_retry_exhausted_failed_registry_then_replay(api, pair): + alice, bob, chat = pair + with service_with_env("worker", WORKER_FAULT_POINTS="transient_error", JOB_RETRY_BASE_SECONDS="0.2", + JOB_RETRY_MAX_SECONDS="0.5"): + att = api.upload(alice, chat, SAMPLE).json() + failed = api.wait_status(bob, att["id"], "failed", timeout=60) + assert failed["error_code"] == "retry_exhausted" and failed["variants"] == [] + [job] = job_rows(att["id"]) + assert (job["state"], job["attempt"], job["error_code"]) == ("failed", 5, "retry_exhausted") # JOB_MAX_ATTEMPTS + registry = jobctl("list-failed", "--limit", "200")["failed"] + assert any(r["attachment_id"] == att["id"] and r["error_code"] == "retry_exhausted" for r in registry) + assert attachment_row(att["id"])["staging_state"] == "present" # kept for the replay + # Operator replay: a NEW job (replay_of = the failed one), audit with operator and reason. + result = jobctl("replay", att["id"], "--operator", "alice", "--reason", "fault removed") + assert result["result"] == "queued" and result["replay_of"] == job["id"] + ready = api.wait_status(bob, att["id"], "ready", timeout=60) + check_variants(api, bob, ready, SAMPLE) + jobs = job_rows(att["id"]) + assert [(j["kind"], j["state"]) for j in jobs] == [("upload", "failed"), ("replay", "succeeded")] + ev = events_of(att["id"]) + req = next(e for e in ev if e["event"] == "replay_requested") + assert req["actor"] == "jobctl:alice" and req["detail"]["reason"] == "fault removed" + # "Repeat" never re-runs a finished job: a replay of a ready attachment is refused, nothing created. + refused = jobctl("replay", att["id"], "--operator", "alice", "--reason", "again", expect_code=3) + assert refused == {"result": "refused", "reason": "already_ready"} + assert len(job_rows(att["id"])) == 2 + + +def test_permanent_error_fails_at_once_without_retries(api, pair): + alice, bob, chat = pair + with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error"): + att = api.upload(alice, chat, SAMPLE).json() + failed = api.wait_status(bob, att["id"], "failed") + assert failed["error_code"] == "invalid_image" + assert [(a["attempt"], a["outcome"]) for a in attempts(att["id"])] == [(1, "failed")] + + +def test_memory_and_time_limits_of_the_worker(api, pair): + """40 Mpx PNG (valid, accepted by the API) with IMAGE_MAX_MEMORY_MB=200: the child process cannot + allocate the raster -> image_too_large (permanent); the worker itself keeps running. + JOB_TIMEOUT_SECONDS=3 with a 10 s stall -> processing_timeout (transient, retried).""" + alice, bob, chat = pair + with service_with_env("worker", IMAGE_MAX_MEMORY_MB="200"): + att = api.upload(alice, chat, imagegen.png(8000, 5000, compress_level=9)).json() + failed = api.wait_status(bob, att["id"], "failed", timeout=90) + assert failed["error_code"] == "image_too_large" + ok = api.upload(alice, chat, SAMPLE).json() # the same worker still works + api.wait_status(bob, ok["id"], "ready") + with service_with_env("worker", WORKER_FAULT_POINTS="slow=10", JOB_TIMEOUT_SECONDS="3"): + slow = api.upload(alice, chat, SAMPLE).json() + wait_for(lambda: any(a["error_code"] == "processing_timeout" for a in attempts(slow["id"])), 60, + "no processing_timeout") + api.wait_status(bob, slow["id"], "ready", timeout=120) # normal worker finishes it + + +def test_bad_message_is_dead_lettered_not_processed(api, pair): + """A message that does not match jobs.schema.json (published here with the relay's own broker + user) is rejected by the worker into the DLQ; nothing is processed.""" + before = queue_depth("messenger.attachment-jobs.dlq") + script = ("import asyncio, aio_pika\n" + "async def m():\n" + " url = open('/run/secrets/broker_url').read().strip()\n" + " c = await aio_pika.connect(url)\n" + " ch = await c.channel(publisher_confirms=True)\n" + " ex = await ch.get_exchange('messenger.jobs', ensure=False)\n" + " await ex.publish(aio_pika.Message(b'{\"url\":\"http://evil/x.png\"}'), routing_key='attachment.process.v1')\n" + " await c.close()\n" + "asyncio.run(m())\n") + compose("exec", "-T", "relay", "python", "-c", script) + wait_for(lambda: queue_depth("messenger.attachment-jobs.dlq") == before + 1, 20, "not dead-lettered") + assert '"bad_message"' in compose("logs", "--no-log-prefix", "worker").stdout + + +# ------------------------------------------------------------------ lease, hung worker, shutdown, concurrency +def worker_containers() -> dict[str, str]: + """hostname (= lease_owner) -> container id of every running worker.""" + ids = compose("ps", "-q", "worker").stdout.split() + out = subprocess.run(["docker", "inspect", "-f", "{{.Config.Hostname}} {{.Id}}", *ids], capture_output=True, + text=True, check=True).stdout + return dict(line.split() for line in out.splitlines()) + + +def test_hung_worker_loses_its_lease_and_cannot_publish(api, pair): + """Two workers. The one processing the job is frozen (docker pause: no heartbeat). Its lease + expires, the reaper re-queues the job, the other worker publishes it. When the frozen worker + resumes, its result is fenced by the token: the published result does not change.""" + alice, bob, chat = pair + with service_with_env("worker", scale=2, WORKER_FAULT_POINTS="slow=8", **FAST_LEASE): + att = api.upload(alice, chat, SAMPLE).json() + owner = wait_for(lambda: psql(f"SELECT lease_owner FROM jobs WHERE attachment_id = '{att['id']}' " + "AND state = 'processing'"), 30, "job never claimed") + frozen = worker_containers()[owner] + subprocess.run(["docker", "pause", frozen], check=True, capture_output=True) + try: + ready = api.wait_status(bob, att["id"], "ready", timeout=120) + published = published_keys(att["id"]) + finally: + subprocess.run(["docker", "unpause", frozen], check=True, capture_output=True) + time.sleep(12) # the resumed attempt finishes its sleep and tries to publish + assert published_keys(att["id"]) == published and api.attachment(bob, att["id"]) == ready + tries = attempts(att["id"]) + assert [(a["attempt"], a["outcome"]) for a in tries] == [(1, "abandoned"), (2, "succeeded")] + assert "lease_expired" in names(events_of(att["id"])) + check_variants(api, bob, ready, SAMPLE) + + +def test_graceful_worker_stop_finishes_the_running_attempt(api, pair): + alice, bob, chat = pair + with service_with_env("worker", WORKER_FAULT_POINTS="slow=5"): + att = api.upload(alice, chat, SAMPLE).json() + wait_for(lambda: api.attachment(bob, att["id"])["status"] == "processing", 30, "never processing") + started = time.monotonic() + compose("stop", "worker") # SIGTERM: drain, not kill + assert time.monotonic() - started < 30 + assert attachment_row(att["id"])["status"] == "ready" # committed before the exit + compose("start", "worker") + wait_healthy("worker") + assert [a["outcome"] for a in attempts(att["id"])] == ["succeeded"] + + +def test_concurrency_is_bounded_by_prefetch(api, pair): + """WORKER_CONCURRENCY=2: never more than 2 jobs processing and 2 unacked messages at once.""" + alice, bob, chat = pair + with service_with_env("worker", WORKER_FAULT_POINTS="slow=3"): + atts = [api.upload(alice, chat, imagegen.png(30 + i, 30)).json() for i in range(6)] + peak = 0 + deadline = time.monotonic() + 90 + while time.monotonic() < deadline: + states = [api.attachment(bob, a["id"])["status"] for a in atts] + peak = max(peak, states.count("processing")) + unacked = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", + "messages_unacknowledged").stdout + for line in unacked.splitlines(): + if line.startswith("messenger.attachment-jobs\t"): + assert int(line.split("\t")[1]) <= 2, line + if all(s == "ready" for s in states): + break + time.sleep(0.3) + assert all(api.attachment(bob, a["id"])["status"] == "ready" for a in atts) + assert peak == 2 + + +# ------------------------------------------------------------------ cleanup never deletes accepted work +def test_queued_staging_is_never_deleted_even_after_retention(api, pair): + """Reviewer's case in another PR: the worker was down longer than the retention and the cleanup + deleted the original of a job that was still queued. Here: the job waits queued (relay down) + while the cleanup runs every second with retention 0 - the staging copy stays, and the + database itself refuses marking it (CHECK attachments_active_has_source).""" + alice, bob, chat = pair + with service_with_env("worker", STAGING_RETENTION_SECONDS="0", CLEANUP_INTERVAL_SECONDS="1"): + with service_down("relay"): + att = api.upload(alice, chat, SAMPLE).json() + time.sleep(5) # several cleanup passes + row = attachment_row(att["id"]) + assert row["status"] == "queued" and row["staging_state"] == "present" + assert s3_size(row["staging_key"], "staging") == len(SAMPLE) + refused = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c", + f"UPDATE attachments SET staging_state = 'deleting' WHERE id = '{att['id']}'", + check=False) + assert refused.returncode != 0 and "attachments_active_has_source" in refused.stderr + ready = api.wait_status(bob, att["id"], "ready", timeout=60) + check_variants(api, bob, ready, SAMPLE) + + +def test_retention_deletes_failed_staging_then_replay_is_refused(api, pair): + alice, bob, chat = pair + with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error", STAGING_RETENTION_SECONDS="1", + CLEANUP_INTERVAL_SECONDS="1"): + att = api.upload(alice, chat, SAMPLE).json() + api.wait_status(bob, att["id"], "failed") + wait_for(lambda: attachment_row(att["id"])["staging_state"] == "deleted", 30, "staging not cleaned") + assert s3_size(attachment_row(att["id"])["staging_key"], "staging") is None + refused = jobctl("replay", att["id"], "--operator", "alice", "--reason", "too late", expect_code=3) + assert refused == {"result": "refused", "reason": "source_missing"} + assert api.attachment(bob, att["id"])["status"] == "failed" and len(job_rows(att["id"])) == 1 + + +def test_cleanup_racing_a_replay_never_deletes_the_replayed_source(api, pair): + """Reviewer's interleaving in another PR: the cleanup READ its candidates (an expired failed + attachment), a replay committed queued, the cleanup went on and deleted the staging copy. + Here the cleanup pauses exactly there (pause_cleanup); the replay commits during the pause; + the cleanup then re-checks under the row lock and skips the row. The replay finishes ready.""" + alice, bob, chat = pair + with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error"): + att = api.upload(alice, chat, SAMPLE).json() + api.wait_status(bob, att["id"], "failed") + # The pause must outlast `docker compose run jobctl` (container start: 3-15 s on a loaded Windows + # stand). With 8 s the replay once came too late: the cleanup went on, deleted the expired staging + # copy and the replay was - correctly - refused with source_missing. 20 s keeps the race window. + with service_with_env("worker", WORKER_FAULT_POINTS="pause_cleanup=20", STAGING_RETENTION_SECONDS="1", + CLEANUP_INTERVAL_SECONDS="1"): + wait_for(lambda: '"cleanup_paused"' in compose("logs", "--no-log-prefix", "--since", "60s", "worker").stdout + and att["id"] in compose("logs", "--no-log-prefix", "--since", "60s", "worker").stdout, + 30, "cleanup did not pick the failed attachment") + result = jobctl("replay", att["id"], "--operator", "alice", "--reason", "race test") + assert result["result"] == "queued" + ready = api.wait_status(bob, att["id"], "ready", timeout=90) + check_variants(api, bob, ready, SAMPLE) + assert attachment_row(att["id"])["staging_state"] == "deleted" # deleted only AFTER ready + + +def test_reprocess_of_a_not_ready_upload_is_refused(api, pair): + """Reviewer's case in another PR: worker stopped -> upload 202 -> reprocess with pipeline 2 -> + the attachment stayed queued forever. Here the command is refused and v1 completes.""" + alice, bob, chat = pair + with service_down("worker"): + att = api.upload(alice, chat, SAMPLE).json() + refused = jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "alice", "--reason", "x", + expect_code=3) + assert refused == {"result": "refused", "reason": "not_ready:queued"} + assert len(job_rows(att["id"])) == 1 + api.wait_status(bob, att["id"], "ready") + assert attachment_row(att["id"])["published_version"] == 1 + + +def test_zz_invariants_hold_after_all_scenarios(): + report = audit("--verify-checksums") + assert report["objects"]["published"] > 0 diff --git a/student-tests/test_sessions.py b/student-tests/test_sessions.py new file mode 100644 index 0000000..40d793b --- /dev/null +++ b/student-tests/test_sessions.py @@ -0,0 +1,66 @@ +"""Session lifetime: expiry with a short SESSION_TTL_SECONDS, no extension by restarts, +and the alternative SESSION_STORE=postgres. The api container is recreated with the +override and ALWAYS recreated back with the normal configuration (api_with_env).""" +from __future__ import annotations + +import datetime as dt +import time + +import pytest + +from conftest import api_env, api_with_env, restart_services, service_down + +pytestmark = pytest.mark.stack + + +def seconds_left(expires_at: str) -> float: + moment = dt.datetime.fromisoformat(expires_at.replace("Z", "+00:00")) + return (moment - dt.datetime.now(dt.timezone.utc)).total_seconds() + + +def login_session(api, actor) -> dict: + from conftest import basic + return api.call("POST", "/api/v1/auth/sessions", 201, + headers={"Authorization": basic(actor["username"], actor["password"])}, schema="Session").json() + + +@pytest.mark.parametrize("store", ["valkey", "postgres"]) +def test_short_ttl_expires(api, store): + with api_with_env(SESSION_TTL_SECONDS="2", SESSION_STORE=store): + assert api_env("SESSION_TTL_SECONDS") == "2" # the contract variable reaches the container + actor = api.register("ttl") + session = login_session(api, actor) + assert 1.0 < seconds_left(session["expires_at"]) <= 2.1 + api.call("GET", "/api/v1/users/me", 200, token=session["token"]) + time.sleep(max(0.0, seconds_left(session["expires_at"])) + 0.3) + api.call("GET", "/api/v1/users/me", 401, token=session["token"]) + api.call("DELETE", "/api/v1/auth/sessions/current", 401, token=session["token"]) + + +def test_restart_does_not_extend_ttl(api): + # 30 s: a restart of Valkey + both API replicas (readiness now also waits for S3) takes ~12-15 s. + with api_with_env(SESSION_TTL_SECONDS="30"): + actor = api.register("ttlrestart") + session = login_session(api, actor) + restart_services("valkey", "api") + assert seconds_left(session["expires_at"]) > 0, "restart took longer than the TTL; increase it" + api.call("GET", "/api/v1/users/me", 200, token=session["token"]) + time.sleep(max(0.0, seconds_left(session["expires_at"])) + 0.3) + api.call("GET", "/api/v1/users/me", 401, token=session["token"]) + + +def test_postgres_session_store(api): + """SESSION_STORE=postgres: sessions survive an API restart, logout revokes, and a DB outage + is 503 for a valid token (not 401 and not anonymous access).""" + with api_with_env(SESSION_STORE="postgres"): + assert api_env("SESSION_STORE") == "postgres" + actor = api.user("pgstore") + restart_services("api") + api.call("GET", "/api/v1/users/me", 200, token=actor["token"]) + with service_down("postgres", "stop"): + assert api.call("GET", "/api/v1/users/me", 503, token=actor["token"], + lb_error_ok=True).json()["error"]["code"] == "unavailable" + api.call("GET", "/api/v1/users/me", (401, 503), lb_error_ok=True) + api.call("GET", "/api/v1/users/me", 200, token=actor["token"]) + api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=actor["token"]) + api.call("GET", "/api/v1/users/me", 401, token=actor["token"]) diff --git a/student-tests/test_storage_failures.py b/student-tests/test_storage_failures.py new file mode 100644 index 0000000..2b07503 --- /dev/null +++ b/student-tests/test_storage_failures.py @@ -0,0 +1,112 @@ +"""S3 outages, private buckets and failover of attachments (lab 4, levels 3 and 4; lab 5: two +buckets, upload 202 + worker). + +Every injected failure is undone in `finally` (conftest.service_down / replica_stopped), and the +stand is waited for until HAProxy sees all replicas UP again.""" +from __future__ import annotations + +import time +from pathlib import Path + +import pytest + +import imagegen +from conftest import attachment_row, compose, probe_inside, replica_stopped, running_replicas, service_down + +pytestmark = pytest.mark.stack + +ROOT = Path(__file__).resolve().parents[1] +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() + + +@pytest.fixture() +def pair(api): + alice, bob = api.user("alice"), api.user("bob") + return alice, bob, api.chat(alice, bob) + + +@pytest.mark.parametrize("how", ["stop", "pause"]) +def test_s3_outage_is_503_and_text_keeps_working(api, pair, how): + """S3 down (stopped: connection refused; paused: no answer at all): + * readiness is 503 on every replica (and through the LB), quickly; + * uploads/downloads are 503 `unavailable` within the S3 deadline, never 500; + * the LB's degraded mode keeps chats/text messages working (HAProxy backend api_core); + * after recovery the earlier file is intact.""" + alice, bob, chat = pair + att = api.upload(alice, chat, SAMPLE).json() + api.wait_status(alice, att["id"], "ready") + with service_down("s3", how): + deadline = time.monotonic() + 15 + while api.client.get("/health/ready").status_code != 503: + assert time.monotonic() < deadline, "readiness did not turn 503" + time.sleep(0.5) + for replica in running_replicas(): + assert probe_inside(replica, "/health/ready") == 503 + assert probe_inside(replica, "/health/ready/core") == 200 + started = time.monotonic() + error = api.upload(alice, chat, SAMPLE, 503).json() + assert error["error"]["code"] == "unavailable" + assert time.monotonic() - started < 8 + started = time.monotonic() + api.call("GET", f"/api/v1/attachments/{att['id']}/content", 503, token=bob["token"]) + assert time.monotonic() - started < 8 + api.call("GET", f"/api/v1/attachments/{att['id']}", 200, token=bob["token"]) # metadata: PostgreSQL only + api.send(alice, chat, "текст работает без S3") # degraded mode + got = api.call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"]) + assert got.content == SAMPLE + api.upload(alice, chat, SAMPLE) + + +def test_upload_survives_failover_of_the_serving_replica(api, pair): + """Upload -> stop the replica that served it -> another replica downloads the same bytes + (nothing of the file lives in the replica).""" + alice, bob, chat = pair + data = imagegen.png_of_size(500_000) + response = api.upload(alice, chat, data) + att, served_by = response.json(), response.headers["x-instance-id"] + replica = next(r for r in running_replicas() if r["hostname"] == served_by) + api.wait_status(bob, att["id"], "ready") + with replica_stopped(replica, "kill"): + for _ in range(5): + got = api.call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"]) + assert got.headers["x-instance-id"] != served_by and got.content == data + + +def test_bucket_is_private_outside_the_api(api, pair): + """Inside the storage network (where the API is): an UNSIGNED GET of a real object and an + unsigned LIST are refused; the same GET signed with the API key pair works (control). + SeaweedFS admin endpoints (master 9333, filer 8888, volume 8080) are not reachable.""" + alice, _, chat = pair + att = api.upload(alice, chat, SAMPLE).json() + api.wait_status(alice, att["id"], "ready") + key = attachment_row(att["id"])["object_key"] + probe = ( + "import urllib.request as u, urllib.error as e, socket\n" + "def st(url):\n" + " try: return u.urlopen(url, timeout=3).status\n" + " except e.HTTPError as x: return x.code\n" + f"print(st('http://s3:8333/messenger-attachments/{key}'), st('http://s3:8333/messenger-attachments?list-type=2'))\n" + "for port in (9333, 8888, 8080):\n" + " s = socket.socket(); s.settimeout(2)\n" + " print(port, s.connect_ex(('s3', port)))\n") + out = compose("exec", "-T", "api", "python", "-c", probe).stdout.split("\n") + get_status, list_status = out[0].split() + assert get_status in ("401", "403") and list_status in ("401", "403"), out[0] + for line in out[1:4]: + port, code = line.split() + assert code != "0", f"admin port {port} reachable" + signed = compose("exec", "-T", "api", "python", "-c", + "import asyncio\nfrom messenger.config import Settings\nfrom messenger.storage import Storage\n" + "async def m():\n s=Storage(Settings.from_env()); await s.open()\n" + f" print((await s.head('{key}')).size); await s.close()\nasyncio.run(m())").stdout.strip() + assert signed == str(len(SAMPLE)) + + +def test_s3_restart_keeps_objects(api, pair): + alice, bob, chat = pair + data = imagegen.png_of_size(200_000) + att = api.upload(alice, chat, data).json() + api.wait_status(bob, att["id"], "ready") + with service_down("s3", "stop"): + pass + assert api.call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"]).content == data diff --git a/student-tests/unit/test_images.py b/student-tests/unit/test_images.py new file mode 100644 index 0000000..94d57f0 --- /dev/null +++ b/student-tests/unit/test_images.py @@ -0,0 +1,148 @@ +"""Unit tests of the image checks (src/messenger/images.py) and the filename rules. No services. + +The JPEG decoder (djpeg) exists in the API image; locally these tests are skipped without it +(the same cases run against the stand in test_attachments.py).""" +from __future__ import annotations + +import asyncio +import shutil +import sys +import time +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "src")) +sys.path.insert(0, str(ROOT / "student-tests")) + +import imagegen # noqa: E402 +from messenger import images, validation # noqa: E402 +from messenger.errors import InvalidRequest # noqa: E402 + +LIMIT = 40_000_000 +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() +has_djpeg = pytest.mark.skipif(shutil.which("djpeg") is None, reason="djpeg (libjpeg-turbo-progs) not installed") + + +def status(data: bytes) -> int: + """201 if accepted, else the HTTP status of the ImageError (413/415).""" + try: + info = images.sniff(data, LIMIT) + if info is None: + return 415 # header never completed + asyncio.run(images.verify(data, info)) + return 201 + except images.ImageError as exc: + return exc.status + + +def test_public_fixture_is_accepted(): + assert images.sniff(SAMPLE, LIMIT) == images.ImageInfo("image/png", 320, 200) + assert status(SAMPLE) == 201 + + +@pytest.mark.parametrize("data", [ + imagegen.png(37, 23, "RGBA"), imagegen.png(33, 17, "P"), imagegen.png(33, 17, "1"), + imagegen.png(33, 17, "L"), imagegen.png(81, 57, "RGB", noise=True), imagegen.png(1, 1), +], ids=["rgba", "palette", "1bit", "gray", "noise", "1x1"]) +def test_valid_png_kinds(data): + assert status(data) == 201 + + +def test_interlaced_png_is_accepted(): + # Pillow cannot write Adam7; build one by hand: 9 x 9 grey, every pass with filter 0. + from messenger.images import _png_segments + raw = b"".join(b"\x00" + bytes(stride - 1) for size, stride in _png_segments(9, 9, 8, 0, 1) + for _ in range(size // stride)) + data = imagegen.PNG_SIGNATURE + imagegen.ihdr(9, 9, 8, 0, 1) + imagegen.chunk(b"IDAT", __import__("zlib").compress(raw)) \ + + imagegen.chunk(b"IEND", b"") + assert status(data) == 201 + + +BROKEN_PNG = { + "first 33 bytes of the fixture": SAMPLE[:33], + "truncated (no IEND)": SAMPLE[:-12], + "truncated in IDAT": SAMPLE[:len(SAMPLE) // 2], + "flipped byte -> CRC error": SAMPLE[:500] + bytes([SAMPLE[500] ^ 0xFF]) + SAMPLE[501:], + "garbage IDAT with valid CRC": imagegen.png_corrupt_idat(), + "fewer rows than IHDR": imagegen.png_short_pixels(), + "bytes after IEND (polyglot)": SAMPLE + b"PK\x03\x04zip", + "text": b"just text, definitely not an image", + "gif": b"GIF89a" + bytes(64), + "two bytes of a signature": b"\x89P", +} + + +@pytest.mark.parametrize("name", list(BROKEN_PNG)) +def test_broken_png_is_415(name): + assert status(BROKEN_PNG[name]) == 415, name + + +def test_pixel_limit_is_checked_from_the_header(): + with pytest.raises(images.ImageError) as exc: + images.sniff(imagegen.png_bomb_header()[:33], LIMIT) # 33 bytes are enough + assert exc.value.status == 413 + exact = imagegen.PNG_SIGNATURE + imagegen.ihdr(8000, 5000) # exactly 40 000 000: allowed + assert images.sniff(exact, LIMIT).width == 8000 + with pytest.raises(images.ImageError) as exc: + images.sniff(imagegen.PNG_SIGNATURE + imagegen.ihdr(8001, 5000), LIMIT) + assert exc.value.status == 413 + with pytest.raises(images.ImageError) as exc: + images.sniff(imagegen.jpeg_bomb_header(), LIMIT) + assert exc.value.status == 413 + + +def test_png_verification_is_streaming_and_fast(): + """40 Mpx RGB = 120 MB of raw pixels: inflated in 1 MiB steps and discarded.""" + big = imagegen.png(8000, 5000, compress_level=9) + started = time.perf_counter() + assert status(big) == 201 + assert time.perf_counter() - started < 5 + + +def test_jpeg_header_is_parsed_incrementally(): + data = imagegen.jpeg(320, 200) + assert images.sniff(data[:4], LIMIT) is None # SOF not arrived yet + assert images.sniff(data, LIMIT) == images.ImageInfo("image/jpeg", 320, 200) + + +@has_djpeg +@pytest.mark.parametrize("data", [imagegen.jpeg(), imagegen.jpeg(640, 480, progressive=True)], ids=["base", "prog"]) +def test_valid_jpeg(data): + assert status(data) == 201 + + +@has_djpeg +@pytest.mark.parametrize("name,data", [ + ("no scan data after SOS", imagegen.jpeg_without_scan_data()), + ("truncated", imagegen.jpeg(320, 240, noise=True)[:3000]), +], ids=lambda v: v if isinstance(v, str) else "") +def test_broken_jpeg_is_415(name, data): + assert status(data) == 415, name + + +# ------------------------------------------------------------------ filename +@pytest.mark.parametrize("name", ["photo.png", "фото отпуска.jpg", "a" * 255, "emoji 👨‍👩‍👧.png", " x ", "..."[:2] + "x"]) +def test_good_filenames(name): + assert validation.filename_param([("filename", name)]) == name + + +@pytest.mark.parametrize("name", ["", " ", " ", ".", "..", "a/b.png", "a\\b.png", "a\x00b", "c1\x85.png", + "tab\t.png", "del\x7f.png", "x
y", "photo‮gnp.exe", "a" * 256]) +def test_bad_filenames(name): + with pytest.raises(InvalidRequest): + validation.filename_param([("filename", name)]) + + +def test_filename_must_be_single_and_present(): + with pytest.raises(InvalidRequest): + validation.filename_param([]) + with pytest.raises(InvalidRequest): + validation.filename_param([("filename", "a.png"), ("filename", "b.png")]) + + +def test_query_must_be_valid_utf8(): + assert validation.query_items(b"filename=%D1%84.png") == [("filename", "ф.png")] + with pytest.raises(InvalidRequest): + validation.query_items(b"filename=%FF%FE.png") diff --git a/student-tests/unit/test_pipeline.py b/student-tests/unit/test_pipeline.py new file mode 100644 index 0000000..64e79fa --- /dev/null +++ b/student-tests/unit/test_pipeline.py @@ -0,0 +1,224 @@ +"""Unit tests of lab 5 without services: variant geometry and encoding (imaging.build, the same +code the worker runs in its child process), the job message schema, backoff with jitter and the +pipeline configuration.""" +from __future__ import annotations + +import io +import json +import sys +import uuid +from pathlib import Path + +import pytest +from jsonschema import Draft202012Validator +from PIL import Image + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "src")) +sys.path.insert(0, str(ROOT / "student-tests")) + +import imagegen # noqa: E402 +from messenger import broker, imaging, jobs # noqa: E402 +from messenger.config import ConfigError, Settings # noqa: E402 +from messenger.pipeline import PIPELINES, center_square, fit # noqa: E402 + +SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() +SCHEMA = json.loads((ROOT / "contracts" / "jobs.schema.json").read_text(encoding="utf-8")) +LIMIT = 40_000_000 + + +def variants(data: bytes, content_type: str = "image/png", version: int = 1) -> dict[str, imaging.Rendered]: + return {v.name: v for v in imaging.build(data, content_type, version, LIMIT)} + + +def decoded(v: imaging.Rendered) -> Image.Image: + img = Image.open(io.BytesIO(v.data)) + img.load() + return img + + +# ------------------------------------------------------------------ geometry (contract rules) +@pytest.mark.parametrize("size, box, expected", [ + ((320, 200), 256, (256, 160)), # public fixture + ((200, 320), 256, (160, 256)), + ((100, 50), 256, (100, 50)), # never upscale + ((256, 256), 256, (256, 256)), + ((1000, 1), 256, (256, 1)), # 0.256 px -> minimum 1 px + ((1, 1000), 256, (1, 256)), + ((257, 255), 256, (256, 254)), # 255 * 256 / 257 = 254.0 (floor) + ((3000, 2000), 1280, (1280, 853)), # 853.33 -> 853 +]) +def test_fit_rounds_down_without_upscaling(size, box, expected): + assert fit(*size, box) == expected + + +def test_center_square(): + assert center_square(320, 200) == (60, 0, 260, 200) + assert center_square(7, 10) == (0, 1, 7, 8) + + +def test_public_fixture_variants_match_the_contract(): + out = variants(SAMPLE) + assert list(out) == ["thumbnail", "crop", "optimized"] + assert (out["thumbnail"].content_type, decoded(out["thumbnail"]).format, decoded(out["thumbnail"]).size) == \ + ("image/jpeg", "JPEG", (256, 160)) + assert (out["crop"].content_type, decoded(out["crop"]).size) == ("image/jpeg", (128, 128)) + assert (out["optimized"].content_type, decoded(out["optimized"]).format, decoded(out["optimized"]).size) == \ + ("image/webp", "WEBP", (320, 200)) # fits 1280 already: no upscale + for v in out.values(): + assert (v.width, v.height) == decoded(v).size + + +def test_small_image_is_not_upscaled_but_crop_is(): + out = variants(imagegen.png(40, 30)) + assert decoded(out["thumbnail"]).size == (40, 30) + assert decoded(out["optimized"]).size == (40, 30) + assert decoded(out["crop"]).size == (128, 128) + + +def test_big_image_is_bounded_by_1280(): + out = variants(imagegen.png(3000, 2000)) + assert decoded(out["optimized"]).size == (1280, 853) + assert decoded(out["thumbnail"]).size == (256, 170) + + +def test_exif_orientation_is_applied_and_dropped(): + # 60x20 stored landscape with Orientation=6 (rotate 90 CW): displayed portrait 20x60. + img = Image.new("RGB", (60, 20), (200, 30, 30)) + exif = Image.Exif() + exif[0x0112] = 6 + buf = io.BytesIO() + img.save(buf, "JPEG", exif=exif.tobytes(), quality=95) + out = variants(buf.getvalue(), "image/jpeg") + assert decoded(out["thumbnail"]).size == (20, 60) + assert decoded(out["optimized"]).size == (20, 60) + for v in out.values(): + assert not decoded(v).getexif(), v.name + + +def test_alpha_is_composited_on_white_for_jpeg_and_kept_for_webp(): + img = Image.new("RGBA", (64, 64), (255, 0, 0, 0)) # fully transparent red + buf = io.BytesIO() + img.save(buf, "PNG") + out = variants(buf.getvalue()) + thumb = decoded(out["thumbnail"]).convert("RGB") + assert min(thumb.getpixel((32, 32))) >= 250, "transparent pixels must become white, not red/black" + webp = decoded(out["optimized"]) + assert webp.mode == "RGBA" and webp.getpixel((10, 10))[3] == 0 + + +def test_metadata_is_not_copied(): + img = Image.new("RGB", (300, 300), (10, 200, 10)) + exif = Image.Exif() + exif[0x010F] = "SecretCamera" # Make + buf = io.BytesIO() + img.save(buf, "JPEG", exif=exif.tobytes(), icc_profile=b"\0" * 128, comment=b"private") + out = variants(buf.getvalue(), "image/jpeg") + for name in ("thumbnail", "crop"): + data = out[name].data + assert b"Exif" not in data and b"ICC_PROFILE" not in data and b"SecretCamera" not in data, name + assert b"EXIF" not in out["optimized"].data and b"ICCP" not in out["optimized"].data + + +@pytest.mark.parametrize("mode", ["RGBA", "P", "1", "L", "LA", "RGB"]) +def test_png_modes_are_processed(mode): + out = variants(imagegen.png(33, 17, mode)) + assert decoded(out["thumbnail"]).size == (33, 17) + + +def test_16_bit_grey_is_scaled_not_clipped(): + img = Image.new("I;16", (8, 8), 32768) # 50 % grey in 16 bits + buf = io.BytesIO() + img.save(buf, "PNG") + out = variants(buf.getvalue()) + value = decoded(out["thumbnail"]).convert("L").getpixel((4, 4)) + assert 120 <= value <= 135 + + +def test_pipeline_versions_differ_in_bytes_not_in_geometry(): + v1, v2 = variants(SAMPLE, version=1), variants(SAMPLE, version=2) + for name in v1: + assert (v1[name].width, v1[name].height) == (v2[name].width, v2[name].height) + assert v1[name].sha256 != v2[name].sha256 + assert variants(SAMPLE, version=1)["thumbnail"].sha256 == v1["thumbnail"].sha256 # deterministic + + +def test_pixel_limit_is_checked_before_decoding(): + # 8001 x 5000 = 40.005 Mpx with only a few rows of data: refused from the header (TooLarge); + # 20000 x 10000 is refused even earlier by Pillow's own bomb check (> 2 x MAX_IMAGE_PIXELS). + with pytest.raises(imaging.TooLarge): + imaging.build(imagegen.png_bomb_header(8001, 5000), "image/png", 1, LIMIT) + with pytest.raises((imaging.TooLarge, Image.DecompressionBombError)): + imaging.build(imagegen.png_bomb_header(), "image/png", 1, LIMIT) + + +def test_child_process_protocol_round_trip(): + out = list(variants(SAMPLE).values()) + raw = json.dumps({"variants": [{"name": v.name, "content_type": v.content_type, "width": v.width, + "height": v.height, "size": len(v.data)} for v in out]}).encode() + b"\n" + raw += b"".join(v.data for v in out) + parsed = imaging.parse_output(raw) + assert [(p.name, p.sha256) for p in parsed] == [(v.name, v.sha256) for v in out] + with pytest.raises(imaging.ProcessingError): + imaging.parse_output(raw[:-1]) + + +# ------------------------------------------------------------------ message format +def test_encoded_message_matches_jobs_schema_and_carries_ids_only(): + import datetime as dt + raw = broker.encode(str(uuid.uuid4()), str(uuid.uuid4()), 1, 2, dt.datetime.now(dt.timezone.utc)) + body = json.loads(raw) + assert not list(Draft202012Validator(SCHEMA, format_checker=Draft202012Validator.FORMAT_CHECKER).iter_errors(body)) + assert set(body) == {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"} + assert broker.decode(raw) == body + + +@pytest.mark.parametrize("change", [ + {"schema_version": 2}, {"type": "other"}, {"job_id": "not-a-uuid"}, {"attempt": 0}, {"attempt": True}, + {"pipeline_version": "1"}, {"created_at": "yesterday"}, {"url": "http://evil"}, {"object_key": "a/b"}, + {"traceparent": "bad"}, +]) +def test_invalid_messages_are_rejected(change): + body = json.loads(broker.encode(str(uuid.uuid4()), str(uuid.uuid4()), 1, 1, + __import__("datetime").datetime(2026, 1, 1, tzinfo=__import__("datetime").timezone.utc))) + body.update(change) + with pytest.raises(broker.BadMessage): + broker.decode(json.dumps(body).encode()) + # The contract schema refuses the same messages (date-time needs an optional jsonschema extra). + checker = Draft202012Validator.FORMAT_CHECKER + assert list(Draft202012Validator(SCHEMA, format_checker=checker).iter_errors(body)) or "created_at" in change + + +def test_garbage_is_rejected(): + for raw in (b"", b"[]", b"{", b"\xff", b"x" * 5000): + with pytest.raises(broker.BadMessage): + broker.decode(raw) + + +# ------------------------------------------------------------------ backoff and configuration +def test_backoff_is_full_jitter_and_capped(): + assert jobs.backoff_delay(1, 2, 60, rnd=lambda: 1.0) == 2 + assert jobs.backoff_delay(3, 2, 60, rnd=lambda: 1.0) == 8 + assert jobs.backoff_delay(10, 2, 60, rnd=lambda: 1.0) == 60 + assert jobs.backoff_delay(4, 2, 60, rnd=lambda: 0.0) == 0 + samples = [jobs.backoff_delay(3, 2, 60) for _ in range(500)] + assert 0 <= min(samples) < 2 and 6 < max(samples) <= 8 # spread over the whole window + + +def test_pipeline_settings(monkeypatch): + monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z") + monkeypatch.setenv("S3_ACCESS_KEY_ID", "AKTEST") + monkeypatch.setenv("S3_SECRET_ACCESS_KEY", "secret-for-unit-tests") + s = Settings.from_env() + assert (s.job_max_attempts, s.job_timeout_seconds, s.worker_concurrency, s.staging_retention_seconds) == (5, 60, 2, 86400) + assert s.s3_staging_bucket == "messenger-staging" and s.pipeline_version == 1 + monkeypatch.setenv("FAULT_POINTS", "transient_error=3,slow") + s = Settings.from_env() + assert s.fault_points == {"transient_error", "slow"} and s.fault_value("transient_error") == 3 + for name, value in (("PIPELINE_VERSION", "9"), ("JOB_MAX_ATTEMPTS", "0"), ("FAULT_POINTS", "slow=x"), + ("S3_STAGING_BUCKET", "messenger-attachments"), ("JOB_RETRY_BASE_SECONDS", "100")): + monkeypatch.setenv(name, value) + with pytest.raises(ConfigError): + Settings.from_env() + monkeypatch.delenv(name) + assert set(PIPELINES) == {1, 2, 3} diff --git a/student-tests/unit/test_telemetry.py b/student-tests/unit/test_telemetry.py new file mode 100644 index 0000000..fa2c936 --- /dev/null +++ b/student-tests/unit/test_telemetry.py @@ -0,0 +1,196 @@ +"""Lab 6 unit tests of the instrumentation (no stand): in-memory span/log/metric exporters. + +What must hold (README level 3/4, reviewer remarks to other students): +* the HTTP SERVER span CONTINUES an incoming W3C traceparent (same trace id, parent = caller span), + it is SERVER (not INTERNAL), named by the route TEMPLATE; 5xx = error, 4xx = not an error; +* metric attributes are low-cardinality only (no ids, no raw path); buckets fit seconds; +* the job message carries traceparent in the schema field (contracts/jobs.schema.json); +* log records carry trace_id/span_id of the active span; successful probes are not exported. +""" +from __future__ import annotations + +import json +import logging +from pathlib import Path + +import pytest +from jsonschema import Draft202012Validator +from opentelemetry import metrics, trace +from opentelemetry._logs import set_logger_provider +from opentelemetry.sdk._logs import LoggerProvider +from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter, SimpleLogRecordProcessor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import InMemoryMetricReader +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter +from opentelemetry.trace import SpanKind, StatusCode +from starlette.applications import Starlette +from starlette.responses import JSONResponse +from starlette.routing import Route +from starlette.testclient import TestClient + +from messenger import broker, telemetry +from messenger.app import RequestContextMiddleware, route_template + +ROOT = Path(__file__).resolve().parents[2] +SPANS = InMemorySpanExporter() +LOGS = InMemoryLogRecordExporter() +METRICS = InMemoryMetricReader() + + +@pytest.fixture(scope="module", autouse=True) +def providers(): + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(SPANS)) + trace.set_tracer_provider(provider) + metrics.set_meter_provider(MeterProvider(metric_readers=[METRICS])) + log_provider = LoggerProvider() + log_provider.add_log_record_processor(SimpleLogRecordProcessor(LOGS)) + set_logger_provider(log_provider) + handler = telemetry.OtlpLogHandler(log_provider) + logger = logging.getLogger("messenger") + level = logger.level + logger.addHandler(handler) + logger.setLevel(logging.INFO) + yield + logger.removeHandler(handler) + logger.setLevel(level) + + +async def item(request): + status = int(request.query_params.get("status", "200")) + logging.getLogger("messenger.test").info("item_served", extra={"fields": {"item": "x", "n": 1}}) + return JSONResponse({"ok": True}, status_code=status) + + +async def health(request): + return JSONResponse({"status": "ok"}) + + +def client() -> TestClient: + app = Starlette(routes=[Route("/api/v1/items/{item_id}", item, methods=["GET"]), + Route("/health/live", health, methods=["GET"])]) + app.add_middleware(RequestContextMiddleware, instance_id="unit-1") + return TestClient(app) + + +def server_spans(): + return [s for s in SPANS.get_finished_spans() if s.kind == SpanKind.SERVER] + + +def test_server_span_continues_incoming_traceparent(): + SPANS.clear() + trace_id, parent = "4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7" + response = client().get("/api/v1/items/123e4567-e89b-12d3-a456-426614174000", + headers={"traceparent": f"00-{trace_id}-{parent}-01"}) + assert response.status_code == 200 + assert response.headers["x-trace-id"] == trace_id + (span,) = server_spans() + assert format(span.context.trace_id, "032x") == trace_id + assert format(span.parent.span_id, "016x") == parent and span.parent.is_remote + assert span.name == "GET /api/v1/items/{item_id}" # template, not the UUID + assert span.attributes["http.route"] == "/api/v1/items/{item_id}" + assert span.attributes["http.response.status_code"] == 200 + assert span.status.status_code == StatusCode.UNSET + assert "123e4567" not in json.dumps(dict(span.attributes)) # no raw path / ids in attributes + + +def test_without_traceparent_a_new_root_trace_is_started(): + SPANS.clear() + response = client().get("/api/v1/items/1") + (span,) = server_spans() + assert span.parent is None + assert response.headers["x-trace-id"] == format(span.context.trace_id, "032x") + + +def test_5xx_is_an_error_4xx_is_not(): + SPANS.clear() + client().get("/api/v1/items/1?status=503") + client().get("/api/v1/items/1?status=404") + by_code = {s.attributes["http.response.status_code"]: s for s in server_spans()} + assert by_code[503].status.status_code == StatusCode.ERROR + assert by_code[404].status.status_code == StatusCode.UNSET + + +def test_health_probes_get_no_span_and_unknown_paths_one_label(): + SPANS.clear() + c = client() + assert c.get("/health/live").status_code == 200 + assert c.get("/scanner/random/path/12345").status_code == 404 + assert [s.name for s in server_spans()] == ["GET UNMATCHED"] + assert route_template({}) == "UNMATCHED" + + +def test_http_metric_attributes_are_low_cardinality_and_buckets_fit_seconds(): + client().get("/api/v1/items/42?status=200") + data = METRICS.get_metrics_data() + points = [p for rm in data.resource_metrics for sm in rm.scope_metrics for m in sm.metrics + if m.name == "http.server.request.duration" for p in m.data.data_points] + assert points + for point in points: + assert set(point.attributes) == {"http.request.method", "http.route", "http.response.status_code", + "http.response.status_class"} + assert "42" not in str(point.attributes["http.route"]) + assert list(points[0].explicit_bounds) == list(telemetry.HTTP_BUCKETS) + assert points[0].explicit_bounds[0] <= 0.001 # millisecond resolution, not 0/5/10 s + + +def test_job_message_carries_traceparent_in_the_schema_field(): + schema = json.loads((ROOT / "contracts" / "jobs.schema.json").read_text(encoding="utf-8")) + tracer = trace.get_tracer("test") + with tracer.start_as_current_span("producer", kind=SpanKind.PRODUCER) as span: + carrier = telemetry.inject() + import datetime as dt + raw = broker.encode("11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222", 1, 1, + dt.datetime(2026, 11, 16, tzinfo=dt.timezone.utc), carrier) + body = json.loads(raw) + assert list(Draft202012Validator(schema).iter_errors(body)) == [] + # flags: 01 = sampled (+ 02 = "random trace id", W3C Trace Context level 2, newer SDKs) + ctx = span.get_span_context() + assert body["traceparent"][:52] == f"00-{format(ctx.trace_id, '032x')}-{format(ctx.span_id, '016x')}" + assert int(body["traceparent"][-2:], 16) & 1 == 1 + assert broker.decode(raw)["traceparent"] == body["traceparent"] + # the consumer side: the extracted context makes the CONSUMER span a child of the producer + ctx = telemetry.extract(body["traceparent"], body.get("tracestate")) + with tracer.start_as_current_span("consumer", context=ctx, kind=SpanKind.CONSUMER) as consumer: + assert consumer.parent.span_id == span.get_span_context().span_id + + +def test_log_records_carry_trace_context_and_fields(): + LOGS.clear() + SPANS.clear() + client().get("/api/v1/items/7", headers={"X-Request-Id": "unit-req-1"}) + records = [r.log_record for r in LOGS.get_finished_logs()] + served = next(r for r in records if r.body == "item_served") + (span,) = server_spans() + assert served.trace_id == span.context.trace_id and served.span_id == span.context.span_id + assert served.attributes["item"] == "x" and served.attributes["n"] == 1 + access = next(r for r in records if r.body == "request") + assert access.attributes["request_id"] == "unit-req-1" + assert access.attributes["route"] == "/api/v1/items/{item_id}" + assert access.trace_id == span.context.trace_id + + +def test_successful_probe_lines_are_not_exported_failed_ones_are(): + LOGS.clear() + log = logging.getLogger("messenger.access") + log.info("request", extra={"fields": {"route": "/health/ready", "status": 200}}) + log.info("request", extra={"fields": {"route": "/health/ready", "status": 503}}) + log.info("request", extra={"fields": {"route": "/api/v1/chats", "status": 200}}) + exported = [(r.log_record.attributes["route"], r.log_record.attributes["status"]) for r in LOGS.get_finished_logs()] + assert exported == [("/health/ready", 503), ("/api/v1/chats", 200)] + + +def test_child_span_only_inside_a_traced_operation(): + SPANS.clear() + with telemetry.child_span("orphan") as span: + assert span is None # no root spans from background loops + tracer = trace.get_tracer("test") + with tracer.start_as_current_span("job"): + with pytest.raises(ValueError): + with telemetry.child_span("step") as span: + assert span is not None + raise ValueError("boom") + step = next(s for s in SPANS.get_finished_spans() if s.name == "step") + assert step.status.status_code == StatusCode.ERROR and step.attributes["error.type"] == "ValueError" diff --git a/student-tests/unit/test_unit.py b/student-tests/unit/test_unit.py new file mode 100644 index 0000000..adf227f --- /dev/null +++ b/student-tests/unit/test_unit.py @@ -0,0 +1,225 @@ +"""Pure functions, no services: validation, cursor, Authorization parsing, Argon2id, config.""" +from __future__ import annotations + +import asyncio +import base64 +import datetime as dt + +import pytest + +from messenger import authhdr, cursor, passwords, validation +from messenger.config import ConfigError, Settings +from messenger.errors import InvalidRequest, Unauthorized +from messenger.timefmt import UTC, from_us, rfc3339, to_us + + +def b64(raw: bytes) -> str: + return base64.b64encode(raw).decode() + + +# ------------------------------------------------------------------ password rules +@pytest.mark.parametrize("password", ["Twelve-chars", "я" * 128, "пароль:с:двоеточиями", "😀" * 12, "a b c d e f g"]) +def test_valid_passwords(password): + assert validation.password_field({"password": password}) == password + + +@pytest.mark.parametrize("password", ["short-11ch", "я" * 129, " " * 12, "\t\n " * 5, "\ud800" * 12, None, 123456789012]) +def test_invalid_passwords(password): + with pytest.raises(InvalidRequest): + validation.password_field({"password": password}) + + +def test_text_may_contain_nul_but_not_lone_surrogates(): + assert validation.text_field({"t": "a\u0000b"}, "t", 10) == "a\u0000b" + with pytest.raises(InvalidRequest): + validation.text_field({"t": "a\ud800"}, "t", 10) + + +# ------------------------------------------------------------------ cursor +CHAT = "3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11" + + +def test_cursor_roundtrip_and_binding(): + key = (to_us(dt.datetime(2026, 10, 12, 12, 0, 0, 123456, tzinfo=UTC)), "11111111-1111-4111-8111-111111111111") + token = cursor.encode(cursor.MESSAGES, CHAT, key) + assert cursor.decode(token, cursor.MESSAGES, CHAT) == key + with pytest.raises(InvalidRequest): + cursor.decode(token, cursor.MESSAGES, "00000000-0000-4000-8000-000000000000") # other chat + with pytest.raises(InvalidRequest): + cursor.decode(token, cursor.CHATS, CHAT) # other resource + + +@pytest.mark.parametrize("payload", [ + b"v1|m|" + CHAT.encode() + b"|253402300800000000|11111111-1111-4111-8111-111111111111", # 1 us after 9999-12-31 + b"v1|m|" + CHAT.encode() + b"|9999999999999999999|11111111-1111-4111-8111-111111111111", # int64 edge + b"v1|m|" + CHAT.encode() + b"|-1|11111111-1111-4111-8111-111111111111", + b"v1|m|" + CHAT.encode() + b"|1|not-a-uuid", + b"v1|m|" + CHAT.encode() + b"|1|11111111-1111-4111-8111-11111111111G", + b"v2|m|" + CHAT.encode() + b"|1|11111111-1111-4111-8111-111111111111", +]) +def test_broken_cursors_are_400_not_500(payload): + token = base64.urlsafe_b64encode(payload).rstrip(b"=").decode() + with pytest.raises(InvalidRequest): + cursor.decode(token, cursor.MESSAGES, CHAT) + + +def test_time_helpers_are_exact(): + moment = dt.datetime(2026, 2, 28, 23, 59, 59, 999999, tzinfo=UTC) + assert from_us(to_us(moment)) == moment + assert rfc3339(moment) == "2026-02-28T23:59:59.999999Z" + assert from_us(cursor.MAX_TS_US).year == 9999 + + +# ------------------------------------------------------------------ Authorization header +def test_basic_is_parsed_and_password_may_contain_colons(): + assert authhdr.parse_basic("Basic " + b64("alice:pa:ss:wörd".encode())) == ("alice", "pa:ss:wörd") + assert authhdr.parse_basic("basic " + b64(b"bob_1:x" * 1)) == ("bob_1", "x") + + +@pytest.mark.parametrize("header", [ + None, "", "Basic", "Basic é", "Basic !!!!", "Basic " + b64(b"no-colon"), "Basic " + b64(b"\xff\xfe:pw"), + "Basic " + b64(b":password"), "Basic " + b64(b"alice:"), "Basic " + b64("Алиса:pw".encode()), + "Bearer " + "a" * 43, "Basic " + "A" * 2000, +]) +def test_bad_basic_is_401_with_basic_challenge(header): + with pytest.raises(Unauthorized) as info: + authhdr.parse_basic(header) + assert info.value.headers["WWW-Authenticate"].startswith("Basic realm=\"messenger\"") + + +@pytest.mark.parametrize("header", [None, "", "Bearer", "Bearer short", "Bearer " + "a" * 43 + "!", + "Basic " + b64(b"alice:password-123"), "Token " + "a" * 43, "Bearer " + "é" * 43]) +def test_bad_bearer_is_401_with_bearer_challenge(header): + with pytest.raises(Unauthorized) as info: + authhdr.parse_bearer(header) + assert info.value.headers["WWW-Authenticate"] == 'Bearer realm="messenger"' + + +def test_bearer_ok(): + token = "A_b-" + "x" * 39 + assert authhdr.parse_bearer("Bearer " + token) == token + + +# ------------------------------------------------------------------ Argon2id +def test_argon2id_hash_and_verify(): + async def scenario(): + stored = await passwords.hash_password("я" * 128) + assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$") + assert await passwords.verify_password(stored, "я" * 128) + assert not await passwords.verify_password(stored, "я" * 127) + assert not await passwords.verify_password(None, "anything") # unknown user, dummy hash + assert not await passwords.verify_password("not-a-hash", "anything") + assert await passwords.hash_password("same password!") != await passwords.hash_password("same password!") # salt + asyncio.run(scenario()) + + +# ------------------------------------------------------------------ config +@pytest.fixture(autouse=True) +def s3_credentials(monkeypatch): + """Lab 4: Settings require the API's S3 key pair; synthetic values for the unit tests.""" + monkeypatch.setenv("S3_ACCESS_KEY_ID", "AKTEST") + monkeypatch.setenv("S3_SECRET_ACCESS_KEY", "secret-for-unit-tests") + + +def test_s3_settings_are_validated_and_contract_limits_cannot_be_raised(monkeypatch): + monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z") + settings = Settings.from_env() + assert (settings.max_upload_bytes, settings.max_image_pixels) == (10 * 1024 * 1024, 40_000_000) + assert settings.fault_points == frozenset() and settings.upload_concurrency == 4 + for name, value in (("MAX_UPLOAD_BYTES", "10485761"), ("MAX_IMAGE_PIXELS", "40000001"), + ("FAULT_POINTS", "drop_database"), ("S3_ENDPOINT", "ftp://s3"), ("S3_BUCKET", "Bad_Bucket")): + monkeypatch.setenv(name, value) + with pytest.raises(ConfigError): + Settings.from_env() + monkeypatch.delenv(name) + monkeypatch.delenv("S3_SECRET_ACCESS_KEY") + with pytest.raises(ConfigError): + Settings.from_env() + + +def test_settings_read_secret_files_and_contract_names(tmp_path, monkeypatch): + url_file = tmp_path / "database_url" + url_file.write_text("postgresql://u:p@db/x\n", encoding="utf-8") + monkeypatch.setenv("DATABASE_URL_FILE", str(url_file)) + monkeypatch.setenv("SESSION_STORE", "redis") + monkeypatch.setenv("CACHE_URL", "redis://:p@valkey:6379/0") + monkeypatch.setenv("SESSION_TTL_SECONDS", "2") + settings = Settings.from_env() + assert settings.database_url == "postgresql://u:p@db/x" + assert settings.session_store == "valkey" and settings.session_ttl_seconds == 2 + monkeypatch.setenv("SESSION_TTL_SECONDS", "0") + with pytest.raises(ConfigError): + Settings.from_env() + monkeypatch.setenv("SESSION_TTL_SECONDS", "2") + monkeypatch.setenv("DATABASE_URL_FILE", str(tmp_path / "missing")) + with pytest.raises(ConfigError) as info: + Settings.from_env() + assert "u:p" not in str(info.value) + + +# ------------------------------------------------------------------ lab 3: idempotency, JSON, instance id +@pytest.mark.parametrize("key", ["a", "k" * 128, "A-Za-z0-9._:-", "2026-10-16T10:00:00.1"]) +def test_valid_idempotency_keys(key): + assert validation.idempotency_key(key) == key + + +@pytest.mark.parametrize("key", [None, "", "k" * 129, "ключ", "a b", "a/b", "a,b", "a\tb", "a\x00b", "*", "é"]) +def test_invalid_idempotency_keys(key): + with pytest.raises(InvalidRequest): + validation.idempotency_key(key) + + +@pytest.mark.parametrize("raw", [b'{"text":"a","text":"b"}', b'{"a":{"x":1,"x":2}}', b'\xff', b'{"text":"x"} {}']) +def test_duplicate_keys_and_garbage_json_are_rejected(raw): + with pytest.raises(InvalidRequest): + validation.parse_json_object(raw) + + +def test_attachment_ids_absent_equals_empty_and_is_validated(): + assert validation.attachment_ids_field({"text": "x"}) == [] + assert validation.attachment_ids_field({"attachment_ids": []}) == [] + one = "11111111-1111-4111-8111-111111111111" + assert validation.attachment_ids_field({"attachment_ids": [one.upper()]}) == [one] + for bad in (None, "x", [1], ["nope"], [one, one.upper()], [one] * 11): + with pytest.raises(InvalidRequest): + validation.attachment_ids_field({"attachment_ids": bad}) + + +def test_request_fingerprint_ignores_key_order_and_default_attachments(): + from messenger.app import request_fingerprint + assert request_fingerprint("привет", []) == request_fingerprint("привет", []) + assert request_fingerprint("привет", []) != request_fingerprint("привет ", []) + assert request_fingerprint("a\u0000b", []) != request_fingerprint("ab", []) + one = "11111111-1111-4111-8111-111111111111" + assert request_fingerprint("x", [one]) != request_fingerprint("x", []) + + +def test_instance_id_defaults_to_hostname_and_is_validated(monkeypatch): + import socket + monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z") + monkeypatch.delenv("INSTANCE_ID", raising=False) + assert Settings.from_env().instance_id == socket.gethostname() + monkeypatch.setenv("INSTANCE_ID", "replica-a") + assert Settings.from_env().instance_id == "replica-a" + for bad in ("with space", "x" * 65, "ip/1"): + monkeypatch.setenv("INSTANCE_ID", bad) + with pytest.raises(ConfigError): + Settings.from_env() + + +def test_idempotency_ttl_cannot_be_below_24_hours(monkeypatch): + monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z") + monkeypatch.setenv("IDEMPOTENCY_TTL_SECONDS", "3600") + with pytest.raises(ConfigError): + Settings.from_env() + + +def test_message_write_path_setting(monkeypatch): + monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z") + monkeypatch.delenv("MESSAGE_WRITE_PATH", raising=False) + assert Settings.from_env().message_write_path == "function" + monkeypatch.setenv("MESSAGE_WRITE_PATH", "multi") + assert Settings.from_env().message_write_path == "multi" + monkeypatch.setenv("MESSAGE_WRITE_PATH", "fast") + with pytest.raises(ConfigError): + Settings.from_env() -- 2.54.0 From 7c43d31dc78756d66d0c9f3e7700962d95c98e58 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:09:46 +0300 Subject: [PATCH 02/16] =?UTF-8?q?lab7:=20=D0=BB=D0=BE=D0=BA=D0=B0=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D0=B0=D1=8F=20PKI=20(public-ca=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20ingress,=20internal-ca=20=D0=B4=D0=BB=D1=8F=20=D1=81?= =?UTF-8?q?=D0=B5=D1=80=D0=B2=D0=B8=D1=81=D0=BE=D0=B2),=20HTTPS=20ingress?= =?UTF-8?q?=20=D0=BD=D0=B0=208443,=20=D0=B1=D0=B5=D0=B7=20=D0=BE=D1=82?= =?UTF-8?q?=D0=BA=D1=80=D1=8B=D1=82=D0=BE=D0=B3=D0=BE=208080?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compose.yaml | 30 ++++--- infra/haproxy/haproxy.cfg | 10 ++- scripts/bg.ps1 | 11 +++ scripts/init_pki.py | 170 ++++++++++++++++++++++++++++++++++++++ scripts/init_secrets.py | 5 +- 5 files changed, 210 insertions(+), 16 deletions(-) create mode 100644 scripts/bg.ps1 create mode 100644 scripts/init_pki.py diff --git a/compose.yaml b/compose.yaml index f1e254b..00fff4f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -21,7 +21,7 @@ # every service gets only the secrets it needs. Only the LB publishes ports (loopback only). # Networks: `edge` (lb <-> api); internal (no route outside): `data` (postgres/valkey), # `storage` (s3), `queue` (broker). The API is NOT on `queue`: it never talks to the broker. -name: mtusi-lab6 +name: ${COMPOSE_PROJECT_NAME:-mtusi-lab7} x-api-env: &api-env APP_ENV: ${APP_ENV:-lab} @@ -231,7 +231,7 @@ services: context: . args: BUILD_REVISION: ${BUILD_REVISION:-dev} - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.migrate"] environment: DATABASE_URL_FILE: /run/secrets/database_url @@ -250,7 +250,7 @@ services: # One-shot, idempotent S3 bootstrap: both buckets, sentinel object, verification of the access # model (private buckets, least-privilege keys). The ONLY holder of the admin key pair besides s3. s3-init: - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.s3_bootstrap"] environment: S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} @@ -292,7 +292,7 @@ services: context: . args: BUILD_REVISION: ${BUILD_REVISION:-dev} - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} environment: <<: [*api-env, *otel-env] OTEL_SERVICE_NAME: messenger-api @@ -340,13 +340,15 @@ services: image: haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 volumes: - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + secrets: + - source: pki_ingress_pem # public-ca leaf + key, SAN localhost/127.0.0.1/::1 + target: ingress.pem ports: - # The ONLY public entry point, on the loopback interfaces only. Both IPv4 and IPv6: + # The ONLY public entry point: HTTPS, on the loopback interfaces only. Both IPv4 and IPv6: # on Windows `localhost` resolves to ::1 first, and a refused ::1 connection costs ~2 s # per request before the fallback to 127.0.0.1 (measured in lab 3: 2.0 s vs 0.007 s). - - "127.0.0.1:${APP_PUBLISH_PORT:-8080}:8080" - - "[::1]:${APP_PUBLISH_PORT:-8080}:8080" - - "127.0.0.1:${LB_STATS_PORT:-8404}:8404" # local status page (UP/DOWN of replicas) + - "127.0.0.1:${APP_PUBLISH_PORT:-8443}:8443" + - "[::1]:${APP_PUBLISH_PORT:-8443}:8443" healthcheck: # Config is valid and the process answers; whether any API is ready is the LB's own job. test: ["CMD-SHELL", "haproxy -c -q -f /usr/local/etc/haproxy/haproxy.cfg && wget -q -O /dev/null http://127.0.0.1:8404/"] @@ -365,7 +367,7 @@ services: # Lab 5: outbox relay + lease reaper (src/messenger/relay.py). One process; a second one would # be safe (SKIP LOCKED) but is not needed. Database + broker only, no S3 keys. relay: - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.relay"] environment: <<: [*pipeline-env, *otel-env] @@ -399,7 +401,7 @@ services: # Lab 5: image worker (src/messenger/worker.py). Scalable (`--scale worker=2`): competing # consumers of one queue; the database lease decides who works on a job. worker: - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.worker"] environment: <<: [*pipeline-env, *otel-env] @@ -452,7 +454,7 @@ services: # S3 auditor key: Read + List, no Write). On demand: docker compose run --rm auditor auditor: profiles: ["tools"] - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} entrypoint: ["python", "-m", "messenger.audit"] command: [] environment: @@ -487,7 +489,7 @@ services: # docker compose run --rm jobctl replay --operator alice --reason "..." jobctl: profiles: ["tools"] - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} entrypoint: ["python", "-m", "messenger.jobctl"] command: [] environment: @@ -681,3 +683,7 @@ secrets: file: ./secrets/broker_url_worker grafana_admin_password: file: ./secrets/grafana_admin_password + # Lab 7 PKI (scripts/init_pki.py). Each service mounts only its own certificate/key and the CA it + # verifies peers with; the CA private keys are mounted nowhere. + pki_ingress_pem: + file: ./secrets/pki/ingress.pem diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg index 13172af..2e01763 100644 --- a/infra/haproxy/haproxy.cfg +++ b/infra/haproxy/haproxy.cfg @@ -74,7 +74,9 @@ defaults http-error status 504 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API-реплика не ответила вовремя; повторите с тем же Idempotency-Key\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]" frontend public - bind :8080 + # Lab 7: the ONLY public listener is HTTPS. Certificate of the public CA (SAN localhost, + # 127.0.0.1, ::1; scripts/init_pki.py), TLS 1.2+. There is no plaintext listener to fall back to. + bind :8443 ssl crt /run/secrets/ingress.pem ssl-min-ver TLSv1.2 alpn http/1.1 # One request id end to end: keep a valid client X-Request-Id, otherwise create one; the # API echoes it, and errors generated by the LB itself carry the same value. http-request set-header X-Request-Id %[uuid()] unless { req.hdr(x-request-id) -m reg ^[A-Za-z0-9._:-]{1,128}$ } @@ -107,9 +109,11 @@ backend api_core default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 server-template core 8 api:8080 -# Local-only status page (127.0.0.1:8404 on the host): which replica is UP/DOWN right now. +# Status page for the container healthcheck only: bound to the container's own loopback and NOT +# published (lab 7: only the TLS ingress leaves the host). Operators use the admin socket +# (`docker compose exec lb ...`, scripts/lbctl.py). frontend stats - bind :8404 + bind 127.0.0.1:8404 stats enable stats uri / stats refresh 2s diff --git a/scripts/bg.ps1 b/scripts/bg.ps1 new file mode 100644 index 0000000..d3ce819 --- /dev/null +++ b/scripts/bg.ps1 @@ -0,0 +1,11 @@ +# Run a long command as a separate Windows process that survives the calling shell/session. +# powershell -File scripts/bg.ps1 -Log evidence/run.log -Cmd "docker compose up -d --build --wait" +# The command runs in Git Bash (same syntax as the Makefile/hooks); the exit code is the last +# line of the log ("exit=N"). Nothing secret is printed by the commands used with it. +param([Parameter(Mandatory)][string]$Log, [Parameter(Mandatory)][string]$Cmd) +$bash = Join-Path $env:ProgramFiles "Git\bin\bash.exe" +$root = Split-Path -Parent $PSScriptRoot +$logPath = if ([IO.Path]::IsPathRooted($Log)) { $Log } else { Join-Path $root $Log } +New-Item -ItemType Directory -Force (Split-Path -Parent $logPath) | Out-Null +$inner = "cd '$($root -replace '\\','/')' && export PYTHONUTF8=1 && { $Cmd ; } > '$($logPath -replace '\\','/')' 2>&1; echo exit=`$? >> '$($logPath -replace '\\','/')'" +Start-Process -FilePath $bash -ArgumentList @('-lc', "`"$inner`"") -WindowStyle Hidden diff --git a/scripts/init_pki.py b/scripts/init_pki.py new file mode 100644 index 0000000..a9e5eab --- /dev/null +++ b/scripts/init_pki.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Local PKI of the lab 7 stand: two CAs and one leaf certificate per service, in ./secrets/pki. + + .venv/Scripts/python scripts/init_pki.py (also called by scripts/init_secrets.py) + +Needs the `cryptography` package (requirements-test.txt). Idempotent: existing files are kept, +so re-running never replaces a CA that already signed the running stand. Prints file names +only, never key material. ./secrets is git-ignored and docker-ignored; nothing here is committed +or baked into an image. Delete ./secrets/pki to start a new PKI (then recreate the containers). + +Two trust domains (contracts/trust-matrix.md): + public-ca signs ONLY what people connect to: the HTTPS ingress (HAProxy, :8443) and the + Grafana UI, SAN localhost / 127.0.0.1 / ::1. Its certificate is the CA_FILE of the + public tests; it may be given to anyone. It is trusted by NO service. + internal-ca signs the service identities. SAN = the compose service name (the DNS name the + peer dials), EKU serverAuth and/or clientAuth by role. Services trust only it. +The CA private keys (*-ca.key) are mounted into no container: only this script uses them. + +Test-only material (never trusted by the stand): `foreign-ca` and a client certificate signed by +it with the allowed SAN `lb` - proves that the right name from a wrong CA is refused. +""" +from __future__ import annotations + +import datetime as dt +import ipaddress +import os +import sys +from pathlib import Path + +try: + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +except ImportError: # pragma: no cover - message for a missing venv + sys.exit("init_pki.py needs `cryptography`: python -m venv .venv && " + ".venv/Scripts/python -m pip install -r requirements-test.txt") + +ROOT = Path(__file__).resolve().parents[1] +PKI = ROOT / "secrets" / "pki" +CA_DAYS = 5 * 365 +LEAF_DAYS = 365 + +SERVER, CLIENT = ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH +LOCAL = ["localhost", "127.0.0.1"] # only for services whose own healthcheck/CLI dials loopback over TLS +# name -> (CA, extra SANs besides the name itself, EKUs). The name is the identity: CN and SAN. +LEAVES = { + # Public trust domain: what the user's client verifies (hostname localhost, both loopbacks). + "ingress": ("public-ca", ["127.0.0.1", "::1"], [SERVER], "localhost"), + "grafana-ui": ("public-ca", ["127.0.0.1", "::1"], [SERVER], "localhost"), + # Internal trust domain. + "lb": ("internal-ca", [], [CLIENT], None), # client of every API replica + "api": ("internal-ca", [], [SERVER, CLIENT], None), # server for lb, client of collector + "relay": ("internal-ca", [], [CLIENT], None), + "worker": ("internal-ca", [], [CLIENT], None), + "postgres": ("internal-ca", LOCAL, [SERVER], None), + "valkey": ("internal-ca", LOCAL, [SERVER], None), + "s3": ("internal-ca", LOCAL, [SERVER], None), + "broker": ("internal-ca", LOCAL, [SERVER], None), + "otel-collector": ("internal-ca", [], [SERVER, CLIENT], None), # server for apps, client of backends + "prometheus": ("internal-ca", LOCAL, [SERVER, CLIENT], None), # client: scrapes loki/tempo + "loki": ("internal-ca", LOCAL, [SERVER], None), + "tempo": ("internal-ca", LOCAL, [SERVER], None), + "grafana": ("internal-ca", [], [CLIENT], None), # client of the three datasources + "openbao": ("internal-ca", LOCAL, [SERVER], None), + # Test only: right SAN, wrong CA. + "foreign-lb": ("foreign-ca", [], [CLIENT], "lb"), +} +CAS = {"public-ca": "MTUSI lab7 public CA", "internal-ca": "MTUSI lab7 internal CA", + "foreign-ca": "Foreign CA (test only, trusted by nobody)"} + + +def now() -> dt.datetime: + return dt.datetime.now(dt.timezone.utc) + + +def save(path: Path, data: bytes) -> None: + path.write_bytes(data) # bytes: PEM keeps LF on Windows too + # Readable by the unprivileged container users through the bind mount (postgres copies its + # key to a 0600 file at start). The folder ./secrets itself is 0700 for the host user. + os.chmod(path, 0o644) + print(f"created secrets/pki/{path.name}") + + +def pem_key(key) -> bytes: + return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption()) + + +def load(name: str): + cert = x509.load_pem_x509_certificate((PKI / f"{name}.crt").read_bytes()) + key = serialization.load_pem_private_key((PKI / f"{name}.key").read_bytes(), None) + return cert, key + + +def make_ca(name: str) -> None: + if (PKI / f"{name}.crt").exists(): + print(f"keep secrets/pki/{name}.crt") + return + key = ec.generate_private_key(ec.SECP256R1()) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, CAS[name])]) + cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(subject) + .public_key(key.public_key()).serial_number(x509.random_serial_number()) + .not_valid_before(now() - dt.timedelta(minutes=5)).not_valid_after(now() + dt.timedelta(days=CA_DAYS)) + .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True) + .add_extension(x509.KeyUsage(digital_signature=False, content_commitment=False, key_encipherment=False, + data_encipherment=False, key_agreement=False, key_cert_sign=True, + crl_sign=True, encipher_only=False, decipher_only=False), critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False) + .sign(key, hashes.SHA256())) + save(PKI / f"{name}.key", pem_key(key)) + save(PKI / f"{name}.crt", cert.public_bytes(serialization.Encoding.PEM)) + + +def san_entry(value: str) -> x509.GeneralName: + try: + return x509.IPAddress(ipaddress.ip_address(value)) + except ValueError: + return x509.DNSName(value) + + +def make_leaf(name: str, ca_name: str, extra: list[str], ekus: list, dns_name: str | None) -> None: + if (PKI / f"{name}.crt").exists(): + print(f"keep secrets/pki/{name}.crt") + return + ca_cert, ca_key = load(ca_name) + identity = dns_name or name + key = ec.generate_private_key(ec.SECP256R1()) + sans = [san_entry(v) for v in dict.fromkeys([identity, *extra])] + cert = (x509.CertificateBuilder() + .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, identity)])) + .issuer_name(ca_cert.subject).public_key(key.public_key()).serial_number(x509.random_serial_number()) + .not_valid_before(now() - dt.timedelta(minutes=5)).not_valid_after(now() + dt.timedelta(days=LEAF_DAYS)) + .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) + .add_extension(x509.KeyUsage(digital_signature=True, content_commitment=False, key_encipherment=False, + data_encipherment=False, key_agreement=True, key_cert_sign=False, + crl_sign=False, encipher_only=False, decipher_only=False), critical=True) + .add_extension(x509.ExtendedKeyUsage(ekus), critical=False) + .add_extension(x509.SubjectAlternativeName(sans), critical=False) + .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False) + .sign(ca_key, hashes.SHA256())) + cert_pem = cert.public_bytes(serialization.Encoding.PEM) + save(PKI / f"{name}.key", pem_key(key)) + save(PKI / f"{name}.crt", cert_pem) + + +def bundle(name: str) -> None: + """HAProxy wants certificate + key in one PEM file.""" + target = PKI / f"{name}.pem" + if target.exists(): + print(f"keep secrets/pki/{target.name}") + return + save(target, (PKI / f"{name}.crt").read_bytes() + (PKI / f"{name}.key").read_bytes()) + + +def main() -> int: + PKI.mkdir(parents=True, exist_ok=True) + os.chmod(PKI.parent, 0o700) + for ca in CAS: + make_ca(ca) + for name, (ca, extra, ekus, dns_name) in LEAVES.items(): + make_leaf(name, ca, extra, ekus, dns_name) + bundle("ingress") # HAProxy :8443 server certificate + bundle("lb") # HAProxy client certificate towards the API replicas + print("CA_FILE for the public tests:", (PKI / "public-ca.crt").as_posix()) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/init_secrets.py b/scripts/init_secrets.py index eb7e13e..7605794 100644 --- a/scripts/init_secrets.py +++ b/scripts/init_secrets.py @@ -74,7 +74,10 @@ def main() -> int: write(f"broker_url_{who}", f"amqp://{who}:{read(f'rabbitmq_{who}_password')}@broker:5672/?heartbeat=10") # Lab 6: Grafana admin (UI on 127.0.0.1:3000 and the evidence scripts, via its datasource proxy). write("grafana_admin_password", secrets.token_urlsafe(18)) - return 0 + # Lab 7: local PKI (two CAs + service certificates) in ./secrets/pki. + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import init_pki + return init_pki.main() if __name__ == "__main__": -- 2.54.0 From f36da9795135ea86d67801534eb0e00f0d98bcbd Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:14:05 +0300 Subject: [PATCH 03/16] =?UTF-8?q?lab7:=20=D0=BE=D0=B1=D1=8F=D0=B7=D0=B0?= =?UTF-8?q?=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D0=BE=D0=B5=20mTLS=20LB->API=20?= =?UTF-8?q?=D1=81=20allowlist=20identity=20(SAN=20lb),=20health=20=D1=82?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE=20=D0=BD=D0=B0=20loopback,=20?= =?UTF-8?q?=D1=81=D0=BA=D1=80=D0=B8=D0=BF=D1=82=20=D0=BE=D1=82=D1=80=D0=B8?= =?UTF-8?q?=D1=86=D0=B0=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BE=D0=BA=20mtls=5Fcheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compose.yaml | 63 +++++++++++++++++- infra/haproxy/haproxy.cfg | 16 +++-- scripts/mtls_check.cmd | 4 ++ scripts/mtls_check.py | 122 ++++++++++++++++++++++++++++++++++ scripts/mtls_check.sh | 12 ++++ src/messenger/__main__.py | 12 +++- src/messenger/app.py | 40 ++++++++---- src/messenger/config.py | 24 +++++++ src/messenger/healthcheck.py | 5 +- src/messenger/tls.py | 123 +++++++++++++++++++++++++++++++++++ 10 files changed, 401 insertions(+), 20 deletions(-) create mode 100644 scripts/mtls_check.cmd create mode 100644 scripts/mtls_check.py create mode 100644 scripts/mtls_check.sh create mode 100644 src/messenger/tls.py diff --git a/compose.yaml b/compose.yaml index 00fff4f..aefc64d 100644 --- a/compose.yaml +++ b/compose.yaml @@ -296,6 +296,13 @@ services: environment: <<: [*api-env, *otel-env] OTEL_SERVICE_NAME: messenger-api + # Lab 7: the only network listener is mTLS on 8443 (tls.py); plaintext health on loopback. + APP_PORT: 8443 + APP_HEALTH_PORT: 8081 + TLS_CERT_FILE: /run/secrets/api.crt + TLS_KEY_FILE: /run/secrets/api.key + TLS_CLIENT_CA_FILE: /run/secrets/internal-ca.crt + MTLS_ALLOWED_CLIENTS: ${MTLS_ALLOWED_CLIENTS:-lb} secrets: - database_url - cache_url @@ -303,9 +310,12 @@ services: target: s3_access_key_id - source: s3_api_secret_access_key target: s3_secret_access_key + - {source: pki_api_crt, target: api.crt} + - {source: pki_api_key, target: api.key} + - {source: pki_internal_ca, target: internal-ca.crt} # No `ports` and no container_name: replicas are reachable only through `lb`, - # and `--scale api=N` / deploy.replicas works. X-Instance-Id = container hostname. - expose: ["8080"] + # and `--scale api=N` / deploy.replicas works. + expose: ["8443"] healthcheck: test: ["CMD", "python", "-m", "messenger.healthcheck"] interval: 2s @@ -343,6 +353,10 @@ services: secrets: - source: pki_ingress_pem # public-ca leaf + key, SAN localhost/127.0.0.1/::1 target: ingress.pem + - source: pki_lb_pem # client identity towards the API (internal CA, SAN lb) + target: lb.pem + - source: pki_internal_ca + target: internal-ca.crt # verifies the replicas (SAN api) ports: # The ONLY public entry point: HTTPS, on the loopback interfaces only. Both IPv4 and IPv6: # on Windows `localhost` resolves to ::1 first, and a refused ::1 connection costs ~2 s @@ -505,6 +519,31 @@ services: resources: limits: {cpus: "0.5", memory: 128m} + # Lab 7: proof of the LB -> API mTLS against every replica directly (scripts/mtls_check.py): + # docker compose run --rm mtls-check + # Joins `edge` like the LB. Test-only material: the LB client key (positive case), the worker + # certificate (trusted CA, wrong role) and a certificate of a foreign CA with SAN lb. + mtls-check: + profiles: ["tools"] + image: ${API_IMAGE:-mtusi-messenger:lab7} + entrypoint: ["python", "/opt/check/mtls_check.py"] + command: [] + volumes: + - ./scripts/mtls_check.py:/opt/check/mtls_check.py:ro + secrets: + - {source: pki_internal_ca, target: internal-ca.crt} + - {source: pki_lb_crt, target: lb.crt} + - {source: pki_lb_key, target: lb.key} + - {source: pki_worker_crt, target: worker.crt} + - {source: pki_worker_key, target: worker.key} + - {source: pki_foreign_lb_crt, target: foreign-lb.crt} + - {source: pki_foreign_lb_key, target: foreign-lb.key} + restart: "no" + networks: [edge] + deploy: + resources: + limits: {cpus: "0.5", memory: 128m} + # ------------------------------------------------------------------ lab 6: observability # Receives OTLP from api/relay/worker, limits memory, batches, forwards to the three stores. # Distroless image (no shell): its health is the `up{job="otel-collector"}` scrape of :8888. @@ -687,3 +726,23 @@ secrets: # verifies peers with; the CA private keys are mounted nowhere. pki_ingress_pem: file: ./secrets/pki/ingress.pem + pki_lb_pem: + file: ./secrets/pki/lb.pem + pki_internal_ca: + file: ./secrets/pki/internal-ca.crt + pki_api_crt: + file: ./secrets/pki/api.crt + pki_api_key: + file: ./secrets/pki/api.key + pki_lb_crt: + file: ./secrets/pki/lb.crt + pki_lb_key: + file: ./secrets/pki/lb.key + pki_worker_crt: + file: ./secrets/pki/worker.crt + pki_worker_key: + file: ./secrets/pki/worker.key + pki_foreign_lb_crt: # test only: foreign CA, SAN lb + file: ./secrets/pki/foreign-lb.crt + pki_foreign_lb_key: + file: ./secrets/pki/foreign-lb.key diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg index 2e01763..05a5428 100644 --- a/infra/haproxy/haproxy.cfg +++ b/infra/haproxy/haproxy.cfg @@ -28,6 +28,14 @@ # because the API has not seen them. Nothing that may have reached the API is retried by # the LB: an uncertain POST is retried by the CLIENT with the same Idempotency-Key. # No sticky sessions: sessions live in Valkey, every replica serves every user. +# +# Lab 7, LB -> API = mandatory mTLS (contracts/trust-matrix.md). Every server line (traffic AND the +# active health checks, which inherit `ssl`): +# ssl verify required ca-file internal-ca.crt verifyhost api the replica must present a certificate +# of the internal CA with SAN `api`: no MITM, no fake replica; +# crt lb.pem our client identity (internal CA, SAN `lb`, EKU clientAuth). +# The replica checks the chain AND the SAN allowlist (src/messenger/tls.py). Plaintext to the API is +# impossible: the replicas have no plaintext listener on the network. global log stdout format raw local0 info @@ -95,8 +103,8 @@ backend api option httpchk http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api http-check expect status 200 - default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 - server-template api 8 api:8080 + default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 ssl verify required ca-file /run/secrets/internal-ca.crt verifyhost api crt /run/secrets/lb.pem ssl-min-ver TLSv1.2 + server-template api 8 api:8443 # Degraded mode only (see the header): used when NO replica is fully ready. backend api_core @@ -106,8 +114,8 @@ backend api_core option httpchk http-check send meth GET uri /health/ready/core ver HTTP/1.1 hdr Host api http-check expect status 200 - default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 - server-template core 8 api:8080 + default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 ssl verify required ca-file /run/secrets/internal-ca.crt verifyhost api crt /run/secrets/lb.pem ssl-min-ver TLSv1.2 + server-template core 8 api:8443 # Status page for the container healthcheck only: bound to the container's own loopback and NOT # published (lab 7: only the TLS ingress leaves the host). Operators use the admin socket diff --git a/scripts/mtls_check.cmd b/scripts/mtls_check.cmd new file mode 100644 index 0000000..ebba4fd --- /dev/null +++ b/scripts/mtls_check.cmd @@ -0,0 +1,4 @@ +@echo off +rem Windows wrapper: runs scripts\mtls_check.sh (LB -> API mTLS proof) with Git Bash. +"%ProgramFiles%\Git\bin\bash.exe" "%~dp0mtls_check.sh" +exit /b %ERRORLEVEL% diff --git a/scripts/mtls_check.py b/scripts/mtls_check.py new file mode 100644 index 0000000..5b2af6d --- /dev/null +++ b/scripts/mtls_check.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Negative/positive proof of the LB -> API mTLS, against EVERY API replica directly (no LB). + +Runs inside the compose network `edge` (the LB's network), as the tools service `mtls-check`: + + docker compose run --rm mtls-check (wrappers: make mtls-check, scripts/mtls_check.cmd) + +For every IP of the DNS name `api` (one per running replica) it opens fresh connections that +always verify the SERVER (internal CA, hostname `api`) and present, as the client: + + 1. no certificate -> refused in the TLS handshake + 2. certificate of a foreign CA, SAN `lb` (right name) -> refused in the TLS handshake (unknown CA) + 3. certificate of OUR CA, SAN `worker` (wrong role) -> handshake OK, connection closed by the + API before any HTTP response (allowlist) + 4. certificate of OUR CA, SAN `lb` (the LB identity) -> HTTP 200 from GET /health/ready +plus two bypass probes: plaintext HTTP to the mTLS port and the loopback health port from another +container (both must fail). Case 4 on the same address proves the refusals are not "network down". + +Which check refused: the API logs `mtls_identity_rejected` (with the client SAN) ONLY for the +allowlist (case 3); cases 1-2 never reach the application - the TLS layer drops them. The wrapper +scripts/mtls_check.sh prints those log lines after the run. + +Exit 0 only if every expectation holds. Prints no key material. Test-only: this container mounts the +LB's client key (to prove the positive case) and the worker's certificate (a trusted but wrong role). +""" +from __future__ import annotations + +import os +import socket +import ssl +import sys + +PORT = int(os.environ.get("API_PORT", "8443")) +HEALTH_PORT = int(os.environ.get("API_HEALTH_PORT", "8081")) +CA = os.environ.get("INTERNAL_CA", "/run/secrets/internal-ca.crt") +CERTS = { + "none": None, + "foreign-ca SAN=lb": ("/run/secrets/foreign-lb.crt", "/run/secrets/foreign-lb.key"), + "internal-ca SAN=worker": ("/run/secrets/worker.crt", "/run/secrets/worker.key"), + "internal-ca SAN=lb": ("/run/secrets/lb.crt", "/run/secrets/lb.key"), +} +EXPECT = {"none": "refused", "foreign-ca SAN=lb": "refused", "internal-ca SAN=worker": "refused", + "internal-ca SAN=lb": "200"} +REQUEST = b"GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n" + + +def attempt(ip: str, cert, version: ssl.TLSVersion) -> tuple[str, str]: + """(outcome, detail): outcome is the HTTP status code, or 'refused'/'error'. + + TLS 1.3: the client finishes its side of the handshake BEFORE the server has checked the client + certificate, so a refusal shows up as an alert/EOF on the first read. TLS 1.2: the server + checks the client certificate inside the handshake, so the alert names the reason + (certificate required / unknown CA). Both versions must refuse; the identity allowlist always + acts after a successful handshake (the chain is fine there). + """ + ctx = ssl.create_default_context(cafile=CA) # server verification is ALWAYS on + ctx.check_hostname = True + ctx.minimum_version = ctx.maximum_version = version + if cert: + ctx.load_cert_chain(*cert) + stage = "tcp" + try: + with socket.create_connection((ip, PORT), timeout=5) as raw: + stage = "handshake" + with ctx.wrap_socket(raw, server_hostname="api") as tls: + stage = "http" + tls.sendall(REQUEST) + data = tls.recv(4096) + if not data: + return "refused", "closed by the server after the handshake (no HTTP response)" + status = data.split(b" ", 2)[1].decode("ascii", "replace") + return status, f"HTTP {status}; server cert SAN api verified" + except ssl.SSLCertVerificationError as exc: + return "error", f"SERVER certificate not trusted: {exc.verify_message}" + except ssl.SSLError as exc: + if exc.reason == "UNEXPECTED_EOF_WHILE_READING": + return "refused", f"server closed the connection during the {stage} (no HTTP response)" + return "refused", f"TLS alert at {stage}: {exc.reason or exc}" + except (ConnectionResetError, BrokenPipeError, ConnectionAbortedError) as exc: + return "refused", f"connection reset at {stage}: {type(exc).__name__}" + except OSError as exc: + return "error", f"{stage}: {type(exc).__name__}: {exc}" # unreachable etc. is NOT a refusal + + +def plaintext(ip: str, port: int) -> tuple[bool, str]: + """True if a plaintext HTTP request got an HTTP answer (= a bypass).""" + try: + with socket.create_connection((ip, port), timeout=3) as s: + s.sendall(REQUEST) + data = s.recv(64) + if data.startswith(b"HTTP/"): + return True, "answered plaintext HTTP: " + data.split(b"\r\n")[0].decode("latin-1") + return False, "no HTTP answer (TLS-only listener)" + except OSError as exc: + return False, f"{type(exc).__name__}" + + +def main() -> int: + ips = sorted({info[4][0] for info in socket.getaddrinfo("api", PORT, socket.AF_INET, socket.SOCK_STREAM)}) + print(f"API replicas behind DNS name `api`: {len(ips)}") + failures = 0 + for ip in ips: + print(f"\nreplica {ip}:{PORT}") + for version in (ssl.TLSVersion.TLSv1_3, ssl.TLSVersion.TLSv1_2): + tag = "1.3" if version == ssl.TLSVersion.TLSv1_3 else "1.2" + for label, cert in CERTS.items(): + outcome, detail = attempt(ip, cert, version) + good = outcome == EXPECT[label] + failures += not good + print(f" {'PASS' if good else 'FAIL'} TLS {tag} client cert {label:24s} -> {outcome:8s} {detail}") + for port, what in ((PORT, "plaintext HTTP to the mTLS port"), (HEALTH_PORT, "loopback health port from outside")): + bypass, detail = plaintext(ip, port) + failures += bypass + print(f" {'FAIL' if bypass else 'PASS'} {what:51s} -> {detail}") + if not ips: + failures += 1 + print(f"\n{'PASS' if failures == 0 else 'FAIL'}: mTLS LB->API, {len(ips)} replica(s), {failures} failure(s)") + return 0 if failures == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/mtls_check.sh b/scripts/mtls_check.sh new file mode 100644 index 0000000..3211811 --- /dev/null +++ b/scripts/mtls_check.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# LB -> API mTLS proof: scripts/mtls_check.py in the `edge` network + the API's own record of the +# identity refusals (event mtls_identity_rejected, SAN of the refused client) since the run started. +set -eu +cd "$(dirname "$0")/.." +since="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +rc=0 +docker compose run --rm mtls-check 2>/dev/null || rc=$? +echo +echo "API log since $since, identity allowlist refusals (cases 1-2 are dropped by TLS and never logged):" +docker compose logs --no-log-prefix --since "$since" api 2>/dev/null | grep mtls_identity_rejected || echo " (none)" +exit "$rc" diff --git a/src/messenger/__main__.py b/src/messenger/__main__.py index badcc59..7760d07 100644 --- a/src/messenger/__main__.py +++ b/src/messenger/__main__.py @@ -20,7 +20,7 @@ from types import FrameType import uvicorn -from . import __version__, logging_setup, telemetry +from . import __version__, logging_setup, telemetry, tls from .app import create_app from .config import ConfigError, Settings @@ -64,8 +64,18 @@ def main() -> int: logging_setup.configure(settings.log_level) telemetry.setup("messenger-api", settings.instance_id, __version__) app = create_app(settings) + mtls: dict = {} + if settings.tls_cert_file: + # Lab 7: mandatory mTLS (client certificate of the internal CA) + identity allowlist + # MTLS_ALLOWED_CLIENTS checked by the protocol class right after the handshake (tls.py). + context = tls.server_context(settings.tls_cert_file, settings.tls_key_file, settings.tls_client_ca_file) + protocol = tls.protocol_class() + mtls = {"ssl_context_factory": lambda _config, _default: context, "http": protocol, + "ssl_certfile": settings.tls_cert_file} + log.info("mtls_enabled", extra={"fields": {"allowed_clients": sorted(protocol.allowed)}}) config = uvicorn.Config( app, + **mtls, host=settings.host, port=settings.port, log_config=None, diff --git a/src/messenger/app.py b/src/messenger/app.py index cfc902f..db9c99e 100644 --- a/src/messenger/app.py +++ b/src/messenger/app.py @@ -22,7 +22,7 @@ from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Sen from opentelemetry import context as otel_context from opentelemetry import trace -from . import attachments, authhdr, cursor, docs, passwords, repo, telemetry, validation +from . import attachments, authhdr, cursor, docs, passwords, repo, telemetry, tls, validation from .config import Settings from .db import Database from .errors import BASIC_CHALLENGE, ApiError, Conflict, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable @@ -275,19 +275,28 @@ async def ready(request: Request) -> JSONResponse: """200 only if the WHOLE mandatory synchronous path can be served: PostgreSQL, Valkey (SESSION_STORE=valkey) and, since lab 4, the S3 bucket (upload/download of attachments) answer. 503 while draining after SIGTERM. HAProxy routes to such replicas first.""" - if request.app.state.draining: - raise Unavailable("Сервер завершает работу") - db_ok, store_ok, s3_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping(), - storage_of(request).ping()) - if not db_ok: - raise Unavailable("PostgreSQL недоступен") - if not store_ok: - raise Unavailable("Хранилище сессий недоступно") - if not s3_ok: - raise Unavailable("Хранилище файлов (S3) недоступно") + problem = await readiness_problem(request.app) + if problem is not None: + raise Unavailable(problem) return ok({"status": "ok"}) +async def readiness_problem(app: Starlette) -> str | None: + """None if ready, otherwise the (public, secret-free) reason. Shared by GET /health/ready and the + loopback health listener of the Docker healthcheck (tls.health_listener, lab 7).""" + if app.state.draining: + return "Сервер завершает работу" + db_ok, store_ok, s3_ok = await asyncio.gather(app.state.db.ping(), app.state.sessions.ping(), + app.state.storage.ping()) + if not db_ok: + return "PostgreSQL недоступен" + if not store_ok: + return "Хранилище сессий недоступно" + if not s3_ok: + return "Хранилище файлов (S3) недоступно" + return None + + async def ready_core(request: Request) -> JSONResponse: """Not in the contract: readiness WITHOUT S3, for the load balancer's degraded mode only. If S3 is down for every replica, /health/ready is 503 everywhere; HAProxy then routes to @@ -633,9 +642,18 @@ def create_app(settings: Settings | None = None) -> Starlette: tasks.append(asyncio.create_task(janitor_loop(settings.janitor_interval_seconds))) if settings.stats_log_seconds > 0: tasks.append(asyncio.create_task(stats_loop(settings.stats_log_seconds))) + health_server = None + if settings.health_port: + async def probe(path: str) -> int: + if path == "/health/live": + return 200 + return 200 if await readiness_problem(app) is None else 503 + health_server = await tls.health_listener(settings.health_port, probe) try: yield finally: + if health_server is not None: + health_server.close() for task in tasks: task.cancel() await sessions.close() diff --git a/src/messenger/config.py b/src/messenger/config.py index b93802e..c7752e7 100644 --- a/src/messenger/config.py +++ b/src/messenger/config.py @@ -154,6 +154,11 @@ class Settings: queued_republish_seconds: float = 300.0 fault_points: frozenset[str] = frozenset() fault_values: dict[str, int] = field(default_factory=dict) + # Lab 7: TLS of the API listener (mTLS, src/messenger/tls.py) and the loopback health port. + tls_cert_file: str = "" + tls_key_file: str = "" + tls_client_ca_file: str = "" + health_port: int = 0 def fault_value(self, point: str, default: int = 0) -> int: return self.fault_values.get(point, default) @@ -210,6 +215,7 @@ class Settings: message_write_path=_choice("MESSAGE_WRITE_PATH", "function", {"function", "multi"}), **s3_settings(credentials_required=s3_credentials), **jobs_settings(broker_required=False), + **tls_settings(), ) @@ -304,6 +310,24 @@ def s3_settings(*, credentials_required: bool = True) -> dict: ) +def _path(name: str) -> str: + """Optional file path setting; if set, the file must exist (fail at start, not at first use).""" + value = os.environ.get(name, "").strip() + if value and not Path(value).is_file(): + raise ConfigError(f"{name}={value} does not exist") + return value + + +def tls_settings() -> dict: + """Lab 7, API listener: TLS_CERT_FILE/TLS_KEY_FILE = the replica's certificate (SAN `api`), + TLS_CLIENT_CA_FILE = the internal CA that client certificates must chain to. All three or none.""" + cert, key, ca = _path("TLS_CERT_FILE"), _path("TLS_KEY_FILE"), _path("TLS_CLIENT_CA_FILE") + if any((cert, key, ca)) and not all((cert, key, ca)): + raise ConfigError("TLS_CERT_FILE, TLS_KEY_FILE and TLS_CLIENT_CA_FILE must be set together") + return dict(tls_cert_file=cert, tls_key_file=key, tls_client_ca_file=ca, + health_port=_int("APP_HEALTH_PORT", 0, 0, 65535)) + + def jobs_settings(*, broker_required: bool) -> dict: """Lab 5 pipeline: retries, lease, worker limits, cleanup, relay (docs/PIPELINE.md).""" from .pipeline import PIPELINES # local import: pipeline.py imports nothing from here diff --git a/src/messenger/healthcheck.py b/src/messenger/healthcheck.py index 37b0040..f064e02 100644 --- a/src/messenger/healthcheck.py +++ b/src/messenger/healthcheck.py @@ -1,6 +1,7 @@ """Docker HEALTHCHECK probe without curl/wget in the image: `python -m messenger.healthcheck`. - (no arguments) API: GET /health/ready on the local port + (no arguments) API: GET /health/ready on the loopback health port + (APP_HEALTH_PORT, lab 7: the main port requires mTLS) --file /tmp/heartbeat --max-age 30 relay/worker: the main loop wrote its heartbeat recently (it writes it only while its database/broker work) """ @@ -19,7 +20,7 @@ def main(argv: list[str]) -> int: return 0 if time.time() - float(f.read().strip()) <= float(argv[3]) else 1 except (OSError, ValueError): return 1 - port = os.environ.get("APP_PORT", "8080").strip() or "8080" + port = os.environ.get("APP_HEALTH_PORT", "").strip() or os.environ.get("APP_PORT", "8080").strip() or "8080" try: with urllib.request.urlopen(f"http://127.0.0.1:{port}/health/ready", timeout=2) as response: return 0 if response.status == 200 else 1 diff --git a/src/messenger/tls.py b/src/messenger/tls.py new file mode 100644 index 0000000..9d064ad --- /dev/null +++ b/src/messenger/tls.py @@ -0,0 +1,123 @@ +"""Lab 7: TLS contexts of the services and mandatory mTLS with an identity allowlist on the API. + +Three separate questions on the LB -> API hop (README "Вопросы на защите"): + +1. Encryption + server identity: TLS. HAProxy verifies the replica's certificate (internal CA, + SAN `api`), so nobody in between can read or impersonate the API. +2. Client identity: the API's TLS context has CERT_REQUIRED and trusts ONLY the internal CA, so the + handshake fails without a client certificate or with a certificate of any other CA. + A valid chain says only "this certificate was issued by our CA". The same CA also issued the + certificates of the worker, the relay, the Collector, ... - so after the handshake + `MtlsHttpProtocol.connection_made` compares the client certificate's SAN (DNS names) with + MTLS_ALLOWED_CLIENTS (default: `lb`) and closes the connection before a single HTTP byte is read + if none matches. A stolen worker key therefore cannot talk to the API directly. +3. Permission for an action: the user's Bearer session (app.py), unchanged. mTLS proves which + PROCESS is calling, never which USER. + +Docker's own healthcheck runs inside the container and has no client certificate: it uses a +separate plaintext listener bound to the container's loopback (127.0.0.1:APP_HEALTH_PORT), which +serves only GET /health/live and /health/ready (`health_listener`). Another container cannot reach +the loopback of this one, so it is not a bypass of the mTLS port. +""" +from __future__ import annotations + +import asyncio +import logging +import os +import ssl +from collections.abc import Awaitable, Callable + +from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol + +log = logging.getLogger("messenger.tls") + + +def client_context(ca_file: str, cert_file: str | None = None, key_file: str | None = None) -> ssl.SSLContext: + """Client side of every internal hop: verify the server chain (internal CA) AND its hostname.""" + ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=ca_file) + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + ctx.check_hostname = True + ctx.verify_mode = ssl.CERT_REQUIRED + if cert_file: + ctx.load_cert_chain(cert_file, key_file) + return ctx + + +def server_context(cert_file: str, key_file: str, client_ca_file: str) -> ssl.SSLContext: + """API listener: TLS 1.2+, client certificate REQUIRED and verified against the internal CA only.""" + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + ctx.load_cert_chain(cert_file, key_file) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(cafile=client_ca_file) # no system CAs: only our internal CA + return ctx + + +def dns_names(peercert: dict | None) -> list[str]: + """DNS SAN entries of a certificate as returned by SSLSocket/SSLObject.getpeercert().""" + if not peercert: + return [] + return [value for kind, value in peercert.get("subjectAltName", ()) if kind == "DNS"] + + +def allowed_clients() -> frozenset[str]: + raw = os.environ.get("MTLS_ALLOWED_CLIENTS", "lb") + names = frozenset(item.strip() for item in raw.split(",") if item.strip()) + if not names: + raise ValueError("MTLS_ALLOWED_CLIENTS must list at least one identity") + return names + + +class MtlsHttpProtocol(HttpToolsProtocol): + """uvicorn's httptools protocol + identity check right after the TLS handshake. + + asyncio calls connection_made() only when the handshake has completed (TLS 1.3 included), so + the verified client certificate is available here. A peer outside the allowlist is aborted: + it never reaches the ASGI application, the router or the session check. + """ + + allowed: frozenset[str] = frozenset({"lb"}) + + def connection_made(self, transport: asyncio.Transport) -> None: # type: ignore[override] + ssl_object = transport.get_extra_info("ssl_object") + names = dns_names(ssl_object.getpeercert() if ssl_object is not None else None) + if ssl_object is None or not self.allowed.intersection(names): + peer = transport.get_extra_info("peername") + log.warning("mtls_identity_rejected", extra={"fields": { + "client_san": names[:4], "peer": peer[0] if peer else None, "allowed": sorted(self.allowed)}}) + transport.abort() + return + super().connection_made(transport) + + +def protocol_class() -> type[MtlsHttpProtocol]: + allowed = allowed_clients() + return type("MtlsHttpProtocol", (MtlsHttpProtocol,), {"allowed": allowed}) + + +# ------------------------------------------------------------------ loopback health listener +async def health_listener(port: int, probe: Callable[[str], Awaitable[int]]) -> asyncio.base_events.Server: + """Minimal HTTP/1.0 server on 127.0.0.1: for the Docker healthcheck only. + + `probe(path)` returns the status code of /health/live or /health/ready (the same checks as the + API endpoints). Any other path gets 404 and nothing else of the API is reachable here. + """ + + async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + status = 400 + try: + line = await asyncio.wait_for(reader.readline(), 2) + parts = line.decode("latin-1").split() + if len(parts) >= 2 and parts[0] == "GET": + status = await probe(parts[1]) if parts[1] in ("/health/live", "/health/ready") else 404 + except Exception: # noqa: BLE001 - a broken probe connection is the prober's problem + status = 503 + body = b'{"status":"ok"}' if status == 200 else b'{"status":"unavailable"}' + try: + writer.write(b"HTTP/1.0 %d X\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s" + % (status, len(body), body)) + await writer.drain() + finally: + writer.close() + + return await asyncio.start_server(handle, "127.0.0.1", port) -- 2.54.0 From 93f4ed10136c713c2b3452784791d2573542e946 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:29:09 +0300 Subject: [PATCH 04/16] =?UTF-8?q?lab7:=20TLS=20=D0=BA=D0=BE=20=D0=B2=D1=81?= =?UTF-8?q?=D0=B5=D0=BC=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D0=B8=D0=BC=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D1=8F=D0=BC=20=D0=B8=20=D1=82=D0=B5=D0=BB=D0=B5?= =?UTF-8?q?=D0=BC=D0=B5=D1=82=D1=80=D0=B8=D0=B8;=20=D1=80=D0=B0=D0=B7?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B5=20=D1=80=D0=BE=D0=BB?= =?UTF-8?q?=D0=B8=20PostgreSQL=20(GRANT=20=D0=BF=D0=BE=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=B4=D1=83),=20ACL=20Valkey,=20AMQPS,=20HTTPS=20S3,=20mTLS=20?= =?UTF-8?q?Collector/Prometheus/Loki/Tempo/Grafana?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compose.yaml | 372 ++++++++++++------ infra/grafana/dashboards/messenger.json | 24 +- .../provisioning/datasources/datasources.yaml | 25 +- infra/loki/loki.yaml | 8 + infra/otel/collector.yaml | 62 ++- infra/postgres/initdb/10-roles.sh | 29 ++ infra/postgres/pg_hba.conf | 18 + infra/prometheus/prometheus.yml | 32 +- infra/prometheus/promtool-http.yml | 7 + infra/prometheus/rules/alerts.yml | 6 +- infra/prometheus/web-config.yml | 10 + infra/rabbitmq/rabbitmq.conf | 19 +- infra/seaweedfs/start.sh | 4 + infra/tempo/tempo.yaml | 13 + infra/valkey/start.sh | 18 + infra/valkey/valkey.conf | 16 +- migrations/0007_least_privilege.sql | 48 +++ scripts/build_dashboard.py | 24 +- scripts/init_secrets.py | 39 +- scripts/obs.py | 7 +- scripts/trace_demo.py | 6 +- src/messenger/broker.py | 10 + src/messenger/config.py | 4 + src/messenger/relay.py | 2 +- src/messenger/s3_bootstrap.py | 5 +- src/messenger/sessions.py | 7 + src/messenger/storage.py | 5 +- src/messenger/worker.py | 2 +- 28 files changed, 621 insertions(+), 201 deletions(-) create mode 100644 infra/postgres/initdb/10-roles.sh create mode 100644 infra/postgres/pg_hba.conf create mode 100644 infra/prometheus/promtool-http.yml create mode 100644 infra/prometheus/web-config.yml create mode 100644 infra/valkey/start.sh create mode 100644 migrations/0007_least_privilege.sql diff --git a/compose.yaml b/compose.yaml index aefc64d..ff54fc1 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,26 +1,31 @@ -# Lab 6 stand = lab 5 + observability (docs/OBSERVABILITY.md): -# api x2 / relay / worker --OTLP/HTTP--> otel-collector --> prometheus (metrics, + alert rules) -# --> loki (logs) --> tempo (traces) -# grafana (127.0.0.1:3000): provisioned datasources + dashboard + Prometheus alert view. -# The application never waits for telemetry: no depends_on on it, bounded SDK queues. -# Network `telemetry` (internal) joins only the apps and these five services. +# Lab 7 stand = lab 6 + security on every trust boundary (contracts/trust-matrix.md): +# client --HTTPS :8443 (public CA)--> lb (HAProxy) --mTLS (internal CA, SAN allowlist lb)--> api x2 +# api/relay/worker --TLS verify-full--> postgres (own role per service, GRANT only what it does) +# api --TLS (rediss)--> valkey (ACL user api) api/worker --HTTPS--> s3 (own key pair each) +# relay/worker --AMQPS 5671--> broker (publish-only / consume-only users) +# api/relay/worker --OTLP/HTTPS + client cert--> otel-collector --mTLS--> prometheus/loki/tempo +# grafana (https://localhost:3000, public CA) --mTLS--> the three datasources +# Nothing speaks plaintext over a container network. Plaintext remains only on a container's own +# loopback (healthchecks, the internal hops of SeaweedFS/Loki/Tempo): closed local hops. # -# Lab 5 part: client -> HAProxy (lb) -> API x N (scalable service `api`) -# -> PostgreSQL (metadata, jobs, outbox: source of truth) + Valkey (sessions) -# + SeaweedFS S3 (staging bucket and final bucket, both private) +# Lab 6 part: api x2 / relay / worker --OTLP--> otel-collector --> prometheus (metrics + alert rules) +# --> loki (logs) --> tempo (traces); grafana: provisioned datasources + dashboard. +# The application never waits for telemetry: no depends_on on it, bounded SDK queues. +# Lab 5 part: PostgreSQL (metadata, jobs, outbox: source of truth) + Valkey (sessions) +# + SeaweedFS S3 (staging bucket and final bucket, both private) # relay : outbox in PostgreSQL -> RabbitMQ (publisher confirms) [service `relay`] # broker : RabbitMQ 4.3, durable quorum queue + dead-letter queue [service `broker`] # worker : RabbitMQ -> variants -> final bucket + PostgreSQL, then ack [service `worker`] -# From a clean clone (details and Windows notes: REPORT.md, docs/WINDOWS.md): -# python scripts/init_secrets.py # once: random local credentials into ./secrets (git-ignored) -# cp .env.example .env # optional overrides (API_REPLICAS, limits, ...) -# docker compose --env-file .env up -d --build --wait +# From a clean clone: docs/OPERATOR.md (Windows: docs/WINDOWS.md). +# .venv/Scripts/python scripts/init_secrets.py # once: credentials + PKI into ./secrets (git-ignored) +# docker compose up -d --build --wait # Order: postgres/valkey/s3/broker healthy -> migrate + s3-init (ONE run each, exit 0) # -> api healthy -> lb; relay and worker start after migrate/s3-init. # Images are pinned by version AND digest. Passwords/keys are passed only as secret files, and -# every service gets only the secrets it needs. Only the LB publishes ports (loopback only). +# every service gets only the secrets it needs. Only the LB (8443) and Grafana (3000) publish +# ports, both HTTPS, both on loopback only. # Networks: `edge` (lb <-> api); internal (no route outside): `data` (postgres/valkey), -# `storage` (s3), `queue` (broker). The API is NOT on `queue`: it never talks to the broker. +# `storage` (s3), `queue` (broker), `telemetry`. The API is NOT on `queue`. name: ${COMPOSE_PROJECT_NAME:-mtusi-lab7} x-api-env: &api-env @@ -42,7 +47,7 @@ x-api-env: &api-env DOCS_ENABLED: ${DOCS_ENABLED:-true} MESSAGE_WRITE_PATH: ${MESSAGE_WRITE_PATH:-function} # S3: the API's own key pair (Write staging + Read final, see infra/seaweedfs/start.sh). - S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:8333} S3_REGION: ${S3_REGION:-us-east-1} S3_BUCKET: ${S3_BUCKET:-messenger-attachments} S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} @@ -62,18 +67,23 @@ x-api-env: &api-env # Lab 5: pipeline version and attempt budget of the jobs created by uploads. PIPELINE_VERSION: ${PIPELINE_VERSION:-1} JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} - # Failure experiments only (student-tests, bench/); empty = no injected failures. + # Failure experiments only (student-tests); empty = no injected failures. FAULT_POINTS: ${API_FAULT_POINTS:-} + # Lab 7: the CA every outgoing TLS connection (S3, Valkey) verifies the server with. + TLS_CA_FILE: /run/secrets/internal-ca.crt # Lab 6: OpenTelemetry SDK settings shared by api, relay and worker (src/messenger/telemetry.py). -# OTEL_SDK_DISABLED=true = telemetry off (track 1 baseline). Sampler: head sampling in the SDK -# (parentbased_always_on | parentbased_traceidratio + OTEL_TRACES_SAMPLER_ARG). Exporter timeout -# 3 s and bounded batch queues (2048 spans / log records): a dead Collector costs dropped telemetry, -# not memory or request latency. +# Exporter timeout 3 s and bounded batch queues (2048 spans / log records): a dead Collector costs +# dropped telemetry, not memory or request latency. +# Lab 7: OTLP over HTTPS; the SDK verifies the Collector (internal CA, hostname otel-collector) and +# presents the service's own certificate (/run/secrets/service.crt: SAN api / relay / worker). x-otel-env: &otel-env OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false} - OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318 OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/secrets/internal-ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/service.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/service.key OTEL_EXPORTER_OTLP_TIMEOUT: ${OTEL_EXPORTER_OTLP_TIMEOUT:-3} OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-parentbased_always_on} @@ -92,7 +102,7 @@ x-pipeline-env: &pipeline-env BROKER_URL_FILE: /run/secrets/broker_url DB_POOL_MAX: ${PIPELINE_DB_POOL_MAX:-6} DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3} - S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:8333} S3_REGION: ${S3_REGION:-us-east-1} S3_BUCKET: ${S3_BUCKET:-messenger-attachments} S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} @@ -105,21 +115,46 @@ x-pipeline-env: &pipeline-env JOB_RETRY_BASE_SECONDS: ${JOB_RETRY_BASE_SECONDS:-2} JOB_RETRY_MAX_SECONDS: ${JOB_RETRY_MAX_SECONDS:-60} QUEUED_REPUBLISH_SECONDS: ${QUEUED_REPUBLISH_SECONDS:-300} + TLS_CA_FILE: /run/secrets/internal-ca.crt services: + # PostgreSQL 18. Lab 7: TLS (internal CA, SAN postgres), pg_hba accepts ONLY hostssl logins of the + # service roles; the superuser `postgres` exists for initdb and the operator (local socket). + # The server key must be 0600 and owned by postgres: it is copied from the secret into a tmpfs + # at start (the bind-mounted secret cannot be chowned), then the image's entrypoint drops root. postgres: image: postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c environment: - POSTGRES_USER: messenger POSTGRES_DB: messenger POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password - # pg_stat_statements: per-statement counters for the experiments. - command: ["postgres", "-c", "shared_preload_libraries=pg_stat_statements", "-c", "max_connections=${PG_MAX_CONNECTIONS:-100}"] - secrets: [postgres_password] + command: + - sh + - -c + - >- + install -o postgres -g postgres -m 600 /run/secrets/postgres.key /run/pgtls/server.key && + exec docker-entrypoint.sh postgres + -c ssl=on -c ssl_cert_file=/run/secrets/postgres.crt -c ssl_key_file=/run/pgtls/server.key + -c ssl_min_protocol_version=TLSv1.2 -c hba_file=/etc/postgresql/pg_hba.conf + -c password_encryption=scram-sha-256 + -c shared_preload_libraries=pg_stat_statements -c max_connections=${PG_MAX_CONNECTIONS:-100} + secrets: + - postgres_password + - pg_migrate_password + - pg_api_password + - pg_relay_password + - pg_worker_password + - pg_jobctl_password + - pg_auditor_password + - {source: pki_postgres_crt, target: postgres.crt} + - {source: pki_postgres_key, target: postgres.key} + tmpfs: + - /run/pgtls:size=1m,mode=0755 volumes: - pgdata:/var/lib/postgresql # PostgreSQL 18 image keeps PGDATA under this path + - ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro + - ./infra/postgres/initdb:/docker-entrypoint-initdb.d:ro healthcheck: - test: ["CMD-SHELL", "pg_isready -U messenger -d messenger -q"] + test: ["CMD-SHELL", "pg_isready -U postgres -d messenger -q"] interval: 2s timeout: 3s retries: 30 @@ -131,24 +166,22 @@ services: resources: limits: {cpus: "${PG_CPUS:-2.0}", memory: "${PG_MEMORY:-1g}"} + # Valkey: sessions + login rate limit. Lab 7: TLS only (port 0, tls-port 6379), ACL user `api` + # (infra/valkey/start.sh), `default` user off. valkey: image: valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 - # The password goes into a config include readable only by the valkey user, - # so it never appears in the process arguments. docker-entrypoint.sh drops root. - command: - - sh - - -c - - >- - umask 077 && - printf 'requirepass %s\n' "$$(cat /run/secrets/valkey_password)" > /tmp/requirepass.conf && - chown valkey /tmp/requirepass.conf && - exec docker-entrypoint.sh valkey-server /etc/valkey/valkey.conf - secrets: [valkey_password] + entrypoint: ["/bin/sh", "/etc/valkey/start.sh"] + secrets: + - valkey_api_password + - {source: pki_valkey_crt, target: valkey.crt} + - {source: pki_valkey_key, target: valkey.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - ./infra/valkey/valkey.conf:/etc/valkey/valkey.conf:ro + - ./infra/valkey/start.sh:/etc/valkey/start.sh:ro - valkeydata:/data healthcheck: - test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/valkey_password)\" valkey-cli ping | grep -q PONG"] + test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/valkey_api_password)\" valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost --user api ping | grep -q PONG"] interval: 2s timeout: 3s retries: 30 @@ -160,8 +193,8 @@ services: limits: {cpus: "${VALKEY_CPUS:-0.5}", memory: 256m} # S3-compatible object storage (SeaweedFS: master + volume + filer + S3 gateway in one process). - # Bytes live ONLY here, on the named volume s3data: staging bucket (originals accepted before - # 202) and final bucket (published originals and variants). Identities: infra/seaweedfs/start.sh. + # Bytes live ONLY here, on the named volume s3data. Identities: infra/seaweedfs/start.sh. + # Lab 7: the S3 port is HTTPS only (internal CA, SAN s3). s3: image: chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62 entrypoint: ["/bin/sh", "/etc/seaweedfs/start.sh"] @@ -179,12 +212,15 @@ services: - s3_worker_secret_access_key - s3_auditor_access_key_id - s3_auditor_secret_access_key + - {source: pki_s3_crt, target: s3.crt} + - {source: pki_s3_key, target: s3.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - ./infra/seaweedfs/start.sh:/etc/seaweedfs/start.sh:ro - s3data:/data healthcheck: - # Unauthenticated health endpoint of the S3 gateway (200 once it serves requests). - test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8333/healthz"] + # Unauthenticated health endpoint of the S3 gateway, over HTTPS with full verification. + test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "--cacert", "/run/secrets/internal-ca.crt", "https://localhost:8333/healthz"] interval: 2s timeout: 3s retries: 30 @@ -196,22 +232,24 @@ services: resources: limits: {cpus: "${S3_CPUS:-1.0}", memory: "${S3_MEMORY:-1g}"} - # Lab 5: RabbitMQ. Topology (exchange, quorum queue, DLX/DLQ) and users come from definition - # files imported at boot (infra/rabbitmq, secrets/rabbitmq_users.json). Messages of the quorum - # queue live on the named volume rabbitmqdata. No management UI, no host port. + # RabbitMQ. Topology (exchange, quorum queue, DLX/DLQ) and users come from definition files + # imported at boot (infra/rabbitmq, secrets/rabbitmq_users.json). Lab 7: AMQPS 5671 only. broker: image: rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5 hostname: broker # node name rabbit@broker: stable across container re-creation secrets: - source: rabbitmq_users target: /etc/rabbitmq/definitions.d/users.json + - {source: pki_broker_crt, target: broker.crt} + - {source: pki_broker_key, target: broker.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - - ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/conf.d/20-lab5.conf:ro + - ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/conf.d/20-lab.conf:ro - ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro - ./infra/rabbitmq/topology.json:/etc/rabbitmq/definitions.d/topology.json:ro - rabbitmqdata:/var/lib/rabbitmq healthcheck: - # The node runs and the AMQP listener accepts connections. + # The node runs and its (TLS) listener accepts connections. test: ["CMD-SHELL", "rabbitmq-diagnostics -q ping && rabbitmq-diagnostics -q check_port_connectivity"] interval: 5s timeout: 10s @@ -224,8 +262,8 @@ services: resources: limits: {cpus: "${BROKER_CPUS:-1.0}", memory: "${BROKER_MEMORY:-512m}"} - # One-shot schema migration: runs ONCE per `up`, before any API replica starts - # (api depends_on service_completed_successfully). Replicas never migrate themselves. + # One-shot schema migration as the schema OWNER messenger_migrate (not a superuser): runs ONCE + # per `up`, before any API replica starts. Replicas never migrate themselves. migrate: build: context: . @@ -235,7 +273,9 @@ services: command: ["python", "-m", "messenger.migrate"] environment: DATABASE_URL_FILE: /run/secrets/database_url - secrets: [database_url] + secrets: + - {source: database_url_migrate, target: database_url} + - {source: pki_internal_ca, target: internal-ca.crt} depends_on: postgres: condition: service_healthy @@ -253,7 +293,7 @@ services: image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.s3_bootstrap"] environment: - S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:8333} S3_REGION: ${S3_REGION:-us-east-1} S3_BUCKET: ${S3_BUCKET:-messenger-attachments} S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} @@ -265,6 +305,7 @@ services: S3_WORKER_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_worker_secret_access_key S3_AUDITOR_ACCESS_KEY_ID_FILE: /run/secrets/s3_auditor_access_key_id S3_AUDITOR_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_auditor_secret_access_key + TLS_CA_FILE: /run/secrets/internal-ca.crt secrets: - s3_admin_access_key_id - s3_admin_secret_access_key @@ -274,6 +315,7 @@ services: - s3_worker_secret_access_key - s3_auditor_access_key_id - s3_auditor_secret_access_key + - {source: pki_internal_ca, target: internal-ca.crt} depends_on: s3: condition: service_healthy @@ -299,19 +341,17 @@ services: # Lab 7: the only network listener is mTLS on 8443 (tls.py); plaintext health on loopback. APP_PORT: 8443 APP_HEALTH_PORT: 8081 - TLS_CERT_FILE: /run/secrets/api.crt - TLS_KEY_FILE: /run/secrets/api.key + TLS_CERT_FILE: /run/secrets/service.crt + TLS_KEY_FILE: /run/secrets/service.key TLS_CLIENT_CA_FILE: /run/secrets/internal-ca.crt MTLS_ALLOWED_CLIENTS: ${MTLS_ALLOWED_CLIENTS:-lb} secrets: - - database_url + - {source: database_url_api, target: database_url} - cache_url - - source: s3_api_access_key_id - target: s3_access_key_id - - source: s3_api_secret_access_key - target: s3_secret_access_key - - {source: pki_api_crt, target: api.crt} - - {source: pki_api_key, target: api.key} + - {source: s3_api_access_key_id, target: s3_access_key_id} + - {source: s3_api_secret_access_key, target: s3_secret_access_key} + - {source: pki_api_crt, target: service.crt} + - {source: pki_api_key, target: service.key} - {source: pki_internal_ca, target: internal-ca.crt} # No `ports` and no container_name: replicas are reachable only through `lb`, # and `--scale api=N` / deploy.replicas works. @@ -340,10 +380,9 @@ services: replicas: ${API_REPLICAS:-2} resources: # 512m: UPLOAD_CONCURRENCY (4) x 10 MiB bodies + one djpeg (<= JPEG_MAX_MEMORY_MB) + runtime; - # measured in lab 4 (bench/upload_memory.py). No resizing happens in the API. + # measured in lab 4. No resizing happens in the API. limits: {cpus: "${API_CPUS:-1.0}", memory: "${API_MEMORY:-512m}"} - # No swap on top of the limit (Docker's default would allow as much swap again): the RAM bound - # of the experiments is a real bound, and running out of it is visible, not hidden in swap. + # No swap on top of the limit: the RAM bound is a real bound. memswap_limit: ${API_MEMORY:-512m} lb: @@ -378,8 +417,7 @@ services: resources: limits: {cpus: "${LB_CPUS:-1.0}", memory: 128m} - # Lab 5: outbox relay + lease reaper (src/messenger/relay.py). One process; a second one would - # be safe (SKIP LOCKED) but is not needed. Database + broker only, no S3 keys. + # Outbox relay + lease reaper (src/messenger/relay.py). Database + broker only, no S3 keys. relay: image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.relay"] @@ -389,9 +427,11 @@ services: RELAY_POLL_SECONDS: ${RELAY_POLL_SECONDS:-0.5} FAULT_POINTS: ${RELAY_FAULT_POINTS:-} secrets: - - database_url - - source: broker_url_relay - target: broker_url + - {source: database_url_relay, target: database_url} + - {source: broker_url_relay, target: broker_url} + - {source: pki_relay_crt, target: service.crt} + - {source: pki_relay_key, target: service.key} + - {source: pki_internal_ca, target: internal-ca.crt} healthcheck: test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"] interval: 5s @@ -412,8 +452,8 @@ services: resources: limits: {cpus: "${RELAY_CPUS:-0.5}", memory: 256m} - # Lab 5: image worker (src/messenger/worker.py). Scalable (`--scale worker=2`): competing - # consumers of one queue; the database lease decides who works on a job. + # Image worker (src/messenger/worker.py). Scalable (`--scale worker=2`): competing consumers of + # one queue; the database lease decides who works on a job. worker: image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.worker"] @@ -430,13 +470,13 @@ services: CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30} FAULT_POINTS: ${WORKER_FAULT_POINTS:-} secrets: - - database_url - - source: broker_url_worker - target: broker_url - - source: s3_worker_access_key_id - target: s3_access_key_id - - source: s3_worker_secret_access_key - target: s3_secret_access_key + - {source: database_url_worker, target: database_url} + - {source: broker_url_worker, target: broker_url} + - {source: s3_worker_access_key_id, target: s3_access_key_id} + - {source: s3_worker_secret_access_key, target: s3_secret_access_key} + - {source: pki_worker_crt, target: service.crt} + - {source: pki_worker_key, target: service.key} + - {source: pki_internal_ca, target: internal-ca.crt} healthcheck: test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"] interval: 5s @@ -464,7 +504,7 @@ services: limits: {cpus: "${WORKER_CPUS:-2.0}", memory: "${WORKER_MEMORY:-1536m}"} memswap_limit: ${WORKER_MEMORY:-1536m} - # Track 2: read-only checker of the pipeline invariants (database in read-only transactions, + # Read-only checker of the pipeline invariants (database role messenger_auditor: SELECT only, # S3 auditor key: Read + List, no Write). On demand: docker compose run --rm auditor auditor: profiles: ["tools"] @@ -474,19 +514,19 @@ services: environment: DATABASE_URL_FILE: /run/secrets/database_url DB_TIMEOUT_SECONDS: ${AUDIT_DB_TIMEOUT_SECONDS:-30} - S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:8333} S3_REGION: ${S3_REGION:-us-east-1} S3_BUCKET: ${S3_BUCKET:-messenger-attachments} S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-3} + TLS_CA_FILE: /run/secrets/internal-ca.crt secrets: - - database_url - - source: s3_auditor_access_key_id - target: s3_access_key_id - - source: s3_auditor_secret_access_key - target: s3_secret_access_key + - {source: database_url_auditor, target: database_url} + - {source: s3_auditor_access_key_id, target: s3_access_key_id} + - {source: s3_auditor_secret_access_key, target: s3_secret_access_key} + - {source: pki_internal_ca, target: internal-ca.crt} depends_on: postgres: condition: service_healthy @@ -500,7 +540,6 @@ services: # Operator CLI (replay of failed jobs, reprocess with a newer pipeline, failed registry): # docker compose run --rm jobctl list-failed - # docker compose run --rm jobctl replay --operator alice --reason "..." jobctl: profiles: ["tools"] image: ${API_IMAGE:-mtusi-messenger:lab7} @@ -509,7 +548,9 @@ services: environment: DATABASE_URL_FILE: /run/secrets/database_url JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} - secrets: [database_url] + secrets: + - {source: database_url_jobctl, target: database_url} + - {source: pki_internal_ca, target: internal-ca.crt} depends_on: postgres: condition: service_healthy @@ -544,17 +585,21 @@ services: resources: limits: {cpus: "0.5", memory: 128m} - # ------------------------------------------------------------------ lab 6: observability + # ------------------------------------------------------------------ observability (lab 6) # Receives OTLP from api/relay/worker, limits memory, batches, forwards to the three stores. - # Distroless image (no shell): its health is the `up{job="otel-collector"}` scrape of :8888. + # Distroless image (no shell). Lab 7: receiver HTTPS + client certificate required, exporters mTLS. otel-collector: image: otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea command: - --config=/etc/otelcol/collector.yaml - # traces-all (keep every span) | traces-tail (tail sampling, track 1) + # traces-all (keep every span) | traces-tail (tail sampling, lab 6 track 1) - --config=/etc/otelcol/${OTEL_COLLECTOR_TRACES:-traces-all}.yaml environment: GOMEMLIMIT: 360MiB # Go heap target under the 512 MiB container limit + secrets: + - {source: pki_otel_collector_crt, target: otel-collector.crt} + - {source: pki_otel_collector_key, target: otel-collector.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - ./infra/otel:/etc/otelcol:ro restart: unless-stopped @@ -564,22 +609,29 @@ services: limits: {cpus: "${COLLECTOR_CPUS:-1.0}", memory: 512m} memswap_limit: 512m - # Metrics store + alert rules (OTLP receiver for the Collector's pushes; scrapes otelcol_*). + # Metrics store + alert rules. Lab 7: HTTPS + client certificate + SAN allowlist (web-config.yml). prometheus: image: prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06 command: - --config.file=/etc/prometheus/prometheus.yml + - --web.config.file=/etc/prometheus/web-config.yml - --storage.tsdb.path=/prometheus - --storage.tsdb.retention.time=15d - --storage.tsdb.retention.size=2GB - --web.enable-otlp-receiver - --web.listen-address=:9090 + secrets: + - {source: pki_prometheus_crt, target: prometheus.crt} + - {source: pki_prometheus_key, target: prometheus.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - ./infra/prometheus/web-config.yml:/etc/prometheus/web-config.yml:ro + - ./infra/prometheus/promtool-http.yml:/etc/prometheus/promtool-http.yml:ro - ./infra/prometheus/rules:/etc/prometheus/rules:ro - promdata:/prometheus healthcheck: - test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9090/-/ready"] + test: ["CMD", "promtool", "check", "ready", "--url=https://localhost:9090", "--http.config.file=/etc/prometheus/promtool-http.yml"] interval: 5s timeout: 3s retries: 30 @@ -592,12 +644,16 @@ services: limits: {cpus: "${PROMETHEUS_CPUS:-1.0}", memory: 512m} memswap_limit: 512m - # Logs store (OTLP endpoint /otlp). Distroless: health = up{job="loki"} + /ready via Grafana. + # Logs store (OTLP endpoint /otlp). Distroless. Lab 7: HTTPS + client certificate required. loki: image: grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7 - command: ["-config.file=/etc/loki/lab6.yaml"] + command: ["-config.file=/etc/loki/lab.yaml"] + secrets: + - {source: pki_loki_crt, target: loki.crt} + - {source: pki_loki_key, target: loki.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - - ./infra/loki/loki.yaml:/etc/loki/lab6.yaml:ro + - ./infra/loki/loki.yaml:/etc/loki/lab.yaml:ro - lokidata:/loki stop_grace_period: 30s restart: unless-stopped @@ -607,12 +663,16 @@ services: limits: {cpus: "${LOKI_CPUS:-1.0}", memory: 512m} memswap_limit: 512m - # Traces store (OTLP/HTTP :4318, query API :3200). Distroless: health = up{job="tempo"}. + # Traces store (OTLP/HTTPS :4318, query API :3200). Distroless. Lab 7: both listeners mTLS. tempo: image: grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38 - command: ["-config.file=/etc/tempo/lab6.yaml"] + command: ["-config.file=/etc/tempo/lab.yaml"] + secrets: + - {source: pki_tempo_crt, target: tempo.crt} + - {source: pki_tempo_key, target: tempo.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - - ./infra/tempo/tempo.yaml:/etc/tempo/lab6.yaml:ro + - ./infra/tempo/tempo.yaml:/etc/tempo/lab.yaml:ro - tempodata:/var/tempo stop_grace_period: 30s restart: unless-stopped @@ -622,13 +682,20 @@ services: limits: {cpus: "${TEMPO_CPUS:-1.0}", memory: 512m} memswap_limit: 512m - # UI: datasources (fixed UIDs) and the dashboard are provisioned from Git; only this port and the - # LB are published, on loopback. Admin password = secrets/grafana_admin_password (init_secrets.py). + # UI: datasources (fixed UIDs) and the dashboard are provisioned from Git. Lab 7: HTTPS on + # 127.0.0.1/[::1]:3000 with a public-CA certificate (SAN localhost), datasources over mTLS. + # Admin password = secrets/grafana_admin_password (init_secrets.py). grafana: image: grafana/grafana:13.2.6@sha256:b21409d7951ddcfd63a4b49083e4ef2cc35bc1437d071813bf82bfb238b00bca environment: GF_SECURITY_ADMIN_USER: admin GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + GF_SERVER_PROTOCOL: https + GF_SERVER_CERT_FILE: /run/secrets/grafana-ui.crt + GF_SERVER_CERT_KEY: /run/secrets/grafana-ui.key + GF_SERVER_MIN_TLS_VERSION: TLS1.2 + GF_SERVER_DOMAIN: localhost + GF_SECURITY_COOKIE_SECURE: "true" GF_USERS_ALLOW_SIGN_UP: "false" GF_AUTH_ANONYMOUS_ENABLED: "false" GF_ANALYTICS_REPORTING_ENABLED: "false" @@ -638,8 +705,15 @@ services: GF_PLUGINS_PREINSTALL_DISABLED: "true" # no plugin downloads at start: works offline GF_DASHBOARDS_DEFAULT_HOME_DASHBOARD_PATH: /var/lib/grafana/dashboards/messenger.json GF_LOG_LEVEL: warn - GOMEMLIMIT: 700MiB # Go heap target under the 1 GiB limit (512 MiB was not enough: GC thrashing) - secrets: [grafana_admin_password] + GOMEMLIMIT: 700MiB # Go heap target under the 1 GiB limit + secrets: + - grafana_admin_password + - {source: pki_grafana_ui_crt, target: grafana-ui.crt} + - {source: pki_grafana_ui_key, target: grafana-ui.key} + - {source: pki_public_ca, target: public-ca.crt} + - {source: pki_grafana_crt, target: grafana.crt} + - {source: pki_grafana_key, target: grafana.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro @@ -648,7 +722,7 @@ services: - "127.0.0.1:${GRAFANA_PORT:-3000}:3000" - "[::1]:${GRAFANA_PORT:-3000}:3000" healthcheck: - test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:3000/api/health"] + test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "--cacert", "/run/secrets/public-ca.crt", "https://localhost:3000/api/health"] interval: 5s timeout: 3s retries: 30 @@ -689,13 +763,37 @@ volumes: tempodata: grafanadata: +# Every value is a file in ./secrets (scripts/init_secrets.py, git-ignored), mounted read-only +# under /run/secrets ONLY into the services listed above. secrets: postgres_password: file: ./secrets/postgres_password - valkey_password: - file: ./secrets/valkey_password - database_url: - file: ./secrets/database_url + pg_migrate_password: + file: ./secrets/pg_migrate_password + pg_api_password: + file: ./secrets/pg_api_password + pg_relay_password: + file: ./secrets/pg_relay_password + pg_worker_password: + file: ./secrets/pg_worker_password + pg_jobctl_password: + file: ./secrets/pg_jobctl_password + pg_auditor_password: + file: ./secrets/pg_auditor_password + database_url_migrate: + file: ./secrets/database_url_migrate + database_url_api: + file: ./secrets/database_url_api + database_url_relay: + file: ./secrets/database_url_relay + database_url_worker: + file: ./secrets/database_url_worker + database_url_jobctl: + file: ./secrets/database_url_jobctl + database_url_auditor: + file: ./secrets/database_url_auditor + valkey_api_password: + file: ./secrets/valkey_api_password cache_url: file: ./secrets/cache_url s3_admin_access_key_id: @@ -724,24 +822,70 @@ secrets: file: ./secrets/grafana_admin_password # Lab 7 PKI (scripts/init_pki.py). Each service mounts only its own certificate/key and the CA it # verifies peers with; the CA private keys are mounted nowhere. + pki_public_ca: + file: ./secrets/pki/public-ca.crt + pki_internal_ca: + file: ./secrets/pki/internal-ca.crt pki_ingress_pem: file: ./secrets/pki/ingress.pem pki_lb_pem: file: ./secrets/pki/lb.pem - pki_internal_ca: - file: ./secrets/pki/internal-ca.crt - pki_api_crt: - file: ./secrets/pki/api.crt - pki_api_key: - file: ./secrets/pki/api.key pki_lb_crt: file: ./secrets/pki/lb.crt pki_lb_key: file: ./secrets/pki/lb.key + pki_api_crt: + file: ./secrets/pki/api.crt + pki_api_key: + file: ./secrets/pki/api.key + pki_relay_crt: + file: ./secrets/pki/relay.crt + pki_relay_key: + file: ./secrets/pki/relay.key pki_worker_crt: file: ./secrets/pki/worker.crt pki_worker_key: file: ./secrets/pki/worker.key + pki_postgres_crt: + file: ./secrets/pki/postgres.crt + pki_postgres_key: + file: ./secrets/pki/postgres.key + pki_valkey_crt: + file: ./secrets/pki/valkey.crt + pki_valkey_key: + file: ./secrets/pki/valkey.key + pki_s3_crt: + file: ./secrets/pki/s3.crt + pki_s3_key: + file: ./secrets/pki/s3.key + pki_broker_crt: + file: ./secrets/pki/broker.crt + pki_broker_key: + file: ./secrets/pki/broker.key + pki_otel_collector_crt: + file: ./secrets/pki/otel-collector.crt + pki_otel_collector_key: + file: ./secrets/pki/otel-collector.key + pki_prometheus_crt: + file: ./secrets/pki/prometheus.crt + pki_prometheus_key: + file: ./secrets/pki/prometheus.key + pki_loki_crt: + file: ./secrets/pki/loki.crt + pki_loki_key: + file: ./secrets/pki/loki.key + pki_tempo_crt: + file: ./secrets/pki/tempo.crt + pki_tempo_key: + file: ./secrets/pki/tempo.key + pki_grafana_crt: + file: ./secrets/pki/grafana.crt + pki_grafana_key: + file: ./secrets/pki/grafana.key + pki_grafana_ui_crt: + file: ./secrets/pki/grafana-ui.crt + pki_grafana_ui_key: + file: ./secrets/pki/grafana-ui.key pki_foreign_lb_crt: # test only: foreign CA, SAN lb file: ./secrets/pki/foreign-lb.crt pki_foreign_lb_key: diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json index 43d487c..7f05f17 100644 --- a/infra/grafana/dashboards/messenger.json +++ b/infra/grafana/dashboards/messenger.json @@ -1047,7 +1047,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "rate(otelcol_process_cpu_seconds[$__rate_interval])", + "expr": "rate(otelcol_process_cpu_seconds_total[$__rate_interval])", "legendFormat": "otel-collector", "range": true } @@ -1112,7 +1112,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "otelcol_process_memory_rss", + "expr": "otelcol_process_memory_rss_bytes", "legendFormat": "otel-collector RSS", "range": true } @@ -1445,7 +1445,7 @@ "type": "prometheus", "uid": "prometheus" }, - "description": "otelcol_* self-metrics, scraped from :8888. sent < accepted with tail sampling (dropped by policy).\n\nUnit: ops.", + "description": "otelcol_* self-metrics, pushed over OTLP/HTTPS (lab 7). sent < accepted with tail sampling (dropped by policy).\n\nUnit: ops.", "gridPos": { "h": 8, "w": 8, @@ -1486,7 +1486,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_receiver_accepted_spans[$__rate_interval]))", + "expr": "sum(rate(otelcol_receiver_accepted_spans_total[$__rate_interval]))", "legendFormat": "accepted", "range": true }, @@ -1496,7 +1496,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_receiver_refused_spans[$__rate_interval]))", + "expr": "sum(rate(otelcol_receiver_refused_spans_total[$__rate_interval]))", "legendFormat": "refused (memory_limiter)", "range": true }, @@ -1506,7 +1506,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_exporter_sent_spans[$__rate_interval]))", + "expr": "sum(rate(otelcol_exporter_sent_spans_total[$__rate_interval]))", "legendFormat": "sent to Tempo", "range": true }, @@ -1516,7 +1516,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_exporter_send_failed_spans[$__rate_interval]))", + "expr": "sum(rate(otelcol_exporter_send_failed_spans_total[$__rate_interval]))", "legendFormat": "send failed (dropped)", "range": true } @@ -1571,7 +1571,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_receiver_accepted_log_records[$__rate_interval]))", + "expr": "sum(rate(otelcol_receiver_accepted_log_records_total[$__rate_interval]))", "legendFormat": "logs accepted", "range": true }, @@ -1581,7 +1581,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_exporter_send_failed_log_records[$__rate_interval]))", + "expr": "sum(rate(otelcol_exporter_send_failed_log_records_total[$__rate_interval]))", "legendFormat": "logs failed", "range": true }, @@ -1591,7 +1591,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_receiver_accepted_metric_points[$__rate_interval]))", + "expr": "sum(rate(otelcol_receiver_accepted_metric_points_total[$__rate_interval]))", "legendFormat": "metric points accepted", "range": true }, @@ -1601,7 +1601,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_exporter_send_failed_metric_points[$__rate_interval]))", + "expr": "sum(rate(otelcol_exporter_send_failed_metric_points_total[$__rate_interval]))", "legendFormat": "metric points failed", "range": true } @@ -1787,7 +1787,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "up{job=~\"otel-collector|prometheus|loki|tempo|grafana\"}", + "expr": "up{job=~\"prometheus|loki|tempo\"}", "legendFormat": "{{job}}", "range": true } diff --git a/infra/grafana/provisioning/datasources/datasources.yaml b/infra/grafana/provisioning/datasources/datasources.yaml index a788578..d286773 100644 --- a/infra/grafana/provisioning/datasources/datasources.yaml +++ b/infra/grafana/provisioning/datasources/datasources.yaml @@ -2,6 +2,10 @@ # the dashboard JSON, the trace->logs and logs->trace links refer to exactly these UIDs # (prometheus / loki / tempo). A datasource without a fixed uid gets a random one and every # reference to it breaks ("data source not found"). +# Lab 7: every datasource is HTTPS with server verification (internal CA, serverName = the SAN) +# and Grafana's own client certificate (SAN grafana): the three backends require one, Prometheus +# also checks the SAN allowlist. The PEM files are read at provisioning time ($__file{}), from +# Docker secrets mounted only into Grafana. apiVersion: 1 deleteDatasources: @@ -14,10 +18,17 @@ datasources: uid: prometheus type: prometheus access: proxy - url: http://prometheus:9090 + url: https://prometheus:9090 isDefault: true editable: false + secureJsonData: &tls_files + tlsCACert: $__file{/run/secrets/internal-ca.crt} + tlsClientCert: $__file{/run/secrets/grafana.crt} + tlsClientKey: $__file{/run/secrets/grafana.key} jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: prometheus httpMethod: POST timeInterval: 15s # = scrape/evaluation interval: $__rate_interval >= 4 x 15 s prometheusType: Prometheus @@ -29,9 +40,13 @@ datasources: uid: loki type: loki access: proxy - url: http://loki:3100 + url: https://loki:3100 editable: false + secureJsonData: *tls_files jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: loki maxLines: 1000 # log line -> its trace in Tempo (trace_id is structured metadata of the OTLP record) derivedFields: @@ -46,9 +61,13 @@ datasources: uid: tempo type: tempo access: proxy - url: http://tempo:3200 + url: https://tempo:3200 editable: false + secureJsonData: *tls_files jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: tempo # span -> the log records of the same trace (and service) in Loki tracesToLogsV2: datasourceUid: loki diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml index c4b8f29..053a4b4 100644 --- a/infra/loki/loki.yaml +++ b/infra/loki/loki.yaml @@ -12,7 +12,15 @@ auth_enabled: false server: http_listen_port: 3100 grpc_listen_port: 9096 + grpc_listen_address: 127.0.0.1 log_level: warn + # Lab 7: HTTPS + mandatory client certificate of the internal CA (otel-collector pushes, + # grafana queries, prometheus scrapes). gRPC is internal to the single binary: loopback only. + http_tls_config: + cert_file: /run/secrets/loki.crt + key_file: /run/secrets/loki.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-ca.crt common: instance_addr: 127.0.0.1 diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml index c034934..ccbe005 100644 --- a/infra/otel/collector.yaml +++ b/infra/otel/collector.yaml @@ -1,24 +1,29 @@ -# OpenTelemetry Collector (otel/opentelemetry-collector-contrib 0.165.0), lab 6. +# OpenTelemetry Collector (otel/opentelemetry-collector-contrib 0.165.0), labs 6-7. # -# API x2 / relay / worker --OTLP/HTTP protobuf :4318--> [receiver otlp] -# -> memory_limiter -> batch -> exporters: -# traces -> Tempo (otlp_http/tempo, http://tempo:4318/v1/traces) -# metrics -> Prometheus (otlp_http/prometheus, http://prometheus:9090/api/v1/otlp/v1/metrics) -# logs -> Loki (otlp_http/loki, http://loki:3100/otlp/v1/logs) +# API x2 / relay / worker --OTLP/HTTPS (mTLS) :4318--> [receiver otlp] +# -> memory_limiter -> batch -> exporters (all HTTPS + client certificate otel-collector): +# traces -> Tempo (otlp_http/tempo, https://tempo:4318/v1/traces) +# metrics -> Prometheus (otlp_http/prometheus, https://prometheus:9090/api/v1/otlp/v1/metrics) +# logs -> Loki (otlp_http/loki, https://loki:3100/otlp/v1/logs) # +# Lab 7 (contracts/trust-matrix.md): the receiver speaks TLS only and REQUIRES a client certificate +# of the internal CA (client_ca_file): a process on the `telemetry` network without such a +# certificate cannot ingest anything. Every exporter verifies the backend (internal CA + hostname) +# and authenticates with the Collector's own certificate (SAN otel-collector); Prometheus also +# checks that SAN against its allowlist. # The Collector stores nothing for long: it receives, limits, batches and forwards. When a backend # is down, each exporter keeps a BOUNDED queue (sending_queue) and retries for at most # max_elapsed_time; then the data is dropped and counted (otelcol_exporter_send_failed_*, -# otelcol_exporter_enqueue_failed_*). memory_limiter refuses new data above its limit (the SDKs -# get a retryable error and drop after their own bounded queue) instead of growing until OOM. -# Its own metrics: Prometheus scrapes :8888 (otelcol_*). Only on the internal `telemetry` network. +# otelcol_exporter_enqueue_failed_*). memory_limiter refuses new data above its limit. +# Its own metrics: PUSHED over OTLP/HTTPS to Prometheus (lab 7; the lab 6 pull endpoint :8888 had no +# TLS). health_check listens on the container's loopback only. # -# Traces pipeline variants (track 1, docs/TRACK1.md): this file keeps EVERY span; the overlay +# Traces pipeline variants (lab 6 track 1): this file keeps EVERY span; the overlay # traces-tail.yaml (passed as a second --config, compose OTEL_COLLECTOR_TRACES) adds tail sampling. extensions: health_check: - endpoint: 0.0.0.0:13133 + endpoint: 127.0.0.1:13133 receivers: otlp: @@ -26,11 +31,15 @@ receivers: http: endpoint: 0.0.0.0:4318 max_request_body_size: 8388608 # 8 MiB per export request + tls: + cert_file: /run/secrets/otel-collector.crt + key_file: /run/secrets/otel-collector.key + client_ca_file: /run/secrets/internal-ca.crt # = RequireAndVerifyClientCert + min_version: "1.2" processors: # First in every pipeline. Container limit 512 MiB: soft limit = 400 - 80 = 320 MiB (start - # refusing + GC), hard limit 400 MiB (forced GC). The contrib binary alone is ~150 MiB RSS; - # 256 MiB of container memory left the limiter refusing data at idle. GOMEMLIMIT = 360 MiB. + # refusing + GC), hard limit 400 MiB (forced GC). The contrib binary alone is ~150 MiB RSS. memory_limiter: check_interval: 1s limit_mib: 400 @@ -43,8 +52,13 @@ processors: exporters: otlp_http/tempo: - endpoint: http://tempo:4318 + endpoint: https://tempo:4318 timeout: 5s + tls: &mtls + ca_file: /run/secrets/internal-ca.crt + cert_file: /run/secrets/otel-collector.crt + key_file: /run/secrets/otel-collector.key + min_version: "1.2" sending_queue: &queue enabled: true num_consumers: 2 @@ -55,29 +69,37 @@ exporters: max_interval: 10s max_elapsed_time: 60s # then the batch is dropped (counted), never retried forever otlp_http/prometheus: - endpoint: http://prometheus:9090/api/v1/otlp + endpoint: https://prometheus:9090/api/v1/otlp timeout: 5s + tls: *mtls sending_queue: *queue retry_on_failure: *retry otlp_http/loki: - endpoint: http://loki:3100/otlp + endpoint: https://loki:3100/otlp timeout: 5s + tls: *mtls sending_queue: *queue retry_on_failure: *retry service: extensions: [health_check] telemetry: + resource: + service.name: otel-collector logs: level: warn metrics: level: normal readers: - - pull: + - periodic: + interval: 15000 exporter: - prometheus: - host: 0.0.0.0 - port: 8888 + otlp: + protocol: http/protobuf + endpoint: https://prometheus:9090/api/v1/otlp/v1/metrics + certificate: /run/secrets/internal-ca.crt + client_certificate: /run/secrets/otel-collector.crt + client_key: /run/secrets/otel-collector.key pipelines: traces: receivers: [otlp] diff --git a/infra/postgres/initdb/10-roles.sh b/infra/postgres/initdb/10-roles.sh new file mode 100644 index 0000000..e8514ee --- /dev/null +++ b/infra/postgres/initdb/10-roles.sh @@ -0,0 +1,29 @@ +#!/bin/sh +# Runs ONCE, when the volume pgdata is initialised (docker-entrypoint-initdb.d), as OS user postgres +# over the local socket. Creates one login role per service; the passwords come from Docker secret +# files and are passed to psql as variables (never on a command line, never printed). +# messenger_migrate owns the database objects (applies migrations, service `migrate`) +# messenger_api / messenger_relay / messenger_worker GRANTs in migrations/0007_least_privilege.sql +# messenger_jobctl / messenger_auditor operator tools (profile tools) +# Nobody but `postgres` (no network login, see pg_hba.conf) is a superuser. +set -eu +for role in migrate api relay worker jobctl auditor; do + pw="$(tr -d '\r\n' < "/run/secrets/pg_${role}_password")" + psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres -v role="messenger_${role}" -v pw="$pw" <<'SQL' +CREATE ROLE :"role" LOGIN PASSWORD :'pw' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION; +SQL +done +psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres <<'SQL' +ALTER DATABASE messenger OWNER TO messenger_migrate; +-- Only the service roles may connect to the application database. +REVOKE ALL ON DATABASE messenger FROM PUBLIC; +GRANT CONNECT ON DATABASE messenger TO messenger_migrate, messenger_api, messenger_relay, messenger_worker, + messenger_jobctl, messenger_auditor; +SQL +psql -v ON_ERROR_STOP=1 --username postgres --dbname messenger <<'SQL' +-- PostgreSQL 15+: schema public belongs to pg_database_owner (= messenger_migrate now), and +-- PUBLIC has no CREATE on it. Make it explicit: only the owner creates objects. +REVOKE CREATE ON SCHEMA public FROM PUBLIC; +GRANT USAGE ON SCHEMA public TO messenger_api, messenger_relay, messenger_worker, messenger_jobctl, messenger_auditor; +SQL +echo "initdb: service roles created" diff --git a/infra/postgres/pg_hba.conf b/infra/postgres/pg_hba.conf new file mode 100644 index 0000000..5930bf8 --- /dev/null +++ b/infra/postgres/pg_hba.conf @@ -0,0 +1,18 @@ +# PostgreSQL client authentication, lab 7 (passed with -c hba_file=..., compose service postgres). +# First matching line wins. +# +# Unix socket inside the container only (docker compose exec): the superuser `postgres` by peer +# (OS user postgres), everyone else by password. initdb scripts and the operator use this path. +# TYPE DATABASE USER ADDRESS METHOD +local all postgres peer +local all all scram-sha-256 +# Network: TLS ONLY and only the service roles, password = SCRAM. The superuser never logs in +# over the network. Clients verify the server with sslmode=verify-full (internal CA, SAN postgres). +hostssl messenger messenger_migrate all scram-sha-256 +hostssl messenger messenger_api all scram-sha-256 +hostssl messenger messenger_relay all scram-sha-256 +hostssl messenger messenger_worker all scram-sha-256 +hostssl messenger messenger_jobctl all scram-sha-256 +hostssl messenger messenger_auditor all scram-sha-256 +# Everything else - any plaintext connection, any other role/database - is refused. +host all all all reject diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml index 4c4591c..32bdc46 100644 --- a/infra/prometheus/prometheus.yml +++ b/infra/prometheus/prometheus.yml @@ -1,11 +1,15 @@ -# Prometheus 3.16 (prom/prometheus:v3.16.0), lab 6: the METRICS store. +# Prometheus 3.16 (prom/prometheus:v3.16.0), labs 6-7: the METRICS store. # -# Application metrics are PUSHED by the Collector over OTLP (flag --web.enable-otlp-receiver, -# endpoint /api/v1/otlp/v1/metrics). Prometheus derives `job` = service.name and -# `instance` = service.instance.id from the OTLP resource, and translates the OTel names with -# suffixes: http.server.request.duration (unit s) -> http_server_request_duration_seconds_bucket, -# messenger.jobs.processed -> messenger_jobs_processed_total (mapping: docs/OBSERVABILITY.md). -# The telemetry components themselves are SCRAPED (pull) below. +# Application metrics AND the Collector's own metrics are PUSHED by the Collector over OTLP/HTTPS +# (flag --web.enable-otlp-receiver, endpoint /api/v1/otlp/v1/metrics). Prometheus derives +# `job` = service.name and `instance` = service.instance.id from the OTLP resource, and translates +# the OTel names with suffixes: http.server.request.duration (unit s) -> +# http_server_request_duration_seconds_bucket (mapping: docs/OBSERVABILITY.md). +# +# Lab 7: the web listener is HTTPS with a REQUIRED client certificate of the internal CA and a SAN +# allowlist (web-config.yml): only otel-collector (push), grafana (queries) and prometheus itself +# (self-scrape, promtool healthcheck) get in. Scrapes of Loki/Tempo use HTTPS + this server's +# own client certificate (they require one too). global: scrape_interval: 15s evaluation_interval: 15s # alert rules: detection delay = condition + `for` + <= 15 s @@ -24,13 +28,19 @@ rule_files: - /etc/prometheus/rules/*.yml scrape_configs: - - job_name: otel-collector # otelcol_* : accepted/refused/sent/failed, queue size, RSS - static_configs: [{targets: ["otel-collector:8888"]}] - job_name: prometheus + scheme: https + tls_config: &mtls + ca_file: /run/secrets/internal-ca.crt + cert_file: /run/secrets/prometheus.crt + key_file: /run/secrets/prometheus.key + min_version: TLS12 static_configs: [{targets: ["localhost:9090"]}] - job_name: loki + scheme: https + tls_config: *mtls static_configs: [{targets: ["loki:3100"]}] - job_name: tempo + scheme: https + tls_config: *mtls static_configs: [{targets: ["tempo:3200"]}] - - job_name: grafana - static_configs: [{targets: ["grafana:3000"]}] diff --git a/infra/prometheus/promtool-http.yml b/infra/prometheus/promtool-http.yml new file mode 100644 index 0000000..7b47720 --- /dev/null +++ b/infra/prometheus/promtool-http.yml @@ -0,0 +1,7 @@ +# HTTP client config of the container healthcheck (`promtool check healthy`): the same mTLS as any +# other client - Prometheus' own client certificate (SAN prometheus, in the allowlist). +tls_config: + ca_file: /run/secrets/internal-ca.crt + cert_file: /run/secrets/prometheus.crt + key_file: /run/secrets/prometheus.key + server_name: localhost diff --git a/infra/prometheus/rules/alerts.yml b/infra/prometheus/rules/alerts.yml index aa9f628..c438dd6 100644 --- a/infra/prometheus/rules/alerts.yml +++ b/infra/prometheus/rules/alerts.yml @@ -78,9 +78,9 @@ groups: # in its bounded queue and then dropped. The application itself is not affected. expr: | sum by (exporter) ( - rate(otelcol_exporter_send_failed_spans[2m]) - or rate(otelcol_exporter_send_failed_log_records[2m]) - or rate(otelcol_exporter_send_failed_metric_points[2m]) + rate(otelcol_exporter_send_failed_spans_total[2m]) + or rate(otelcol_exporter_send_failed_log_records_total[2m]) + or rate(otelcol_exporter_send_failed_metric_points_total[2m]) ) > 0 for: 30s labels: diff --git a/infra/prometheus/web-config.yml b/infra/prometheus/web-config.yml new file mode 100644 index 0000000..de436ea --- /dev/null +++ b/infra/prometheus/web-config.yml @@ -0,0 +1,10 @@ +# Prometheus web listener (--web.config.file), lab 7: HTTPS + mandatory client certificate of the +# internal CA + allowlist of client identities (SAN). A certificate of the same CA with another +# name (api, worker, loki, ...) is refused in the TLS handshake. +tls_server_config: + cert_file: /run/secrets/prometheus.crt + key_file: /run/secrets/prometheus.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-ca.crt + client_allowed_sans: [otel-collector, grafana, prometheus] + min_version: TLS12 diff --git a/infra/rabbitmq/rabbitmq.conf b/infra/rabbitmq/rabbitmq.conf index 05165e0..aae31b2 100644 --- a/infra/rabbitmq/rabbitmq.conf +++ b/infra/rabbitmq/rabbitmq.conf @@ -1,7 +1,18 @@ -# RabbitMQ 4.3 of the lab 5 stand (compose service `broker`), mounted as conf.d/20-lab5.conf. -# Only AMQP 0-9-1 on 5672 inside the internal network `queue`: no management UI, no Prometheus -# listener (enabled_plugins is empty), nothing published on the host. -listeners.tcp.default = 5672 +# RabbitMQ 4.3 of the stand (compose service `broker`), mounted as conf.d/20-lab.conf. +# Lab 7: AMQP 0-9-1 over TLS ONLY (amqps, 5671) inside the internal network `queue`. The plaintext +# listener is off, there is no management UI and no Prometheus listener (enabled_plugins is +# empty), nothing is published on the host. Clients verify the server certificate (internal CA, +# SAN broker); their identity is the user relay / worker with its own permissions (grade 3: no +# client certificates; mTLS to the broker is grade 4). +listeners.tcp = none +listeners.ssl.default = 5671 +ssl_options.cacertfile = /run/secrets/internal-ca.crt +ssl_options.certfile = /run/secrets/broker.crt +ssl_options.keyfile = /run/secrets/broker.key +ssl_options.verify = verify_none +ssl_options.fail_if_no_peer_cert = false +ssl_options.versions.1 = tlsv1.3 +ssl_options.versions.2 = tlsv1.2 # Users, permissions and topology are imported from files at every boot (idempotent): # /etc/rabbitmq/definitions.d/topology.json exchanges, quorum queues, bindings (this repo) diff --git a/infra/seaweedfs/start.sh b/infra/seaweedfs/start.sh index f496154..78c3699 100644 --- a/infra/seaweedfs/start.sh +++ b/infra/seaweedfs/start.sh @@ -14,6 +14,9 @@ # Exposure: master (9333), volume (8080), filer (8888) with their web UIs and gRPC listen on # 127.0.0.1 INSIDE the container only (-ip.bind); only the S3 API port 8333 listens on the # container network `storage` (internal, not published on the host). Telemetry is off. +# Lab 7: the S3 port speaks HTTPS only (-s3.cert.file/-s3.key.file: internal CA, SAN s3); the +# clients verify chain + hostname (aiobotocore verify=TLS_CA_FILE). The plaintext master/volume/filer +# hops stay on the container's own loopback (closed local hop, not reachable from the network). set -eu umask 077 secret() { tr -d '\r\n' < "/run/secrets/$1"; } @@ -49,4 +52,5 @@ exec weed server \ -filer -filer.disableDirListing -filer.concurrentUploadLimitMB=128 \ -volume.concurrentUploadLimitMB=128 \ -s3 -s3.ip.bind=0.0.0.0 -s3.port=8333 -s3.config=/tmp/s3.json -s3.concurrentUploadLimitMB=128 \ + -s3.cert.file=/run/secrets/s3.crt -s3.key.file=/run/secrets/s3.key \ -s3.iam=false -s3.autoCreateBucket=false -s3.port.iceberg=0 -s3.port.lance=0 diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml index a268041..dbac002 100644 --- a/infra/tempo/tempo.yaml +++ b/infra/tempo/tempo.yaml @@ -6,7 +6,15 @@ stream_over_http_enabled: true server: http_listen_port: 3200 + grpc_listen_address: 127.0.0.1 log_level: warn + # Lab 7: HTTPS + mandatory client certificate of the internal CA (otel-collector pushes, + # grafana queries, prometheus scrapes). gRPC is internal to the single binary: loopback only. + http_tls_config: + cert_file: /run/secrets/tempo.crt + key_file: /run/secrets/tempo.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-ca.crt distributor: receivers: @@ -14,6 +22,11 @@ distributor: protocols: http: endpoint: 0.0.0.0:4318 + tls: # only the Collector (client certificate of the internal CA) + cert_file: /run/secrets/tempo.crt + key_file: /run/secrets/tempo.key + client_ca_file: /run/secrets/internal-ca.crt + min_version: "1.2" ingester: max_block_duration: 5m # small blocks: a restart loses at most the WAL replay time diff --git a/infra/valkey/start.sh b/infra/valkey/start.sh new file mode 100644 index 0000000..55b7010 --- /dev/null +++ b/infra/valkey/start.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# Entry point of the compose service `valkey` (lab 7). Writes the ACL file from the Docker secret and +# starts Valkey through the image's entrypoint (which drops root to the valkey user). +# user default off no anonymous/shared-password access at all +# user api SHA-256 of its password only (the plain password never lands in a file here), +# keys session:* (sessions.py) and ratelimit:* (login limit), commands it uses: +# GET/SET/DEL (sessions), INCR/PEXPIRE/PTTL in MULTI/EXEC (rate limit), PING +# (readiness), CLIENT SETINFO (sent by redis-py on connect). FLUSHALL, CONFIG, +# KEYS, DEBUG, ACL, ... are refused with NOPERM. +set -eu +umask 077 +mkdir -p /tmp/valkey +hash="$(tr -d '\r\n' < /run/secrets/valkey_api_password | sha256sum | cut -d' ' -f1)" +printf 'user default off\n' > /tmp/valkey/users.acl +printf 'user api on #%s resetkeys ~session:* ~ratelimit:* resetchannels -@all +get +set +del +incr +pexpire +pttl +multi +exec +discard +ping +client|setinfo\n' \ + "$hash" >> /tmp/valkey/users.acl +chown -R valkey /tmp/valkey +exec docker-entrypoint.sh valkey-server /etc/valkey/valkey.conf diff --git a/infra/valkey/valkey.conf b/infra/valkey/valkey.conf index 510785b..5da25db 100644 --- a/infra/valkey/valkey.conf +++ b/infra/valkey/valkey.conf @@ -8,10 +8,20 @@ appenddirname "appendonlydir" # RDB snapshots are not needed on top of AOF. save "" dir /data -port 6379 protected-mode yes +# Lab 7: TLS only. The plaintext port is closed (port 0); clients verify the server certificate +# (internal CA, SAN valkey). No client certificates at grade 3 (tls-auth-clients no): the client +# identity is the ACL user + password below. +port 0 +tls-port 6379 +tls-cert-file /run/secrets/valkey.crt +tls-key-file /run/secrets/valkey.key +tls-ca-cert-file /run/secrets/internal-ca.crt +tls-auth-clients no +tls-protocols "TLSv1.2 TLSv1.3" # Sessions are never evicted silently: if memory is full, writes fail and login returns 503. maxmemory 128mb maxmemory-policy noeviction -# Password, generated by scripts/init_secrets.py and written here at container start. -include /tmp/requirepass.conf +# Lab 7: ACL users instead of one shared password (file written by infra/valkey/start.sh at start): +# `default` is off, `api` may touch only session:* / ratelimit:* keys with the commands it uses. +aclfile /tmp/valkey/users.acl diff --git a/migrations/0007_least_privilege.sql b/migrations/0007_least_privilege.sql new file mode 100644 index 0000000..2d951e3 --- /dev/null +++ b/migrations/0007_least_privilege.sql @@ -0,0 +1,48 @@ +-- Lab 7: least privilege in PostgreSQL. The roles are created once by +-- infra/postgres/initdb/10-roles.sh; this migration (run by the owner messenger_migrate) gives +-- every service exactly the table privileges its code uses (src/messenger/*.py) and nothing else: +-- no DDL, no TRUNCATE, no DELETE where the service never deletes, no access to other services' +-- tables. Matrix with the reasons: contracts/trust-matrix.md ("PostgreSQL"). + +-- API: users, chats, messages, idempotency, sessions (SESSION_STORE=postgres), upload intents, +-- the job + outbox row of an accepted upload (one transaction with the attachment, lab 5). +GRANT SELECT, INSERT ON users TO messenger_api; +GRANT SELECT, INSERT, UPDATE ON chats TO messenger_api; -- per-chat clock (0001) +GRANT SELECT, INSERT ON chat_members TO messenger_api; +GRANT SELECT, INSERT ON messages TO messenger_api; +GRANT SELECT, INSERT ON message_attachments TO messenger_api; +GRANT SELECT, INSERT, UPDATE, DELETE ON idempotency_keys TO messenger_api; -- purge after 24 h +GRANT SELECT, INSERT, DELETE ON sessions TO messenger_api; -- logout = DELETE +GRANT SELECT, INSERT, UPDATE, DELETE ON attachments TO messenger_api; -- janitor: stale intents +GRANT SELECT ON attachment_variants TO messenger_api; +GRANT SELECT, INSERT ON jobs TO messenger_api; +GRANT INSERT ON outbox, job_events TO messenger_api; + +-- Relay: outbox -> broker, lease reaper, republish of stale jobs, queue statistics. +GRANT SELECT, INSERT, UPDATE, DELETE ON outbox TO messenger_relay; -- purge published rows +GRANT SELECT, UPDATE ON jobs, job_attempts, attachments TO messenger_relay; +GRANT INSERT ON job_events TO messenger_relay; + +-- Worker: claim/lease/complete/retry of jobs, variants, staging/attempt cleanup bookkeeping. +-- No access to users, chats, messages, sessions or idempotency keys. +GRANT SELECT, UPDATE ON jobs, attachments TO messenger_worker; +GRANT SELECT, INSERT, UPDATE ON job_attempts TO messenger_worker; +GRANT SELECT, INSERT ON attachment_variants TO messenger_worker; +GRANT INSERT ON outbox, job_events TO messenger_worker; + +-- Operator CLI (jobctl): failed registry, replay/reprocess = new job + outbox row + audit event. +GRANT SELECT ON jobs, job_attempts, job_events, outbox, attachments, attachment_variants, failed_jobs TO messenger_jobctl; +GRANT INSERT ON jobs, outbox, job_events TO messenger_jobctl; +GRANT UPDATE ON jobs, attachments TO messenger_jobctl; + +-- Auditor: read-only checker of the pipeline invariants. +GRANT SELECT ON jobs, job_attempts, job_events, outbox, attachments, attachment_variants TO messenger_auditor; + +-- Identity columns of outbox/job_events: inserting roles need the sequences. +GRANT USAGE ON SEQUENCE outbox_id_seq, job_events_id_seq + TO messenger_api, messenger_relay, messenger_worker, messenger_jobctl; + +-- Functions are executable by PUBLIC by default; only the API sends messages. +REVOKE EXECUTE ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC; +GRANT EXECUTE ON FUNCTION post_message, post_message_v2, post_message_v3 TO messenger_api; +ALTER DEFAULT PRIVILEGES REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC; diff --git a/scripts/build_dashboard.py b/scripts/build_dashboard.py index 865b8bb..095dbcc 100644 --- a/scripts/build_dashboard.py +++ b/scripts/build_dashboard.py @@ -180,11 +180,11 @@ ts("DB pool wait p95 by service", "s", "db.client.connection.wait_time: time to get a connection from the pool.") ts("Container CPU (cores)", [("sum by (job, instance) (rate(container_cpu_time_seconds_total[$__rate_interval]))", "{{job}} {{instance}}"), - ("rate(otelcol_process_cpu_seconds[$__rate_interval])", "otel-collector")], + ("rate(otelcol_process_cpu_seconds_total[$__rate_interval])", "otel-collector")], "short", "cgroup cpu.stat of each application container (1 = one full core); Collector: its own counter.", w=12) ts("Container memory", [("sum by (job, instance) (container_memory_usage_bytes)", "{{job}} {{instance}}"), - ("otelcol_process_memory_rss", "otel-collector RSS")], + ("otelcol_process_memory_rss_bytes", "otel-collector RSS")], "bytes", "cgroup memory.current of each application container; Collector RSS (memory_limiter: 400 MiB).", w=12) grid.end() @@ -216,16 +216,16 @@ grid.end() # =============================================================================== telemetry pipeline row("Telemetry pipeline (Collector, SDK)") ts("Collector: spans accepted / sent / failed per second", - [("sum(rate(otelcol_receiver_accepted_spans[$__rate_interval]))", "accepted"), - ("sum(rate(otelcol_receiver_refused_spans[$__rate_interval]))", "refused (memory_limiter)"), - ("sum(rate(otelcol_exporter_sent_spans[$__rate_interval]))", "sent to Tempo"), - ("sum(rate(otelcol_exporter_send_failed_spans[$__rate_interval]))", "send failed (dropped)")], - "ops", "otelcol_* self-metrics, scraped from :8888. sent < accepted with tail sampling (dropped by policy).") + [("sum(rate(otelcol_receiver_accepted_spans_total[$__rate_interval]))", "accepted"), + ("sum(rate(otelcol_receiver_refused_spans_total[$__rate_interval]))", "refused (memory_limiter)"), + ("sum(rate(otelcol_exporter_sent_spans_total[$__rate_interval]))", "sent to Tempo"), + ("sum(rate(otelcol_exporter_send_failed_spans_total[$__rate_interval]))", "send failed (dropped)")], + "ops", "otelcol_* self-metrics, pushed over OTLP/HTTPS (lab 7). sent < accepted with tail sampling (dropped by policy).") ts("Collector: logs and metric points per second", - [("sum(rate(otelcol_receiver_accepted_log_records[$__rate_interval]))", "logs accepted"), - ("sum(rate(otelcol_exporter_send_failed_log_records[$__rate_interval]))", "logs failed"), - ("sum(rate(otelcol_receiver_accepted_metric_points[$__rate_interval]))", "metric points accepted"), - ("sum(rate(otelcol_exporter_send_failed_metric_points[$__rate_interval]))", "metric points failed")], + [("sum(rate(otelcol_receiver_accepted_log_records_total[$__rate_interval]))", "logs accepted"), + ("sum(rate(otelcol_exporter_send_failed_log_records_total[$__rate_interval]))", "logs failed"), + ("sum(rate(otelcol_receiver_accepted_metric_points_total[$__rate_interval]))", "metric points accepted"), + ("sum(rate(otelcol_exporter_send_failed_metric_points_total[$__rate_interval]))", "metric points failed")], "ops", "Same for the logs and metrics pipelines.") ts("Collector: exporter queues", [("max by (exporter) (otelcol_exporter_queue_size)", "{{exporter}} size"), @@ -237,7 +237,7 @@ ts("SDK: spans recorded vs exported (all processes)", "ops", "Spans finished in the process (sampled) and handed to the OTLP exporter: success / failure (Collector down).", w=12) ts("Telemetry components up", - [("up{job=~\"otel-collector|prometheus|loki|tempo|grafana\"}", "{{job}}")], + [("up{job=~\"prometheus|loki|tempo\"}", "{{job}}")], "short", "1 = the scrape succeeded.", w=12, maximum=1) grid.end() diff --git a/scripts/init_secrets.py b/scripts/init_secrets.py index 7605794..1d9970c 100644 --- a/scripts/init_secrets.py +++ b/scripts/init_secrets.py @@ -1,11 +1,22 @@ #!/usr/bin/env python3 -"""Create local synthetic credentials for the stand in ./secrets (ignored by Git). +"""Create local synthetic credentials and the PKI of the stand in ./secrets (ignored by Git). - python scripts/init_secrets.py + .venv/Scripts/python scripts/init_secrets.py (Linux/macOS: .venv/bin/python) Idempotent: existing files are kept, so re-running never changes passwords of a database that already has data. Prints only file names, never values. Delete ./secrets together with the volumes (`docker compose down -v`) to start over. + +Lab 7: one credential per service and role (contracts/trust-matrix.md): + PostgreSQL postgres (superuser: initdb + operator via `docker compose exec`, never over the + network), messenger_migrate (owner of the schema), messenger_api / _relay / _worker + (GRANT only what the service does, migrations/0007_least_privilege.sql), + messenger_jobctl / _auditor (operator tools). Every URL has sslmode=verify-full. + Valkey ACL user `api` (session:* and ratelimit:* keys, a few commands), `default` user off. + S3 admin (s3-init only) / api / worker / auditor key pairs. + RabbitMQ relay (publish only) / worker (consume only), amqps:// (TLS 5671). +The application services do not mount these files from lab 7 step 5 on: they read their own +values from OpenBao (scripts/bao_operator.py copies them there), see docs/OPERATOR.md. """ from __future__ import annotations @@ -19,6 +30,8 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SECRETS = ROOT / "secrets" +CA = "/run/secrets/internal-ca.crt" # path INSIDE the containers +DB_ROLES = ("migrate", "api", "relay", "worker", "jobctl", "auditor") def write(name: str, value: str) -> None: @@ -28,7 +41,7 @@ def write(name: str, value: str) -> None: return path.write_text(value + "\n", encoding="utf-8", newline="\n") # Readable by the container users (postgres, valkey, seaweedfs, rabbitmq, app uid 10001) - # through the compose bind mount. Local synthetic lab credentials only. + # through the compose bind mount; the folder ./secrets itself is 0700 for the host user. os.chmod(path, 0o644) print(f"created secrets/{name}") @@ -46,17 +59,23 @@ def rabbit_hash(password: str) -> str: def main() -> int: SECRETS.mkdir(exist_ok=True) + os.chmod(SECRETS, 0o700) + # PostgreSQL: superuser (no network login, pg_hba) + one login role per service. write("postgres_password", secrets.token_urlsafe(24)) # [A-Za-z0-9_-]: safe inside URLs - write("valkey_password", secrets.token_urlsafe(24)) - write("database_url", f"postgresql://messenger:{read('postgres_password')}@postgres:5432/messenger") - write("cache_url", f"redis://:{read('valkey_password')}@valkey:6379/0") + for role in DB_ROLES: + write(f"pg_{role}_password", secrets.token_urlsafe(24)) + write(f"database_url_{role}", f"postgresql://messenger_{role}:{read(f'pg_{role}_password')}@postgres:5432/" + f"messenger?sslmode=verify-full&sslrootcert={CA}") + # Valkey: ACL user `api` (infra/valkey/start.sh); TLS only (rediss). + write("valkey_api_password", secrets.token_urlsafe(24)) + write("cache_url", f"rediss://api:{read('valkey_api_password')}@valkey:6379/0") # S3 key pairs (SeaweedFS identities, infra/seaweedfs/start.sh): admin = bucket bootstrap only; # api = Write staging + Read final; worker = Read/Write both; auditor = Read + List (no Write). for who in ("admin", "api", "worker", "auditor"): write(f"s3_{who}_access_key_id", "AK" + secrets.token_hex(9).upper()) write(f"s3_{who}_secret_access_key", secrets.token_hex(20)) - # Lab 5: RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume - # the jobs queue; neither may declare/delete anything (configure "^$"). + # RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume the jobs + # queue; neither may declare/delete anything (configure "^$"). write("rabbitmq_relay_password", secrets.token_urlsafe(24)) write("rabbitmq_worker_password", secrets.token_urlsafe(24)) users = { @@ -71,8 +90,8 @@ def main() -> int: for who in ("relay", "worker"): # AMQP heartbeat 10 s: a frozen client loses its connection after ~2 missed heartbeats, and # the broker returns its unacked messages to the queue for the other consumers. - write(f"broker_url_{who}", f"amqp://{who}:{read(f'rabbitmq_{who}_password')}@broker:5672/?heartbeat=10") - # Lab 6: Grafana admin (UI on 127.0.0.1:3000 and the evidence scripts, via its datasource proxy). + write(f"broker_url_{who}", f"amqps://{who}:{read(f'rabbitmq_{who}_password')}@broker:5671/?heartbeat=10") + # Grafana admin (UI on https://localhost:3000 and the evidence scripts, via its datasource proxy). write("grafana_admin_password", secrets.token_urlsafe(18)) # Lab 7: local PKI (two CAs + service certificates) in ./secrets/pki. sys.path.insert(0, str(Path(__file__).resolve().parent)) diff --git a/scripts/obs.py b/scripts/obs.py index 218e838..87b5fa5 100644 --- a/scripts/obs.py +++ b/scripts/obs.py @@ -16,6 +16,7 @@ from __future__ import annotations import base64 import json import os +import ssl import sys import time import urllib.error @@ -24,7 +25,9 @@ import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -GRAFANA = os.environ.get("GRAFANA_URL", "http://127.0.0.1:3000").rstrip("/") +GRAFANA = os.environ.get("GRAFANA_URL", "https://localhost:3000").rstrip("/") +# Lab 7: Grafana is HTTPS with a public-CA certificate (SAN localhost); verified, never skipped. +TLS = ssl.create_default_context(cafile=os.environ.get("CA_FILE") or str(ROOT / "secrets" / "pki" / "public-ca.crt")) def _auth() -> str: @@ -38,7 +41,7 @@ def get(uid: str, path: str, params: dict | None = None, timeout: float = 30) -> if params: url += "?" + urllib.parse.urlencode(params) request = urllib.request.Request(url, headers={"Authorization": _auth(), "Accept": "application/json"}) - with urllib.request.urlopen(request, timeout=timeout) as response: + with urllib.request.urlopen(request, timeout=timeout, context=TLS) as response: return json.loads(response.read()) diff --git a/scripts/trace_demo.py b/scripts/trace_demo.py index 52ff523..585b11a 100644 --- a/scripts/trace_demo.py +++ b/scripts/trace_demo.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Controlled request -> its trace and logs (defense scenario, steps 2-3; evidence/trace-demo.txt). - python scripts/trace_demo.py [--base-url http://localhost:8080] [--output evidence/trace-demo.txt] + python scripts/trace_demo.py [--base-url https://localhost:8443] [--output evidence/trace-demo.txt] 1. creates a synthetic user and chat, uploads tests/fixtures/sample.png with OUR OWN W3C `traceparent` header (trace id chosen here) and X-Request-Id; @@ -36,13 +36,13 @@ def call(base: str, method: str, path: str, body=None, headers=None, raw: bytes data = json.dumps(body).encode() h["Content-Type"] = "application/json" request = urllib.request.Request(base + path, data=data, method=method, headers=h) - with urllib.request.urlopen(request, timeout=30) as response: + with urllib.request.urlopen(request, timeout=30, context=obs.TLS) as response: return response.status, response.headers, json.loads(response.read() or b"null") def main() -> int: parser = argparse.ArgumentParser() - parser.add_argument("--base-url", default="http://localhost:8080") + parser.add_argument("--base-url", default="https://localhost:8443") parser.add_argument("--output") args = parser.parse_args() base = args.base_url.rstrip("/") + "/api/v1" diff --git a/src/messenger/broker.py b/src/messenger/broker.py index 524d3c7..b14e061 100644 --- a/src/messenger/broker.py +++ b/src/messenger/broker.py @@ -21,6 +21,7 @@ from __future__ import annotations import datetime as dt import json import re +import ssl import uuid EXCHANGE = "messenger.jobs" @@ -28,6 +29,15 @@ QUEUE = "messenger.attachment-jobs" DLX = "messenger.jobs.dlx" DLQ = "messenger.attachment-jobs.dlq" ROUTING_KEY = "attachment.process.v1" + + +def ssl_context(settings) -> ssl.SSLContext | None: + """Lab 7: amqps:// -> TLS context that verifies the broker (internal CA + hostname `broker`). + A plain amqp:// URL gets None and is refused by the broker anyway (its TCP listener is off).""" + if not settings.broker_url.startswith("amqps://"): + return None + from .tls import client_context + return client_context(settings.tls_ca_file) JOB_TYPE = "attachment.process.v1" MAX_MESSAGE_BYTES = 4096 diff --git a/src/messenger/config.py b/src/messenger/config.py index c7752e7..3516f20 100644 --- a/src/messenger/config.py +++ b/src/messenger/config.py @@ -157,6 +157,9 @@ class Settings: # Lab 7: TLS of the API listener (mTLS, src/messenger/tls.py) and the loopback health port. tls_cert_file: str = "" tls_key_file: str = "" + # CA that every OUTGOING TLS connection verifies the server with (internal CA): S3, Valkey, + # RabbitMQ (PostgreSQL: sslrootcert in DATABASE_URL, OTLP: OTEL_EXPORTER_OTLP_CERTIFICATE). + tls_ca_file: str = "" tls_client_ca_file: str = "" health_port: int = 0 @@ -307,6 +310,7 @@ def s3_settings(*, credentials_required: bool = True) -> dict: janitor_interval_seconds=_float("JANITOR_INTERVAL_SECONDS", 60.0, 0.0, 3600.0), fault_points=faults, fault_values=fault_values, + tls_ca_file=_path("TLS_CA_FILE"), ) diff --git a/src/messenger/relay.py b/src/messenger/relay.py index cd397c6..59ef6e5 100644 --- a/src/messenger/relay.py +++ b/src/messenger/relay.py @@ -58,7 +58,7 @@ class Relay: async def connect(self) -> None: self.connection = await aio_pika.connect( - self.settings.broker_url, timeout=5, + self.settings.broker_url, timeout=5, ssl_context=broker.ssl_context(self.settings), client_properties={"connection_name": "relay@" + self.settings.instance_id}) self.lost = service.watch_connection(self.connection) # Confirm mode: every publish() waits for basic.ack of the broker (message in the quorum log). diff --git a/src/messenger/s3_bootstrap.py b/src/messenger/s3_bootstrap.py index d7f2e65..3cb1d74 100644 --- a/src/messenger/s3_bootstrap.py +++ b/src/messenger/s3_bootstrap.py @@ -18,6 +18,7 @@ from __future__ import annotations import asyncio import os +import ssl import sys import time import urllib.error @@ -36,8 +37,10 @@ def say(text: str) -> None: def anonymous_status(url: str) -> int: """HTTP status of an UNSIGNED request (what anyone on the network could do).""" + ca = os.environ.get("TLS_CA_FILE", "").strip() or None + context = ssl.create_default_context(cafile=ca) if url.startswith("https://") else None try: - with urllib.request.urlopen(url, timeout=3) as response: + with urllib.request.urlopen(url, timeout=3, context=context) as response: return response.status except urllib.error.HTTPError as exc: return exc.code diff --git a/src/messenger/sessions.py b/src/messenger/sessions.py index 53736e4..4804789 100644 --- a/src/messenger/sessions.py +++ b/src/messenger/sessions.py @@ -18,6 +18,7 @@ Two interchangeable stores (SESSION_STORE): from __future__ import annotations import asyncio +import ssl import datetime as dt import hashlib import json @@ -107,12 +108,18 @@ class ValkeySessionStore: def __init__(self, settings: Settings): self.timeout = settings.cache_timeout_seconds + tls = {} + if settings.cache_url.startswith("rediss://"): + # Lab 7: TLS to Valkey, server verified by the internal CA AND hostname (SAN valkey). + tls = {"ssl_ca_certs": settings.tls_ca_file or None, "ssl_cert_reqs": "required", + "ssl_check_hostname": True, "ssl_min_version": ssl.TLSVersion.TLSv1_2} self.client = Redis.from_url( settings.cache_url, socket_timeout=self.timeout, socket_connect_timeout=self.timeout, retry=Retry(NoBackoff(), 0), # no hidden retries: a failure is reported at once decode_responses=False, + **tls, ) def _key(self, token: str) -> str: diff --git a/src/messenger/storage.py b/src/messenger/storage.py index 9c891d7..4672d9e 100644 --- a/src/messenger/storage.py +++ b/src/messenger/storage.py @@ -68,6 +68,7 @@ class Storage: self._region = settings.s3_region self._access_key = access_key or settings.s3_access_key_id self._secret_key = secret_key or settings.s3_secret_access_key + self._ca_file = settings.tls_ca_file self._config = AioConfig( connect_timeout=settings.s3_connect_timeout_seconds, read_timeout=settings.s3_timeout_seconds, @@ -86,7 +87,9 @@ class Storage: session = get_session() self._client = await self._stack.enter_async_context(session.create_client( "s3", endpoint_url=self._endpoint, region_name=self._region, - aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key, config=self._config)) + aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key, config=self._config, + # Lab 7: https endpoint, chain AND hostname verified against the internal CA only. + verify=self._ca_file or True)) async def close(self) -> None: if self._stack is not None: diff --git a/src/messenger/worker.py b/src/messenger/worker.py index 63e691e..fca419a 100644 --- a/src/messenger/worker.py +++ b/src/messenger/worker.py @@ -74,7 +74,7 @@ class Worker: # ---------------------------------------------------------------- broker async def connect(self) -> None: self.connection = await aio_pika.connect( - self.settings.broker_url, timeout=5, + self.settings.broker_url, timeout=5, ssl_context=broker.ssl_context(self.settings), client_properties={"connection_name": "worker@" + self.name}) self.lost = service.watch_connection(self.connection) self.channel = await self.connection.channel() -- 2.54.0 From 876f6108478bd20835bb7ab080d4c0dd0460ad5c Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:41:57 +0300 Subject: [PATCH 05/16] =?UTF-8?q?lab7:=20OpenBao=202.7.3=20(=D0=BD=D0=B5?= =?UTF-8?q?=20dev,=20raft=20=D0=BD=D0=B0=20volume,=20TLS,=20audit),=20AppR?= =?UTF-8?q?ole=20=D0=B8=20scoped=20policy=20=D0=B4=D0=BB=D1=8F=20api/relay?= =?UTF-8?q?/worker,=20=D1=81=D0=B5=D0=BA=D1=80=D0=B5=D1=82=D1=8B=20=D1=82?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE=20=D0=B8=D0=B7=20OpenBao,=20?= =?UTF-8?q?=D1=81=D0=BA=D1=80=D0=B8=D0=BF=D1=82=20=D0=BE=D0=BF=D0=B5=D1=80?= =?UTF-8?q?=D0=B0=D1=82=D0=BE=D1=80=D0=B0=20=D0=B8=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B5=D1=80=D0=BA=D0=B0=20allow/deny?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compose.yaml | 123 ++++++++++++++------ infra/openbao/config.hcl | 39 +++++++ infra/openbao/policies/api.hcl | 16 +++ infra/openbao/policies/relay.hcl | 13 +++ infra/openbao/policies/worker.hcl | 14 +++ scripts/bao_check.cmd | 4 + scripts/bao_check.py | 80 +++++++++++++ scripts/bao_check.sh | 35 ++++++ scripts/bao_operator.py | 183 ++++++++++++++++++++++++++++++ scripts/restart.sh | 21 ++-- src/messenger/__main__.py | 1 + src/messenger/bao.py | 116 +++++++++++++++++++ src/messenger/config.py | 13 ++- src/messenger/logging_setup.py | 8 ++ src/messenger/relay.py | 1 + src/messenger/worker.py | 1 + 16 files changed, 623 insertions(+), 45 deletions(-) create mode 100644 infra/openbao/config.hcl create mode 100644 infra/openbao/policies/api.hcl create mode 100644 infra/openbao/policies/relay.hcl create mode 100644 infra/openbao/policies/worker.hcl create mode 100644 scripts/bao_check.cmd create mode 100644 scripts/bao_check.py create mode 100644 scripts/bao_check.sh create mode 100644 scripts/bao_operator.py create mode 100644 src/messenger/bao.py diff --git a/compose.yaml b/compose.yaml index ff54fc1..ac09912 100644 --- a/compose.yaml +++ b/compose.yaml @@ -28,13 +28,22 @@ # `storage` (s3), `queue` (broker), `telemetry`. The API is NOT on `queue`. name: ${COMPOSE_PROJECT_NAME:-mtusi-lab7} +# Lab 7: how a service gets its secrets: AppRole login to OpenBao with ITS role_id/secret_id +# (Docker secrets of that service only), read ITS path messenger/data/, revoke the token. +# database_url, cache_url, broker_url and the S3 key pair are NOT mounted as files into api, relay, +# worker any more (src/messenger/bao.py). +x-bao-env: &bao-env + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/secrets/internal-ca.crt + BAO_ROLE_ID_FILE: /run/secrets/bao_role_id + BAO_SECRET_ID_FILE: /run/secrets/bao_secret_id + BAO_STARTUP_TIMEOUT_SECONDS: ${BAO_STARTUP_TIMEOUT_SECONDS:-60} + x-api-env: &api-env APP_ENV: ${APP_ENV:-lab} LOG_LEVEL: ${LOG_LEVEL:-info} SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} SESSION_STORE: ${SESSION_STORE:-valkey} - DATABASE_URL_FILE: /run/secrets/database_url - CACHE_URL_FILE: /run/secrets/cache_url DB_POOL_MIN: ${DB_POOL_MIN:-1} DB_POOL_MAX: ${DB_POOL_MAX:-10} DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3} @@ -51,8 +60,6 @@ x-api-env: &api-env S3_REGION: ${S3_REGION:-us-east-1} S3_BUCKET: ${S3_BUCKET:-messenger-attachments} S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} - S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id - S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-3} MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} @@ -98,8 +105,6 @@ x-otel-env: &otel-env x-pipeline-env: &pipeline-env APP_ENV: ${APP_ENV:-lab} LOG_LEVEL: ${LOG_LEVEL:-info} - DATABASE_URL_FILE: /run/secrets/database_url - BROKER_URL_FILE: /run/secrets/broker_url DB_POOL_MAX: ${PIPELINE_DB_POOL_MAX:-6} DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3} S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:8333} @@ -336,8 +341,9 @@ services: BUILD_REVISION: ${BUILD_REVISION:-dev} image: ${API_IMAGE:-mtusi-messenger:lab7} environment: - <<: [*api-env, *otel-env] + <<: [*api-env, *otel-env, *bao-env] OTEL_SERVICE_NAME: messenger-api + BAO_SECRET_PATH: messenger/data/api # Lab 7: the only network listener is mTLS on 8443 (tls.py); plaintext health on loopback. APP_PORT: 8443 APP_HEALTH_PORT: 8081 @@ -346,10 +352,8 @@ services: TLS_CLIENT_CA_FILE: /run/secrets/internal-ca.crt MTLS_ALLOWED_CLIENTS: ${MTLS_ALLOWED_CLIENTS:-lb} secrets: - - {source: database_url_api, target: database_url} - - cache_url - - {source: s3_api_access_key_id, target: s3_access_key_id} - - {source: s3_api_secret_access_key, target: s3_secret_access_key} + - {source: bao_api_role_id, target: bao_role_id} + - {source: bao_api_secret_id, target: bao_secret_id} - {source: pki_api_crt, target: service.crt} - {source: pki_api_key, target: service.key} - {source: pki_internal_ca, target: internal-ca.crt} @@ -373,9 +377,11 @@ services: condition: service_completed_successfully s3-init: condition: service_completed_successfully + openbao: + condition: service_healthy # healthy = unsealed (see the openbao healthcheck) stop_grace_period: 15s # > DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS (11 s) restart: unless-stopped - networks: [edge, data, storage, telemetry] + networks: [edge, data, storage, telemetry, vault] deploy: replicas: ${API_REPLICAS:-2} resources: @@ -422,13 +428,14 @@ services: image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.relay"] environment: - <<: [*pipeline-env, *otel-env] + <<: [*pipeline-env, *otel-env, *bao-env] OTEL_SERVICE_NAME: messenger-relay + BAO_SECRET_PATH: messenger/data/relay RELAY_POLL_SECONDS: ${RELAY_POLL_SECONDS:-0.5} FAULT_POINTS: ${RELAY_FAULT_POINTS:-} secrets: - - {source: database_url_relay, target: database_url} - - {source: broker_url_relay, target: broker_url} + - {source: bao_relay_role_id, target: bao_role_id} + - {source: bao_relay_secret_id, target: bao_secret_id} - {source: pki_relay_crt, target: service.crt} - {source: pki_relay_key, target: service.key} - {source: pki_internal_ca, target: internal-ca.crt} @@ -445,9 +452,11 @@ services: condition: service_healthy migrate: condition: service_completed_successfully + openbao: + condition: service_healthy stop_grace_period: 10s restart: unless-stopped - networks: [data, queue, telemetry] + networks: [data, queue, telemetry, vault] deploy: resources: limits: {cpus: "${RELAY_CPUS:-0.5}", memory: 256m} @@ -458,10 +467,9 @@ services: image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.worker"] environment: - <<: [*pipeline-env, *otel-env] + <<: [*pipeline-env, *otel-env, *bao-env] OTEL_SERVICE_NAME: messenger-worker - S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id - S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + BAO_SECRET_PATH: messenger/data/worker WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} WORKER_SHUTDOWN_SECONDS: ${WORKER_SHUTDOWN_SECONDS:-20} IMAGE_MAX_MEMORY_MB: ${IMAGE_MAX_MEMORY_MB:-768} @@ -470,10 +478,8 @@ services: CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30} FAULT_POINTS: ${WORKER_FAULT_POINTS:-} secrets: - - {source: database_url_worker, target: database_url} - - {source: broker_url_worker, target: broker_url} - - {source: s3_worker_access_key_id, target: s3_access_key_id} - - {source: s3_worker_secret_access_key, target: s3_secret_access_key} + - {source: bao_worker_role_id, target: bao_role_id} + - {source: bao_worker_secret_id, target: bao_secret_id} - {source: pki_worker_crt, target: service.crt} - {source: pki_worker_key, target: service.key} - {source: pki_internal_ca, target: internal-ca.crt} @@ -494,9 +500,11 @@ services: condition: service_completed_successfully s3-init: condition: service_completed_successfully + openbao: + condition: service_healthy stop_grace_period: 30s # > WORKER_SHUTDOWN_SECONDS (20 s) + release restart: unless-stopped - networks: [data, storage, queue, telemetry] + networks: [data, storage, queue, telemetry, vault] deploy: replicas: ${WORKER_REPLICAS:-1} resources: @@ -585,6 +593,41 @@ services: resources: limits: {cpus: "0.5", memory: 128m} + # ------------------------------------------------------------------ secrets (lab 7) + # OpenBao, NOT dev mode: file storage on the volume baodata, TLS listener (infra/openbao/config.hcl), + # starts SEALED. Operator: scripts/bao_operator.py bootstrap | unseal (docs/OPERATOR.md); the root + # token and the unseal shares stay with the operator, outside the repository and all containers. + # Reachable only on the internal network `vault` (api, relay, worker). Image user: openbao (non-root). + openbao: + image: openbao/openbao:2.7.3@sha256:b9418c63e2185157d8ee8689a8a93265d5aadad677d6320156172bd42ad3b10b + command: ["server"] # entrypoint: bao server -config=/openbao/config (no -dev) + environment: + # For the operator CLI inside the container (docker compose exec): TLS to itself, verified. + BAO_ADDR: https://127.0.0.1:8200 + BAO_CACERT: /run/secrets/internal-ca.crt + secrets: + - {source: pki_openbao_crt, target: openbao.crt} + - {source: pki_openbao_key, target: openbao.key} + - {source: pki_internal_ca, target: internal-ca.crt} + volumes: + - ./infra/openbao/config.hcl:/openbao/config/lab.hcl:ro + - baodata:/openbao/file + healthcheck: + # `bao status` exits 0 only when initialized AND unsealed (2 = sealed): the application + # services wait for this (depends_on service_healthy) - a sealed OpenBao starts no new replica. + test: ["CMD", "bao", "status"] + interval: 3s + timeout: 3s + retries: 3 + start_period: 5s + stop_grace_period: 15s + restart: unless-stopped + networks: [vault] + deploy: + resources: + limits: {cpus: "0.5", memory: 256m} + memswap_limit: 256m + # ------------------------------------------------------------------ observability (lab 6) # Receives OTLP from api/relay/worker, limits memory, batches, forwards to the three stores. # Distroless image (no shell). Lab 7: receiver HTTPS + client certificate required, exporters mTLS. @@ -752,6 +795,8 @@ networks: telemetry: internal: true # OTLP + stores: apps, collector, prometheus, loki, tempo, grafana ui: # only Grafana: publishes 127.0.0.1:3000 + vault: + internal: true # OpenBao: reachable only by api, relay, worker volumes: pgdata: @@ -762,6 +807,7 @@ volumes: lokidata: tempodata: grafanadata: + baodata: # OpenBao storage (encrypted by its barrier key) # Every value is a file in ./secrets (scripts/init_secrets.py, git-ignored), mounted read-only # under /run/secrets ONLY into the services listed above. @@ -782,20 +828,12 @@ secrets: file: ./secrets/pg_auditor_password database_url_migrate: file: ./secrets/database_url_migrate - database_url_api: - file: ./secrets/database_url_api - database_url_relay: - file: ./secrets/database_url_relay - database_url_worker: - file: ./secrets/database_url_worker database_url_jobctl: file: ./secrets/database_url_jobctl database_url_auditor: file: ./secrets/database_url_auditor valkey_api_password: file: ./secrets/valkey_api_password - cache_url: - file: ./secrets/cache_url s3_admin_access_key_id: file: ./secrets/s3_admin_access_key_id s3_admin_secret_access_key: @@ -814,10 +852,6 @@ secrets: file: ./secrets/s3_auditor_secret_access_key rabbitmq_users: file: ./secrets/rabbitmq_users.json - broker_url_relay: - file: ./secrets/broker_url_relay - broker_url_worker: - file: ./secrets/broker_url_worker grafana_admin_password: file: ./secrets/grafana_admin_password # Lab 7 PKI (scripts/init_pki.py). Each service mounts only its own certificate/key and the CA it @@ -886,6 +920,23 @@ secrets: file: ./secrets/pki/grafana-ui.crt pki_grafana_ui_key: file: ./secrets/pki/grafana-ui.key + pki_openbao_crt: + file: ./secrets/pki/openbao.crt + pki_openbao_key: + file: ./secrets/pki/openbao.key + # AppRole credentials, written by scripts/bao_operator.py bootstrap (the first secret of a service). + bao_api_role_id: + file: ./secrets/bao/api_role_id + bao_api_secret_id: + file: ./secrets/bao/api_secret_id + bao_relay_role_id: + file: ./secrets/bao/relay_role_id + bao_relay_secret_id: + file: ./secrets/bao/relay_secret_id + bao_worker_role_id: + file: ./secrets/bao/worker_role_id + bao_worker_secret_id: + file: ./secrets/bao/worker_secret_id pki_foreign_lb_crt: # test only: foreign CA, SAN lb file: ./secrets/pki/foreign-lb.crt pki_foreign_lb_key: diff --git a/infra/openbao/config.hcl b/infra/openbao/config.hcl new file mode 100644 index 0000000..92ae1fc --- /dev/null +++ b/infra/openbao/config.hcl @@ -0,0 +1,39 @@ +# OpenBao 2.7 server of the lab 7 stand (compose service `openbao`). NOT dev mode: +# * persistent storage: integrated storage (Raft, ONE node - OpenBao 2.7 has no "file" backend +# any more) on the named volume baodata (/openbao/file). Everything in it is encrypted by the +# barrier key; it starts SEALED after every start and is unsealed by the operator +# (scripts/bao_operator.py unseal). Single node = no replication: losing the volume loses the +# secrets (they can be re-created from ./secrets by `bootstrap` on a fresh instance). +# * TLS listener only (internal CA, SAN openbao + localhost/127.0.0.1 for the operator CLI inside +# the container), TLS 1.2+; no plaintext listener, no UI, port not published on the host. The +# Raft cluster port 8201 uses OpenBao's own automatic TLS and has no peers here. +# * disable_mlock: the container runs without IPC_LOCK (no extra capabilities). The trade-off - +# memory pages could be swapped - is accepted on this single-host lab stand: the container has +# memswap_limit = memory limit (no swap). See docs/OPERATOR.md. +ui = false +disable_mlock = true +api_addr = "https://openbao:8200" +cluster_addr = "https://openbao:8201" +log_level = "warn" + +storage "raft" { + path = "/openbao/file" + node_id = "openbao-1" +} + +# Audit log of every request and response (secret values HMAC'ed, never in clear) to the container +# stdout: `docker compose logs openbao` shows who read what and every denied request. +audit "file" "stdout" { + description = "lab 7 audit log" + options { + file_path = "stdout" + } +} + +listener "tcp" { + address = "0.0.0.0:8200" + cluster_address = "0.0.0.0:8201" + tls_cert_file = "/run/secrets/openbao.crt" + tls_key_file = "/run/secrets/openbao.key" + tls_min_version = "tls12" +} diff --git a/infra/openbao/policies/api.hcl b/infra/openbao/policies/api.hcl new file mode 100644 index 0000000..eff45de --- /dev/null +++ b/infra/openbao/policies/api.hcl @@ -0,0 +1,16 @@ +# Policy of the AppRole `api` (API replicas). Exactly one secret path, read only: +# messenger/data/api = database_url (role messenger_api), cache_url (Valkey ACL user api), +# s3_access_key_id / s3_secret_access_key (identity messenger-api: Write staging + Read final). +# No metadata/list/write, no other service's path, no sys/*, no policy management. The token is +# created with token_no_default_policy=true, so self-management is granted explicitly below. +path "messenger/data/api" { + capabilities = ["read"] +} + +path "auth/token/lookup-self" { + capabilities = ["read"] +} + +path "auth/token/revoke-self" { + capabilities = ["update"] +} diff --git a/infra/openbao/policies/relay.hcl b/infra/openbao/policies/relay.hcl new file mode 100644 index 0000000..8779cc1 --- /dev/null +++ b/infra/openbao/policies/relay.hcl @@ -0,0 +1,13 @@ +# Policy of the AppRole `relay`: messenger/data/relay = database_url (role messenger_relay) and +# broker_url (RabbitMQ user relay: publish to the jobs exchange only). Read only, nothing else. +path "messenger/data/relay" { + capabilities = ["read"] +} + +path "auth/token/lookup-self" { + capabilities = ["read"] +} + +path "auth/token/revoke-self" { + capabilities = ["update"] +} diff --git a/infra/openbao/policies/worker.hcl b/infra/openbao/policies/worker.hcl new file mode 100644 index 0000000..c959bb0 --- /dev/null +++ b/infra/openbao/policies/worker.hcl @@ -0,0 +1,14 @@ +# Policy of the AppRole `worker`: messenger/data/worker = database_url (role messenger_worker), +# broker_url (RabbitMQ user worker: consume the jobs queue only), s3 key pair messenger-worker +# (staging + final, no List, no Admin). No admin credentials of the API, the database or S3. +path "messenger/data/worker" { + capabilities = ["read"] +} + +path "auth/token/lookup-self" { + capabilities = ["read"] +} + +path "auth/token/revoke-self" { + capabilities = ["update"] +} diff --git a/scripts/bao_check.cmd b/scripts/bao_check.cmd new file mode 100644 index 0000000..3221aa4 --- /dev/null +++ b/scripts/bao_check.cmd @@ -0,0 +1,4 @@ +@echo off +rem Windows wrapper: runs scripts\bao_check.sh (OpenBao allow/deny, no root credential in apps) with Git Bash. +"%ProgramFiles%\Git\bin\bash.exe" "%~dp0bao_check.sh" +exit /b %ERRORLEVEL% diff --git a/scripts/bao_check.py b/scripts/bao_check.py new file mode 100644 index 0000000..62ce3d6 --- /dev/null +++ b/scripts/bao_check.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""OpenBao allow/deny check, run INSIDE a service container with that service's own credentials: + + docker compose exec -T api python - < scripts/bao_check.py (wrapper: scripts/bao_check.sh) + +Uses exactly what the service has: BAO_ADDR, BAO_CACERT (server verified), BAO_ROLE_ID_FILE, +BAO_SECRET_ID_FILE, BAO_SECRET_PATH. Prints status codes and key NAMES only, never values or tokens. +Expected for service S (api | relay | worker): + allow AppRole login; read messenger/data/S; token lookup-self; revoke-self + deny read messenger/data/; write/patch messenger/data/S; list metadata; + write a policy; read the policy list; create a token; enable an auth method; read sys/mounts + deny the revoked token afterwards; a login with a wrong secret_id +""" +import json +import os +import ssl +import sys +import urllib.error +import urllib.request + +ADDR = os.environ["BAO_ADDR"].rstrip("/") +CTX = ssl.create_default_context(cafile=os.environ["BAO_CACERT"]) +PATH = os.environ["BAO_SECRET_PATH"] +SERVICE = PATH.rsplit("/", 1)[-1] +OTHERS = [s for s in ("api", "relay", "worker") if s != SERVICE] + + +def call(method, path, token=None, body=None): + data = json.dumps(body).encode() if body is not None else (b"{}" if method in ("POST", "PUT") else None) + req = urllib.request.Request(f"{ADDR}/v1/{path}", data=data, method=method, + headers={"Content-Type": "application/json", **({"X-Vault-Token": token} if token else {})}) + try: + with urllib.request.urlopen(req, timeout=5, context=CTX) as r: + raw = r.read() + return r.status, (json.loads(raw) if raw else {}) + except urllib.error.HTTPError as exc: + return exc.code, {} + + +def read(name): + with open(os.environ[name], encoding="utf-8") as f: + return f.read().strip() + + +failures = 0 + + +def expect(label, status, allowed): + global failures + ok = (200 <= status < 300) if allowed else status in (400, 403) + failures += not ok + print(f" {'PASS' if ok else 'FAIL'} {'allow' if allowed else 'deny '} {label:58s} -> HTTP {status}") + + +print(f"service {SERVICE}: OpenBao {ADDR} (TLS verified against {os.environ['BAO_CACERT']})") +status, body = call("POST", "auth/approle/login", body={"role_id": read("BAO_ROLE_ID_FILE"), "secret_id": read("BAO_SECRET_ID_FILE")}) +expect("AppRole login with the service's role_id/secret_id", status, True) +auth = body.get("auth") or {} +token = auth.get("client_token", "") +print(f" token policies={auth.get('token_policies')} ttl={auth.get('lease_duration')}s renewable={auth.get('renewable')}") +status, body = call("GET", PATH, token) +expect(f"read own path {PATH}", status, True) +print(f" keys: {sorted((body.get('data') or {}).get('data') or {})}") +status, _ = call("GET", "auth/token/lookup-self", token) +expect("token lookup-self", status, True) +for other in OTHERS: + expect(f"read other service's path messenger/data/{other}", call("GET", f"messenger/data/{other}", token)[0], False) +expect(f"write own path {PATH}", call("POST", PATH, token, {"data": {"x": "y"}})[0], False) +expect("list messenger/metadata", call("LIST", "messenger/metadata", token)[0], False) +expect(f"write policy sys/policies/acl/{SERVICE}", call("PUT", f"sys/policies/acl/{SERVICE}", token, {"policy": 'path "*" {capabilities=["sudo"]}'})[0], False) +expect("read policy list sys/policies/acl", call("LIST", "sys/policies/acl", token)[0], False) +expect("create a child token auth/token/create", call("POST", "auth/token/create", token, {"policies": ["api"]})[0], False) +expect("enable an auth method sys/auth/userpass", call("POST", "sys/auth/userpass", token, {"type": "userpass"})[0], False) +expect("read sys/mounts", call("GET", "sys/mounts", token)[0], False) +expect("revoke-self", call("POST", "auth/token/revoke-self", token)[0], True) +expect("use the token after revoke-self (lookup-self)", call("GET", "auth/token/lookup-self", token)[0], False) +expect("read own path with the revoked token", call("GET", PATH, token)[0], False) +expect("AppRole login with a wrong secret_id", call("POST", "auth/approle/login", body={"role_id": read("BAO_ROLE_ID_FILE"), "secret_id": "00000000-0000-0000-0000-000000000000"})[0], False) +print(f"{'PASS' if failures == 0 else 'FAIL'}: OpenBao policy of {SERVICE}, {failures} failure(s)") +sys.exit(1 if failures else 0) diff --git a/scripts/bao_check.sh b/scripts/bao_check.sh new file mode 100644 index 0000000..6b2fdd4 --- /dev/null +++ b/scripts/bao_check.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# OpenBao proof (README defense step 4): policy allow/deny for every service + no root credential +# in the application containers. Prints PASS/FAIL lines, never a token, share or secret value. +# sh scripts/bao_check.sh (Windows: scripts\bao_check.cmd) +set -u +cd "$(dirname "$0")/.." +export MSYS_NO_PATHCONV=1 # Git Bash: keep /run/secrets as a container path +OPERATOR_DIR="${OPERATOR_DIR:-$HOME/.mtusi-lab7-operator/${COMPOSE_PROJECT_NAME:-mtusi-lab7}}" +rc=0 +for svc in api relay worker; do + echo "== $svc" + docker compose exec -T "$svc" python - < scripts/bao_check.py || rc=1 +done +echo +echo "== root credential / unseal material in the application containers (values compared, never printed)" +for svc in api relay worker; do + # 1. no token-like variable in the container configuration + names="$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$(docker compose ps -q "$svc" | head -1)" \ + | cut -d= -f1 | grep -iE 'TOKEN|UNSEAL|ROOT' || true)" + if [ -n "$names" ]; then echo " FAIL $svc: token-like env names: $names"; rc=1; else echo " PASS $svc: no *TOKEN*/*UNSEAL*/*ROOT* environment variable"; fi + # 2. the operator's root token and unseal shares do not occur anywhere in the container's + # secrets, code, temp files or process environment (fed via stdin, compared inside) + # Positive control: the same search MUST find a value that is there (the service's own role_id), + # otherwise "absent" below would prove nothing. + found="$(docker compose exec -T "$svc" sh -c 'read -r v; grep -rlsF -- "$v" /run/secrets | head -1' < "secrets/bao/${svc}_role_id")" + if [ -n "$found" ]; then echo " PASS control: own role_id found by the same search ($found)"; else echo " FAIL control search found nothing"; rc=1; fi + for f in root-token unseal-share-1 unseal-share-2 unseal-share-3; do + if [ ! -f "$OPERATOR_DIR/$f" ]; then echo " FAIL operator file $f missing in $OPERATOR_DIR"; rc=1; continue; fi + found="$(docker compose exec -T "$svc" sh -c 'read -r v; for p in /run/secrets /app /tmp /proc/1/environ; do grep -rqsF -- "$v" "$p" && echo "$p"; done; true' < "$OPERATOR_DIR/$f")" + if [ -n "$found" ]; then echo " FAIL $svc: $f found in $found"; rc=1; else echo " PASS $svc: $f absent (/run/secrets, /app, /tmp, PID 1 environment)"; fi + done + echo " $svc /run/secrets: $(docker compose exec -T "$svc" ls /run/secrets | tr '\n' ' ')" +done +[ "$rc" = 0 ] && echo "PASS: OpenBao allow/deny and no root credential in the application" || echo "FAIL" +exit "$rc" diff --git a/scripts/bao_operator.py b/scripts/bao_operator.py new file mode 100644 index 0000000..307e739 --- /dev/null +++ b/scripts/bao_operator.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""OpenBao operator actions of the lab 7 stand (docs/OPERATOR.md). Stdlib only; run on the host. + + python scripts/bao_operator.py bootstrap # init (once) + unseal + configure + issue AppRole creds + python scripts/bao_operator.py unseal # after every OpenBao (re)start: it starts SEALED + python scripts/bao_operator.py status # initialized / sealed / mounts / roles (no secrets) + python scripts/bao_operator.py new-secret-id api # issue a new SecretID for one service + +Who holds what: + * unseal shares (3, threshold 2) and the root token: the OPERATOR, in OPERATOR_DIR, outside the + repository (default ~/.mtusi-lab7-operator//, files 0600). Never in Git, never + in a container of the application, never printed. In a real team the 3 shares go to 3 people. + * role_id + secret_id of api / relay / worker: ./secrets/bao/ (git-ignored), each pair mounted as + a Docker secret ONLY into its own service - the "first secret" the service logs in with. + * the root token is used only by this script, for configuration. + +Every secret travels to the OpenBao CLI over the STDIN of `docker compose exec` (never as a command +line argument or an environment variable of a process): the root token is the first stdin line, +read by `read -r BAO_TOKEN`; KV values and policies follow as JSON/HCL on stdin (`-`). +The CLI runs inside the openbao container against https://127.0.0.1:8200 with the internal CA +(BAO_ADDR/BAO_CACERT in compose.yaml): the server certificate is verified. + +Idempotent: init only if not initialized; mounts/auth/policies/roles/KV are (re)written to the +state described here; an existing secret_id file is kept unless `new-secret-id` is asked. +""" +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SECRETS = ROOT / "secrets" +POLICIES = ROOT / "infra" / "openbao" / "policies" +PROJECT = os.environ.get("COMPOSE_PROJECT_NAME", "mtusi-lab7") +OPERATOR_DIR = Path(os.environ.get("OPERATOR_DIR") or Path.home() / ".mtusi-lab7-operator" / PROJECT) +SHARES, THRESHOLD = 3, 2 +# Token of a service: 1 h, at most 4 h with renewals; the services revoke it right after reading. +# SecretID: valid 30 days, unlimited logins (every restart of a replica logs in again). +ROLE_SETTINGS = ["token_ttl=1h", "token_max_ttl=4h", "token_type=service", "token_no_default_policy=true", + "secret_id_ttl=720h", "secret_id_num_uses=0"] +# What each service may read: KV v2 messenger/data/. Values come from ./secrets. +SERVICE_SECRETS = { + "api": {"database_url": "database_url_api", "cache_url": "cache_url", + "s3_access_key_id": "s3_api_access_key_id", "s3_secret_access_key": "s3_api_secret_access_key"}, + "relay": {"database_url": "database_url_relay", "broker_url": "broker_url_relay"}, + "worker": {"database_url": "database_url_worker", "broker_url": "broker_url_worker", + "s3_access_key_id": "s3_worker_access_key_id", "s3_secret_access_key": "s3_worker_secret_access_key"}, +} + + +def say(text: str) -> None: + print(f"bao-operator: {text}", flush=True) + + +def bao(*args: str, token: str | None = None, stdin: bytes = b"", check: bool = True) -> subprocess.CompletedProcess: + """Run `bao ` inside the openbao container; the token (if any) is the first stdin line.""" + script = 'read -r BAO_TOKEN; export BAO_TOKEN; exec bao "$@"' if token else 'exec bao "$@"' + data = ((token + "\n").encode() if token else b"") + stdin + result = subprocess.run(["docker", "compose", "exec", "-T", "openbao", "sh", "-c", script, "sh", *args], + input=data, capture_output=True, cwd=ROOT) + if check and result.returncode != 0: + # stderr of the CLI names the failing path/permission; it never contains our stdin data. + raise SystemExit(f"bao-operator: `bao {' '.join(args)}` failed: {result.stderr.decode(errors='replace').strip()[:400]}") + return result + + +def status() -> dict: + result = bao("status", "-format=json", check=False) # exit 2 = sealed, still prints JSON + if result.returncode not in (0, 2): + raise SystemExit("bao-operator: OpenBao is not reachable (is `docker compose up -d openbao` running?): " + + result.stderr.decode(errors="replace").strip()[:300]) + return json.loads(result.stdout) + + +def private_write(path: Path, value: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(value + "\n", encoding="utf-8", newline="\n") + os.chmod(path, 0o600) + + +def operator_file(name: str) -> str: + path = OPERATOR_DIR / name + if not path.exists(): + raise SystemExit(f"bao-operator: {path} is missing: the operator material of this OpenBao is not here") + return path.read_text(encoding="utf-8").strip() + + +def init() -> None: + if status()["initialized"]: + say("already initialized") + return + if (OPERATOR_DIR / "root-token").exists(): + raise SystemExit(f"bao-operator: OpenBao is NOT initialized but {OPERATOR_DIR} has material of an older " + "instance; move it away first (it does not belong to this storage)") + out = json.loads(bao("operator", "init", f"-key-shares={SHARES}", f"-key-threshold={THRESHOLD}", "-format=json").stdout) + for i, share in enumerate(out["unseal_keys_b64"], 1): + private_write(OPERATOR_DIR / f"unseal-share-{i}", share) + private_write(OPERATOR_DIR / "root-token", out["root_token"]) + os.chmod(OPERATOR_DIR, 0o700) + say(f"initialized: {SHARES} unseal shares (threshold {THRESHOLD}) and the root token saved to {OPERATOR_DIR} " + "(outside the repository; not printed)") + + +def unseal() -> None: + state = status() + if not state["initialized"]: + raise SystemExit("bao-operator: not initialized yet: run `bootstrap`") + if not state["sealed"]: + say("already unsealed") + return + for i in range(1, THRESHOLD + 1): + bao("write", "-format=json", "sys/unseal", "key=-", stdin=operator_file(f"unseal-share-{i}").encode()) + state = status() + if state["sealed"]: + raise SystemExit("bao-operator: still sealed after the threshold of shares") + say(f"unsealed with {THRESHOLD} of {SHARES} shares") + + +def secret(name: str) -> str: + return (SECRETS / name).read_text(encoding="utf-8").strip() + + +def configure() -> None: + token = operator_file("root-token") + mounts = json.loads(bao("secrets", "list", "-format=json", token=token).stdout) + if "messenger/" not in mounts: + bao("secrets", "enable", "-path=messenger", "-version=2", "kv", token=token) + say("KV v2 mounted at messenger/") + auths = json.loads(bao("auth", "list", "-format=json", token=token).stdout) + if "approle/" not in auths: + bao("auth", "enable", "approle", token=token) + say("auth method approle enabled") + # The audit device (file -> container stdout) is declared in infra/openbao/config.hcl: + # OpenBao 2.7 refuses to enable audit devices over the API. + for service, values in SERVICE_SECRETS.items(): + bao("policy", "write", service, "-", token=token, stdin=(POLICIES / f"{service}.hcl").read_bytes()) + bao("write", f"auth/approle/role/{service}", f"token_policies={service}", *ROLE_SETTINGS, token=token) + data = {key: secret(source) for key, source in values.items()} + bao("kv", "put", "-mount=messenger", service, "-", token=token, stdin=json.dumps(data).encode()) + role_id = json.loads(bao("read", "-format=json", f"auth/approle/role/{service}/role-id", token=token).stdout)["data"]["role_id"] + private_write(SECRETS / "bao" / f"{service}_role_id", role_id) + os.chmod(SECRETS / "bao" / f"{service}_role_id", 0o644) # readable by the container user (bind mount) + if not (SECRETS / "bao" / f"{service}_secret_id").exists(): + issue_secret_id(service, token) + say(f"{service}: policy {service} (read messenger/data/{service}), AppRole, KV keys {sorted(data)}") + + +def issue_secret_id(service: str, token: str | None = None) -> None: + token = token or operator_file("root-token") + out = json.loads(bao("write", "-f", "-format=json", f"auth/approle/role/{service}/secret-id", token=token).stdout) + path = SECRETS / "bao" / f"{service}_secret_id" + private_write(path, out["data"]["secret_id"]) + os.chmod(path, 0o644) # the service reads it through the bind mount (folder ./secrets is 0700) + say(f"{service}: new SecretID written to secrets/bao/{service}_secret_id (TTL 720h; not printed)") + + +def main(argv: list[str]) -> int: + command = argv[0] if argv else "status" + if command == "bootstrap": + init() + unseal() + configure() + say("done; start the stand: docker compose up -d --build --wait") + elif command == "unseal": + unseal() + elif command == "status": + state = status() + say(f"initialized={state['initialized']} sealed={state['sealed']} storage={state.get('storage_type')} " + f"version={state.get('version')} operator_dir={OPERATOR_DIR}") + elif command == "new-secret-id" and len(argv) == 2 and argv[1] in SERVICE_SECRETS: + issue_secret_id(argv[1]) + say(f"restart the service to use it: docker compose up -d --force-recreate {argv[1]}") + else: + print(__doc__) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/restart.sh b/scripts/restart.sh index a16c322..16b53c9 100644 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -1,21 +1,26 @@ #!/bin/sh # Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`. # Restarts EVERY process of the stand: LB, all API replicas, relay, worker(s), PostgreSQL, Valkey, -# S3 (SeaweedFS) and the broker (RabbitMQ). Volumes, schema, data and queued messages are -# preserved: no `down -v`, no FLUSH, no purge, no re-seed. -# Output is suppressed by the test; run it by hand to see the steps. +# S3 (SeaweedFS), the broker (RabbitMQ) and OpenBao. Volumes, schema, data, queued messages and the +# OpenBao storage are preserved: no `down -v`, no FLUSH, no purge, no re-seed. +# Lab 7: OpenBao comes back SEALED; the operator unseal step (scripts/bao_operator.py unseal, shares +# from the operator directory outside the repository) runs before the services that need secrets. +# Output is suppressed by the test; run it by hand to see the steps (no secret is printed). set -eu cd "$(dirname "$0")/.." +PY="${PYTHON:-python}" # 1. Entry point, API and the pipeline processes first: nothing is served or processed while the # stores restart underneath. docker compose stop lb api relay worker # 2. Stores: clean shutdown (PostgreSQL checkpoint, Valkey AOF fsync, SeaweedFS volume/filer -# flush, RabbitMQ quorum log), then start again. Bytes live on s3data, messages on rabbitmqdata. -docker compose restart postgres valkey s3 broker -# 3. API replicas (wait for healthy stores via depends_on), the LB, then relay and worker. HAProxy -# resolves the new replica addresses through Docker DNS by itself - no stale backend list. +# flush, RabbitMQ quorum log, OpenBao raft), then start again. +docker compose restart postgres valkey s3 broker openbao +# 3. Operator: unseal (OpenBao is sealed after every start). +"$PY" scripts/bao_operator.py unseal +# 4. API replicas (log in to OpenBao again, read their secrets), the LB, then relay and worker. +# HAProxy resolves the new replica addresses through Docker DNS by itself. docker compose start api docker compose start lb docker compose start relay worker -echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3 and broker restarted with volumes preserved" +echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3, broker and openbao restarted with volumes preserved; openbao unsealed" diff --git a/src/messenger/__main__.py b/src/messenger/__main__.py index 7760d07..84220c5 100644 --- a/src/messenger/__main__.py +++ b/src/messenger/__main__.py @@ -56,6 +56,7 @@ class GracefulServer(uvicorn.Server): def main() -> int: + logging_setup.configure_early() try: settings = Settings.from_env() except ConfigError as exc: diff --git a/src/messenger/bao.py b/src/messenger/bao.py new file mode 100644 index 0000000..75486d9 --- /dev/null +++ b/src/messenger/bao.py @@ -0,0 +1,116 @@ +"""Lab 7: secrets of a service from OpenBao (AppRole login -> read own KV path -> revoke token). + +Used by config._secret(): when BAO_ADDR is set, DATABASE_URL / CACHE_URL / S3_* / BROKER_URL come from +`BAO_SECRET_PATH` (e.g. messenger/data/api) instead of files. Startup sequence (once per process): + +1. read role_id + secret_id from BAO_ROLE_ID_FILE / BAO_SECRET_ID_FILE (Docker secrets of THIS + service only; the "first secret" delivered by the operator, scripts/bao_operator.py); +2. POST auth/approle/login over HTTPS (server verified: BAO_CACERT = internal CA, hostname openbao) + -> a service token with ONE policy (read its own path), TTL 1 h; +3. GET the KV path -> the values stay in process memory only (never logged, never written); +4. POST auth/token/revoke-self: the token is dead seconds after it was created. + +Failure modes (README "что происходит при ..."): +* OpenBao sealed/stopped at start: retried for BAO_STARTUP_TIMEOUT_SECONDS, then the process exits + (configuration error) and Docker restarts it; replicas that are already running are not + affected - they do not need OpenBao after startup. +* Token expiry: irrelevant after startup (revoked anyway); every new process logs in again. +* Wrong/expired secret_id or a policy denial: fail at once with the HTTP status, no retry. +No root token, no unseal key and no long-lived token ever exist in an application container. +""" +from __future__ import annotations + +import json +import logging +import os +import ssl +import time +import urllib.error +import urllib.request +from pathlib import Path + +log = logging.getLogger("messenger.bao") + +_cache: dict[str, str] | None = None + + +class BaoError(RuntimeError): + pass + + +def enabled() -> bool: + return bool(os.environ.get("BAO_ADDR", "").strip()) + + +def _file(name: str) -> str: + path = os.environ.get(name, "").strip() + if not path: + raise BaoError(f"{name} must be set when BAO_ADDR is set") + try: + return Path(path).read_text(encoding="utf-8").strip() + except OSError as exc: + raise BaoError(f"{name}={path} cannot be read: {exc.strerror}") from None + + +class Client: + def __init__(self, addr: str, ca_file: str, timeout: float = 5.0): + self.addr = addr.rstrip("/") + self.timeout = timeout + self.context = ssl.create_default_context(cafile=ca_file or None) # verify chain + hostname + self.context.minimum_version = ssl.TLSVersion.TLSv1_2 + + def call(self, method: str, path: str, token: str | None = None, body: dict | None = None) -> dict: + data = json.dumps(body).encode() if body is not None else (b"" if method == "POST" else None) + request = urllib.request.Request(f"{self.addr}/v1/{path}", data=data, method=method) + request.add_header("Content-Type", "application/json") + if token: + request.add_header("X-Vault-Token", token) + with urllib.request.urlopen(request, timeout=self.timeout, context=self.context) as response: + raw = response.read() + return json.loads(raw) if raw else {} + + +def _status(exc: Exception) -> int | None: + return exc.code if isinstance(exc, urllib.error.HTTPError) else None + + +def fetch() -> dict[str, str]: + """Login, read the service's KV path, revoke the token. Values are cached for the process.""" + global _cache + if _cache is not None: + return _cache + client = Client(os.environ["BAO_ADDR"], os.environ.get("BAO_CACERT", "").strip()) + path = os.environ.get("BAO_SECRET_PATH", "").strip() + if not path: + raise BaoError("BAO_SECRET_PATH must be set when BAO_ADDR is set") + role_id, secret_id = _file("BAO_ROLE_ID_FILE"), _file("BAO_SECRET_ID_FILE") + deadline = time.monotonic() + float(os.environ.get("BAO_STARTUP_TIMEOUT_SECONDS", "60")) + while True: + try: + auth = client.call("POST", "auth/approle/login", body={"role_id": role_id, "secret_id": secret_id})["auth"] + token = auth["client_token"] + try: + data = client.call("GET", path, token=token)["data"]["data"] + finally: + try: + client.call("POST", "auth/token/revoke-self", token=token) + except (urllib.error.URLError, OSError): + pass # TTL (1 h) bounds the token anyway + break + except (urllib.error.URLError, OSError, KeyError, ValueError) as exc: + status = _status(exc) + # 503 = sealed / standby, no status = unreachable: wait for the operator. 4xx = our + # credentials or the policy are wrong: retrying would not help. + if status is not None and status != 503: + raise BaoError(f"OpenBao refused {path!r} for this service: HTTP {status}") from None + if time.monotonic() > deadline: + raise BaoError(f"OpenBao unavailable (sealed or unreachable): {type(exc).__name__}") from None + log.warning("openbao_unavailable", extra={"fields": {"status": status, "error": type(exc).__name__}}) + time.sleep(2) + if not isinstance(data, dict): + raise BaoError(f"OpenBao path {path!r} has no KV data") + log.info("secrets_loaded", extra={"fields": { + "path": path, "keys": sorted(data), "policies": auth.get("token_policies"), + "token_ttl_s": auth.get("lease_duration"), "token_revoked": True}}) + _cache = {str(k): str(v) for k, v in data.items()} + return _cache diff --git a/src/messenger/config.py b/src/messenger/config.py index 3516f20..6fd0b75 100644 --- a/src/messenger/config.py +++ b/src/messenger/config.py @@ -77,7 +77,18 @@ def _choice(name: str, default: str, allowed: set[str]) -> str: def _secret(name: str, required: bool) -> str: - """Value of _FILE (preferred, Docker secret) or (local runs/tests).""" + """Value of a secret setting, in this order: + 1. OpenBao (lab 7, BAO_ADDR set): key name.lower() of the service's KV path (bao.py); + 2. _FILE (Docker secret file: bootstrap jobs and operator tools); + 3. (local runs/tests).""" + from . import bao + if bao.enabled(): + try: + values = bao.fetch() + except bao.BaoError as exc: + raise ConfigError(str(exc)) from None + if name.lower() in values: + return values[name.lower()] path = os.environ.get(f"{name}_FILE", "").strip() if path: try: diff --git a/src/messenger/logging_setup.py b/src/messenger/logging_setup.py index b06640c..df465ac 100644 --- a/src/messenger/logging_setup.py +++ b/src/messenger/logging_setup.py @@ -7,6 +7,7 @@ from __future__ import annotations import datetime as dt import json import logging +import os import sys from . import telemetry @@ -42,3 +43,10 @@ def configure(level: str) -> None: for name in ("uvicorn", "uvicorn.error"): logging.getLogger(name).handlers[:] = [] logging.getLogger(name).propagate = True + + +def configure_early() -> None: + """Before Settings exist (lab 7: secrets are fetched from OpenBao while the settings load, and + those log lines must not be lost). Settings.from_env() validates LOG_LEVEL properly later.""" + raw = os.environ.get("LOG_LEVEL", "info").strip().lower() + configure(raw if raw in {"debug", "info", "warning", "error"} else "info") diff --git a/src/messenger/relay.py b/src/messenger/relay.py index 59ef6e5..ec45a0f 100644 --- a/src/messenger/relay.py +++ b/src/messenger/relay.py @@ -214,6 +214,7 @@ class Relay: def main() -> int: + logging_setup.configure_early() try: settings = Settings.from_env(s3_credentials=False) if not settings.broker_url: diff --git a/src/messenger/worker.py b/src/messenger/worker.py index fca419a..42f4989 100644 --- a/src/messenger/worker.py +++ b/src/messenger/worker.py @@ -379,6 +379,7 @@ class Worker: def main() -> int: + logging_setup.configure_early() try: settings = Settings.from_env() if not settings.broker_url: -- 2.54.0 From 05df1695febfb45edbebb0a7a1365b10bcd0a4a2 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:57:24 +0300 Subject: [PATCH 06/16] =?UTF-8?q?lab7:=20Argon2id=20=D0=B8=D0=B7=20env=20(?= =?UTF-8?q?=D0=B7=D0=B0=D0=BC=D0=B5=D1=80=20bench/argon2=5Fbench.py),=20?= =?UTF-8?q?=D0=BB=D0=B8=D0=BC=D0=B8=D1=82=20=D0=BD=D0=B5=D1=83=D0=B4=D0=B0?= =?UTF-8?q?=D1=87=D0=BD=D1=8B=D1=85=20=D0=B2=D1=85=D0=BE=D0=B4=D0=BE=D0=B2?= =?UTF-8?q?=20=D0=B2=20Valkey=20(429=20+=20Retry-After),=20cap=5Fdrop=20AL?= =?UTF-8?q?L=20=D0=B8=20no-new-privileges,=20X-Instance-Id=20=3D=20=D1=81?= =?UTF-8?q?=D0=BB=D1=83=D1=87=D0=B0=D0=B9=D0=BD=D1=8B=D0=B9=20alias?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bench/argon2_bench.py | 96 +++++++++++++++++++++++ compose.yaml | 78 +++++++++++++++++++ infra/haproxy/haproxy.cfg | 4 + infra/valkey/start.sh | 4 +- scripts/lbctl.py | 12 ++- scripts/stop-one.sh | 13 ++-- src/messenger/__main__.py | 3 +- src/messenger/app.py | 32 +++++++- src/messenger/config.py | 55 ++++++++++--- src/messenger/passwords.py | 36 ++++++--- src/messenger/ratelimit.py | 116 ++++++++++++++++++++++++++++ src/messenger/relay.py | 3 +- src/messenger/worker.py | 3 +- student-tests/test_balancing.py | 16 ++-- student-tests/test_idempotency.py | 2 +- student-tests/test_pipeline_flow.py | 8 +- 16 files changed, 431 insertions(+), 50 deletions(-) create mode 100644 bench/argon2_bench.py create mode 100644 src/messenger/ratelimit.py diff --git a/bench/argon2_bench.py b/bench/argon2_bench.py new file mode 100644 index 0000000..804a7dd --- /dev/null +++ b/bench/argon2_bench.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Argon2id parameter measurement ON THIS STAND (README grade 3: "параметры обоснованы измерением"). + +Runs INSIDE an API replica, i.e. with exactly the CPU/RAM limits of production (compose: 1 CPU, +512 MiB) and the same argon2-cffi build: + + docker compose exec -T api python - < bench/argon2_bench.py > evidence/argon2/bench.json + +For every (m, t) of the grid (p = 1): N sequential hashes -> median / p95 latency and CPU time per +hash; then, for the candidate parameters, K threads hashing at once (K = 1, 2, 4) -> latency +under contention and hashes/s of the replica = the most logins/s one replica can verify +(the cost of a password guessing / login DoS attempt). Prints one JSON document (no passwords: +a fixed synthetic one is hashed). +""" +import json +import os +import platform +import statistics +import threading +import time + +import importlib.metadata +from argon2 import PasswordHasher, Type + +PASSWORD = "synthetic-benchmark-password" +GRID_M = [19456, 32768, 47104, 65536] # KiB: 19 MiB (OWASP minimum), 32, 46, 64 MiB +GRID_T = [2, 3, 4] +N = int(os.environ.get("BENCH_N", "15")) +THREADS = [1, 2, 4] +PER_THREAD = int(os.environ.get("BENCH_PER_THREAD", "6")) + + +def cgroup_limits() -> dict: + out = {} + for name, path in (("cpu_max", "/sys/fs/cgroup/cpu.max"), ("memory_max", "/sys/fs/cgroup/memory.max")): + try: + with open(path) as f: + out[name] = f.read().strip() + except OSError: + out[name] = None + return out + + +def sequential(m: int, t: int) -> dict: + ph = PasswordHasher(time_cost=t, memory_cost=m, parallelism=1, hash_len=32, salt_len=16, type=Type.ID) + ph.hash(PASSWORD) # warm-up (allocator, first-touch of the pages) + wall, cpu = [], [] + for _ in range(N): + w0, c0 = time.perf_counter(), time.thread_time() + ph.hash(PASSWORD) + wall.append((time.perf_counter() - w0) * 1000) + cpu.append((time.thread_time() - c0) * 1000) + wall.sort() + return {"m_kib": m, "t": t, "p": 1, "n": N, "median_ms": round(statistics.median(wall), 1), + "p95_ms": round(wall[min(len(wall) - 1, int(0.95 * len(wall)))], 1), + "cpu_ms_per_hash": round(statistics.median(cpu), 1), + "hash_example_prefix": ph.hash(PASSWORD).split("$")[1:4]} + + +def concurrent(m: int, t: int, threads: int) -> dict: + ph = PasswordHasher(time_cost=t, memory_cost=m, parallelism=1, hash_len=32, salt_len=16, type=Type.ID) + lat: list[float] = [] + lock = threading.Lock() + + def work(): + for _ in range(PER_THREAD): + w0 = time.perf_counter() + ph.hash(PASSWORD) + with lock: + lat.append((time.perf_counter() - w0) * 1000) + + c0, w0 = time.process_time(), time.perf_counter() + pool = [threading.Thread(target=work) for _ in range(threads)] + for th in pool: + th.start() + for th in pool: + th.join() + wall = time.perf_counter() - w0 + lat.sort() + return {"m_kib": m, "t": t, "threads": threads, "hashes": len(lat), "wall_s": round(wall, 2), + "hashes_per_s": round(len(lat) / wall, 1), "median_ms": round(statistics.median(lat), 1), + "p95_ms": round(lat[min(len(lat) - 1, int(0.95 * len(lat)))], 1), + "cpu_utilisation": round((time.process_time() - c0) / wall, 2), + "ram_mib_hashing": round(m * threads / 1024, 1)} + + +def main() -> None: + report = {"when": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "python": platform.python_version(), + "argon2_cffi": importlib.metadata.version("argon2-cffi"), "cpus_visible": os.cpu_count(), "cgroup": cgroup_limits(), + "sequential": [sequential(m, t) for m in GRID_M for t in GRID_T]} + report["concurrent"] = [concurrent(m, t, k) for (m, t) in ((19456, 2), (47104, 2), (19456, 3)) for k in THREADS] + print(json.dumps(report, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/compose.yaml b/compose.yaml index ac09912..f23a7b1 100644 --- a/compose.yaml +++ b/compose.yaml @@ -33,6 +33,9 @@ name: ${COMPOSE_PROJECT_NAME:-mtusi-lab7} # database_url, cache_url, broker_url and the S3 key pair are NOT mounted as files into api, relay, # worker any more (src/messenger/bao.py). x-bao-env: &bao-env + # Not a secret: the random X-Instance-Id alias of the process (config.py), for the operator's + # alias -> container mapping (scripts/stop-one.sh). + INSTANCE_ID_FILE: /tmp/instance_id BAO_ADDR: https://openbao:8200 BAO_CACERT: /run/secrets/internal-ca.crt BAO_ROLE_ID_FILE: /run/secrets/bao_role_id @@ -49,6 +52,16 @@ x-api-env: &api-env DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3} CACHE_TIMEOUT_SECONDS: ${CACHE_TIMEOUT_SECONDS:-0.5} PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-2} + # Lab 7: Argon2id parameters, chosen by a measurement on this stand (bench/argon2_bench.py, + # REPORT.md); the application refuses values below m=19456 KiB, t=2, p=1. + ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456} + ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2} + ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1} + # Lab 7: failed-login limits (src/messenger/ratelimit.py) -> 429 + Retry-After. + LOGIN_RATE_LIMIT_USER: ${LOGIN_RATE_LIMIT_USER:-5} + LOGIN_RATE_LIMIT_USER_WINDOW_SECONDS: ${LOGIN_RATE_LIMIT_USER_WINDOW_SECONDS:-60} + LOGIN_RATE_LIMIT_IP: ${LOGIN_RATE_LIMIT_IP:-50} + LOGIN_RATE_LIMIT_IP_WINDOW_SECONDS: ${LOGIN_RATE_LIMIT_IP_WINDOW_SECONDS:-300} IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} # Graceful stop: 3 s drain (readiness 503, still serving) + up to 8 s for in-flight requests. DRAIN_SECONDS: ${DRAIN_SECONDS:-3} @@ -166,6 +179,11 @@ services: start_period: 10s stop_grace_period: 30s # clean shutdown checkpoint instead of crash recovery restart: unless-stopped + # Lab 7 hardening: the image starts as root only to chown its data and drop to its own user + # (gosu/su-exec): exactly the capabilities for that, nothing else (no NET_RAW, MKNOD, ...). + cap_drop: [ALL] + cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID] + security_opt: ["no-new-privileges:true"] networks: [data] deploy: resources: @@ -192,6 +210,11 @@ services: retries: 30 start_period: 5s restart: unless-stopped + # Lab 7 hardening: the image starts as root only to chown its data and drop to its own user + # (gosu/su-exec): exactly the capabilities for that, nothing else (no NET_RAW, MKNOD, ...). + cap_drop: [ALL] + cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID] + security_opt: ["no-new-privileges:true"] networks: [data] deploy: resources: @@ -232,6 +255,11 @@ services: start_period: 10s stop_grace_period: 30s restart: unless-stopped + # Lab 7 hardening: the image starts as root only to chown its data and drop to its own user + # (gosu/su-exec): exactly the capabilities for that, nothing else (no NET_RAW, MKNOD, ...). + cap_drop: [ALL] + cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID] + security_opt: ["no-new-privileges:true"] networks: [storage] deploy: resources: @@ -262,6 +290,11 @@ services: start_period: 20s stop_grace_period: 30s restart: unless-stopped + # Lab 7 hardening: the image starts as root only to chown its data and drop to its own user + # (gosu/su-exec): exactly the capabilities for that, nothing else (no NET_RAW, MKNOD, ...). + cap_drop: [ALL] + cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID] + security_opt: ["no-new-privileges:true"] networks: [queue] deploy: resources: @@ -287,6 +320,9 @@ services: healthcheck: disable: true restart: "no" + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [data] deploy: resources: @@ -329,6 +365,9 @@ services: healthcheck: disable: true restart: "no" + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [storage] deploy: resources: @@ -381,6 +420,9 @@ services: condition: service_healthy # healthy = unsealed (see the openbao healthcheck) stop_grace_period: 15s # > DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS (11 s) restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [edge, data, storage, telemetry, vault] deploy: replicas: ${API_REPLICAS:-2} @@ -418,6 +460,9 @@ services: api: condition: service_healthy restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [edge] deploy: resources: @@ -456,6 +501,9 @@ services: condition: service_healthy stop_grace_period: 10s restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [data, queue, telemetry, vault] deploy: resources: @@ -504,6 +552,9 @@ services: condition: service_healthy stop_grace_period: 30s # > WORKER_SHUTDOWN_SECONDS (20 s) + release restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [data, storage, queue, telemetry, vault] deploy: replicas: ${WORKER_REPLICAS:-1} @@ -541,6 +592,9 @@ services: s3: condition: service_healthy restart: "no" + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [data, storage] deploy: resources: @@ -563,6 +617,9 @@ services: postgres: condition: service_healthy restart: "no" + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [data] deploy: resources: @@ -588,6 +645,9 @@ services: - {source: pki_foreign_lb_crt, target: foreign-lb.crt} - {source: pki_foreign_lb_key, target: foreign-lb.key} restart: "no" + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [edge] deploy: resources: @@ -622,6 +682,9 @@ services: start_period: 5s stop_grace_period: 15s restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [vault] deploy: resources: @@ -646,6 +709,9 @@ services: volumes: - ./infra/otel:/etc/otelcol:ro restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [telemetry] deploy: resources: @@ -681,6 +747,9 @@ services: start_period: 10s stop_grace_period: 30s restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [telemetry] deploy: resources: @@ -700,6 +769,9 @@ services: - lokidata:/loki stop_grace_period: 30s restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [telemetry] deploy: resources: @@ -719,6 +791,9 @@ services: - tempodata:/var/tempo stop_grace_period: 30s restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [telemetry] deploy: resources: @@ -778,6 +853,9 @@ services: tempo: condition: service_started restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [telemetry, ui] deploy: resources: diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg index 05a5428..ad25c42 100644 --- a/infra/haproxy/haproxy.cfg +++ b/infra/haproxy/haproxy.cfg @@ -89,6 +89,10 @@ frontend public # API echoes it, and errors generated by the LB itself carry the same value. http-request set-header X-Request-Id %[uuid()] unless { req.hdr(x-request-id) -m reg ^[A-Za-z0-9._:-]{1,128}$ } http-request set-var(txn.request_id) req.hdr(x-request-id) + # Lab 7: the client address for the API's login rate limit. OVERWRITTEN (never appended to a + # client-supplied value), so a client cannot pick its own "IP"; the API trusts it only because + # nobody but this LB (mTLS identity lb) can connect to the API. + http-request set-header X-Forwarded-For %[src] log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq rid=%[var(txn.request_id)] \"%HM %HPO\"" use_backend api if { nbsrv(api) gt 0 } default_backend api_core diff --git a/infra/valkey/start.sh b/infra/valkey/start.sh index 55b7010..8f53fd6 100644 --- a/infra/valkey/start.sh +++ b/infra/valkey/start.sh @@ -4,7 +4,7 @@ # user default off no anonymous/shared-password access at all # user api SHA-256 of its password only (the plain password never lands in a file here), # keys session:* (sessions.py) and ratelimit:* (login limit), commands it uses: -# GET/SET/DEL (sessions), INCR/PEXPIRE/PTTL in MULTI/EXEC (rate limit), PING +# GET/SET/DEL (sessions), INCR(BY)/PEXPIRE/PTTL in MULTI/EXEC (rate limit), PING # (readiness), CLIENT SETINFO (sent by redis-py on connect). FLUSHALL, CONFIG, # KEYS, DEBUG, ACL, ... are refused with NOPERM. set -eu @@ -12,7 +12,7 @@ umask 077 mkdir -p /tmp/valkey hash="$(tr -d '\r\n' < /run/secrets/valkey_api_password | sha256sum | cut -d' ' -f1)" printf 'user default off\n' > /tmp/valkey/users.acl -printf 'user api on #%s resetkeys ~session:* ~ratelimit:* resetchannels -@all +get +set +del +incr +pexpire +pttl +multi +exec +discard +ping +client|setinfo\n' \ +printf 'user api on #%s resetkeys ~session:* ~ratelimit:* resetchannels -@all +get +set +del +incr +incrby +pexpire +pttl +multi +exec +discard +ping +client|setinfo\n' \ "$hash" >> /tmp/valkey/users.acl chown -R valkey /tmp/valkey exec docker-entrypoint.sh valkey-server /etc/valkey/valkey.conf diff --git a/scripts/lbctl.py b/scripts/lbctl.py index 259d35e..9d393a3 100644 --- a/scripts/lbctl.py +++ b/scripts/lbctl.py @@ -13,6 +13,7 @@ from __future__ import annotations import argparse import json +import os import subprocess import sys import time @@ -33,6 +34,13 @@ def run(*args: str, timeout: float = 60) -> str: return result.stdout +def instance_alias(container_id: str) -> str | None: + """X-Instance-Id of the process running in the container (lab 7: random alias, not the hostname).""" + result = subprocess.run(["docker", "exec", container_id, "cat", "/tmp/instance_id"], capture_output=True, + text=True, timeout=30, env={**os.environ, "MSYS_NO_PATHCONV": "1"}) + return (result.stdout.strip() or None) if result.returncode == 0 else None + + def replicas(all_states: bool = True) -> list[dict]: """API containers of this compose project (running and stopped).""" ids = run("docker", "compose", "ps", "-q", *(["-a"] if all_states else []), "api").split() @@ -46,6 +54,8 @@ def replicas(all_states: bool = True) -> list[dict]: "id": item["Id"][:12], "name": item["Name"].lstrip("/"), "hostname": item["Config"]["Hostname"], + # Lab 7: X-Instance-Id is a random alias the process writes to /tmp/instance_id. + "instance": instance_alias(item["Id"][:12]) if item["State"]["Status"] == "running" else None, "state": item["State"]["Status"], "health": (item["State"].get("Health") or {}).get("Status", "-"), "exit_code": item["State"]["ExitCode"], @@ -75,7 +85,7 @@ def lb_servers() -> list[dict]: container = by_ip.get(addr) servers.append({"slot": name, "addr": addr, "state": state, "container": container["name"] if container else None, - "instance_id": container["hostname"] if container else None}) + "instance_id": container["instance"] if container else None}) return servers diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh index 85bc37a..2e73fe2 100644 --- a/scripts/stop-one.sh +++ b/scripts/stop-one.sh @@ -1,14 +1,17 @@ #!/bin/sh # Failover hook for `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`. -# Stops exactly ONE API replica: the container whose X-Instance-Id (= container hostname, -# see src/messenger/config.py) is in TARGET_INSTANCE_ID. DB, Valkey, LB and volumes are -# not touched. The replica is LEFT STOPPED (`docker stop` = no restart by the policy); -# restore it explicitly afterwards: scripts/restore-api.sh. +# Stops exactly ONE API replica: the container whose X-Instance-Id is TARGET_INSTANCE_ID. +# Lab 7: X-Instance-Id is a random alias (no hostname/IP, src/messenger/config.py); each replica +# writes its alias to /tmp/instance_id inside its own container, which is how the operator maps +# alias -> container. DB, Valkey, LB, OpenBao and volumes are not touched. The replica is LEFT +# STOPPED (`docker stop` = no restart by the policy); restore it explicitly afterwards: +# scripts/restore-api.sh (make restore). # STOP_MODE=stop (default) SIGTERM: readiness 503, 3 s drain, graceful exit (~4 s) # STOP_MODE=kill SIGKILL at once (`docker stop -t 0`): crash of the process # Returns within 10 s. The test hides the output; run by hand to see it (no secrets printed). set -eu cd "$(dirname "$0")/.." +export MSYS_NO_PATHCONV=1 # Git Bash: keep /tmp/instance_id a container path : "${TARGET_INSTANCE_ID:?test provides target API instance alias}" case "$TARGET_INSTANCE_ID" in *[!A-Za-z0-9._-]*) echo "stop-one: invalid TARGET_INSTANCE_ID" >&2; exit 2 ;; @@ -18,7 +21,7 @@ mode="${STOP_MODE:-stop}" target="" # Only RUNNING containers of THIS compose project's service `api` are candidates. for id in $(docker compose ps -q api); do - if [ "$(docker inspect -f '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then + if [ "$(docker exec "$id" cat /tmp/instance_id 2>/dev/null | tr -d '\r\n')" = "$TARGET_INSTANCE_ID" ]; then target="$id" fi done diff --git a/src/messenger/__main__.py b/src/messenger/__main__.py index 84220c5..a1a7b3a 100644 --- a/src/messenger/__main__.py +++ b/src/messenger/__main__.py @@ -22,7 +22,7 @@ import uvicorn from . import __version__, logging_setup, telemetry, tls from .app import create_app -from .config import ConfigError, Settings +from .config import ConfigError, Settings, publish_instance_id log = logging.getLogger("messenger") @@ -63,6 +63,7 @@ def main() -> int: print(f"configuration error: {exc}", file=sys.stderr) return 2 logging_setup.configure(settings.log_level) + publish_instance_id(settings.instance_id) telemetry.setup("messenger-api", settings.instance_id, __version__) app = create_app(settings) mtls: dict = {} diff --git a/src/messenger/app.py b/src/messenger/app.py index db9c99e..5ad080f 100644 --- a/src/messenger/app.py +++ b/src/messenger/app.py @@ -22,7 +22,7 @@ from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Sen from opentelemetry import context as otel_context from opentelemetry import trace -from . import attachments, authhdr, cursor, docs, passwords, repo, telemetry, tls, validation +from . import attachments, authhdr, cursor, docs, passwords, ratelimit, repo, telemetry, tls, validation from .config import Settings from .db import Database from .errors import BASIC_CHALLENGE, ApiError, Conflict, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable @@ -322,15 +322,36 @@ async def register_user(request: Request) -> JSONResponse: return ok(user.to_json(), 201) +def client_ip(request: Request) -> str: + """Client address for the login rate limit: X-Forwarded-For as SET (overwritten) by HAProxy. + Trusted because only the LB identity can connect to the API (mTLS allowlist, tls.py).""" + forwarded = request.headers.get("x-forwarded-for", "").strip() + if forwarded and len(forwarded) <= 64 and "," not in forwarded: + return forwarded + return request.client.host if request.client else "-" + + async def create_session(request: Request) -> JSONResponse: - """Login: only `Authorization: Basic`; wrong user and wrong password give the same 401.""" + """Login: only `Authorization: Basic`; wrong user and wrong password give the same 401. + Lab 7: failed attempts are limited per username and per client IP (ratelimit.py) -> 429 with + Retry-After, checked BEFORE the Argon2 work.""" username, password = authhdr.parse_basic(request.headers.get("authorization")) await reject_body(request) + limiter: ratelimit.LoginLimiter = request.app.state.login_limiter + ip = client_ip(request) + try: + await limiter.check(username, ip) + except ratelimit.RateLimited as exc: + log.info("login_rate_limited", extra={"fields": {"request_id": request.state.request_id, + "retry_after_s": exc.retry_after}}) + raise found = await repo.get_credentials(db_of(request), username) user, stored_hash = found if found else (None, None) if not await passwords.verify_password(stored_hash, password) or user is None: + await limiter.failed(username, ip) log.info("login_failed", extra={"fields": {"request_id": request.state.request_id}}) raise Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE) + await limiter.succeeded(username) ttl = request.app.state.settings.session_ttl_seconds token, expires_at = await sessions_of(request).create(user.id, ttl) log.info("session_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}}) @@ -623,7 +644,8 @@ def create_app(settings: Settings | None = None) -> Starlette: @contextlib.asynccontextmanager async def lifespan(app: Starlette): - passwords.configure(settings.hash_concurrency) + passwords.configure(settings.hash_concurrency, settings.argon2_memory_kib, settings.argon2_iterations, + settings.argon2_parallelism) telemetry.observe_pool(db.pool, db.name) await db.open() await storage.open() @@ -636,6 +658,9 @@ def create_app(settings: Settings | None = None) -> Starlette: "s3_staging_bucket": settings.s3_staging_bucket, "pipeline_version": settings.pipeline_version, "upload_concurrency": settings.upload_concurrency, "verify_concurrency": settings.image_verify_concurrency, "pending_grace_s": settings.pending_grace_seconds, + "argon2": passwords.parameters(), + "login_limit": {"user": f"{settings.login_user_limit}/{settings.login_user_window_seconds}s", + "ip": f"{settings.login_ip_limit}/{settings.login_ip_window_seconds}s"}, "fault_points": sorted(settings.fault_points)}}) tasks = [asyncio.create_task(purge_loop())] if settings.janitor_interval_seconds > 0: @@ -692,6 +717,7 @@ def create_app(settings: Settings | None = None) -> Starlette: app.state.settings = settings app.state.db = db app.state.sessions = sessions + app.state.login_limiter = ratelimit.LoginLimiter(settings, getattr(sessions, "client", None)) app.state.storage = storage app.state.staging = staging app.state.upload_slots = asyncio.Semaphore(settings.upload_concurrency) diff --git a/src/messenger/config.py b/src/messenger/config.py index 6fd0b75..10e471a 100644 --- a/src/messenger/config.py +++ b/src/messenger/config.py @@ -9,7 +9,7 @@ from __future__ import annotations import os import re -import socket +import secrets from dataclasses import dataclass, field from pathlib import Path @@ -21,17 +21,34 @@ class ConfigError(ValueError): INSTANCE_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}") -def _instance_id() -> str: - """X-Instance-Id of this process: INSTANCE_ID or the container hostname. +_INSTANCE_ID: str | None = None - Docker sets the hostname of a container to its short container ID, so the value - is unique per replica, stable for the life of the process and maps 1:1 to a real - container (`docker inspect`), which scripts/stop-one.sh relies on. + +def _instance_id() -> str: + """X-Instance-Id of this process (also service.instance.id, lease owner, broker connection name). + + Lab 7 (contract, balancing): a RANDOM alias drawn at process start, e.g. `i-3f9a1c2b7d10` + (48 random bits) - it reveals neither the hostname/container ID nor an IP, is unique per process + and stable for its life. INSTANCE_ID overrides it (tests). The MAIN process of a service writes it + to INSTANCE_ID_FILE (publish_instance_id), so the operator can map alias -> container. """ - value = os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname() - if INSTANCE_ID_RE.fullmatch(value) is None: - raise ConfigError("INSTANCE_ID must match [A-Za-z0-9._-]{1,64}") - return value + global _INSTANCE_ID + if _INSTANCE_ID is None: + value = os.environ.get("INSTANCE_ID", "").strip() or "i-" + secrets.token_hex(6) + if INSTANCE_ID_RE.fullmatch(value) is None: + raise ConfigError("INSTANCE_ID must match [A-Za-z0-9._-]{1,64}") + _INSTANCE_ID = value + return _INSTANCE_ID + + +def publish_instance_id(instance_id: str) -> None: + """Called by the service's main process only (api/relay/worker entry points): writes the alias to + INSTANCE_ID_FILE (compose: /tmp/instance_id inside the container) for + `docker exec cat /tmp/instance_id` (scripts/stop-one.sh, lbctl.py). A helper process + started in the same container (docker compose exec ... python) must not overwrite it.""" + target = os.environ.get("INSTANCE_ID_FILE", "").strip() + if target: + Path(target).write_text(instance_id + "\n", encoding="ascii") def _int(name: str, default: int, low: int, high: int) -> int: @@ -173,6 +190,14 @@ class Settings: tls_ca_file: str = "" tls_client_ca_file: str = "" health_port: int = 0 + # Lab 7: Argon2id parameters (passwords.py) and the login rate limit (ratelimit.py). + argon2_memory_kib: int = 19456 + argon2_iterations: int = 2 + argon2_parallelism: int = 1 + login_user_limit: int = 5 + login_user_window_seconds: int = 60 + login_ip_limit: int = 50 + login_ip_window_seconds: int = 300 def fault_value(self, point: str, default: int = 0) -> int: return self.fault_values.get(point, default) @@ -230,6 +255,16 @@ class Settings: **s3_settings(credentials_required=s3_credentials), **jobs_settings(broker_required=False), **tls_settings(), + # OWASP minimum for Argon2id is m=19 MiB, t=2, p=1: never configurable below it. + argon2_memory_kib=_int("ARGON2_MEMORY_KIB", 19456, 19456, 1024 * 1024), + argon2_iterations=_int("ARGON2_ITERATIONS", 2, 2, 20), + argon2_parallelism=_int("ARGON2_PARALLELISM", 1, 1, 8), + # Failed logins: per username (brute force of one account) and per client IP (spraying + # many accounts), fixed windows in Valkey, shared by all replicas. + login_user_limit=_int("LOGIN_RATE_LIMIT_USER", 5, 1, 1000), + login_user_window_seconds=_int("LOGIN_RATE_LIMIT_USER_WINDOW_SECONDS", 60, 1, 86400), + login_ip_limit=_int("LOGIN_RATE_LIMIT_IP", 50, 1, 100000), + login_ip_window_seconds=_int("LOGIN_RATE_LIMIT_IP_WINDOW_SECONDS", 300, 1, 86400), ) diff --git a/src/messenger/passwords.py b/src/messenger/passwords.py index a1fc35a..573b08e 100644 --- a/src/messenger/passwords.py +++ b/src/messenger/passwords.py @@ -1,28 +1,40 @@ -"""Password hashing with Argon2id (memory-hard password KDF; also mandatory in lab 7). +"""Password hashing with Argon2id (memory-hard password KDF; mandatory in lab 7). -* Parameters follow the OWASP minimum for Argon2id: m=19 MiB, t=2, p=1. Unlike bcrypt - there is no 72-byte limit, so any 12-128 code point UTF-8 password is hashed whole. -* Hashing takes tens of milliseconds of CPU and 19 MiB of RAM. It runs in a worker - thread (argon2-cffi releases the GIL), so the event loop keeps serving other - requests, and a semaphore caps parallel hashes (memory/CPU DoS protection). -* An unknown username is checked against a dummy hash, so "no such user" and - "wrong password" take the same time and return the same 401. +* Parameters: ARGON2_MEMORY_KIB / ARGON2_ITERATIONS / ARGON2_PARALLELISM, never below the OWASP + minimum m=19 MiB, t=2, p=1 (config.py refuses lower values). The values in compose.yaml were + chosen by a measurement on this stand (bench/argon2_bench.py, REPORT.md, evidence/argon2/). +* The stored value is the PHC string `$argon2id$v=19$m=...,t=...,p=...$$`: algorithm, + version, parameters and a random 16-byte salt travel WITH the hash, so verification always uses + the parameters the hash was made with, and a change of parameters does not break old hashes. +* No 72-byte limit (unlike bcrypt): any 12-128 code point UTF-8 password is hashed whole. +* Hashing takes tens of milliseconds of CPU and m KiB of RAM. It runs in a worker thread + (argon2-cffi releases the GIL), so the event loop keeps serving other requests, and a semaphore + caps parallel hashes per replica (PASSWORD_HASH_CONCURRENCY: RAM = concurrency x m). +* An unknown username is checked against a dummy hash, so "no such user" and "wrong password" + take the same time and return the same 401. """ from __future__ import annotations import asyncio -from argon2 import PasswordHasher +from argon2 import PasswordHasher, Type from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError -_hasher = PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1, hash_len=32, salt_len=16) +_hasher = PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1, hash_len=32, salt_len=16, type=Type.ID) _semaphore: asyncio.Semaphore | None = None _dummy_hash: str | None = None -def configure(concurrency: int) -> None: - global _semaphore +def configure(concurrency: int, memory_kib: int = 19456, iterations: int = 2, parallelism: int = 1) -> None: + global _semaphore, _hasher, _dummy_hash _semaphore = asyncio.Semaphore(concurrency) + _hasher = PasswordHasher(time_cost=iterations, memory_cost=memory_kib, parallelism=parallelism, + hash_len=32, salt_len=16, type=Type.ID) + _dummy_hash = None # re-created with the current parameters (same cost as a real verify) + + +def parameters() -> dict: + return {"memory_kib": _hasher.memory_cost, "iterations": _hasher.time_cost, "parallelism": _hasher.parallelism} async def _run(func, *args): diff --git a/src/messenger/ratelimit.py b/src/messenger/ratelimit.py new file mode 100644 index 0000000..f0517ca --- /dev/null +++ b/src/messenger/ratelimit.py @@ -0,0 +1,116 @@ +"""Lab 7: rate limit of FAILED logins -> 429 rate_limited + Retry-After (POST /api/v1/auth/sessions). + +Two fixed-window counters of failed attempts, kept in Valkey (keys ratelimit:*, the API's ACL +user may touch only these and session:*), so every replica sees the same numbers: + + per username LOGIN_RATE_LIMIT_USER failures / LOGIN_RATE_LIMIT_USER_WINDOW_SECONDS (5 / 60 s): + stops a password guessing attack on ONE account; + per client IP LOGIN_RATE_LIMIT_IP failures / LOGIN_RATE_LIMIT_IP_WINDOW_SECONDS (50 / 300 s): + stops trying one password on MANY accounts from one address. + +Order in the handler: check (no Argon2 work at all while blocked: a blocked attacker costs one +Valkey GET, not 19+ MiB and ~tens of ms of CPU) -> verify the password -> on failure count it, +on success reset the username counter. Retry-After = the remaining TTL of the window, in seconds +(rounded up). A correct password during the block is also 429: otherwise the block would be an +oracle that tells the attacker when the guess was right. + +The client IP comes from X-Forwarded-For, which HAProxy OVERWRITES with the TCP source address +(infra/haproxy/haproxy.cfg). It can be trusted here only because the API accepts connections from +the LB identity alone (mTLS allowlist, tls.py): a client cannot reach the API without the LB. +Keys contain SHA-256 prefixes, not raw usernames/IPs. Valkey unavailable -> 503 (the login cannot +create a session without it anyway). With SESSION_STORE=postgres (no Valkey) the counters live in +the process (per replica) - documented limitation, not the default of the stand. +Known residual risk: anybody can lock a known username for one window (60 s) by failing on purpose. +""" +from __future__ import annotations + +import asyncio +import hashlib +import math +import time +from dataclasses import dataclass + +from redis import exceptions as redis_errors + +from .errors import ApiError, Unavailable + + +class RateLimited(ApiError): + status = 429 + code = "rate_limited" + default_message = "Слишком много неудачных попыток входа, повторите позже" + + def __init__(self, retry_after: int): + super().__init__() + self.retry_after = max(1, retry_after) + + @property + def headers(self) -> dict[str, str]: + return {"Retry-After": str(self.retry_after)} + + +@dataclass(frozen=True) +class Rule: + name: str + limit: int + window_s: int + + +def _digest(value: str) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest()[:32] + + +class LoginLimiter: + def __init__(self, settings, client=None): + self.client = client # redis.asyncio.Redis of the session store, or None + self.timeout = settings.cache_timeout_seconds * 2 + self.rules = (Rule("u", settings.login_user_limit, settings.login_user_window_seconds), + Rule("ip", settings.login_ip_limit, settings.login_ip_window_seconds)) + self._local: dict[str, tuple[int, float]] = {} # fallback without Valkey: key -> (count, until) + + def _keys(self, username: str, ip: str) -> list[tuple[Rule, str]]: + return [(self.rules[0], f"ratelimit:login:u:{_digest(username)}"), + (self.rules[1], f"ratelimit:login:ip:{_digest(ip)}")] + + async def _call(self, coro): + try: + async with asyncio.timeout(self.timeout): + return await coro + except (redis_errors.RedisError, TimeoutError, OSError): + raise Unavailable("Хранилище сессий недоступно") from None + + async def check(self, username: str, ip: str) -> None: + """Raise RateLimited if any window is exhausted.""" + for rule, key in self._keys(username, ip): + if self.client is None: + count, until = self._local.get(key, (0, 0.0)) + ttl_ms = (until - time.monotonic()) * 1000 + if ttl_ms <= 0: + continue + else: + pipe = self.client.pipeline(transaction=True) + pipe.get(key) + pipe.pttl(key) + raw, ttl_ms = await self._call(pipe.execute()) + count = int(raw or 0) + if count >= rule.limit and ttl_ms > 0: + raise RateLimited(math.ceil(ttl_ms / 1000)) + + async def failed(self, username: str, ip: str) -> None: + for rule, key in self._keys(username, ip): + if self.client is None: + count, until = self._local.get(key, (0, 0.0)) + now = time.monotonic() + self._local[key] = (count + 1, until) if until > now else (1, now + rule.window_s) + continue + pipe = self.client.pipeline(transaction=True) + pipe.incr(key) + pipe.pexpire(key, rule.window_s * 1000, nx=True) # the window starts at the FIRST failure + await self._call(pipe.execute()) + + async def succeeded(self, username: str) -> None: + rule, key = self._keys(username, "")[0] + if self.client is None: + self._local.pop(key, None) + else: + await self._call(self.client.delete(key)) diff --git a/src/messenger/relay.py b/src/messenger/relay.py index ec45a0f..388e8dd 100644 --- a/src/messenger/relay.py +++ b/src/messenger/relay.py @@ -32,7 +32,7 @@ import aio_pika from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractExchange from . import __version__, broker, jobs, logging_setup, service, telemetry -from .config import ConfigError, Settings +from .config import ConfigError, Settings, publish_instance_id from .db import Database from .errors import Unavailable @@ -223,6 +223,7 @@ def main() -> int: print(f"configuration error: {exc}", file=sys.stderr) return 2 logging_setup.configure(settings.log_level) + publish_instance_id(settings.instance_id) telemetry.setup("messenger-relay", settings.instance_id, __version__) log.info("relay_starting", extra={"fields": {"instance_id": settings.instance_id, "fault_points": sorted(settings.fault_points)}}) diff --git a/src/messenger/worker.py b/src/messenger/worker.py index 42f4989..6efa19c 100644 --- a/src/messenger/worker.py +++ b/src/messenger/worker.py @@ -42,7 +42,7 @@ import aio_pika from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractIncomingMessage, AbstractQueue from . import __version__, broker, imaging, jobs, logging_setup, service, telemetry -from .config import ConfigError, Settings +from .config import ConfigError, Settings, publish_instance_id from .db import Database from .errors import Unavailable from .imaging import ProcessingError @@ -388,6 +388,7 @@ def main() -> int: print(f"configuration error: {exc}", file=sys.stderr) return 2 logging_setup.configure(settings.log_level) + publish_instance_id(settings.instance_id) telemetry.setup("messenger-worker", settings.instance_id, __version__) log.info("worker_starting", extra={"fields": { "instance_id": settings.instance_id, "concurrency": settings.worker_concurrency, diff --git a/student-tests/test_balancing.py b/student-tests/test_balancing.py index 6ee08bc..98065ea 100644 --- a/student-tests/test_balancing.py +++ b/student-tests/test_balancing.py @@ -29,9 +29,9 @@ def instances_seen(api: Api, token: str, requests: int = 40) -> list[str]: def test_one_session_is_served_by_every_real_replica(api): actor = api.user("rr") seen = instances_seen(api, actor["token"]) - running = {r["hostname"] for r in running_replicas()} + running = {r["instance"] for r in running_replicas()} assert len(running) == REPLICAS >= 2 - assert set(seen) == running, "X-Instance-Id values must be exactly the hostnames of the running containers" + assert set(seen) == running, "X-Instance-Id values must be exactly the aliases of the running containers" # Round robin on ONE keep-alive client connection: consecutive requests switch replicas, # so there is no sticky session hiding split state. switches = sum(1 for a, b in zip(seen, seen[1:]) if a != b) @@ -104,7 +104,7 @@ def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position isolate = isolated_from_postgres if how == "pg_hba" else disconnected_from_data_network with isolate(replica): started = time.monotonic() - while replica["hostname"] in lbctl.up_instances(): + while replica["instance"] in lbctl.up_instances(): assert time.monotonic() - started < 5, "HAProxy did not mark the unready replica DOWN within 5 s" time.sleep(0.1) detected = time.monotonic() - started @@ -114,7 +114,7 @@ def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position assert probe_inside(replica, "/health/ready") == 503 # ... but not ready assert time.monotonic() - started_probe < 4.5, "replica froze while its dependencies were unreachable" seen = instances_seen(api, actor["token"], 40) - assert replica["hostname"] not in seen and len(seen) == 40 + assert replica["instance"] not in seen and len(seen) == 40 for i in range(20): # writes keep working, only through the ready replicas assert api.register(f"r{i}")["id"] print(f"{replica['name']} ({how}): unready replica out of rotation after {detected:.2f} s") @@ -195,7 +195,7 @@ def test_graceful_stop_of_each_replica_loses_no_request(api, position): stopped_after = time.monotonic() - started time.sleep(3) after = [e for e in traffic.events if e[0] > time.monotonic() - 2] - assert after and replica["hostname"] not in {e[3] for e in after} + assert after and replica["instance"] not in {e[3] for e in after} time.sleep(1) state = json.loads(subprocess.run(["docker", "inspect", replica["id"]], capture_output=True, text=True, check=True).stdout)[0]["State"] @@ -220,7 +220,7 @@ def test_killed_replica_bounded_errors_recovery_and_no_duplicates(api, position) post_ok = [e for e in traffic.events if e[0] > killed_at and e[1] == "POST" and e[2] == 201] assert post_ok and post_ok[0][0] - killed_at <= 10, "writes did not recover within 10 s" late = [e for e in traffic.events if e[0] > killed_at + 3.5] - assert late and replica["hostname"] not in {e[3] for e in late} + assert late and replica["instance"] not in {e[3] for e in late} assert last_failure <= 10 traffic.check_history(api) print(f"{replica['name']}: killed; {len(failures)} failed of {len(traffic.events)}, last failure +{last_failure:.2f} s") @@ -248,11 +248,11 @@ def test_graceful_shutdown_order_in_logs(api): # ------------------------------------------------------------------ discovery: restart and scaling def test_full_restart_lb_rediscovers_all_replicas(api): actor = api.user("restart") - before = {r["hostname"]: r["started_at"] for r in running_replicas()} + before = {r["instance"]: r["started_at"] for r in running_replicas()} run_hook("restart.sh") wait_healthy("postgres", "valkey", "api") wait_stand() - after = {r["hostname"]: r["started_at"] for r in running_replicas()} + after = {r["instance"]: r["started_at"] for r in running_replicas()} assert set(after) == set(before) and all(after[h] != before[h] for h in after), "every replica restarted" assert set(instances_seen(api, actor["token"])) == set(after) # same token, both replicas, no LB restart needed diff --git a/student-tests/test_idempotency.py b/student-tests/test_idempotency.py index a1e2bcc..e704485 100644 --- a/student-tests/test_idempotency.py +++ b/student-tests/test_idempotency.py @@ -273,7 +273,7 @@ def test_replay_after_the_serving_replica_is_stopped(api, pair): key = uuid.uuid4().hex first = api.post_message(alice, chat, {"text": "до остановки"}, key=key) served_by = first.headers["x-instance-id"] - replica = next(r for r in running_replicas() if r["hostname"] == served_by) + replica = next(r for r in running_replicas() if r["instance"] == served_by) with replica_stopped(replica): for _ in range(5): again = Api().post_message(alice, chat, {"text": "до остановки"}, key=key) diff --git a/student-tests/test_pipeline_flow.py b/student-tests/test_pipeline_flow.py index 3d25e4f..8cc7071 100644 --- a/student-tests/test_pipeline_flow.py +++ b/student-tests/test_pipeline_flow.py @@ -20,7 +20,7 @@ import pytest from PIL import Image import imagegen -from conftest import (attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys, +from conftest import (lbctl, attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys, s3_size, service_down, service_with_env, wait_healthy, wait_stand) pytestmark = pytest.mark.stack @@ -359,11 +359,9 @@ def test_bad_message_is_dead_lettered_not_processed(api, pair): # ------------------------------------------------------------------ lease, hung worker, shutdown, concurrency def worker_containers() -> dict[str, str]: - """hostname (= lease_owner) -> container id of every running worker.""" + """instance alias (= lease_owner, lab 7: random, in /tmp/instance_id) -> container id of every running worker.""" ids = compose("ps", "-q", "worker").stdout.split() - out = subprocess.run(["docker", "inspect", "-f", "{{.Config.Hostname}} {{.Id}}", *ids], capture_output=True, - text=True, check=True).stdout - return dict(line.split() for line in out.splitlines()) + return {lbctl.instance_alias(cid): cid for cid in ids} def test_hung_worker_loses_its_lease_and_cannot_publish(api, pair): -- 2.54.0 From 84dbdb473573d0db1fe8ae1c4c6bac7d01a1b2b2 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:43:14 +0300 Subject: [PATCH 07/16] =?UTF-8?q?lab7:=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20?= =?UTF-8?q?=D0=B1=D0=B5=D0=B7=D0=BE=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D0=B8=20=D0=B8=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20=D1=81=D0=B2=D0=BE=D0=B8=D1=85=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=BE=D0=B2=20=D0=BD=D0=B0=20HTTPS,=20=D0=B4=D0=BE=D0=BA?= =?UTF-8?q?=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D1=8B=20(trust-matrix,=20THREAT?= =?UTF-8?q?=5FMODEL,=20OPERATOR,=20DEFENSE,=20WINDOWS,=20PR),=20=D1=81?= =?UTF-8?q?=D0=B1=D0=BE=D1=80=D1=89=D0=B8=D0=BA=20=D0=B4=D0=BE=D0=BA=D0=B0?= =?UTF-8?q?=D0=B7=D0=B0=D1=82=D0=B5=D0=BB=D1=8C=D1=81=D1=82=D0=B2,=20?= =?UTF-8?q?=D1=87=D0=B8=D1=81=D1=82=D0=BA=D0=B0=20legacy=20bench?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/app.yml | 45 ++- Makefile | 76 +++-- bench/failover_series.py | 141 -------- bench/incidents.py | 424 ------------------------- bench/loadgen.py | 212 ------------- bench/pipeline_faults.py | 309 ------------------ bench/rolling_under_load.py | 75 ----- bench/track1.py | 361 --------------------- bench/track1_summary.py | 146 --------- bench/upload_memory.py | 244 -------------- compose.yaml | 11 +- contracts/trust-matrix.md | 108 +++++-- docs/DEFENSE.md | 80 +++++ docs/OBSERVABILITY.md | 9 +- docs/OPERATOR.md | 91 ++++++ docs/PR.md | 70 ++++ docs/RUNBOOK.md | 2 +- docs/SLO.md | 2 +- docs/WINDOWS.md | 117 +++---- evidence/argon2/bench.json | 290 +++++++++++++++++ infra/otel/collector.yaml | 4 +- infra/otel/traces-all.yaml | 6 - infra/otel/traces-tail.yaml | 39 --- migrations/0007_least_privilege.sql | 5 + requirements-test.txt | 2 + scripts/collect_evidence.py | 336 +++++++++----------- scripts/collect_evidence_resume.py | 50 --- scripts/demo_attachments.py | 138 -------- scripts/demo_pipeline.py | 132 -------- scripts/explain_history.py | 2 +- security/THREAT_MODEL.md | 76 ++++- src/messenger/app.py | 21 +- src/messenger/tls.py | 9 +- student-tests/conftest.py | 38 ++- student-tests/test_balancing.py | 88 +++-- student-tests/test_consistency.py | 4 +- student-tests/test_db.py | 22 +- student-tests/test_failures.py | 2 +- student-tests/test_idempotency.py | 2 +- student-tests/test_pipeline_flow.py | 14 +- student-tests/test_security.py | 327 +++++++++++++++++++ student-tests/test_storage_failures.py | 7 +- student-tests/unit/test_lab7.py | 179 +++++++++++ student-tests/unit/test_unit.py | 14 +- 44 files changed, 1644 insertions(+), 2686 deletions(-) delete mode 100644 bench/failover_series.py delete mode 100644 bench/incidents.py delete mode 100644 bench/loadgen.py delete mode 100644 bench/pipeline_faults.py delete mode 100644 bench/rolling_under_load.py delete mode 100644 bench/track1.py delete mode 100644 bench/track1_summary.py delete mode 100644 bench/upload_memory.py create mode 100644 docs/DEFENSE.md create mode 100644 docs/OPERATOR.md create mode 100644 docs/PR.md create mode 100644 evidence/argon2/bench.json delete mode 100644 infra/otel/traces-all.yaml delete mode 100644 infra/otel/traces-tail.yaml delete mode 100644 scripts/collect_evidence_resume.py delete mode 100644 scripts/demo_attachments.py delete mode 100644 scripts/demo_pipeline.py create mode 100644 student-tests/test_security.py create mode 100644 student-tests/unit/test_lab7.py diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml index 80b299d..34af828 100644 --- a/.github/workflows/app.yml +++ b/.github/workflows/app.yml @@ -1,42 +1,41 @@ -name: Application (lab6) +name: Application (lab7) on: [push, pull_request] permissions: contents: read jobs: app: runs-on: ubuntu-latest - timeout-minutes: 60 + timeout-minutes: 75 + env: + PYTHONUTF8: "1" steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.13' - - name: Synthetic secrets and env (CI only, never committed) - run: python scripts/init_secrets.py && cp .env.example .env - - name: Build, migrate once, bootstrap S3, start broker, 2 API replicas, LB, relay, worker, Collector, Prometheus, Loki, Tempo, Grafana - run: docker compose --env-file .env up -d --build --wait - - name: Contract and public smoke - run: make check test PYTHON=python - - name: Persistence across restart of LB, API replicas, relay, worker, PostgreSQL, Valkey, S3, RabbitMQ - run: make test-persistence ACTION_SCRIPT=scripts/restart.sh PYTHON=python - - name: Failover of the replica that served the test, then restore it - run: | - make test-failover ACTION_SCRIPT=scripts/stop-one.sh PYTHON=python - sh scripts/restore-api.sh && python scripts/lbctl.py wait-up 2 - - name: Defense scenario - worker stopped, 202, 409, restart API and broker, ready - run: python -m pip install -q pillow==12.3.0 && python scripts/demo_pipeline.py - - name: Own tests (unit + stand; every failure is restored in finally) + - name: Test/tooling dependencies (cryptography for the local PKI) run: | python -m pip install --require-hashes --no-deps -r requirements.txt python -m pip install -r requirements-test.txt - make student-test PYTHON=python - - name: Lab 6 - controlled trace in Tempo + logs in Loki, every dashboard query through Grafana - run: python scripts/trace_demo.py && python scripts/check_dashboard.py - - name: Lab 5 invariants (read-only audit of PostgreSQL and both buckets) - run: docker compose run --rm --no-deps auditor --verify-checksums + - name: Synthetic secrets + PKI (CI only, never committed; operator dir outside the checkout) + run: python scripts/init_secrets.py + - name: OpenBao (sealed) -> operator init/unseal/configure -> whole stand over TLS/mTLS + run: make up PYTHON=python + - name: Contract and public smoke over HTTPS (public CA) + run: make check test test-security PYTHON=python CA_FILE="$PWD/secrets/pki/public-ca.crt" + - name: Persistence across restart of every process incl. OpenBao (unsealed by the hook) + run: make test-persistence ACTION_SCRIPT=scripts/restart.sh PYTHON=python CA_FILE="$PWD/secrets/pki/public-ca.crt" + - name: Failover of the replica that served the test, then restore it + run: | + make test-failover ACTION_SCRIPT=scripts/stop-one.sh PYTHON=python CA_FILE="$PWD/secrets/pki/public-ca.crt" + sh scripts/restore-api.sh && python scripts/lbctl.py wait-up 2 + - name: Lab 7 defense steps 3-4 - mTLS LB->API and OpenBao allow/deny + run: make mtls-check bao-check PYTHON=python + - name: Own tests (unit + stand; every failure is restored in finally) + run: make student-test PYTHON=python - name: Logs if: always() - run: docker compose logs --tail 100 api lb s3 s3-init broker relay worker otel-collector prometheus loki tempo grafana + run: docker compose logs --tail 100 api lb s3 s3-init broker relay worker openbao otel-collector prometheus loki tempo grafana - name: Remove CI stand and its synthetic data if: always() run: docker compose down -v diff --git a/Makefile b/Makefile index 5c940fb..2199886 100644 --- a/Makefile +++ b/Makefile @@ -33,23 +33,38 @@ test-security: $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) # --------------------------------------------------------------------------- -# Student solution (lab 5, Python). On Windows: PowerShell/Git Bash with GNU make, public -# tests need PYTHONUTF8=1, and the hooks are started through scripts/*.cmd (Git Bash). -.PHONY: grafana alerts trace-demo dashboard dashboard-check incidents track1 obs-test secrets up down logs ps migrate student-test unit-test explain lb-status restore rolling-update failover-series bench-memory worker-stop worker-start jobs failed audit track2 +# Student solution (lab 7, Python). On Windows: Git Bash `sh` in PATH (C:\Program Files\Git\usr\bin), +# PYTHONUTF8=1, PYTHON=.venv/Scripts/python; the hooks are started through scripts/*.cmd. +# Full first start from a clean clone (docs/OPERATOR.md): make secrets && make up +CA ?= secrets/pki/public-ca.crt +.PHONY: secrets up bao-bootstrap bao-unseal bao-status down logs ps migrate lb-status restore rolling-update worker-stop worker-start jobs failed audit student-test unit-test security-test mtls-check bao-check argon2-bench explain grafana alerts trace-demo dashboard dashboard-check obs-test +# Local synthetic credentials + PKI (two CAs, service certificates) into ./secrets (git-ignored). secrets: $(PYTHON) scripts/init_secrets.py -# Build, apply migrations ONCE (service migrate), start broker, API replicas, LB, relay and worker. -up: secrets +# OpenBao first (it starts sealed), operator init/unseal/configuration, then the whole stand. +up: + docker compose up -d openbao + $(PYTHON) scripts/bao_operator.py bootstrap docker compose up -d --build --wait -# Safe stop: containers stop, named volumes (data, queue) stay. +bao-bootstrap: + $(PYTHON) scripts/bao_operator.py bootstrap + +# After every restart of OpenBao (it comes back sealed). +bao-unseal: + $(PYTHON) scripts/bao_operator.py unseal + +bao-status: + $(PYTHON) scripts/bao_operator.py status + +# Safe stop: containers stop, named volumes (data, queue, secrets storage) stay. down: docker compose down logs: - docker compose logs --tail 50 api lb relay worker + docker compose logs --tail 50 api lb relay worker openbao ps: docker compose ps -a @@ -57,7 +72,7 @@ ps: migrate: docker compose run --rm migrate -# HAProxy view of the replicas (UP/DOWN) mapped to containers and X-Instance-Id. +# HAProxy view of the replicas (UP/DOWN) mapped to containers and X-Instance-Id aliases. lb-status: $(PYTHON) scripts/lbctl.py status $(PYTHON) scripts/lbctl.py replicas @@ -71,32 +86,21 @@ restore: rolling-update: sh scripts/rolling-update.sh -# Lab 3: stop each replica in turn under load, measure RPS/errors/recovery (evidence/failover/). -failover-series: - $(PYTHON) bench/failover_series.py --output evidence/failover - -# Lab 5 demo: stop the worker (uploads still get 202, content answers 409), start it again. worker-stop: docker compose stop worker worker-start: docker compose start worker -# Lab 5 operator view: jobs by state + outbox backlog; failed registry (replay: see REPORT.md). jobs: docker compose run --rm --no-deps jobctl stats failed: docker compose run --rm --no-deps jobctl list-failed -# Track 2: read-only check of the pipeline invariants over PostgreSQL and both buckets. audit: docker compose run --rm --no-deps auditor -# Track 2: automatic fault-injection matrix (duplicate, reorder, crashes, stale versions). -track2: - $(PYTHON) bench/pipeline_faults.py --output evidence/track2 - # Own tests: unit + black-box against the running stand (needs requirements*.txt in a venv). student-test: $(PYTHON) -m pytest student-tests -v @@ -104,17 +108,28 @@ student-test: unit-test: $(PYTHON) -m pytest student-tests -m "not stack" -q +# Lab 7: the trust matrix proofs only (TLS, mTLS, roles/ACL, OpenBao, rate limit, hardening). +security-test: + $(PYTHON) -m pytest student-tests/test_security.py -v + +# Lab 7 defense step 3: LB -> API mTLS (no cert / foreign CA / wrong identity / lb). +mtls-check: + sh scripts/mtls_check.sh + +# Lab 7 defense step 4: OpenBao allow/deny for api/relay/worker + no root credential in the apps. +bao-check: + sh scripts/bao_check.sh + +# Lab 7: Argon2id parameter measurement inside an API replica (its CPU/RAM limits). +argon2-bench: + docker compose exec -T api python - < bench/argon2_bench.py > evidence/argon2/bench.json + explain: $(PYTHON) scripts/explain_history.py --output evidence/explain-history.txt -# Lab 4: peak RAM of the replicas under 16 simultaneous uploads (evidence/memory/). -bench-memory: - $(PYTHON) bench/upload_memory.py --output evidence/memory - -# --------------------------------------------------------------------------- -# Lab 6: observability (docs/OBSERVABILITY.md, docs/SLO.md, docs/RUNBOOK.md, docs/TRACK1.md) +# Lab 6: observability (docs/OBSERVABILITY.md, docs/SLO.md, docs/RUNBOOK.md) grafana: - @echo "Grafana: http://127.0.0.1:3000 user admin, password in secrets/grafana_admin_password" + @echo "Grafana: https://localhost:3000 (CA $(CA)), user admin, password in secrets/grafana_admin_password" alerts: $(PYTHON) scripts/obs.py alerts @@ -123,20 +138,11 @@ alerts: trace-demo: $(PYTHON) scripts/trace_demo.py --output evidence/trace-demo.txt -# Regenerate the dashboard JSON / run every dashboard query through Grafana. dashboard: $(PYTHON) scripts/build_dashboard.py dashboard-check: $(PYTHON) scripts/check_dashboard.py --output evidence/dashboard-check.txt -# Level 4 incidents under load (worker stop, DB lock, slow handler, backend/collector down). -incidents: - $(PYTHON) bench/incidents.py all - -# Track 1: price of observability (off / full / head10 / tail), 3 runs each. -track1: - $(PYTHON) bench/track1.py --runs 3 --output evidence/track1 - obs-test: $(PYTHON) -m pytest student-tests/test_observability.py -v diff --git a/bench/failover_series.py b/bench/failover_series.py deleted file mode 100644 index b4c5daf..0000000 --- a/bench/failover_series.py +++ /dev/null @@ -1,141 +0,0 @@ -#!/usr/bin/env python3 -"""Level 4: stop EACH API replica in turn under load (restoring the previous one first) and -measure RPS, errors and recovery. Modes: graceful `stop` (SIGTERM + drain), `kill` (SIGKILL) -and `pause` (frozen process: the kernel still accepts TCP, nothing answers - the worst case -for detection, only the active health check can find it). - - python bench/failover_series.py --output evidence/failover # ~5 min for 2 replicas x 3 modes - -Timeline of one round (all times from the moment the stop command is issued): - warm-up 6 s -> stop replica -> 12 s with it down -> start it again -> wait until HAProxy - has every replica UP (rejoin time) -> 6 s steady state. -Measured per round: requests/ok/failed and ok-RPS before / during / after, the last failed -request (+s), the first moment after which the stopped replica never answered again -(= removal from rotation), time until the restarted replica is UP in HAProxy and serves -traffic again, plus the history check (no confirmed message lost, no duplicate). -Output: /series.json (summary), /timeline--.csv (per second), -/series.md (table for REPORT.md). No tokens are written. -""" -from __future__ import annotations - -import argparse -import csv -import datetime as dt -import json -import platform -import subprocess -import sys -import time -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "scripts")) -sys.path.insert(0, str(ROOT / "bench")) -import lbctl # noqa: E402 -from loadgen import Load # noqa: E402 - - -def docker(*args: str) -> str: - return subprocess.run(["docker", *args], capture_output=True, text=True, check=True, timeout=120).stdout - - -def one_round(replica: dict, mode: str, replicas: int, workers: int, out: Path) -> dict: - load = Load(workers).start() - time.sleep(6) - t_stop = load.now() - if mode == "pause": - docker("pause", replica["id"]) - else: - docker("stop", "--time", "15" if mode == "stop" else "0", replica["id"]) - t_stopped = load.now() - time.sleep(12) - t_start = load.now() - docker("unpause" if mode == "pause" else "start", replica["id"]) - lbctl.wait_up(replicas, timeout=90) - t_up = load.now() - # The restarted container keeps its hostname: wait until it serves requests again. - deadline = time.monotonic() + 30 - while time.monotonic() < deadline: - if any(e[3] == replica["hostname"] and e[0] > t_up for e in load.events): - break - time.sleep(0.1) - t_serves = load.now() - time.sleep(6) - load.stop() - t_end = load.now() - - failed_after_stop = [e for e in load.events if e[0] >= t_stop and e[2] not in (200, 201)] - served_by_target = [e[0] for e in load.events if e[3] == replica["hostname"] and t_stop <= e[0] < t_start] - out_of_rotation = (max(served_by_target) - t_stop) if served_by_target else 0.0 - rows = load.per_second() - with (out / f"timeline-{mode}-{replica['name']}.csv").open("w", newline="", encoding="utf-8") as f: - writer = csv.DictWriter(f, fieldnames=["second", "ok", "failed", "instances"]) - writer.writeheader() - for row in rows: - row = dict(row) - row["instances"] = row["instances"].replace(replica["hostname"], "TARGET") - writer.writerow(row) - state = json.loads(docker("inspect", replica["id"]))[0]["State"] - return { - "mode": mode, "replica": replica["name"], "instance_id": replica["hostname"], - "stop_command_seconds": round(t_stopped - t_stop, 2), - "before": load.window(0.5, t_stop), "during": load.window(t_stop, t_start), "after": load.window(t_serves, t_end), - "failed_after_stop": len(failed_after_stop), - "failed_statuses": sorted({e[2] for e in failed_after_stop}), - "last_failure_after_stop_s": round(max((e[0] for e in failed_after_stop), default=t_stop) - t_stop, 3), - "target_last_served_after_stop_s": round(out_of_rotation, 3), - "rejoin_up_in_lb_s": round(t_up - t_start, 2), "rejoin_serving_s": round(t_serves - t_start, 2), - "client_retries_same_key": load.retries, - "history": load.verify_history(), - "restarted_state": f"{state['Status']} health={(state.get('Health') or {}).get('Status')}", - } - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - parser.add_argument("--output", default="evidence/failover") - parser.add_argument("--modes", default="stop,kill,pause") - parser.add_argument("--workers", type=int, default=4) - args = parser.parse_args() - out = ROOT / args.output - out.mkdir(parents=True, exist_ok=True) - replicas = sorted((r for r in lbctl.replicas() if r["state"] == "running"), key=lambda r: r["name"]) - assert len(replicas) >= 2, "need at least two running replicas" - lbctl.wait_up(len(replicas)) - results = [] - for mode in args.modes.split(","): - for replica in replicas: # each replica in turn; the previous one is already restored - print(f"== {mode} {replica['name']} ...", flush=True) - result = one_round(replica, mode, len(replicas), args.workers, out) - results.append(result) - print(json.dumps({k: result[k] for k in ("failed_after_stop", "last_failure_after_stop_s", - "target_last_served_after_stop_s", "rejoin_serving_s")}), flush=True) - meta = {"date": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"), - "commit": subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True, - text=True).stdout.strip(), - "host": f"{platform.system()} {platform.release()}, docker {docker('version', '--format', '{{.Server.Version}}').strip()}", - "workload": f"{args.workers} closed-loop workers from the host via 127.0.0.1:8080: POST message " - "(Idempotency-Key, uncertain -> same key) + GET last page; client timeout 3 s", - "lb": "HAProxy: check GET /health/ready inter 1s fastinter 500ms fall 2 rise 2, timeout check 1s; " - "retry-on conn-failure + redispatch", - "api": "DRAIN_SECONDS=3, SHUTDOWN_TIMEOUT_SECONDS=8, stop_grace_period 15s"} - (out / "series.json").write_text(json.dumps({"meta": meta, "rounds": results}, ensure_ascii=False, indent=2) + "\n", - encoding="utf-8") - lines = ["| Режим | Реплика | Запросов во время отказа | Ошибок после stop | ok-RPS до / во время / после | " - "Последняя ошибка, с | Цель ушла из ротации, с | Возврат в LB / обслуживает, с | Потери / дубли |", - "| --- | --- | --- | --- | --- | --- | --- | --- | --- |"] - for r in results: - h = r["history"] - lines.append(f"| {r['mode']} | {r['replica']} | {r['during']['requests']} | {r['failed_after_stop']} " - f"{r['failed_statuses'] or ''} | {r['before']['ok_rps']} / {r['during']['ok_rps']} / {r['after']['ok_rps']} | " - f"{r['last_failure_after_stop_s']} | {r['target_last_served_after_stop_s']} | " - f"{r['rejoin_up_in_lb_s']} / {r['rejoin_serving_s']} | " - f"{h['lost_confirmed']} / {h['duplicate_ids'] + h['duplicate_texts']} |") - (out / "series.md").write_text("\n".join([f"Дата {meta['date']}, commit {meta['commit']}. {meta['workload']}.", "", - *lines, ""]), encoding="utf-8") - print("\n".join(lines)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/bench/incidents.py b/bench/incidents.py deleted file mode 100644 index f8ae7be..0000000 --- a/bench/incidents.py +++ /dev/null @@ -1,424 +0,0 @@ -#!/usr/bin/env python3 -"""Lab 6 level 4: controlled incidents under load, found and timed with the STORED observations. - - python bench/incidents.py worker-stop # (1) worker stopped -> queue lag alert -> resolved - python bench/incidents.py db-lock # (2a) slow/blocked database (table lock held 90 s) - python bench/incidents.py slow-handler # (2b) contrast: slow handler code, healthy database - python bench/incidents.py backend-down # (3a) Tempo + Loki stopped: API unaffected, Collector bounded - python bench/incidents.py collector-down # (3b) Collector stopped: SDK queues bounded, API unaffected - python bench/incidents.py all -Results: evidence/incidents/.json (timeline, alert times, metric snapshots, client counts) -and .txt (human-readable). Every incident restores the stand in `finally`. - -Load during every incident (own threads, fixed pacing): 4 writers posting messages -(~8 req/s in total) and 1 uploader (one PNG every 2 s). Client-side counts are kept separately -from the telemetry, so the effect of an incident on users is measured independently of it. -""" -from __future__ import annotations - -import argparse -import base64 -import json -import os -import secrets -import subprocess -import sys -import threading -import time -import urllib.error -import urllib.request -import uuid -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "scripts")) -import obs # noqa: E402 - -BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") + "/api/v1" -OUT = ROOT / "evidence" / "incidents" -SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() - - -# ----------------------------------------------------------------------------- HTTP + load -def http(method: str, path: str, body=None, headers=None, raw: bytes | None = None, timeout: float = 15): - h = dict(headers or {}) - data = raw - if body is not None: - data = json.dumps(body).encode() - h["Content-Type"] = "application/json" - request = urllib.request.Request(BASE + path, data=data, method=method, headers=h) - try: - with urllib.request.urlopen(request, timeout=timeout) as r: - return r.status, r.headers, json.loads(r.read() or b"null") - except urllib.error.HTTPError as exc: - return exc.code, exc.headers, None - - -def new_actor() -> dict: - username = "inc_" + uuid.uuid4().hex[:12] - password = "Incident-" + secrets.token_hex(8) - _, _, user = http("POST", "/users", {"username": username, "display_name": "load", "password": password}) - auth = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode() - _, _, session = http("POST", "/auth/sessions", headers={"Authorization": auth}) - headers = {"Authorization": "Bearer " + session["token"]} - _, _, chat = http("POST", "/chats", {"title": "incident load", "member_ids": [user["id"]]}, headers) - return {"headers": headers, "chat": chat["id"]} - - -class Load: - """Background traffic; per-second client-side outcome counts (status classes, timeouts).""" - - def __init__(self, writers: int = 4, write_interval: float = 0.5, upload_interval: float = 2.0): - self.actors = [new_actor() for _ in range(writers + 1)] - self.write_interval, self.upload_interval = write_interval, upload_interval - self.stop = threading.Event() - self.lock = threading.Lock() - self.events: list[tuple[float, str, int, float]] = [] # (time, kind, status, latency) - self.uploads: list[tuple[float, str]] = [] # (accepted at, attachment id) - self.threads = [threading.Thread(target=self.writer, args=(a,), daemon=True) for a in self.actors[:-1]] - self.threads.append(threading.Thread(target=self.uploader, args=(self.actors[-1],), daemon=True)) - - def record(self, kind: str, status: int, began: float) -> None: - with self.lock: - self.events.append((time.time(), kind, status, time.perf_counter() - began)) - - def writer(self, actor: dict) -> None: - while not self.stop.is_set(): - began = time.perf_counter() - try: - status, _, _ = http("POST", f"/chats/{actor['chat']}/messages", {"text": "load"}, - {**actor["headers"], "Idempotency-Key": uuid.uuid4().hex}, timeout=10) - except Exception: # noqa: BLE001 - timeout / connection error - status = 0 - self.record("message", status, began) - self.stop.wait(max(0.0, self.write_interval - (time.perf_counter() - began))) - - def uploader(self, actor: dict) -> None: - while not self.stop.is_set(): - began = time.perf_counter() - try: - status, _, body = http("POST", f"/chats/{actor['chat']}/attachments?filename=load.png", raw=SAMPLE, - headers={**actor["headers"], "Content-Type": "image/png"}, timeout=15) - if status == 202: - with self.lock: - self.uploads.append((time.time(), body["id"])) - except Exception: # noqa: BLE001 - status = 0 - self.record("upload", status, began) - self.stop.wait(max(0.0, self.upload_interval - (time.perf_counter() - began))) - - def __enter__(self): - for t in self.threads: - t.start() - return self - - def __exit__(self, *exc): - self.stop.set() - for t in self.threads: - t.join(20) - - def summary(self, start: float, end: float) -> dict: - with self.lock: - ev = [e for e in self.events if start <= e[0] < end] - out = {} - for kind in ("message", "upload"): - rows = [e for e in ev if e[1] == kind] - lat = sorted(e[3] for e in rows if 200 <= e[2] < 300) - out[kind] = {"total": len(rows), - "2xx": sum(200 <= e[2] < 300 for e in rows), "4xx": sum(400 <= e[2] < 500 for e in rows), - "5xx": sum(e[2] >= 500 for e in rows), "no_response": sum(e[2] == 0 for e in rows), - "p50_ms": _pct(lat, 0.50), "p95_ms": _pct(lat, 0.95), "p99_ms": _pct(lat, 0.99)} - return out - - -def _pct(values: list[float], q: float): - if not values: - return None - return round(values[min(len(values) - 1, int(q * len(values)))] * 1000, 1) - - -# ----------------------------------------------------------------------------- stand control -def compose(*args: str, timeout: float = 180) -> str: - return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", - timeout=timeout, check=True).stdout - - -def docker_mem(service: str) -> float | None: - """Current memory (MiB) of a compose service's first container, from `docker stats`.""" - ids = compose("ps", "-q", service).split() - if not ids: - return None - raw = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", ids[0]], - capture_output=True, text=True).stdout.split("/")[0].strip() - num = float("".join(c for c in raw if c.isdigit() or c == ".")) - return round(num / 1024 if raw.endswith("KiB") else num * 1024 if raw.endswith("GiB") else num, 1) - - -class Timeline: - def __init__(self, name: str): - self.name = name - self.t0 = time.time() - self.rows: list[dict] = [] - self.lines: list[str] = [] - - def mark(self, what: str, **data) -> float: - now = time.time() - self.rows.append({"t": round(now - self.t0, 1), "event": what, **data}) - line = f"+{now - self.t0:7.1f} s {what}" + (f" {json.dumps(data, ensure_ascii=False)}" if data else "") - print(line, flush=True) - self.lines.append(line) - return now - - -def wait_alert(tl: Timeline, alert: str, state: str, since: float, timeout: float) -> float | None: - """Poll Prometheus every 2 s; returns seconds from `since` to the alert reaching `state`.""" - deadline = time.time() + timeout - last = None - while time.time() < deadline: - current = obs.alert_state(alert) - if current != last: - tl.mark(f"alert {alert}: {current}") - last = current - if (state == "resolved" and current == "inactive") or current == state: - return round(time.time() - since, 1) - time.sleep(2) - tl.mark(f"alert {alert}: still {last} after {timeout} s") - return None - - -def wait_quiet(tl: Timeline, timeout: float = 420) -> None: - """Start every incident from a calm stand: no alert pending/firing (a previous incident's alert - would otherwise make the detection time look like 0 s).""" - deadline = time.time() + timeout - while time.time() < deadline: - active = [a["name"] for a in obs.alerts()] - if not active: - tl.mark("stand quiet: no pending/firing alerts") - return - time.sleep(5) - raise SystemExit(f"alerts still active after {timeout} s: {active}") - - -def snapshot(queries: dict[str, str]) -> dict: - out = {} - for name, expr in queries.items(): - try: - value = obs.scalar(expr) - out[name] = None if value is None else round(value, 4) - except Exception as exc: # noqa: BLE001 - out[name] = f"error: {type(exc).__name__}" - return out - - -Q_API = { - "rps": "messenger:http_requests:rate1m", - "error_ratio_5xx": "messenger:http_error_ratio:rate1m", - "p99_s": "messenger:http_latency:p99_2m", - "db_p95_s_api": 'histogram_quantile(0.95, sum by (le) (rate(db_client_operation_duration_seconds_bucket{job="messenger-api"}[1m])))', - "db_pool_waiting_api": 'sum(db_client_connection_pending_requests{job="messenger-api"})', - "db_pool_used_api": 'sum(db_client_connection_count{job="messenger-api", db_client_connection_state="used"})', -} -Q_QUEUE = { - "queued": 'max(messenger_queue_depth{state="queued"})', - "oldest_age_s": "max(messenger_queue_oldest_age_seconds)", - "jobs_succeeded_per_s": 'sum(rate(messenger_jobs_processed_total{outcome="succeeded"}[1m]))', - "worker_busy": "sum(messenger_worker_busy)", - "time_to_ready_p95_s": 'histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[2m])))', -} -Q_COLLECTOR = { - "collector_rss_mib": "otelcol_process_memory_rss / 1048576", - "spans_accepted_per_s": "sum(rate(otelcol_receiver_accepted_spans[1m]))", - "spans_failed_total": "sum(otelcol_exporter_send_failed_spans) or vector(0)", - "logs_failed_total": "sum(otelcol_exporter_send_failed_log_records) or vector(0)", - "queue_size_tempo": 'max(otelcol_exporter_queue_size{exporter="otlp_http/tempo"})', - "queue_capacity_tempo": 'max(otelcol_exporter_queue_capacity{exporter="otlp_http/tempo"})', - "sdk_export_failures_total": 'sum(messenger_telemetry_spans_exported_total{result="failure"}) or vector(0)', -} - - -# ----------------------------------------------------------------------------- incidents -def worker_stop(tl: Timeline, load: Load) -> dict: - """(1) The worker is stopped: uploads still get 202, nothing is processed. Expected: queue - depth and the oldest job age grow -> MessengerQueueLagGrowing firing; after the start the - backlog drains -> resolved. HTTP SLIs stay green (the API does not depend on the worker).""" - time.sleep(30) - result = {"before": {**snapshot(Q_API), **snapshot(Q_QUEUE)}} - start = tl.mark("FAULT: docker compose stop worker") - compose("stop", "worker") - try: - result["detect_s"] = wait_alert(tl, "MessengerQueueLagGrowing", "firing", start, 240) - result["during"] = {**snapshot(Q_API), **snapshot(Q_QUEUE)} - result["during_client"] = load.summary(start, time.time()) - tl.mark("observed during", **result["during"]) - finally: - fixed = tl.mark("FIX: docker compose start worker") - compose("start", "worker") - result["resolve_s"] = wait_alert(tl, "MessengerQueueLagGrowing", "resolved", fixed, 300) - result["after"] = {**snapshot(Q_API), **snapshot(Q_QUEUE)} - tl.mark("observed after", **result["after"]) - result["client_total"] = load.summary(tl.t0, time.time()) - return result - - -def db_lock(tl: Timeline, load: Load) -> dict: - """(2a) A long transaction holds an EXCLUSIVE lock on `messages` for 150 s (an "ALTER TABLE"/ - migration-like incident). Message writes wait for the lock until lock_timeout and answer 503; - reads keep working. Expected: 5xx ratio and p99 grow, DB pool waits; the trace of a failed - POST shows the time inside the `db ...` span (error LockNotAvailable), not in handler code.""" - time.sleep(30) - result = {"before": snapshot(Q_API)} - sql = "BEGIN; LOCK TABLE messages IN EXCLUSIVE MODE; SELECT pg_sleep(150); COMMIT;" - start = tl.mark("FAULT: psql holds LOCK TABLE messages IN EXCLUSIVE MODE for 150 s") - locker = subprocess.Popen(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", - "-c", sql], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - try: - result["detect_error_s"] = wait_alert(tl, "MessengerApiHighErrorRate", "firing", start, 140) - result["during"] = snapshot(Q_API) - tl.mark("observed during", **result["during"]) - result["during_client"] = load.summary(start, time.time()) - result["example_trace"] = example_trace('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && status = error }') - result["pg_locks"] = subprocess.run( - ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", - "SELECT state, wait_event_type, wait_event, count(*), max(now() - xact_start)::text " - "FROM pg_stat_activity WHERE datname = 'messenger' AND state <> 'idle' GROUP BY 1, 2, 3"], - cwd=ROOT, capture_output=True, text=True, encoding="utf-8").stdout.strip().splitlines() - tl.mark("pg_stat_activity lock waits", waits=result["pg_locks"]) - finally: - locker.wait(200) - fixed = tl.mark("FIX: lock released (transaction ended)") - result["resolve_s"] = wait_alert(tl, "MessengerApiHighErrorRate", "resolved", fixed, 240) - result["after"] = snapshot(Q_API) - result["client_total"] = load.summary(tl.t0, time.time()) - return result - - -def slow_handler(tl: Timeline, load: Load) -> dict: - """(2b) Contrast to (2a): API_FAULT_POINTS=slow_handler=1500 - 1.5 s of handler code before the - database call in POST messages, database healthy. Expected: p99 > 1 s -> MessengerApiLatencyHigh, - NO 5xx, DB p95 unchanged; the trace shows a 1.5 s server span whose `db` child is a few ms.""" - time.sleep(30) - result = {"before": snapshot(Q_API)} - env = {**os.environ, "API_FAULT_POINTS": "slow_handler=1500"} - start = tl.mark("FAULT: api recreated with API_FAULT_POINTS=slow_handler=1500") - subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--wait", "api"], cwd=ROOT, env=env, - capture_output=True, check=True, timeout=180) - try: - result["detect_s"] = wait_alert(tl, "MessengerApiLatencyHigh", "firing", start, 300) - result["during"] = snapshot(Q_API) - tl.mark("observed during", **result["during"]) - result["during_client"] = load.summary(start, time.time()) - result["example_trace"] = example_trace('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && duration > 1s }') - finally: - fixed = tl.mark("FIX: api recreated without fault points") - clean = {k: v for k, v in os.environ.items() if k != "API_FAULT_POINTS"} - subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--wait", "api"], cwd=ROOT, env=clean, - capture_output=True, check=True, timeout=180) - result["resolve_s"] = wait_alert(tl, "MessengerApiLatencyHigh", "resolved", fixed, 300) - result["after"] = snapshot(Q_API) - result["client_total"] = load.summary(tl.t0, time.time()) - return result - - -def backend_down(tl: Timeline, load: Load) -> dict: - """(3a) Tempo and Loki stopped for ~4 min. Expected: API/worker unaffected (client counts), the - Collector retries into a BOUNDED queue (size <= capacity), then drops and counts - (send_failed), its RSS stays under the memory_limiter; TelemetryExportFailing fires.""" - time.sleep(20) - result = {"before": {**snapshot(Q_API), **snapshot(Q_COLLECTOR)}, "collector_mem_mib": []} - start = tl.mark("FAULT: docker compose stop tempo loki") - compose("stop", "tempo", "loki") - try: - # failures appear only after the exporter gave up (retry max_elapsed_time 60 s), then the - # 2 min rate window and `for: 30s`: 120-190 s were measured, so wait up to 240 s. - result["detect_s"] = wait_alert(tl, "TelemetryExportFailing", "firing", start, 240) - while time.time() - start < 250: - result["collector_mem_mib"].append(docker_mem("otel-collector")) - time.sleep(10) - result["during"] = {**snapshot(Q_API), **snapshot(Q_COLLECTOR)} - tl.mark("observed during", **result["during"], collector_mem_mib=result["collector_mem_mib"]) - result["during_client"] = load.summary(start, time.time()) - finally: - fixed = tl.mark("FIX: docker compose start tempo loki") - compose("start", "tempo", "loki") - result["resolve_s"] = wait_alert(tl, "TelemetryExportFailing", "resolved", fixed, 300) - result["after"] = {**snapshot(Q_API), **snapshot(Q_COLLECTOR)} - result["client_total"] = load.summary(tl.t0, time.time()) - return result - - -def collector_down(tl: Timeline, load: Load) -> dict: - """(3b) The Collector itself stopped for 2 min. Expected: API unaffected; the SDK exporters fail - fast (3 s timeout) in their background threads, BatchSpanProcessor drops beyond 2048 queued - spans, API memory flat. Counted afterwards: messenger_telemetry_spans_exported_total{result=failure} - (cumulative, delivered once the Collector is back). Metrics of the outage window are missing: - a gap in the graphs, not a lie.""" - time.sleep(20) - api_mem = [] - result = {"before": {**snapshot(Q_API), **snapshot(Q_COLLECTOR)}} - start = tl.mark("FAULT: docker compose stop otel-collector") - compose("stop", "otel-collector") - try: - while time.time() - start < 120: - api_mem.append(docker_mem("api")) - time.sleep(10) - result["api_mem_mib"] = api_mem - result["during_client"] = load.summary(start, time.time()) - tl.mark("client during outage", **result["during_client"]["message"], api_mem_mib=api_mem) - finally: - tl.mark("FIX: docker compose start otel-collector") - compose("start", "otel-collector") - time.sleep(45) - result["after"] = {**snapshot(Q_API), **snapshot(Q_COLLECTOR)} - tl.mark("observed after", **result["after"]) - result["client_total"] = load.summary(tl.t0, time.time()) - return result - - -def example_trace(traceql: str) -> dict | None: - """First matching trace: its span tree as text (the diagnosis evidence).""" - time.sleep(8) - found = obs.search(traceql, minutes=5, limit=5) - if not found: - return None - trace_id = found[0]["traceID"] - return {"traceql": traceql, "trace_id": trace_id, "tree": obs.tree(obs.trace_spans(trace_id)).splitlines()} - - -INCIDENTS = {"worker-stop": worker_stop, "db-lock": db_lock, "slow-handler": slow_handler, - "backend-down": backend_down, "collector-down": collector_down} - - -def run(name: str) -> dict: - print(f"\n=== incident {name}") - tl = Timeline(name) - wait_quiet(tl) - with Load() as load: - tl.mark("load started (4 writers x 2 req/s, 1 upload / 2 s)") - result = INCIDENTS[name](tl, load) - result.update({"incident": name, "timeline": tl.rows, "doc": INCIDENTS[name].__doc__.strip()}) - OUT.mkdir(parents=True, exist_ok=True) - (OUT / f"{name}.json").write_text(json.dumps(result, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") - text = [f"incident {name}: {time.strftime('%Y-%m-%d %H:%M:%S')}", INCIDENTS[name].__doc__.strip(), "", *tl.lines, ""] - for key in ("detect_s", "detect_error_s", "resolve_s"): - if key in result: - text.append(f"{key}: {result[key]}") - for key in ("before", "during", "after", "during_client", "client_total"): - if key in result: - text.append(f"{key}: {json.dumps(result[key], ensure_ascii=False)}") - if result.get("example_trace"): - text += ["", f"example trace ({result['example_trace']['traceql']}):", *result["example_trace"]["tree"]] - (OUT / f"{name}.txt").write_text("\n".join(text) + "\n", encoding="utf-8", newline="\n") - return result - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("incident", choices=[*INCIDENTS, "all"]) - args = parser.parse_args() - for name in (INCIDENTS if args.incident == "all" else [args.incident]): - run(name) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/bench/loadgen.py b/bench/loadgen.py deleted file mode 100644 index 97a94de..0000000 --- a/bench/loadgen.py +++ /dev/null @@ -1,212 +0,0 @@ -#!/usr/bin/env python3 -"""Background HTTP traffic through the LB for failover / rolling-update experiments (level 4). - -Closed loop, N worker threads, each: POST a message (Idempotency-Key) + GET the last page. -An uncertain POST (timeout, connection error, 5xx) is retried with the SAME key and body, -exactly as a correct client must do; the history is checked afterwards for losses and -duplicates. Every request is recorded as (t, kind, status, instance, latency). -This is a correctness/availability probe, not a capacity benchmark (see bench/track1 for that). - - python bench/loadgen.py --duration 30 --workers 4 # prints a summary JSON -""" -from __future__ import annotations - -import argparse -import base64 -import json -import math -import os -import threading -import time -import uuid -from collections import Counter, defaultdict - -import urllib.error -import urllib.request - -BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") - - -class Http: - """Minimal stdlib client with keep-alive per thread (http.client under urllib is not).""" - - def __init__(self, base_url: str, timeout: float): - import http.client - from urllib.parse import urlsplit - parts = urlsplit(base_url) - self.host, self.port = parts.hostname, parts.port or 80 - self.timeout = timeout - self.factory = lambda: http.client.HTTPConnection(self.host, self.port, timeout=self.timeout) - self.conn = self.factory() - - def request(self, method: str, path: str, body: bytes | None = None, headers: dict | None = None): - try: - self.conn.request(method, path, body=body, headers=headers or {}) - response = self.conn.getresponse() - data = response.read() - if response.getheader("connection", "").lower() == "close": - self.conn.close() - self.conn = self.factory() - return response.status, dict(response.getheaders()), data - except Exception: - self.conn.close() - self.conn = self.factory() - raise - - -def call(method: str, path: str, body=None, headers=None, timeout=10.0): - data = json.dumps(body).encode() if body is not None else None - h = {"Content-Type": "application/json", **(headers or {})} - req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method) - try: - with urllib.request.urlopen(req, timeout=timeout) as r: - return r.status, json.loads(r.read() or b"null") - except urllib.error.HTTPError as e: - return e.code, json.loads(e.read() or b"null") - - -def make_user(label: str) -> dict: - username = f"{label}_{uuid.uuid4().hex[:12]}" - password = "Load-password-" + uuid.uuid4().hex - status, user = call("POST", "/api/v1/users", {"username": username, "display_name": label, "password": password}) - assert status == 201, (status, user) - cred = base64.b64encode(f"{username}:{password}".encode()).decode() - status, session = call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}) - assert status == 201, (status, session) - return {"id": user["id"], "token": session["token"]} - - -class Load: - def __init__(self, workers: int = 4, timeout: float = 3.0, pause: float = 0.0): - self.workers = workers - self.timeout = timeout - self.pause = pause - self.alice, self.bob = make_user("load"), make_user("load") - status, chat = call("POST", "/api/v1/chats", {"title": "load", "member_ids": [self.alice["id"], self.bob["id"]]}, - headers={"Authorization": "Bearer " + self.alice["token"]}) - assert status == 201, chat - self.chat = chat - self.stop_event = threading.Event() - self.lock = threading.Lock() - self.events: list[tuple[float, str, int, str, float]] = [] - self.confirmed: dict[str, dict] = {} - self.retries = 0 - self.t0 = time.monotonic() - self.threads = [threading.Thread(target=self._worker, args=(i,), daemon=True) for i in range(workers)] - - def now(self) -> float: - return time.monotonic() - self.t0 - - def _record(self, kind: str, status: int, instance: str, latency: float) -> None: - with self.lock: - self.events.append((round(self.now(), 4), kind, status, instance, round(latency * 1000, 2))) - - def _worker(self, index: int) -> None: - http = Http(BASE_URL, self.timeout) - auth = {"Authorization": "Bearer " + self.alice["token"]} - path = f"/api/v1/chats/{self.chat['id']}/messages" - n, key = 0, uuid.uuid4().hex - text = f"w{index}-0-{key[:6]}" - while not self.stop_event.is_set(): - started = time.monotonic() - try: - status, headers, data = http.request("POST", path, json.dumps({"text": text}).encode(), - {**auth, "Idempotency-Key": key, "Content-Type": "application/json"}) - instance = headers.get("x-instance-id") or headers.get("X-Instance-Id") or "-" - except Exception: - status, instance, data = 0, "-", b"" - self._record("POST", status, instance, time.monotonic() - started) - if status == 201: - msg = json.loads(data) - with self.lock: - self.confirmed[msg["id"]] = msg - n += 1 - key = uuid.uuid4().hex - text = f"w{index}-{n}-{key[:6]}" - elif status in (0, 502, 503, 504, 500): - with self.lock: - self.retries += 1 # same key + same text on the next iteration - started = time.monotonic() - try: - status, headers, _ = http.request("GET", path + "?limit=5", None, auth) - instance = headers.get("x-instance-id") or headers.get("X-Instance-Id") or "-" - except Exception: - status, instance = 0, "-" - self._record("GET", status, instance, time.monotonic() - started) - if self.pause: - time.sleep(self.pause) - - def start(self) -> "Load": - self.t0 = time.monotonic() - for t in self.threads: - t.start() - return self - - def stop(self) -> None: - self.stop_event.set() - for t in self.threads: - t.join(timeout=15) - - def verify_history(self) -> dict: - """Walk the whole history with the second user: no confirmed message lost, no duplicate.""" - items, cursor = [], None - while True: - q = "?limit=100" + (f"&cursor={cursor}" if cursor else "") - status, page = call("GET", f"/api/v1/chats/{self.chat['id']}/messages{q}", - headers={"Authorization": "Bearer " + self.bob["token"]}, timeout=30) - assert status == 200, page - items += page["items"] - cursor = page["next_cursor"] - if not cursor: - break - ids = [m["id"] for m in items] - texts = [m["text"] for m in items] - lost = [i for i in self.confirmed if i not in set(ids)] - changed = [m for m in items if m["id"] in self.confirmed and self.confirmed[m["id"]] != m] - return {"history_messages": len(items), "confirmed_messages": len(self.confirmed), - "lost_confirmed": len(lost), "altered_confirmed": len(changed), - "duplicate_ids": len(ids) - len(set(ids)), "duplicate_texts": len(texts) - len(set(texts)), - "unconfirmed_but_stored": len(set(ids) - set(self.confirmed))} - - # ------------------------------------------------------------------ summaries - def window(self, start: float, end: float) -> dict: - ev = [e for e in self.events if start <= e[0] < end] - ok = [e for e in ev if e[2] in (200, 201)] - lat = sorted(e[4] for e in ok) - - def pct(p: float): - return lat[max(0, math.ceil(p * len(lat)) - 1)] if lat else None - span = max(end - start, 1e-9) - return {"seconds": round(span, 2), "requests": len(ev), "ok": len(ok), "failed": len(ev) - len(ok), - "ok_rps": round(len(ok) / span, 1), "error_ratio": round((len(ev) - len(ok)) / len(ev), 5) if ev else None, - "statuses": dict(Counter(e[2] for e in ev)), "instances": dict(Counter(e[3] for e in ok)), - "p50_ms": pct(.5), "p95_ms": pct(.95), "p99_ms": pct(.99)} - - def per_second(self) -> list[dict]: - buckets: dict[int, list] = defaultdict(list) - for e in self.events: - buckets[int(e[0])].append(e) - rows = [] - for second in sorted(buckets): - ev = buckets[second] - rows.append({"second": second, "ok": sum(1 for e in ev if e[2] in (200, 201)), - "failed": sum(1 for e in ev if e[2] not in (200, 201)), - "instances": "|".join(f"{k}:{v}" for k, v in sorted(Counter(e[3] for e in ev).items()))}) - return rows - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - parser.add_argument("--duration", type=float, default=20) - parser.add_argument("--workers", type=int, default=4) - args = parser.parse_args() - load = Load(args.workers).start() - time.sleep(args.duration) - load.stop() - print(json.dumps({"total": load.window(0, load.now()), "history": load.verify_history(), - "client_retries_same_key": load.retries}, ensure_ascii=False, indent=2)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/bench/pipeline_faults.py b/bench/pipeline_faults.py deleted file mode 100644 index ea225a7..0000000 --- a/bench/pipeline_faults.py +++ /dev/null @@ -1,309 +0,0 @@ -#!/usr/bin/env python3 -"""Track 2 experiment: proven idempotency of the versioned pipeline under injected faults. - -Hypothesis. With at-least-once delivery, duplicated and reordered messages, crashes of the worker -before/after its side effects and stale jobs of an older pipeline version: - H1 no accepted (202) work is lost - every upload ends ready (or failed with a code, never stuck); - H2 every effect (attachment, pipeline_version, variant) is published exactly once - one set of - variant rows written by ONE successful attempt, one set of objects in the bucket; - H3 the published version only grows - an older job never overwrites a newer result, `ready` - never goes back to queued/processing; - H4 objects of interrupted attempts are garbage that the cleanup removes; nothing published is - ever deleted. - -Method. For every scenario the affected service (relay/worker) is recreated with FAULT_POINTS of -the scenario (the real code paths, real crashes = os._exit of the process, real `docker pause`), -N uploads go through the LB, then the scenario-specific facts are read from PostgreSQL and S3 and -the read-only invariant audit (messenger.audit, I1-I7, with SHA-256 of every published object) -runs over the WHOLE stand. The normal configuration is restored after each scenario. - - python bench/pipeline_faults.py --output evidence/track2 [--uploads 5] -""" -from __future__ import annotations - -import argparse -import datetime as dt -import json -import platform -import statistics -import subprocess -import sys -import time -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "student-tests")) -import imagegen # noqa: E402 -from conftest import (Api, attachment_row, compose, events_of, jobctl, psql, s3_keys, service_with_env, # noqa: E402 - wait_healthy) - -FAST = {"JOB_LEASE_SECONDS": "6", "ORPHAN_GRACE_SECONDS": "3", "CLEANUP_INTERVAL_SECONDS": "1"} - - -def now() -> str: - return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def wait(condition, timeout: float, what: str): - deadline = time.monotonic() + timeout - while True: - value = condition() - if value: - return value - if time.monotonic() > deadline: - raise AssertionError(what) - time.sleep(0.5) - - -def facts(attachment_id: str, objects: set[str]) -> dict: - row = attachment_row(attachment_id) - out = psql("SELECT json_build_object(" - "'claims', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id WHERE j.attachment_id = '{0}'), " - "'succeeded_attempts', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id " - " WHERE j.attachment_id = '{0}' AND a.outcome = 'succeeded'), " - "'variant_rows', (SELECT count(*) FROM attachment_variants WHERE attachment_id = '{0}'), " - "'versions', (SELECT coalesce(json_agg(DISTINCT pipeline_version), '[]') FROM attachment_variants " - " WHERE attachment_id = '{0}'), " - "'job_states', (SELECT coalesce(json_agg(state || ':v' || pipeline_version ORDER BY created_at), '[]') " - " FROM jobs WHERE attachment_id = '{0}'), " - "'uncleaned_failed_attempts', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id " - " WHERE j.attachment_id = '{0}' AND a.outcome <> 'succeeded' AND a.objects_cleaned_at IS NULL))" - .format(attachment_id)) - f = json.loads(out) - f.update(status=row["status"], published_version=row["published_version"], staging_state=row["staging_state"], - objects=len([k for k in objects if k.startswith(f"a/{attachment_id}/")])) - f["events"] = [e["event"] for e in events_of(attachment_id)] - return f - - -def audit() -> dict: - r = compose("run", "--rm", "--no-deps", "-T", "auditor", "--verify-checksums", check=False, timeout=600) - report = json.loads(r.stdout) - return {"ok": report["ok"], "violations": report["violations"], "notes": len(report["notes"]), - "objects": report["objects"]} - - -class Run: - def __init__(self, api: Api, uploads: int): - self.api = api - self.n = uploads - self.alice, self.bob = api.user("t2a"), api.user("t2b") - self.chat = api.chat(self.alice, self.bob) - - def upload_many(self, n: int | None = None) -> list[dict]: - return [self.api.upload(self.alice, self.chat, imagegen.png(60 + i, 40, noise=True)).json() - for i in range(n or self.n)] - - def finish(self, atts: list[dict], timeout: float = 180) -> tuple[list[dict], list[float]]: - started = time.monotonic() - took = [] - for a in atts: - self.api.wait_status(self.bob, a["id"], timeout=timeout) - took.append(round(time.monotonic() - started, 2)) - return atts, took - - -def expect_one_effect(f: dict, version: int = 1) -> list[str]: - """H1 + H2 for a plain upload of pipeline `version`.""" - problems = [] - if f["status"] != "ready": - problems.append(f"status {f['status']}") - if f["succeeded_attempts"] != 1 or f["variant_rows"] != 3 or f["published_version"] != version: - problems.append(f"effect {f['succeeded_attempts']} attempts/{f['variant_rows']} rows/v{f['published_version']}") - if f["objects"] != 4: # original + thumbnail + crop + optimized, cleanup done - problems.append(f"{f['objects']} objects in the bucket") - return problems - - -def plain_scenario(run: Run, name: str, service: str, env: dict, *, scale: int | None = None, - cleanup_wait: bool = True) -> dict: - with service_with_env(service, scale=scale, **env): - atts, took = run.finish(run.upload_many()) - if cleanup_wait: # garbage of interrupted attempts: cleaned after ORPHAN_GRACE_SECONDS - try: - wait(lambda: all(json.loads(psql( - "SELECT json_build_object('n', count(*)) FROM job_attempts a JOIN jobs j ON j.id = a.job_id " - f"WHERE j.attachment_id = '{a['id']}' AND a.outcome <> 'succeeded' " - "AND a.objects_cleaned_at IS NULL"))["n"] == 0 for a in atts), 60, "cleanup") - except AssertionError: - pass # reported below as uncleaned attempts - objects = s3_keys("a/") - per = [facts(a["id"], objects) for a in atts] - problems = {a["id"]: p for a, f in zip(atts, per) if (p := expect_one_effect(f))} - return {"scenario": name, "faults": {service: env}, "uploads": len(atts), - "ready": sum(f["status"] == "ready" for f in per), "claims_total": sum(f["claims"] for f in per), - "max_claims": max(f["claims"] for f in per), "time_to_ready_s": {"p50": statistics.median(took), - "max": max(took)}, - "event_sequences": sorted({" > ".join(f["events"]) for f in per}), "problems": problems} - - -def versions_scenario(run: Run) -> dict: - """Stale job after a newer version: v2 (slow) and v3 run at the same time; v3 publishes first, - v2 finishes later and must end superseded without touching the published v3 result.""" - att = run.upload_many(1)[0] - run.api.wait_status(run.bob, att["id"], "ready") - observed = set() - with service_with_env("worker", WORKER_FAULT_POINTS="slow=10,slow_pipeline=2"): - jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "track2", "--reason", "new encoder") - wait(lambda: "processing:v2" in facts(att["id"], set())["job_states"], 60, "v2 not claimed") - jobctl("reprocess", att["id"], "--pipeline", "3", "--operator", "track2", "--reason", "newer encoder") - deadline = time.monotonic() + 120 - while time.monotonic() < deadline: - meta = run.api.attachment(run.bob, att["id"]) - observed.add(meta["status"]) - states = facts(att["id"], set())["job_states"] - if not any(s.startswith(("queued", "processing")) for s in states): - break - time.sleep(0.3) - final = run.api.attachment(run.bob, att["id"]) - f = facts(att["id"], s3_keys("a/")) - thumb_v3 = psql(f"SELECT encode(sha256, 'hex') FROM attachment_variants WHERE attachment_id = '{att['id']}' " - "AND pipeline_version = 3 AND name = 'thumbnail'") - problems = [] - if f["job_states"] != ["succeeded:v1", "superseded:v2", "succeeded:v3"]: - problems.append(f"job states {f['job_states']}") - if f["published_version"] != 3 or observed != {"ready"}: - problems.append(f"published v{f['published_version']}, statuses seen {sorted(observed)}") - if next(v["sha256"] for v in final["variants"] if v["name"] == "thumbnail") != thumb_v3: - problems.append("published thumbnail is not the v3 one") - # Stale duplicate of the FIRST job, published by hand with the relay's broker user: a no-op. - job_v1 = psql(f"SELECT id FROM jobs WHERE attachment_id = '{att['id']}' AND pipeline_version = 1") - script = ("import asyncio, aio_pika, datetime as d\n" - "from messenger import broker\n" - "async def m():\n" - " c = await aio_pika.connect(open('/run/secrets/broker_url').read().strip())\n" - " ch = await c.channel(publisher_confirms=True)\n" - " ex = await ch.get_exchange(broker.EXCHANGE, ensure=False)\n" - f" body = broker.encode('{job_v1}', '{att['id']}', 1, 1, d.datetime.now(d.timezone.utc))\n" - " await ex.publish(aio_pika.Message(body), routing_key=broker.ROUTING_KEY)\n" - " await c.close()\n" - "asyncio.run(m())\n") - compose("exec", "-T", "relay", "python", "-c", script) - time.sleep(3) - after = run.api.attachment(run.bob, att["id"]) - if after != final: - problems.append("stale v1 message changed the attachment") - return {"scenario": "stale_version_and_reorder", "uploads": 1, "statuses_seen_during_reprocess": sorted(observed), - "job_states": f["job_states"], "published_version": f["published_version"], - "variant_rows_by_version": f["variant_rows"], "objects": f["objects"], - "events": f["events"], "problems": problems} - - -def queued_reorder_scenario(run: Run) -> dict: - """Both newer versions wait in the outbox; the relay publishes them in REVERSE order and one worker - takes them one by one: v3 is published first, v2 is then superseded at its claim (no work).""" - att = run.upload_many(1)[0] - run.api.wait_status(run.bob, att["id"], "ready") - # The worker stays stopped until it is recreated with concurrency 1 (no normal start in between). - # Worker and relay stay stopped until each is recreated with the scenario's settings: no normal - # start in between that would consume/publish the jobs in the ordinary order. - compose("stop", "worker", "relay") - try: - jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "track2", "--reason", "v2") - jobctl("reprocess", att["id"], "--pipeline", "3", "--operator", "track2", "--reason", "v3") - with service_with_env("relay", RELAY_FAULT_POINTS="reverse_order"): - wait(lambda: psql("SELECT count(*) FROM outbox o JOIN jobs j ON j.id = o.job_id WHERE j.attachment_id = " - f"'{att['id']}' AND j.pipeline_version > 1 AND o.published_at IS NOT NULL") == "2", - 30, "both reprocess jobs not published") # in one relay batch: v3 first, then v2 - with service_with_env("worker", WORKER_CONCURRENCY="1"): - wait(lambda: not any(s.startswith(("queued", "processing")) - for s in facts(att["id"], set())["job_states"]), 120, "reprocess jobs did not finish") - finally: - compose("start", "worker", "relay") - wait_healthy("worker", "relay") - f = facts(att["id"], s3_keys("a/")) - problems = [] - if f["job_states"] != ["succeeded:v1", "superseded:v2", "succeeded:v3"] or f["published_version"] != 3: - problems.append(f"{f['job_states']} published v{f['published_version']}") - if f["claims"] != 2: # v1 and v3 only: v2 was superseded before any work - problems.append(f"{f['claims']} claims") - return {"scenario": "reordered_versions_in_queue", "job_states": f["job_states"], "claims": f["claims"], - "published_version": f["published_version"], "events": f["events"], "problems": problems} - - -def hung_worker_scenario(run: Run) -> dict: - with service_with_env("worker", scale=2, WORKER_FAULT_POINTS="slow=8", **FAST): - att = run.upload_many(1)[0] - owner = wait(lambda: psql(f"SELECT lease_owner FROM jobs WHERE attachment_id = '{att['id']}' " - "AND state = 'processing'"), 30, "not claimed") - ids = compose("ps", "-q", "worker").stdout.split() - names = dict(line.split() for line in subprocess.run( - ["docker", "inspect", "-f", "{{.Config.Hostname}} {{.Id}}", *ids], capture_output=True, text=True, - check=True).stdout.splitlines()) - subprocess.run(["docker", "pause", names[owner]], check=True) - try: - run.api.wait_status(run.bob, att["id"], "ready", timeout=150) - published = psql(f"SELECT string_agg(object_key, ',' ORDER BY object_key) FROM attachment_variants " - f"WHERE attachment_id = '{att['id']}'") - finally: - subprocess.run(["docker", "unpause", names[owner]], check=True) - time.sleep(15) - again = psql(f"SELECT string_agg(object_key, ',' ORDER BY object_key) FROM attachment_variants " - f"WHERE attachment_id = '{att['id']}'") - wait(lambda: json.loads(psql("SELECT json_build_object('n', count(*)) FROM job_attempts a JOIN jobs j " - f"ON j.id = a.job_id WHERE j.attachment_id = '{att['id']}' AND a.outcome <> " - "'succeeded' AND a.objects_cleaned_at IS NULL"))["n"] == 0, 60, "cleanup") - f = facts(att["id"], s3_keys("a/")) - problems = expect_one_effect(f) - if published != again: - problems.append("the resumed (fenced) attempt changed the published result") - return {"scenario": "hung_worker_docker_pause", "frozen": owner, "claims": f["claims"], "events": f["events"], - "problems": problems} - - -def main() -> int: - p = argparse.ArgumentParser() - p.add_argument("--output", default="evidence/track2") - p.add_argument("--uploads", type=int, default=5) - args = p.parse_args() - out = ROOT / args.output - out.mkdir(parents=True, exist_ok=True) - api = Api() - run = Run(api, args.uploads) - started = now() - results = [] - plan = [ - ("baseline_no_faults", "worker", {}), - ("duplicate_publish", "relay", {"RELAY_FAULT_POINTS": "duplicate_publish"}), - ("duplicate_and_reverse_order", "relay", {"RELAY_FAULT_POINTS": "duplicate_publish,reverse_order"}), - ("relay_crash_after_confirm_before_mark", "relay", {"RELAY_FAULT_POINTS": "crash_after_publish"}), - ("worker_crash_before_side_effect", "worker", {"WORKER_FAULT_POINTS": "crash_after_claim", **FAST}), - ("worker_crash_after_s3_before_commit", "worker", {"WORKER_FAULT_POINTS": "crash_after_s3_write", **FAST}), - ("worker_crash_after_commit_before_ack", "worker", {"WORKER_FAULT_POINTS": "crash_after_commit", **FAST}), - ("transient_errors_then_success", "worker", {"WORKER_FAULT_POINTS": "transient_error=2", - "JOB_RETRY_BASE_SECONDS": "0.5", **FAST}), - ] - for name, service, env in plan: - print(f"[{now()}] {name}", flush=True) - results.append(plain_scenario(run, name, service, env)) - print(f"[{now()}] two_workers_duplicate_publish", flush=True) - with service_with_env("relay", RELAY_FAULT_POINTS="duplicate_publish"): - results.append(plain_scenario(run, "two_workers_duplicate_publish", "worker", {}, scale=2)) - for scenario in (versions_scenario, queued_reorder_scenario, hung_worker_scenario): - print(f"[{now()}] {scenario.__name__}", flush=True) - results.append(scenario(run)) - wait_healthy("worker", "relay") - report = audit() - summary = { - "experiment": "track 2: idempotency of the versioned pipeline under injected faults", - "started": started, "finished": now(), - "host": {"os": platform.platform(), "python": platform.python_version()}, - "uploads_per_plain_scenario": args.uploads, - "scenarios": results, - "audit_after_all": report, - "violations": sum(len(r["problems"]) for r in results) + len(report["violations"]), - } - (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1), encoding="utf-8") - lines = [f"{'scenario':45} {'uploads':>7} {'ready':>5} {'claims':>6} problems"] - for r in results: - lines.append(f"{r['scenario']:45} {r.get('uploads', 1):>7} {r.get('ready', '-'):>5} " - f"{r.get('claims_total', r.get('claims', '-')):>6} {len(r['problems'])}") - lines.append(f"audit after all scenarios: ok={report['ok']} violations={len(report['violations'])} " - f"objects={report['objects']}") - (out / "summary.txt").write_text("\n".join(lines) + "\n", encoding="utf-8") - print("\n".join(lines)) - return 0 if summary["violations"] == 0 else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/bench/rolling_under_load.py b/bench/rolling_under_load.py deleted file mode 100644 index c4fd9ba..0000000 --- a/bench/rolling_under_load.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python3 -"""Level 4: scripts/rolling-update.sh while bench/loadgen.py traffic runs through the LB. - - python bench/rolling_under_load.py --output evidence/rolling-update - -Writes /summary.json (errors, RPS, history check, revisions before/after), -/timeline.csv (per second ok/failed/instances) and /script-output.txt. -""" -from __future__ import annotations - -import argparse -import csv -import json -import os -import subprocess -import sys -import time -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "scripts")) -sys.path.insert(0, str(ROOT / "bench")) -import lbctl # noqa: E402 -from loadgen import Load # noqa: E402 - - -def revisions() -> dict[str, str]: - result = {} - for r in lbctl.replicas(): - if r["state"] == "running": - label = subprocess.run(["docker", "inspect", "-f", '{{index .Config.Labels "org.opencontainers.image.revision"}}', - r["id"]], capture_output=True, text=True).stdout.strip() - result[r["name"]] = f"{r['hostname']} revision={label}" - return result - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - parser.add_argument("--output", default="evidence/rolling-update") - parser.add_argument("--workers", type=int, default=4) - args = parser.parse_args() - out = ROOT / args.output - out.mkdir(parents=True, exist_ok=True) - before = revisions() - load = Load(args.workers).start() - time.sleep(5) - t_begin = load.now() - bash = (os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe") - if os.name == "nt" else "sh") - env = {**os.environ, "PYTHON": sys.executable} - script = subprocess.run([bash, str(ROOT / "scripts" / "rolling-update.sh")], cwd=ROOT, env=env, - capture_output=True, text=True, encoding="utf-8", timeout=900) - t_end = load.now() - time.sleep(5) - load.stop() - (out / "script-output.txt").write_text(f"$ sh scripts/rolling-update.sh (exit {script.returncode})\n" - + script.stdout + script.stderr, encoding="utf-8") - with (out / "timeline.csv").open("w", newline="", encoding="utf-8") as f: - writer = csv.DictWriter(f, fieldnames=["second", "ok", "failed", "instances"]) - writer.writeheader() - writer.writerows(load.per_second()) - summary = {"script_exit_code": script.returncode, "update_seconds": round(t_end - t_begin, 1), - "before": before, "after": revisions(), - "during_update": load.window(t_begin, t_end), "whole_run": load.window(0, load.now()), - "client_retries_same_key": load.retries, "history": load.verify_history(), - "workload": f"{args.workers} closed-loop workers: POST (Idempotency-Key) + GET page via 127.0.0.1:8080"} - (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print(json.dumps({k: summary[k] for k in ("script_exit_code", "update_seconds", "before", "after", "history")}, - ensure_ascii=False, indent=2)) - print(json.dumps(summary["during_update"], ensure_ascii=False)) - return 0 if script.returncode == 0 else 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/bench/track1.py b/bench/track1.py deleted file mode 100644 index 81db3f9..0000000 --- a/bench/track1.py +++ /dev/null @@ -1,361 +0,0 @@ -#!/usr/bin/env python3 -"""Track 1 "the price of observability": the same load under four telemetry configurations. - - python bench/track1.py --runs 3 --rate 40 --duration 90 --output evidence/track1 - python bench/track1.py --configs full,tail --runs 1 # subset, quick check - -Configurations (only the telemetry differs; image, limits, load and data are the same): - off OTEL_SDK_DISABLED=true in api/relay/worker (stdout JSON logs only) - baseline - full SDK on, every trace kept (parentbased_always_on, Collector traces-all) - head10 SDK head sampling 10 % (parentbased_traceidratio 0.1), Collector traces-all - tail SDK on 100 %, Collector TAIL sampling: all errors + all traces >= 250 ms + 10 % of the - rest (infra/otel/traces-tail.yaml) - proposed balance -Metrics and logs are NOT sampled in any configuration: the dashboards/alerts stay exact. - -Load (open loop, fixed arrival rate, latency measured from the SCHEDULED start of each request, -so a slow server cannot slow down the generator - no coordinated omission): `rate` req/s, -70 % POST message / 30 % GET history page, + 1 upload/s for the worker. Rare events on purpose: -API_FAULT_POINTS=random_5xx=10,random_slow=10 -> ~1 % of POSTs answer 503, ~1 % take +500 ms. -The client counts them exactly; then Tempo is asked how many of them are still findable. - -Per run: recreate the services for the configuration, warm up `warmup` s, measure `duration` s, -wait for ingestion, read: client RPS/latency/errors; CPU of api/worker/relay/postgres EXACTLY from -the cgroup counter (`/sys/fs/cgroup/cpu.stat` usage_usec at the start and the end of the window), -CPU of the telemetry stack from its own counters (increase of process_cpu_seconds_total), RAM from -docker stats (sampled every 5 s); GET latency (no faults injected there) as the clean overhead; -Collector counters (accepted / sent / dropped spans, log records, metric points); Tempo/Loki bytes -received; SDK spans recorded/exported; error and slow traces found in Tempo vs injected. -Order of runs: off, full, head10, tail repeated `runs` times (drift spreads over all configs). -""" -from __future__ import annotations - -import argparse -import base64 -import json -import os -import random -import secrets -import statistics -import subprocess -import sys -import threading -import time -import urllib.error -import urllib.request -import uuid -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "scripts")) -import obs # noqa: E402 - -BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") + "/api/v1" -SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() -FAULTS = "random_5xx=10,random_slow=10" - -CONFIGS = { - "off": {"OTEL_SDK_DISABLED": "true", "OTEL_COLLECTOR_TRACES": "traces-all"}, - "full": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_always_on", - "OTEL_COLLECTOR_TRACES": "traces-all"}, - "head10": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_traceidratio", - "OTEL_TRACES_SAMPLER_ARG": "0.1", "OTEL_COLLECTOR_TRACES": "traces-all"}, - "tail": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_always_on", - "OTEL_COLLECTOR_TRACES": "traces-tail"}, -} -WATCHED = ["api", "worker", "relay", "otel-collector", "tempo", "loki", "prometheus", "postgres"] - - -# ----------------------------------------------------------------------------- stand -def compose_up(env: dict) -> None: - """`docker compose up` of the telemetry-dependent services; retried: on Windows the CLI itself - sometimes fails to start (exit 0xC0000142) when the desktop session is busy.""" - for attempt in range(3): - result = subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--wait", "otel-collector", "api", - "relay", "worker"], cwd=ROOT, env=env, capture_output=True, timeout=300) - if result.returncode == 0: - return - print(f" compose up failed (exit {result.returncode}), retry {attempt + 1}", flush=True) - time.sleep(10) - raise RuntimeError("docker compose up failed 3 times") - - -def apply_config(name: str) -> None: - env = {k: v for k, v in os.environ.items() if not k.startswith("OTEL_")} - env.update(CONFIGS[name]) - env["API_FAULT_POINTS"] = FAULTS - compose_up(env) - deadline = time.time() + 90 - while time.time() < deadline: # LB sees both replicas again - try: - with urllib.request.urlopen(BASE.rsplit("/api/v1", 1)[0] + "/health/ready", timeout=2) as r: - if r.status == 200: - break - except Exception: # noqa: BLE001 - pass - time.sleep(1) - time.sleep(5) - - -def restore() -> None: - env = {k: v for k, v in os.environ.items() if not k.startswith("OTEL_") and k != "API_FAULT_POINTS"} - compose_up(env) - - -def container_ids() -> dict[str, str]: - out = {} - for service in WATCHED: - ids = subprocess.run(["docker", "compose", "ps", "-q", service], cwd=ROOT, capture_output=True, - text=True).stdout.split() - for i, cid in enumerate(ids): - out[f"{service}-{i + 1}" if len(ids) > 1 else service] = cid - return out - - -CGROUP_SERVICES = ("api", "worker", "relay", "postgres") # images with a shell (`cat`) - - -def cgroup_cpu(ids: dict[str, str]) -> dict[str, float]: - """usage_usec of every application container's cgroup, read in parallel (seconds).""" - out: dict[str, float] = {} - - def one(name: str, cid: str) -> None: - raw = subprocess.run(["docker", "exec", cid, "cat", "/sys/fs/cgroup/cpu.stat"], capture_output=True, - text=True, timeout=30).stdout - for line in raw.splitlines(): - if line.startswith("usage_usec "): - out[name] = int(line.split()[1]) / 1e6 - - threads = [threading.Thread(target=one, args=(n, c)) for n, c in ids.items() if n.split("-")[0] in CGROUP_SERVICES] - for t in threads: - t.start() - for t in threads: - t.join(40) - return out - - -class Stats(threading.Thread): - """docker stats every 5 s: CPU % (100 = one core) and memory (MiB) per container.""" - - def __init__(self, ids: dict[str, str]): - super().__init__(daemon=True) - self.ids = ids - self.samples: dict[str, list[tuple[float, float]]] = {k: [] for k in ids} - self.stop = threading.Event() - - def run(self) -> None: - names = {v[:12]: k for k, v in self.ids.items()} - while not self.stop.is_set(): - raw = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.ID}};{{.CPUPerc}};{{.MemUsage}}", - *self.ids.values()], capture_output=True, text=True).stdout - for line in raw.splitlines(): - cid, cpu, mem = line.split(";") - if cid[:12] in names: - self.samples[names[cid[:12]]].append((float(cpu.rstrip("%")), _mib(mem.split("/")[0].strip()))) - self.stop.wait(5) - - def summary(self) -> dict: - out = {} - for name, rows in self.samples.items(): - if rows: - out[name] = {"cpu_pct_avg": round(statistics.mean(r[0] for r in rows), 1), - "mem_mib_avg": round(statistics.mean(r[1] for r in rows), 1), - "mem_mib_max": round(max(r[1] for r in rows), 1)} - return out - - -def _mib(text: str) -> float: - num = float("".join(c for c in text if c.isdigit() or c == ".")) - return num / 1024 if text.endswith("KiB") else num * 1024 if text.endswith("GiB") else num - - -# ----------------------------------------------------------------------------- load -def http(method, path, body=None, headers=None, raw=None, timeout=10.0): - h = dict(headers or {}) - data = raw - if body is not None: - data = json.dumps(body).encode() - h["Content-Type"] = "application/json" - request = urllib.request.Request(BASE + path, data=data, method=method, headers=h) - try: - with urllib.request.urlopen(request, timeout=timeout) as r: - return r.status, json.loads(r.read() or b"null") - except urllib.error.HTTPError as exc: - exc.read() - return exc.code, None - except Exception: # noqa: BLE001 - return 0, None - - -def actor() -> dict: - username = "t1_" + uuid.uuid4().hex[:12] - password = "Track1-" + secrets.token_hex(8) - _, user = http("POST", "/users", {"username": username, "display_name": "track1", "password": password}) - _, session = http("POST", "/auth/sessions", - headers={"Authorization": "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()}) - headers = {"Authorization": "Bearer " + session["token"]} - _, chat = http("POST", "/chats", {"title": "track1", "member_ids": [user["id"]]}, headers) - return {"headers": headers, "chat": chat["id"]} - - -def load(rate: float, seconds: float, warmup: float, ids: dict[str, str]) -> dict: - actors = [actor() for _ in range(8)] - for a in actors: # same history size in every run - for _ in range(20): - http("POST", f"/chats/{a['chat']}/messages", {"text": "seed"}, {**a["headers"], "Idempotency-Key": uuid.uuid4().hex}) - results: list[tuple[float, str, int, float]] = [] - lock = threading.Lock() - rnd = random.Random(42) # the same request mix in every run - - def one(scheduled: float, kind: str, a: dict) -> None: - if kind == "post": - status, _ = http("POST", f"/chats/{a['chat']}/messages", {"text": "load"}, - {**a["headers"], "Idempotency-Key": uuid.uuid4().hex}) - elif kind == "get": - status, _ = http("GET", f"/chats/{a['chat']}/messages?limit=20", headers=a["headers"]) - else: - status, _ = http("POST", f"/chats/{a['chat']}/attachments?filename=t1.png", raw=SAMPLE, - headers={**a["headers"], "Content-Type": "image/png"}, timeout=20) - with lock: - results.append((scheduled, kind, status, time.perf_counter() - scheduled)) - - total = warmup + seconds - plan = [] - for i in range(int(total * rate)): - plan.append((i / rate, "post" if rnd.random() < 0.7 else "get", rnd.randrange(len(actors)))) - for i in range(int(total)): - plan.append((i + 0.5, "upload", rnd.randrange(len(actors)))) - plan.sort() - start = time.perf_counter() - snap: dict = {} - - def snapshot_start() -> None: - snap["t0"], snap["cpu0"] = time.time(), cgroup_cpu(ids) - - starter = None - with ThreadPoolExecutor(max_workers=96) as pool: - for offset, kind, idx in plan: - if starter is None and offset >= warmup: - starter = threading.Thread(target=snapshot_start) - starter.start() - delay = start + offset - time.perf_counter() - if delay > 0: - time.sleep(delay) - pool.submit(one, start + offset, kind, actors[idx]) - t1, cpu1 = time.time(), cgroup_cpu(ids) - starter.join(60) - measured = [r for r in results if r[0] - start >= warmup] - window_s = t1 - snap["t0"] - out = {"window": [snap["t0"], t1], - "cpu_pct": {name: round(100 * (cpu1[name] - snap["cpu0"][name]) / window_s, 1) - for name in cpu1 if name in snap["cpu0"]}} - for kind in ("post", "get", "upload"): - rows = [r for r in measured if r[1] == kind] - ok = sorted(r[3] for r in rows if 200 <= r[2] < 300) - out[kind] = {"sent": len(rows), "ok": len(ok), "5xx": sum(r[2] >= 500 for r in rows), - "no_response": sum(r[2] == 0 for r in rows), - "ok_rps": round(len(ok) / seconds, 2), - "p50_ms": _pct(ok, .5), "p95_ms": _pct(ok, .95), "p99_ms": _pct(ok, .99), - "slow_over_450ms": sum(1 for r in rows if 200 <= r[2] < 300 and r[3] > 0.45)} - return out - - -def _pct(values, q): - return round(values[min(len(values) - 1, int(q * len(values)))] * 1000, 1) if values else None - - -# ----------------------------------------------------------------------------- telemetry side -def increase(expr: str, start: float, end: float) -> float | None: - """Counter growth inside [start, end]: sum(increase(expr[window])) evaluated at `end`. increase() - handles counter resets (services are recreated for every configuration) and series of old - processes (they do not grow); subtracting two raw sums did not, and gave negative numbers.""" - window = max(15, int(round(end - start))) - try: - result = obs.promql(f"sum(increase({expr}[{window}s]))", at=end) - except Exception: # noqa: BLE001 - return None - return round(float(result[0]["value"][1]), 1) if result else 0.0 - - -def tempo_count(traceql: str, start: float, end: float) -> int: - end_i, start_i = int(end) + 1, int(start) - try: - found = obs.get("tempo", "api/search", {"q": traceql, "start": start_i, "end": end_i, "limit": 5000}, - timeout=60).get("traces", []) - except Exception: # noqa: BLE001 - return -1 - return len(found) - - -def telemetry_side(window: list[float], config: str) -> dict: - start, end = window - end_q = end + 25 # counters pushed every 5 s, batch 2 s - return { - "sdk_spans_recorded": increase("messenger_telemetry_spans_ended_total", start, end_q), - "sdk_spans_export_failed": increase('messenger_telemetry_spans_exported_total{result="failure"}', start, end_q), - "collector_spans_accepted": increase("otelcol_receiver_accepted_spans", start, end_q), - "collector_spans_refused": increase("otelcol_receiver_refused_spans", start, end_q), - "collector_spans_sent": increase('otelcol_exporter_sent_spans{exporter="otlp_http/tempo"}', start, end_q), - "collector_spans_send_failed": increase("otelcol_exporter_send_failed_spans", start, end_q), - "collector_logs_accepted": increase("otelcol_receiver_accepted_log_records", start, end_q), - "collector_metric_points_accepted": increase("otelcol_receiver_accepted_metric_points", start, end_q), - "tempo_bytes_received": increase("tempo_distributor_bytes_received_total", start, end_q), - "loki_bytes_received": increase("loki_distributor_bytes_received_total", start, end_q), - # the Collector names its own CPU counter otelcol_process_cpu_seconds (no _total suffix) - "telemetry_cpu_s": {"otel-collector": increase('otelcol_process_cpu_seconds{job="otel-collector"}', start, end_q), - **{job: increase(f'process_cpu_seconds_total{{job="{job}"}}', start, end_q) - for job in ("tempo", "loki", "prometheus")}}, - "error_traces_in_tempo": tempo_count('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && span.http.response.status_code = 503 }', - start, end), - "slow_traces_in_tempo": tempo_count('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && kind = server && duration > 450ms }', - start, end), - "server_traces_in_tempo": tempo_count('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && kind = server }', start, end), - } - - -# ----------------------------------------------------------------------------- main -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--configs", default="off,full,head10,tail") - parser.add_argument("--runs", type=int, default=3) - parser.add_argument("--first-run", type=int, default=1, help="continue an interrupted series (keeps earlier files)") - parser.add_argument("--rate", type=float, default=40) - parser.add_argument("--duration", type=float, default=90) - parser.add_argument("--warmup", type=float, default=20) - parser.add_argument("--output", default="evidence/track1") - args = parser.parse_args() - out_dir = ROOT / args.output - out_dir.mkdir(parents=True, exist_ok=True) - configs = args.configs.split(",") - meta = {"started": time.strftime("%Y-%m-%d %H:%M:%S"), "rate": args.rate, "duration": args.duration, - "warmup": args.warmup, "faults": FAULTS, "configs": {c: CONFIGS[c] for c in configs}} - if args.first_run == 1 or not (out_dir / "meta.json").exists(): - (out_dir / "meta.json").write_text(json.dumps(meta, indent=1) + "\n", encoding="utf-8") - try: - for run in range(args.first_run, args.runs + 1): - for config in configs: - print(f"--- run {run} config {config}", flush=True) - apply_config(config) - ids = container_ids() - stats = Stats(ids) - stats.start() - client = load(args.rate, args.duration, args.warmup, ids) - stats.stop.set() - stats.join(15) - time.sleep(30) # ingestion + tail decision_wait + metric push - result = {"config": config, "run": run, "client": client, "resources": stats.summary(), - "telemetry": telemetry_side(client["window"], config)} - (out_dir / f"run{run}-{config}.json").write_text(json.dumps(result, indent=1) + "\n", encoding="utf-8") - c, t = client["post"], result["telemetry"] - print(f" post ok_rps={c['ok_rps']} p50={c['p50_ms']} p95={c['p95_ms']} p99={c['p99_ms']} " - f"5xx={c['5xx']} slow={c['slow_over_450ms']} | get p99={client['get']['p99_ms']} | cpu " - f"{client['cpu_pct']} | " - f"errors in tempo={t.get('error_traces_in_tempo')} slow in tempo={t.get('slow_traces_in_tempo')}", - flush=True) - finally: - restore() - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/bench/track1_summary.py b/bench/track1_summary.py deleted file mode 100644 index 686acf0..0000000 --- a/bench/track1_summary.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python3 -"""Summarise evidence/track1/run*-.json into evidence/track1/summary.md (+ summary.json). - - python bench/track1_summary.py [evidence/track1] - -Per configuration: median over the runs (in brackets min..max), so one noisy run cannot decide. -CPU: application containers from cgroup usage_usec (exact, per window), the telemetry stack from -its own process CPU counters; RAM: docker stats average. Kept rare events = traces found in Tempo / -events the client saw (5xx answers, POSTs > 450 ms). -""" -from __future__ import annotations - -import json -import statistics -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -ORDER = ["off", "full", "head10", "tail"] - - -def med(values): - values = [v for v in values if v is not None] - if not values: - return None, None, None - return statistics.median(values), min(values), max(values) - - -def fmt(triple, digits=1, unit=""): - m, lo, hi = triple - if m is None: - return "—" - if lo == hi: - return f"{m:.{digits}f}{unit}" - return f"{m:.{digits}f}{unit} ({lo:.{digits}f}–{hi:.{digits}f})" - - -def kept(found, seen): - if found is None or found < 0 or not seen: - return None - return 100.0 * found / seen - - -def summarise(rs: list[dict]) -> dict: - post = [r["client"]["post"] for r in rs] - get = [r["client"]["get"] for r in rs] - cpu = [r["client"].get("cpu_pct", {}) for r in rs] - res = [r["resources"] for r in rs] - tel = [r["telemetry"] for r in rs] - windows = [r["client"]["window"][1] - r["client"]["window"][0] + 25 for r in rs] - - def tele_cpu(t, w): - values = (t.get("telemetry_cpu_s") or {}).values() - return None if not values or any(v is None for v in values) else 100 * sum(values) / w - - return { - "runs": len(rs), - "post_ok_rps": med([p["ok_rps"] for p in post]), - "post_p50_ms": med([p["p50_ms"] for p in post]), "post_p95_ms": med([p["p95_ms"] for p in post]), - "post_p99_ms": med([p["p99_ms"] for p in post]), - "get_p50_ms": med([g["p50_ms"] for g in get]), "get_p95_ms": med([g["p95_ms"] for g in get]), - "get_p99_ms": med([g["p99_ms"] for g in get]), - "api_cpu_pct": med([sum(v for k, v in c.items() if k.startswith("api")) or None for c in cpu]), - "worker_cpu_pct": med([c.get("worker") for c in cpu]), - "relay_cpu_pct": med([c.get("relay") for c in cpu]), - "postgres_cpu_pct": med([c.get("postgres") for c in cpu]), - "api_mem_mib": med([sum(v["mem_mib_avg"] for k, v in x.items() if k.startswith("api")) or None for x in res]), - "telemetry_cpu_pct": med([tele_cpu(t, w) for t, w in zip(tel, windows)]), - "telemetry_mem_mib": med([sum(x.get(k, {}).get("mem_mib_avg", 0) for k in ("otel-collector", "tempo", "loki", - "prometheus")) for x in res]), - "collector_mem_mib": med([x.get("otel-collector", {}).get("mem_mib_avg") for x in res]), - "spans_recorded": med([t.get("sdk_spans_recorded") for t in tel]), - "spans_accepted": med([t.get("collector_spans_accepted") for t in tel]), - "spans_to_tempo": med([t.get("collector_spans_sent") for t in tel]), - "spans_refused_or_failed": med([None if t.get("collector_spans_refused") is None else - t["collector_spans_refused"] + (t.get("collector_spans_send_failed") or 0) - + (t.get("sdk_spans_export_failed") or 0) for t in tel]), - "tempo_kib": med([None if t.get("tempo_bytes_received") is None else t["tempo_bytes_received"] / 1024 for t in tel]), - "loki_kib": med([None if t.get("loki_bytes_received") is None else t["loki_bytes_received"] / 1024 for t in tel]), - "logs": med([t.get("collector_logs_accepted") for t in tel]), - "metric_points": med([t.get("collector_metric_points_accepted") for t in tel]), - "errors_injected": med([p["5xx"] for p in post]), - "errors_in_tempo": med([t.get("error_traces_in_tempo") for t in tel]), - "errors_kept_pct": med([kept(t.get("error_traces_in_tempo"), p["5xx"]) for t, p in zip(tel, post)]), - "slow_seen": med([p["slow_over_450ms"] for p in post]), - "slow_in_tempo": med([t.get("slow_traces_in_tempo") for t in tel]), - "slow_kept_pct": med([kept(t.get("slow_traces_in_tempo"), p["slow_over_450ms"]) for t, p in zip(tel, post)]), - "post_traces_in_tempo": med([t.get("server_traces_in_tempo") for t in tel]), - } - - -def main() -> int: - folder = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / "evidence" / "track1" - runs: dict[str, list[dict]] = {} - for f in sorted(folder.glob("run*-*.json")): - data = json.loads(f.read_text(encoding="utf-8")) - runs.setdefault(data["config"], []).append(data) - meta = json.loads((folder / "meta.json").read_text(encoding="utf-8")) - summary = {c: summarise(runs[c]) for c in ORDER if c in runs} - rows = list(summary.items()) - L = [f"# Трек 1: цена наблюдаемости — сводка (серия от {meta['started']})", "", - f"Нагрузка: open loop {meta['rate']:.0f} req/s (70 % POST message, 30 % GET history) + 1 upload/s, " - f"прогрев {meta['warmup']:.0f} с, замер {meta['duration']:.0f} с; редкие события `{meta['faults']}` " - "(~1 % POST → 503, ~1 % POST +500 мс). Медиана по повторам, в скобках min–max.", "", - "## Задержка (клиент, от запланированного момента запроса)", "", - "| Конфигурация | POST ok RPS | POST p50, мс | POST p95, мс | POST p99, мс* | GET p50, мс | GET p95, мс | GET p99, мс |", - "| --- | --- | --- | --- | --- | --- | --- | --- |"] - for c, s in rows: - L.append(f"| {c} ({s['runs']}) | {fmt(s['post_ok_rps'], 2)} | {fmt(s['post_p50_ms'])} | {fmt(s['post_p95_ms'])} | " - f"{fmt(s['post_p99_ms'])} | {fmt(s['get_p50_ms'])} | {fmt(s['get_p95_ms'])} | {fmt(s['get_p99_ms'])} |") - L += ["", "\\* p99 POST определяется внедрёнными медленными запросами (1 % × +500 мс), поэтому ≈ 500 мс во всех " - "конфигурациях; чистая цена телеметрии видна по GET (там отказы не внедряются) и по p50/p95.", "", - "## Ресурсы", "", - "| Конфигурация | CPU api×2, % | CPU worker, % | CPU relay, % | CPU postgres, % | CPU телеметрии**, % | RAM api×2, MiB | RAM телеметрии**, MiB | RAM Collector, MiB |", - "| --- | --- | --- | --- | --- | --- | --- | --- | --- |"] - for c, s in rows: - L.append(f"| {c} | {fmt(s['api_cpu_pct'])} | {fmt(s['worker_cpu_pct'])} | {fmt(s['relay_cpu_pct'])} | " - f"{fmt(s['postgres_cpu_pct'])} | {fmt(s['telemetry_cpu_pct'])} | {fmt(s['api_mem_mib'])} | " - f"{fmt(s['telemetry_mem_mib'])} | {fmt(s['collector_mem_mib'])} |") - L += ["", "100 % = одно ядро. CPU приложения — точный счётчик cgroup (`cpu.stat usage_usec`) за окно замера; " - "\\*\\* телеметрия = Collector + Tempo + Loki + Prometheus (их собственные счётчики CPU; RAM — docker stats).", "", - "## Объём телеметрии и потери (окно замера + 25 с на доставку)", "", - "| Конфигурация | spans записано SDK | принято Collector | ушло в Tempo | отказ/сбой отправки | Tempo, KiB | Loki, KiB | log records | metric points |", - "| --- | --- | --- | --- | --- | --- | --- | --- | --- |"] - for c, s in rows: - L.append(f"| {c} | {fmt(s['spans_recorded'], 0)} | {fmt(s['spans_accepted'], 0)} | {fmt(s['spans_to_tempo'], 0)} | " - f"{fmt(s['spans_refused_or_failed'], 0)} | {fmt(s['tempo_kib'], 0)} | {fmt(s['loki_kib'], 0)} | " - f"{fmt(s['logs'], 0)} | {fmt(s['metric_points'], 0)} |") - L += ["", "«Отказ/сбой» = отказано memory_limiter-ом + не отправлено Collector-ом + не отправлено SDK. " - "Отброшенное политикой sampling (head в SDK, tail в Collector) потерей не считается: это решение.", "", - "## Что осталось найти: редкие ошибки и медленные запросы", "", - "| Конфигурация | 5xx у клиента | 5xx-трасс в Tempo | найдено ошибок | медленных (> 450 мс) у клиента | медленных трасс в Tempo | найдено медленных | трасс POST в Tempo |", - "| --- | --- | --- | --- | --- | --- | --- | --- |"] - for c, s in rows: - L.append(f"| {c} | {fmt(s['errors_injected'], 0)} | {fmt(s['errors_in_tempo'], 0)} | {fmt(s['errors_kept_pct'], 0, ' %')} | " - f"{fmt(s['slow_seen'], 0)} | {fmt(s['slow_in_tempo'], 0)} | {fmt(s['slow_kept_pct'], 0, ' %')} | " - f"{fmt(s['post_traces_in_tempo'], 0)} |") - out = "\n".join(L) + "\n" - (folder / "summary.md").write_text(out, encoding="utf-8", newline="\n") - (folder / "summary.json").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8", newline="\n") - print(out) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/bench/upload_memory.py b/bench/upload_memory.py deleted file mode 100644 index e2c6f35..0000000 --- a/bench/upload_memory.py +++ /dev/null @@ -1,244 +0,0 @@ -#!/usr/bin/env python3 -"""Level 4 experiment: peak memory of the API replicas under >= 10 simultaneous uploads. - -Hypothesis: the memory of one replica is bounded by UPLOAD_CONCURRENCY x MAX_UPLOAD_BYTES (bodies -waiting for a slot stay in TCP buffers, not in the process) + one image check at a time -(IMAGE_VERIFY_CONCURRENCY), independent of how many clients upload at once. - -Method (repeatable, the stand must be up): -* for every scenario the api replicas are RECREATED with the scenario's settings, so the cgroup - counter memory.peak starts from an idle process (it never decreases during a container's life); -* idle memory.current of each replica is read; then N clients upload at the same moment through - the LB (a barrier releases them together), each a different file; -* during the run memory.current of every replica is sampled every 50 ms inside the container; - afterwards memory.peak (cgroup v2: all processes of the container incl. djpeg) and VmHWM of - PID 1 (the Python server alone) are read; -* the normal configuration is restored at the end. - - python bench/upload_memory.py --output evidence/memory -""" -from __future__ import annotations - -import argparse -import io -import json -import os -import platform -import statistics -import subprocess -import sys -import threading -import time -import uuid -from pathlib import Path - -import httpx2 as httpx -from PIL import Image - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "student-tests")) -import imagegen # noqa: E402 - -BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080") -PASSWORD = "Bench-password-Ω-12345" -MiB = 1024 * 1024 - - -def sh(*args: str, env: dict | None = None, timeout: float = 300) -> str: - return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, check=True, timeout=timeout, - env={**os.environ, **(env or {})}).stdout - - -def replicas() -> list[str]: - return sh("docker", "compose", "ps", "-q", "api").split() - - -def cg(cid: str, name: str) -> int: - return int(sh("docker", "exec", cid, "cat", f"/sys/fs/cgroup/{name}").split()[0]) - - -def memory_stat(cid: str, key: str) -> int: - for line in sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.stat").splitlines(): - name, value = line.split() - if name == key: - return int(value) - return 0 - - -def vmhwm(cid: str) -> int: - for line in sh("docker", "exec", cid, "cat", "/proc/1/status").splitlines(): - if line.startswith("VmHWM:"): - return int(line.split()[1]) * 1024 - return 0 - - -def container_events() -> dict[str, str]: - """restart count + OOM-kill events per container (cgroup memory.events oom_kill counter).""" - out = {} - for cid in sh("docker", "compose", "ps", "-q").split(): - name, restarts = sh("docker", "inspect", "-f", "{{.Name}} {{.RestartCount}}", cid).split() - events = dict(line.split() for line in sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.events").splitlines()) - out[name.lstrip("/")] = f"restarts={restarts} oom_kill={events.get('oom_kill', '?')}" - return out - - -def recreate(env: dict) -> None: - sh("docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "--wait", "api", env=env, timeout=300) - sh(sys.executable, "scripts/lbctl.py", "wait-up", str(len(replicas())), "--timeout", "90") # LB sees them UP - time.sleep(3) - - -class Sampler(threading.Thread): - """memory.current of one container every 50 ms, read by a shell loop inside it.""" - - def __init__(self, cid: str): - super().__init__(daemon=True) - self.cid = cid - self.values: list[int] = [] - self.proc = subprocess.Popen(["docker", "exec", cid, "sh", "-c", - "while :; do cat /sys/fs/cgroup/memory.current; sleep 0.05; done"], - stdout=subprocess.PIPE, text=True) - - def run(self) -> None: - for line in self.proc.stdout: - if line.strip().isdigit(): - self.values.append(int(line)) - - def stop(self) -> None: - self.proc.kill() - - -def actor(client: httpx.Client) -> tuple[str, str]: - name = "mem_" + uuid.uuid4().hex[:10] - client.post("/api/v1/users", json={"username": name, "display_name": "bench", "password": PASSWORD}).raise_for_status() - import base64 - basic = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode() - token = client.post("/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}).json()["token"] - me = client.get("/api/v1/users/me", headers={"Authorization": "Bearer " + token}).json() - chat = client.post("/api/v1/chats", headers={"Authorization": "Bearer " + token}, - json={"title": "mem", "member_ids": [me["id"]]}).json() - return token, chat["id"] - - -def big_jpeg(width: int, height: int, seed: int) -> bytes: - """Large progressive JPEG (smooth content keeps it < 10 MiB): the costliest file to check.""" - image = Image.linear_gradient("L").resize((width, height)).convert("RGB") - image.putpixel((seed % width, 0), (seed % 255, 0, 0)) - out = io.BytesIO() - image.save(out, "JPEG", quality=90, progressive=True, subsampling=0) - return out.getvalue() - - -def run_scenario(name: str, env: dict, files: list[tuple[bytes, str]]) -> dict: - recreate(env) - ids = replicas() - idle = {cid: cg(cid, "memory.current") for cid in ids} - client = httpx.Client(base_url=BASE, timeout=120) - token, chat_id = actor(client) - barrier = threading.Barrier(len(files)) - results: list[tuple[int, float, str]] = [None] * len(files) # type: ignore[list-item] - - def upload(i: int, data: bytes, ctype: str) -> None: - c = httpx.Client(base_url=BASE, timeout=120) - barrier.wait() - started = time.perf_counter() - r = c.post(f"/api/v1/chats/{chat_id}/attachments?filename=f{i}", content=data, - headers={"Authorization": "Bearer " + token, "Content-Type": ctype}) - reason = r.json()["error"]["message"] if r.status_code != 201 else "" - results[i] = (r.status_code, time.perf_counter() - started, r.headers.get("x-instance-id", "-"), reason) - c.close() - - s3_id = sh("docker", "compose", "ps", "-q", "s3").strip() - restarts_before = container_events() - samplers = [Sampler(cid) for cid in ids] + [Sampler(s3_id)] - for s in samplers: - s.start() - time.sleep(0.5) - threads = [threading.Thread(target=upload, args=(i, d, t)) for i, (d, t) in enumerate(files)] - wall = time.perf_counter() - for t in threads: - t.start() - for t in threads: - t.join() - wall = time.perf_counter() - wall - time.sleep(0.5) - for s in samplers: - s.stop() - per_replica = {} - for cid, s in zip(ids, samplers[:-1]): - hostname = sh("docker", "inspect", "-f", "{{.Config.Hostname}}", cid).strip() - per_replica[hostname] = { - "idle_mib": round(idle[cid] / MiB, 1), - "peak_mib": round(cg(cid, "memory.peak") / MiB, 1), - "sampled_max_mib": round(max(s.values or [0]) / MiB, 1), - "python_vmhwm_mib": round(vmhwm(cid) / MiB, 1), - "uploads_served": sum(1 for r in results if r[2] == hostname), - "limit_mib": round(cg(cid, "memory.max") / MiB, 1), - } - per_replica[hostname]["peak_minus_idle_mib"] = round(per_replica[hostname]["peak_mib"] - - per_replica[hostname]["idle_mib"], 1) - lat = sorted(r[1] for r in results if r[0] == 201) - codes: dict[str, int] = {} - reasons: dict[str, int] = {} - for r in results: - codes[str(r[0])] = codes.get(str(r[0]), 0) + 1 - if r[3]: - reasons[r[3]] = reasons.get(r[3], 0) + 1 - summary = { - "scenario": name, "settings": env, "clients": len(files), - "s3_sampled_max_mib": round(max(samplers[-1].values or [0]) / MiB, 1), - "s3_anon_after_mib": round(memory_stat(s3_id, "anon") / MiB, 1), - "s3_limit_mib": round(cg(s3_id, "memory.max") / MiB, 1), - # OOM kills / restarts DURING the scenario (any container of the stand): must be empty - "incidents": {k: v for k, v in container_events().items() if v != restarts_before.get(k)}, - "file_mib_each": round(statistics.mean(len(d) for d, _ in files) / MiB, 2), - "types": sorted({t for _, t in files}), "status_codes": codes, "error_reasons": reasons, "wall_seconds": round(wall, 2), - "latency_s": {"p50": round(lat[len(lat) // 2], 2), "max": round(lat[-1], 2)} if lat else None, - "replicas": per_replica, - } - print(json.dumps(summary, ensure_ascii=False), flush=True) - return summary - - -def main() -> int: - p = argparse.ArgumentParser() - p.add_argument("--clients", type=int, default=16) - p.add_argument("--output", default="evidence/memory") - args = p.parse_args() - out = ROOT / args.output - out.mkdir(parents=True, exist_ok=True) - print("generating files ...", flush=True) - pngs = [(imagegen.png_of_size(int(9.5 * MiB)), "image/png") for _ in range(2 * args.clients)] - jpegs = [(big_jpeg(8000, 5000, i), "image/jpeg") for i in range(args.clients)] - base = {"UPLOAD_CONCURRENCY": "4", "IMAGE_VERIFY_CONCURRENCY": "1"} - n, n2 = args.clients, 2 * args.clients - scenarios = [ - (f"png-9.4MiB x{n}, slots=4 (default)", base, pngs[:n]), - (f"png-9.4MiB x{n2}, slots=4 (default)", base, pngs), - (f"png-9.4MiB x{n2}, slots=16 (bound raised)", {"UPLOAD_CONCURRENCY": "16", "IMAGE_VERIFY_CONCURRENCY": "1"}, pngs), - (f"jpeg-40Mpx-progressive-4:4:4 x{n}, verify=1 (default)", base, jpegs), - (f"jpeg-40Mpx-progressive-4:4:4 x{n}, verify=4", {"UPLOAD_CONCURRENCY": "4", "IMAGE_VERIFY_CONCURRENCY": "4"}, jpegs), - ] - results = [] - sh("docker", "compose", "restart", "s3") # S3 memory counters start from an idle process - sh("docker", "compose", "up", "-d", "--wait", "s3") - try: - for name, env, files in scenarios: - results.append(run_scenario(name, env, files)) - finally: - recreate({}) # back to the compose defaults - meta = { - "date": time.strftime("%Y-%m-%d %H:%M:%S"), "host": platform.platform(), "cpus": os.cpu_count(), - "commit": sh("git", "rev-parse", "--short", "HEAD").strip(), - "api_limits": sh("docker", "inspect", "-f", "{{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}", - replicas()[0]).strip(), - "jpeg_file_mib": round(len(jpegs[0][0]) / MiB, 2), "png_file_mib": round(len(pngs[0][0]) / MiB, 2), - } - (out / "summary.json").write_text(json.dumps({"meta": meta, "scenarios": results}, ensure_ascii=False, indent=1), - encoding="utf-8") - print(json.dumps(meta, ensure_ascii=False)) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/compose.yaml b/compose.yaml index f23a7b1..57335a4 100644 --- a/compose.yaml +++ b/compose.yaml @@ -140,6 +140,8 @@ services: # service roles; the superuser `postgres` exists for initdb and the operator (local socket). # The server key must be 0600 and owned by postgres: it is copied from the secret into a tmpfs # at start (the bind-mounted secret cannot be chowned), then the image's entrypoint drops root. + # pg_hba.conf (infra/postgres, the source of truth in Git) is copied there too, so the lab 3 + # failure test can add a temporary reject line and reload (student-tests/test_balancing.py). postgres: image: postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c environment: @@ -150,9 +152,10 @@ services: - -c - >- install -o postgres -g postgres -m 600 /run/secrets/postgres.key /run/pgtls/server.key && + install -m 644 /etc/postgresql/pg_hba.conf /run/pgtls/pg_hba.conf && exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/run/secrets/postgres.crt -c ssl_key_file=/run/pgtls/server.key - -c ssl_min_protocol_version=TLSv1.2 -c hba_file=/etc/postgresql/pg_hba.conf + -c ssl_min_protocol_version=TLSv1.2 -c hba_file=/run/pgtls/pg_hba.conf -c password_encryption=scram-sha-256 -c shared_preload_libraries=pg_stat_statements -c max_connections=${PG_MAX_CONNECTIONS:-100} secrets: @@ -165,6 +168,7 @@ services: - pg_auditor_password - {source: pki_postgres_crt, target: postgres.crt} - {source: pki_postgres_key, target: postgres.key} + - {source: pki_internal_ca, target: internal-ca.crt} # operator/tests: psql verify-full inside tmpfs: - /run/pgtls:size=1m,mode=0755 volumes: @@ -696,10 +700,7 @@ services: # Distroless image (no shell). Lab 7: receiver HTTPS + client certificate required, exporters mTLS. otel-collector: image: otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea - command: - - --config=/etc/otelcol/collector.yaml - # traces-all (keep every span) | traces-tail (tail sampling, lab 6 track 1) - - --config=/etc/otelcol/${OTEL_COLLECTOR_TRACES:-traces-all}.yaml + command: ["--config=/etc/otelcol/collector.yaml"] environment: GOMEMLIMIT: 360MiB # Go heap target under the 512 MiB container limit secrets: diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a977..31cc6c3 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,37 +1,101 @@ -# Матрица доверия — заполнить в решении lab7 +# Матрица доверия — решение lab7 (уровень 3) -Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. +Это обязательная матрица покрытия. Для каждой строки указаны реальный порт, endpoint, CA, service identity, проверка SAN/ACL, срок жизни credentials и команда положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. -| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | -| --- | --- | --- | --- | -| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | -| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | -| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | -| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | -| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | -| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO | -| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO | -| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO | -| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO | -| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO | -| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO | -| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO | +**Два домена доверия** (`scripts/init_pki.py`, ключи в `./secrets/pki`, вне Git и образов): + +* `public-ca` подписывает только то, к чему подключается человек: ingress `:8443` и Grafana UI (SAN `localhost`, `127.0.0.1`, `::1`). Это `CA_FILE` публичных тестов. Ни один сервис ему не доверяет. +* `internal-ca` подписывает identity сервисов. SAN = имя сервиса compose (то, что набирает клиент), EKU `serverAuth`/`clientAuth` по роли. Сервисы доверяют только ему. +* Ключи CA не монтируются ни в один контейнер. Leaf-сертификаты: ECDSA P-256, срок 365 дней, CA — 5 лет. Каждый контейнер получает через compose `secrets:` только свой cert/key и нужный ему CA. + +Колонки «Минимум на 3» и «Дополнительно на 4» — из задания (уровень 4 не заявлен), «Решение» — что сделано (порт, CA/SAN, identity, срок жизни credentials), «Доказательство» — конфиг и тест (положительный / отрицательный). Тесты лежат в `student-tests/test_security.py` (`make security-test`), выводы — в `evidence/`. + +| Связь | Минимум на 3 | Дополнительно на 4 | Решение (порт, CA/SAN, identity, срок жизни) | Доказательство / конфиг | +| --- | --- | --- | --- | --- | +| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit — *не заявлено (цель — уровень 3)* | HAProxy `bind :8443 ssl crt ingress.pem ssl-min-ver TLSv1.2`, опубликован только на `127.0.0.1`/`[::1]`. Сервер: `public-ca`, SAN `localhost`/`127.0.0.1`/`::1`. Клиент: Bearer-сессия (≥256 бит, TTL `SESSION_TTL_SECONDS`), вход Basic + Argon2id, лимит неудачных входов. Открытого порта 8080 нет | `infra/haproxy/haproxy.cfg`. **+** `make test`, `make test-security` с `CA_FILE`. **−** пустой trust store и чужой hostname → `SSLCertVerificationError`; внутренний CA не подходит; открытый HTTP на 8443 не отвечает 200; порты 8080/8404/5432/… закрыты (`test_ingress_verifies_ca_and_hostname`, `test_no_plaintext_entry_point`) | +| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки — *не заявлено (цель — уровень 3)* | HAProxy → `api:8443` (`server-template`, DNS): `ssl verify required ca-file internal-ca.crt verifyhost api crt lb.pem`. API (`src/messenger/tls.py`): `CERT_REQUIRED`, доверяет только `internal-ca`, после рукопожатия класс протокола uvicorn сверяет DNS SAN клиента с `MTLS_ALLOWED_CLIENTS=lb`, иначе `abort()` до чтения HTTP. Health-проверки HAProxy идут тем же mTLS. Docker healthcheck — отдельный listener `127.0.0.1:8081` в loopback контейнера, только `/health/*` | `scripts/mtls_check.py` (`make mtls-check`) по **каждой** реплике напрямую. **−** без cert, cert `foreign-ca` с SAN `lb`, cert `internal-ca` с SAN `worker` → отказ при TLS 1.3 и TLS 1.2; открытый HTTP на 8443 и порт 8081 снаружи → отказ. **+** cert `lb` → `200`. В логе API `mtls_identity_rejected client_san=[worker]` | +| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление — *не заявлено (цель — уровень 3)* | `postgres:5432`, `ssl=on`, TLS 1.2+, SAN `postgres`. `pg_hba.conf`: только `hostssl` для 6 сервисных ролей (SCRAM), `host all all all reject`. Суперпользователь `postgres` — только через локальный сокет (peer). Роли: `messenger_migrate` (владелец схемы), `messenger_api`/`_relay`/`_worker` (GRANT по коду, `migrations/0007_least_privilege.sql`), `messenger_jobctl`/`_auditor` (инструменты). URL: `sslmode=verify-full&sslrootcert=internal-ca.crt`. URL api/relay/worker приходят из OpenBao, файлом их нет. Пароли статические (ротация — уровень 4) | `test_postgres_tls_only_and_roles_least_privilege`. **+** `SELECT 1` по TLS (`pg_stat_ssl.ssl = t`). **−** `sslmode=disable` → `no encryption`; суперпользователь по сети → `pg_hba.conf`; api: `DELETE FROM messages`, `job_attempts`, `CREATE TABLE`, `TRUNCATE`, `UPDATE users`; relay/worker: `users`, `messages`, `sessions`; worker: `post_message_v3`; auditor: запись → `permission denied` | +| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация — *не заявлено (цель — уровень 3)* | SeaweedFS S3 `s3:8333` только HTTPS (`-s3.cert.file`), SAN `s3`. Клиенты aiobotocore с `verify=internal-ca.crt`. Identities: `messenger-api` = Write staging + Read final; `messenger-worker` = Read/Write обоих; `messenger-auditor` = Read+List; `bootstrap-admin` — только у `s3-init` и самого `s3`. Ключи api/worker — из OpenBao. Внутренние master/volume/filer слушают `127.0.0.1` контейнера (закрытый local hop) | `s3-init` проверяет модель доступа при каждом старте: `api: write final: refused (AccessDenied)`, `auditor: delete staging: refused`, `api: ListBuckets: []`. `test_s3_https_and_scoped_keys`. **−** `http://s3:8333` → нет ответа | +| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей — *не заявлено (цель — уровень 3)* | RabbitMQ: `listeners.tcp = none`, `listeners.ssl.default = 5671`, SAN `broker`, TLS 1.2/1.3. Пользователи: `relay` — `configure ^$`, `write ^messenger\.jobs$`, `read ^$`; `worker` — `read ^messenger\.attachment-jobs$`, остальное `^$`. API в сети `queue` не состоит. URL `amqps://` — из OpenBao | `test_broker_tls_only_and_users_scoped`. **−** relay пытается читать очередь → `ChannelAccessRefused`; порт 5672 закрыт. **+** relay публикует и worker потребляет (smoke: thumbnail готов) | +| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities — *не заявлено (цель — уровень 3)* | OTLP/HTTPS `otel-collector:4318`, SAN `otel-collector`. Receiver `tls.client_ca_file` = обязательный клиентский сертификат `internal-ca`. SDK: `OTEL_EXPORTER_OTLP_CERTIFICATE` (CA) + свой cert `api`/`relay`/`worker`. Сеть `telemetry` — `internal`. `health_check` только на `127.0.0.1` | `test_telemetry_endpoints_require_client_certificates`. **−** процесс без client cert → отказ. **+** `make trace-demo`: span'ы и логи api/relay/worker доходят (7/7 PASS) | +| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege — *не заявлено (цель — уровень 3)* | mTLS: Collector предъявляет cert `otel-collector`. Prometheus `--web.config.file`: `RequireAndVerifyClientCert`, `client_allowed_sans: [otel-collector, grafana, prometheus]`. Loki (`:3100`) и Tempo (`:4318`, `:3200`): `RequireAndVerifyClientCert` по `internal-ca`, gRPC на `127.0.0.1`. Собственные метрики Collector — OTLP push по mTLS (pull-endpoint `:8888` без TLS убран) | **−** worker с сертификатом того же CA → Prometheus отказывает (SAN не в allowlist). **+** метрики, логи и трассы в хранилищах (`scripts/obs.py`, trace-demo). Ограничение: Loki/Tempo проверяют только цепочку CA, без allowlist SAN | +| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа — *не заявлено (цель — уровень 3)* | Datasources `https://prometheus:9090`, `https://loki:3100`, `https://tempo:3200`: `tlsAuthWithCACert` (internal CA), `serverName` = SAN, клиентский cert `grafana`, файлы через `$__file{}`. Grafana UI — HTTPS `127.0.0.1:3000`, cert `public-ca`, cookie secure | **+** `scripts/check_dashboard.py` — все запросы dashboard через datasource proxy. **−** без client cert backend отказывает (см. строку выше). Ограничение: identity `grafana` в Prometheus может и писать (OTLP) — роли чтения нет | +| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation — *не заявлено (цель — уровень 3)* | `openbao:8200` (сеть `vault`, `internal`), TLS 1.2+, SAN `openbao`. AppRole на каждый сервис: `token_policies=`, `token_no_default_policy`, `token_ttl=1h`, `token_max_ttl=4h`; SecretID `ttl=720h`. Policy: `read messenger/data/` + lookup/revoke-self. Сервис при старте делает login → читает свой путь → `revoke-self` (`src/messenger/bao.py`). role_id/secret_id — Docker secrets только своего сервиса | `scripts/bao_check.py` (`make bao-check`) внутри api/relay/worker. **+** login, свой путь. **−** чужие пути, запись своего, list metadata, запись policy, `sys/policies`, `auth/token/create`, `sys/auth`, `sys/mounts` → 403; отозванный токен → 403; неверный secret_id → 400 | +| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles — *не заявлено (цель — уровень 3)* | OpenBao: `docker compose exec openbao bao …` к `https://127.0.0.1:8200` с проверкой CA, root token и доли передаются **через stdin** (`scripts/bao_operator.py`). Root token и 3 доли unseal (порог 2) лежат в `~/.mtusi-lab7-operator//` (0600, вне репозитория). Grafana: `https://localhost:3000`, admin + пароль из `secrets/`. S3 admin: порт не опубликован, ключ только у `s3-init`. PostgreSQL superuser: `docker compose exec -u postgres postgres psql` | `scripts/bao_check.sh`: root token и доли не найдены в `/run/secrets`, `/app`, `/tmp`, окружении PID 1 api/relay/worker. Положительный контроль: свой role_id тем же поиском находится. В env нет `*TOKEN*` | +| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности — *не заявлено (цель — уровень 3)* | Valkey `port 0`, `tls-port 6379`, SAN `valkey`, `tls-auth-clients no`. ACL: `user default off`; `user api` (SHA-256 пароля) `~session:* ~ratelimit:*`, `-@all +get +set +del +incr +incrby +pexpire +pttl +multi +exec +discard +ping +client|setinfo`. Клиент: `rediss://` + `ssl_ca_certs` + `ssl_check_hostname`. URL — из OpenBao | `test_valkey_tls_and_acl`. **+** `PING` → `PONG`. **−** FLUSHALL, CONFIG, KEYS, ACL, чужой ключ, EVAL → `NOPERM`; без TLS и пользователем `default` → нет `PONG` | +| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа — *не заявлено (цель — уровень 3)* | N/A: каждое хранилище в одном экземпляре (один Docker-host). Raft-порт OpenBao 8201 слушает, но пиров нет; если бы были, использовался бы его собственный автоматический TLS | — | Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. +## Служебные каналы: scrape, health, bootstrap + +| Канал | Как защищён | Почему не обход | +| --- | --- | --- | +| Docker healthcheck API | `python -m messenger.healthcheck` → `http://127.0.0.1:8081/health/ready` | listener на loopback контейнера, только `/health/live`, `/health/ready`, `/health/ready/core`, иначе 404. `mtls_check`: порт 8081 с другого контейнера → `ConnectionRefused` | +| Healthcheck хранилищ | postgres `pg_isready` (socket); valkey `valkey-cli --tls --cacert`; s3 и grafana `curl --cacert https://localhost…`; prometheus `promtool check ready` с mTLS; openbao `bao status` (TLS, CA) | только изнутри своего контейнера | +| HAProxy health checks | тот же mTLS, что и трафик (`ssl` наследуется) | реплика без правильного cert не попадает в ротацию | +| HAProxy stats | `bind 127.0.0.1:8404` в контейнере, не опубликован; admin socket — через `docker compose exec` | недоступен из сети | +| Prometheus scrape | `prometheus` (self), `loki`, `tempo` по HTTPS + client cert `prometheus`; scrape Grafana убран | все цели требуют mTLS | +| Bootstrap | `migrate` (роль-владелец, TLS), `s3-init` (admin-ключ S3, HTTPS), `bao_operator.py` (stdin → CLI в контейнере OpenBao), `init_secrets.py`/`init_pki.py` (файлы на хосте) | одноразовые задачи, своих портов нет | + +## Сравнительная матрица разрешений (S3, брокер, PostgreSQL) + +«—» значит запрещено. Источник правды — конфиги: `infra/seaweedfs/start.sh`, `scripts/init_secrets.py` (RabbitMQ), `migrations/0007_least_privilege.sql`, `infra/valkey/start.sh`, `infra/openbao/policies/*.hcl`. + +| Ресурс | api | relay | worker | migrate / s3-init | jobctl / auditor (оператор) | +| --- | --- | --- | --- | --- | --- | +| S3 staging bucket | Write (+DELETE для уборщика) | — | Read, Write | s3-init: Admin (создать bucket) | auditor: Read, List | +| S3 final bucket | Read | — | Read, Write | s3-init: Admin | auditor: Read, List | +| S3 ListBuckets / Admin | — | — | — | s3-init | — | +| RabbitMQ exchange `messenger.jobs` | — (не в сети `queue`) | write | — | — | — | +| RabbitMQ queue `messenger.attachment-jobs` | — | — | read (consume/ack) | — | — | +| RabbitMQ configure (declare/delete) | — | — | — | топология из definitions самого брокера | — | +| PG `users`, `chat_members`, `messages`, `message_attachments` | SELECT, INSERT | — | — | migrate: владелец (DDL) | — | +| PG `chats` | SELECT, INSERT, UPDATE | — | — | владелец | — | +| PG `sessions`, `idempotency_keys` | SELECT, INSERT, (UPDATE), DELETE | — | — | владелец | — | +| PG `attachments` | SELECT, INSERT, UPDATE, DELETE | SELECT, UPDATE | SELECT, UPDATE | владелец | jobctl: SELECT, UPDATE; auditor: SELECT | +| PG `attachment_variants` | SELECT | — | SELECT, INSERT | владелец | SELECT | +| PG `jobs` | SELECT, INSERT | SELECT, UPDATE | SELECT, UPDATE | владелец | jobctl: SELECT, INSERT, UPDATE; auditor: SELECT | +| PG `job_attempts` | — | SELECT, UPDATE | SELECT, INSERT, UPDATE | владелец | SELECT | +| PG `outbox` | INSERT | SELECT, INSERT, UPDATE, DELETE | INSERT | владелец | jobctl: SELECT, INSERT; auditor: SELECT | +| PG `job_events` | SELECT, INSERT | SELECT, INSERT | SELECT, INSERT | владелец | jobctl: SELECT, INSERT; auditor: SELECT | +| PG `post_message*()` | EXECUTE | — | — | владелец | — | +| PG DDL / TRUNCATE / superuser | — | — | — | migrate: DDL своей схемы; superuser ни у кого из сервисов | — | +| Valkey `session:*`, `ratelimit:*` | GET/SET/DEL/INCR/PEXPIRE/PTTL | — | — | — | — | +| OpenBao | read `messenger/data/api` | read `messenger/data/relay` | read `messenger/data/worker` | — | оператор: root token (вне контейнеров) | + ## Обязательные отрицательные проверки -1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». -2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. -3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. -4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. -5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. -6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. +1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». → `make test-security`, `test_ingress_verifies_ca_and_hostname`. +2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. → `make mtls-check` (каждая реплика, TLS 1.3 и 1.2). +3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. → уровень 4 не заявлен. На уровне 3 Collector уже требует client cert, Prometheus — allowlist SAN. +4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. → `test_api.py::test_foreign_chat_is_indistinguishable_from_missing`, `test_x_user_id_basic_and_garbage_do_not_authenticate`, `test_attachments.py` (чужое вложение → 404). +5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. → `make bao-check`; KV worker = роль `messenger_worker` + ключ `messenger-worker`. +6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. → уровень 4 не заявлен. ## Bootstrap и эксплуатация В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. +**Как сделано:** подробно в [docs/OPERATOR.md](../docs/OPERATOR.md). + +* Ключи CA и leaf создаёт `init_pki.py` в `./secrets/pki`: папка 0700, `.gitignore`, `.dockerignore`. Доступ к ним есть только у оператора хоста. +* Root token и 3 доли unseal создаёт `bao_operator.py bootstrap` в `~/.mtusi-lab7-operator//` — вне репозитория и вне контейнеров. В реальной команде каждую долю хранит отдельный человек. +* После рестарта OpenBao запечатан. Уже работающие сервисы продолжают работу, новые реплики не стартуют, пока оператор не выполнит `bao_operator.py unseal` (это делает и `scripts/restart.sh`). +* Хук `test_security.py::test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones` это доказывает. + OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии. +**Как сделано:** + +* Integrated storage (Raft, один узел) на volume `baodata`, AppRole, KV v2 `messenger/`. +* Токен сервиса живёт секунды: login → read → revoke-self. Max TTL 1 ч — граница, если отзыв не удался. +* Re-auth выполняется при каждом старте процесса. +* SecretID живёт 30 дней и выдаётся заново командой `bao_operator.py new-secret-id `. Это осознанный компромисс уровня 3; короткий SecretID и wrapping относятся к уровню 4. + Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. + +**Как сделано:** + +* Доли хранятся у оператора, не в volume и не в контейнере OpenBao. +* Обычный рестарт API unseal не требует: unseal нужен только после рестарта самого OpenBao. diff --git a/docs/DEFENSE.md b/docs/DEFENSE.md new file mode 100644 index 0000000..cecc20c --- /dev/null +++ b/docs/DEFENSE.md @@ -0,0 +1,80 @@ +# Защита lab7 — ответы на вопросы README + +## 1. Какая часть mTLS проверяет шифрование, какая идентичность и где разрешение на действие? + +Возьмём связь LB → API. На ней три разных проверки, и каждая отвечает на свой вопрос. + +1. **Шифрование и подлинность сервера** — TLS-рукопожатие и проверка сертификата **сервера**. + * Ключ сессии согласуется через ECDHE, дальше трафик шифруется AEAD-шифром (TLS 1.2+/1.3). + * HAProxy проверяет, что сертификат реплики подписан `internal-ca` и в нём SAN `api` (`ssl verify required ca-file ... verifyhost api`). Посредник без ключа `api` ничего не прочитает и не выдаст себя за API. +2. **Идентичность клиента** — вторая половина mTLS, в двух шагах. + * a) **Цепочка.** Контекст API настроен с `CERT_REQUIRED` и доверяет только `internal-ca`. Без сертификата или с сертификатом чужого CA рукопожатие не завершается. Это говорит только о том, что сертификат выпустил наш CA. + * b) **Allowlist identity.** `MtlsHttpProtocol.connection_made` в `src/messenger/tls.py` сверяет DNS SAN клиентского сертификата с `MTLS_ALLOWED_CLIENTS=lb`. Если не совпало — `transport.abort()` до первого байта HTTP, а в логе запись `mtls_identity_rejected`. +3. **Разрешение на действие** — уже не TLS, а приложение. + * Bearer-сессия пользователя (`authenticate`) говорит, *кто из пользователей* просит. + * Проверка членства в чате (SQL) говорит, *можно ли ему* это сделать. Посторонний получает 404. + * mTLS доказывает, что запрос пришёл от *процесса LB*, но не даёт прав ни одному пользователю. Поэтому `X-User-Id` по-прежнему игнорируется. + +Доказательство: `make mtls-check`, по каждой реплике, TLS 1.3 и 1.2: + +| Клиент | Результат | Какой уровень отказал | +| --- | --- | --- | +| без сертификата | отказ | 2a | +| `foreign-ca`, SAN `lb` | отказ | 2a (имя правильное, CA чужой) | +| `internal-ca`, SAN `worker` | отказ | 2b, в логе `client_san=["worker"]` | +| `internal-ca`, SAN `lb` | 200 | — | + +Аналогия: TLS — бронированный фургон, который нельзя вскрыть по дороге. CA — отдел кадров, выдающий пропуска. Allowlist — список «на этот этаж с пропуском пускать только инкассаторов». Сессия — подпись клиента на платёжке. + +## 2. Почему доверенный CA ещё не означает, что любой его клиент может быть LB? + +* Наш `internal-ca` выпускает сертификаты всем сервисам: `api`, `relay`, `worker`, `otel-collector`, `grafana`, `prometheus` и другим. Цепочка у всех правильная. +* Если API проверяет только цепочку, «быть LB» может любой, у кого есть любой ключ этого CA. Например, взломанный worker: он в своей сети, у него есть свой валидный сертификат. +* Такой процесс пошёл бы в API мимо HAProxy: + * обошёл бы ограничение частоты входа (подставил бы свой `X-Forwarded-For`); + * обошёл бы лимиты LB; + * получил бы канал к API, которого по модели у него нет. +* Поэтому сервер проверяет **роль** — SAN `lb` — а не только факт подписи. Тест: сертификат `worker` от нашего CA → отказ. + +Альтернатива — отдельный CA только для LB-клиентов. Цепочка тогда сама означает «LB», но это хуже: + +* Identity держится на дисциплине выпуска. Достаточно случайно подписать этим CA второй сертификат, и он тоже станет «LB»: в конфигурации API нигде не видно, кому именно можно. +* Каждой новой роли нужен новый CA. +* Allowlist по SAN явный, проверяемый тестом и меняется одной переменной. + +Тот же принцип в Prometheus: `client_allowed_sans: [otel-collector, grafana, prometheus]`. Сертификат worker от того же CA туда не пускают — это проверяет тест. + +## 3. Где хранится первый секрет для доступа к OpenBao и кто имеет право unseal? + +* **Первый секрет — это `secret_id` AppRole.** + * Его выпускает оператор (`scripts/bao_operator.py bootstrap`) в `./secrets/bao/_secret_id`: вне Git, вне образов, папка 0700. + * Монтируется он только в свой сервис как Docker secret `/run/secrets/bao_secret_id`. + * Рядом лежит `role_id` — это не секрет, а имя роли. +* Вход требует **обе** части. Он даёт токен с одной политикой (`read messenger/data/`), TTL 1 ч, без default policy. Сервис читает свой путь и тут же отзывает токен (`revoke-self`). +* Срок жизни secret_id — 30 дней: учебный компромисс уровня 3. На уровне 4 был бы короткий secret_id с response wrapping или cert-auth. +* **Unseal может только оператор.** + * При `init` создаются 3 доли ключа (Shamir, порог 2) и root token. + * Они лежат в `~/.mtusi-lab7-operator//` с правами 0600: вне репозитория, вне volume OpenBao и вне всех контейнеров. В команде доли были бы у трёх разных людей. + * Root token нужен только для настройки. Он передаётся в CLI через stdin и никогда не попадает в приложение — это проверяет `make bao-check` с положительным контролем. + +## 4. Что происходит при истечении credentials, остановке OpenBao и рестарте API? + +| Событие | Что видит система | Почему так | +| --- | --- | --- | +| Истёк токен сервиса | ничего | токен отзывается через секунды после старта; секреты в памяти процесса; TTL 1 ч — верхняя граница, если отзыв не удался | +| Истёк secret_id | новый процесс получает 400 при входе и не стартует; работающие продолжают | оператор: `bao_operator.py new-secret-id ` + пересоздать сервис | +| Истекла сессия пользователя | 401 `Bearer realm="messenger"` | TTL в Valkey проверяется при каждом запросе; рестарт TTL не продлевает | +| Истёк leaf-сертификат | новые TLS-соединения отказываются (рукопожатие) | перевыпуск `init_pki.py` + пересоздать сервис; CA остаётся | +| OpenBao остановлен или sealed | работающие api/relay/worker обслуживают запросы; новая реплика пишет `openbao_unavailable`, ждёт 60 с, падает, Docker перезапускает её, пока не будет unseal | секреты нужны только при старте; доказано в `test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones` | +| Рестарт OpenBao | он запечатан, нужен `bao_operator.py unseal`; данные на месте (raft на volume `baodata`) | `scripts/restart.sh` делает это после рестарта хранилищ; `make test-persistence` PASS | +| Рестарт API | новый процесс: AppRole login → свой путь → revoke; новый случайный `X-Instance-Id`; unseal не нужен | `make test-failover`: реплика остановлена и восстановлена, запросы шли через вторую | + +## Короткие фразы для защиты + +* **PKI:** «Два CA. Публичный знают только клиенты, внутренний — только сервисы; ключи CA не лежат ни в одном контейнере.» +* **mTLS:** «Подпись CA — это пропуск, allowlist SAN — список допущенных ролей, сессия — права пользователя.» +* **PostgreSQL:** «Шесть ролей, никто из сервисов не суперпользователь, `pg_hba` принимает только `hostssl`; GRANT выписаны по коду, а worker не видит даже таблицу users.» +* **OpenBao:** «Не dev, raft на volume, TLS. AppRole на каждый сервис, токен живёт секунды, root token и доли — у оператора вне репозитория.» +* **Argon2id:** «Параметры m=19 MiB, t=2, p=1 выбраны замером в контейнере API с лимитом 1 CPU. Это ~31 мс на вход; более тяжёлые давали 70–250 мс и 4–14 входов в секунду на реплику, то есть дешёвый DoS.» +* **Лимит входа:** «Счётчик неудач в Valkey, общий для реплик, проверяется до Argon2; при блокировке даже верный пароль получает 429, иначе блокировка подсказывала бы, что пароль угадан.» +* **Hardening:** «Везде `cap_drop: ALL` и `no-new-privileges`, app/worker с uid 10001 и нулевыми capabilities; наружу только 8443 и 3000, оба HTTPS на loopback.» diff --git a/docs/OBSERVABILITY.md b/docs/OBSERVABILITY.md index 063c9aa..11ca01c 100644 --- a/docs/OBSERVABILITY.md +++ b/docs/OBSERVABILITY.md @@ -7,9 +7,9 @@ api ×2 ─┐ ┌─► Prometheus 3.16 (метрик relay ─┼─ OTLP/HTTP protobuf ─► otel-collector ─┼─► Loki 3.7 (логи, том lokidata) worker ─┘ :4318, сеть telemetry 0.165 contrib └─► Tempo 2.10 (трассы, том tempodata) ▲ - Grafana 13.2 (127.0.0.1:3000) ────────────┘ datasources с фиксированными UID, + Grafana 13.2 (https 127.0.0.1:3000) ──────┘ datasources с фиксированными UID, dashboard из Git (provisioning) -Prometheus сам опрашивает (scrape): otel-collector:8888, loki, tempo, grafana, себя. +Prometheus сам опрашивает (scrape) по HTTPS с клиентским сертификатом: loki, tempo, себя. Собственные метрики Collector (lab 7) приходят OTLP push по mTLS, pull-порт :8888 убран (у него не было TLS). ``` | Компонент | Зачем | Что хранит / делает | Где конфиг | @@ -92,19 +92,18 @@ CPU/RAM контейнера читаются из cgroup v2 (`/sys/fs/cgroup/cp | Collector | SDK: экспорт в фоновом потоке, таймаут 3 с; очереди BatchSpanProcessor / BatchLogRecordProcessor по 2048 записей, лишнее отбрасывается | очереди SDK ограничены; запросы не ждут экспорта | `messenger_telemetry_spans_exported_total{result="failure"}` (доставится после восстановления), «дырка» в графиках | | Grafana | Ничего: приложение о Grafana не знает | — | — | -Приложение не зависит от телеметрии: ни один сервис приложения не имеет `depends_on` на телеметрию, readiness API её не проверяет. Доказательства: `evidence/incidents/backend-down.txt`, `collector-down.txt`. +Приложение не зависит от телеметрии: ни один сервис приложения не имеет `depends_on` на телеметрию, readiness API её не проверяет. Доказательства — в ЛР 6 (`evidence/incidents/` того репозитория); в ЛР 7 топология та же, только по TLS. ## Переменные окружения (`compose.yaml`, якорь `x-otel-env`) | Переменная | По умолчанию | Смысл | | --- | --- | --- | | `OTEL_SDK_DISABLED` | `false` | `true` — телеметрия выключена (трек 1, baseline) | -| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://otel-collector:4318` | Collector | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | `https://otel-collector:4318` (lab 7: + `OTEL_EXPORTER_OTLP_CERTIFICATE`, клиентский cert/key сервиса) | Collector | | `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/protobuf` | как в `.env.example` | | `OTEL_EXPORTER_OTLP_TIMEOUT` | `3` (секунды) | таймаут одного экспорта | | `OTEL_TRACES_SAMPLER` / `_ARG` | `parentbased_always_on` / `1.0` | head sampling | | `OTEL_METRIC_EXPORT_INTERVAL` | `5000` мс | как часто SDK отправляет метрики | | `OTEL_BSP_MAX_QUEUE_SIZE`, `OTEL_BLRP_MAX_QUEUE_SIZE` | `2048` | ограничение очередей span/log в процессе | -| `OTEL_COLLECTOR_TRACES` | `traces-all` | `traces-tail` — tail sampling в Collector | | `OTEL_SERVICE_NAME` | по сервису | задано в compose для api/relay/worker | | `OTEL_RESOURCE_ATTRIBUTES` | `deployment.environment.name=lab` | ресурс | diff --git a/docs/OPERATOR.md b/docs/OPERATOR.md new file mode 100644 index 0000000..c3d8e28 --- /dev/null +++ b/docs/OPERATOR.md @@ -0,0 +1,91 @@ +# Инструкция оператора — lab7 + +Кто такой оператор: человек, у которого есть доступ к хосту и Docker. Только он держит: + +* ключи CA (`./secrets/pki/*-ca.key`); +* root token и доли unseal OpenBao (`~/.mtusi-lab7-operator//`); +* файлы паролей (`./secrets/*`). + +У приложения ничего из этого нет: у него только свой сертификат и свой AppRole. + +Команды ниже для Git Bash/Linux. На Windows `python` — это `.venv/Scripts/python`; подробнее в [WINDOWS.md](WINDOWS.md). + +## 1. Первый запуск из чистого clone + +```sh +python -m venv .venv +.venv/Scripts/python -m pip install --require-hashes --no-deps -r requirements.txt # для unit-тестов +.venv/Scripts/python -m pip install -r requirements-test.txt # pytest, httpx2, cryptography + +# 1) Пароли (по одному на сервис и роль) + PKI (два CA и сертификаты сервисов) -> ./secrets +.venv/Scripts/python scripts/init_secrets.py + +# 2) OpenBao. Стартует ЗАПЕЧАТАННЫМ (sealed); dev-режима нет +docker compose up -d openbao + +# 3) init (3 доли, порог 2) + unseal + KV/AppRole/политики + секреты + role_id/secret_id +.venv/Scripts/python scripts/bao_operator.py bootstrap + +# 4) Весь стенд: сборка, миграции (один раз), bucket'ы, API x2, LB, relay, worker, телеметрия +docker compose up -d --build --wait + +# 5) Проверка +make test CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.venv/Scripts/python +``` + +То же короче: `make secrets up PYTHON=.venv/Scripts/python`. + +Что создаётся и где лежит: + +| Что | Где | Кто читает | +| --- | --- | --- | +| Ключи CA `public-ca.key`, `internal-ca.key` | `./secrets/pki/` (вне Git и образов; папка `./secrets` 0700) | только `init_pki.py`; в контейнеры не монтируются | +| Leaf-сертификат и ключ сервиса | `./secrets/pki/.crt/.key` | только свой сервис, через compose `secrets:` (`/run/secrets/...`, read-only) | +| `public-ca.crt` | `./secrets/pki/` | любой клиент (`CA_FILE`); это не секрет | +| Пароли ролей БД, ключи S3, пароли RabbitMQ и Valkey | `./secrets/` | серверы (postgres, s3, broker, valkey), bootstrap-задачи (migrate, s3-init) и OpenBao KV. api/relay/worker файлов не получают | +| Root token, `unseal-share-1..3` | `~/.mtusi-lab7-operator//` (0600, **вне репозитория**) | только оператор (`bao_operator.py`) | +| role_id/secret_id api/relay/worker | `./secrets/bao/` | только свой сервис | + +Скрипты печатают только имена файлов, а не значения. Секреты попадают в CLI OpenBao через stdin `docker compose exec`: их нет в аргументах команд и в переменных окружения. + +## 2. Ежедневная работа + +| Ситуация | Что делать | +| --- | --- | +| Остановить стенд, сохранив данные | `docker compose stop` (или `down`, но **без** `-v`) | +| Запустить снова | `docker compose up -d openbao && python scripts/bao_operator.py unseal && docker compose up -d --wait` | +| Рестарт API / relay / worker | просто `docker compose restart api`: новый процесс заново входит по AppRole, unseal **не нужен** | +| Рестарт OpenBao (или всего хоста) | OpenBao запечатан. Уже работающие сервисы продолжают работу (секреты у них в памяти), новые реплики не стартуют, пока оператор не выполнит `python scripts/bao_operator.py unseal` | +| Проверить состояние OpenBao | `python scripts/bao_operator.py status` | +| Полный перезапуск всех процессов (хук теста) | `sh scripts/restart.sh` — в нём есть шаг unseal | +| Остановить одну реплику API (хук теста) и вернуть | `TARGET_INSTANCE_ID= sh scripts/stop-one.sh`, затем `make restore` | +| Чей это `X-Instance-Id`? | `docker compose exec api cat /tmp/instance_id` у каждой реплики (alias случайный, без hostname/IP) | + +## 3. Что происходит при отказах + +* **OpenBao sealed или остановлен.** Сервис при старте ждёт до `BAO_STARTUP_TIMEOUT_SECONDS` (60 с) и пишет `openbao_unavailable`. Потом завершается с ошибкой конфигурации, Docker его перезапускает, цикл повторяется до unseal. Healthcheck OpenBao (`bao status`) зелёный только у распечатанного сервера, поэтому `depends_on: service_healthy` не даёт `docker compose up` запустить api/relay/worker к запечатанному OpenBao. +* **Истёк токен сервиса.** Ничего не происходит: токен отзывается сразу после чтения (`revoke-self`), TTL 1 ч — только верхняя граница. Каждый новый процесс входит заново. +* **Истёк secret_id (30 дней).** Новый процесс получит 400 при входе и не стартует. Выпустить новый: `python scripts/bao_operator.py new-secret-id api`, затем `docker compose up -d --force-recreate api`. +* **Истёк leaf-сертификат (365 дней).** Удалить `secrets/pki/.crt/.key` (для LB ещё `lb.pem`/`ingress.pem`), запустить `python scripts/init_pki.py`, пересоздать сервис. CA при этом сохраняется. +* **Потерян volume `baodata`.** Секреты пропали, но их источник — `./secrets`. Нужно убрать старый каталог оператора (он принадлежит удалённому хранилищу), заново выполнить `bao_operator.py bootstrap` и удалить `secrets/bao/*_secret_id`, чтобы выпустились новые. + +## 4. Намеренное удаление учебных данных + +```sh +docker compose down -v # ВСЕ volumes стенда: БД, S3, очередь, OpenBao +rm -rf secrets ~/.mtusi-lab7-operator/mtusi-lab7 # пароли, PKI, доли unseal и root token +``` + +После этого остаётся только первый запуск (раздел 1). + +## 5. Второй (чистый) стенд рядом с рабочим + +Порты 8443 и 3000 у обоих стендов одинаковые, поэтому рабочий стенд сначала останавливается (`docker compose -p mtusi-lab7 stop`). Чистый стенд разворачивается в отдельной папке со своим проектом: + +```sh +git clone lab7-clean && cd lab7-clean && git checkout solution/bvt2302-bodanyuk +export COMPOSE_PROJECT_NAME=mtusi-lab7-clean # свои контейнеры, volumes, сети и свой каталог оператора +python -m venv .venv && .venv/Scripts/python -m pip install -r requirements-test.txt \ + && .venv/Scripts/python -m pip install --require-hashes --no-deps -r requirements.txt +make secrets up PYTHON=.venv/Scripts/python +``` diff --git a/docs/PR.md b/docs/PR.md new file mode 100644 index 0000000..4876a46 --- /dev/null +++ b/docs/PR.md @@ -0,0 +1,70 @@ +# Текст PR + +**Заголовок:** `ЛР 7 — БВТ2302 — Боданюк — на 3` + +**База:** `mtusi2026/mtusi2026lab7:main` ← `wfa/mtusi2026lab7:solution/bvt2302-bodanyuk` + +--- + +## Лабораторная 7 + +Автор / группа: Боданюк Алексей, БВТ2302 +Целевая оценка (3/4/5): 3 +Трек 5, если заявлен: нет + +**Что реализовано и что перенесено.** Перенесено решение ЛР 6 (первый коммит, без изменений): Python 3.13, Starlette/uvicorn, PostgreSQL 18, Valkey 8.1, HAProxy 3.2 (2 реплики API), SeaweedFS 4.46, RabbitMQ 4.3 (outbox, relay, worker, lease), OpenTelemetry → Collector → Prometheus/Loki/Tempo → Grafana. + +Новое в ЛР 7: + +* **PKI.** `scripts/init_pki.py`: `public-ca` для ingress и Grafana, `internal-ca` для сервисов, leaf на каждый сервис (SAN = имя compose). Ключи лежат вне Git и образов, каждому сервису монтируется только его пара. +* **Внешний HTTPS.** HAProxy на `127.0.0.1/[::1]:8443`, TLS 1.2+, открытого 8080 нет. +* **LB → API: обязательное mTLS с allowlist identity.** API требует клиентский сертификат `internal-ca` и после рукопожатия сверяет SAN с `lb` (`src/messenger/tls.py`). Docker-healthcheck ходит на loopback-listener. +* **TLS ко всем зависимостям с проверкой сервера:** + * PostgreSQL `verify-full`, в `pg_hba` только `hostssl`; + * Valkey только TLS-порт, ACL-пользователь `api`; + * RabbitMQ только AMQPS 5671; + * SeaweedFS S3 только HTTPS; + * OTLP → Collector с обязательным клиентским сертификатом; + * Collector/Grafana → Prometheus/Loki/Tempo по mTLS, у Prometheus allowlist SAN. +* **Минимальные права.** 6 ролей PostgreSQL с GRANT по коду (`migrations/0007_least_privilege.sql`), раздельные ключи S3 (admin только у `s3-init`), пользователи RabbitMQ publish-only / consume-only. +* **OpenBao 2.7.3.** + * Не dev-режим: raft на volume, TLS, audit в stdout. + * Вход по AppRole с отдельной политикой для api/relay/worker, у каждого свой путь KV. Сервис входит, читает свой путь и отзывает токен. + * Root token и доли unseal лежат у оператора вне репозитория (`scripts/bao_operator.py`). + * У приложения нет ни одного файла с паролем. +* **Argon2id** m=19 MiB / t=2 / p=1, формат PHC. Параметры выбраны замером в контейнере API (`bench/argon2_bench.py`). +* **Лимит неудачных входов.** Хранится в Valkey, общий для реплик: 429 + `Retry-After`, проверяется до Argon2. +* **Hardening.** Везде `cap_drop: [ALL]` и `no-new-privileges`; app/worker работают от uid 10001 с нулевыми capabilities; лимиты у всех контейнеров; наружу открыты только 8443 и 3000 (HTTPS, loopback). +* **`X-Instance-Id`** — случайный alias `i-<12 hex>`, без hostname/IP. + +**Команды запуска из чистого clone** (подробно — REPORT.md, docs/OPERATOR.md, docs/WINDOWS.md): + +```sh +python -m venv .venv && .venv/bin/python -m pip install -r requirements-test.txt +.venv/bin/python scripts/init_secrets.py # пароли + PKI -> ./secrets (вне Git) +docker compose up -d openbao # стартует sealed +.venv/bin/python scripts/bao_operator.py bootstrap # init/unseal/политики/секреты +docker compose up -d --build --wait +make test test-security CA_FILE=$PWD/secrets/pki/public-ca.crt +make mtls-check bao-check +``` + +**Результаты проверок и ссылка на REPORT.md:** см. таблицу «критерий → команда → результат → файл» в [REPORT.md](../REPORT.md) и [evidence/SUMMARY.md](../evidence/SUMMARY.md). Доказательства собраны из чистого clone в отдельной папке с отдельным `COMPOSE_PROJECT_NAME`. + +**Ограничения / известные ошибки** (подробно — REPORT.md, «Ограничения»): + +* уровень 4 не заявлен: нет ротации и отзыва leaf/secret, нет mTLS к брокеру, нет сканирования образов; +* SecretID живёт 30 дней; +* Loki/Tempo проверяют только цепочку CA, без allowlist SAN; +* четыре stateful-образа стартуют от root ради `chown` (оставлены CHOWN/SETUID/SETGID/DAC_OVERRIDE/FOWNER). + +**Замечания к другим PR учтены.** Сгенерированные `secrets/` и учётные данные в Git не попадают (это проверяет тест); API не получает admin-ключ S3, bucket создаёт `s3-init`; сравнительная матрица разрешений S3/брокер/PostgreSQL есть в `contracts/trust-matrix.md`. + +**Источники и использование ИИ:** документация OpenBao (AppRole, policies, production hardening), OWASP Password Storage, документация HAProxy, PostgreSQL, Valkey, RabbitMQ TLS, OpenTelemetry Collector, Prometheus web-config. Код, тесты, конфигурации и документы написаны с помощью ИИ-ассистента Claude (Anthropic). Решения разобраны и проверены мной; на защите объясняю их сам. + +- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [x] Контракт и публичные тесты не ослаблены. +- [x] make check и make test выполнены; приложен реальный вывод. +- [x] Сценарии отказов/безопасности своего уровня воспроизведены. +- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. +- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md index 7a46d17..0571ed0 100644 --- a/docs/RUNBOOK.md +++ b/docs/RUNBOOK.md @@ -1,6 +1,6 @@ # Runbook: что делать, когда сработал алерт -Общий порядок: **метрика говорит «что и насколько», трасса — «где по пути», лог — «что именно случилось»**. Начинать с dashboard «Messenger lab 6» (Grafana, http://127.0.0.1:3000), потом Explore → Tempo/Loki. Без Grafana: `python scripts/obs.py alerts|promql|search|trace|logs`. +Общий порядок: **метрика говорит «что и насколько», трасса — «где по пути», лог — «что именно случилось»**. Начинать с dashboard «Messenger lab 6» (Grafana, https://localhost:3000, CA `secrets/pki/public-ca.crt`), потом Explore → Tempo/Loki. Без Grafana: `python scripts/obs.py alerts|promql|search|trace|logs`. ## MessengerApiHighErrorRate diff --git a/docs/SLO.md b/docs/SLO.md index 7c81d8a..6710fe7 100644 --- a/docs/SLO.md +++ b/docs/SLO.md @@ -29,4 +29,4 @@ Время обнаружения ≈ время, пока условие станет истинным по окну rate (до 1 мин) + `for` + до 15 с интервала вычисления. Порог «трафик > 0,2 req/s» убирает ложное срабатывание на пустом стенде, где одна ошибка из пяти запросов — уже 20 %. -Доставки наружу нет (нет Alertmanager): состояния pending → firing → resolved видны в Prometheus (`/api/v1/alerts`, ряд `ALERTS`), на dashboard (панели «Alerts firing» и таблица) и через `python scripts/obs.py alerts`. Проверка искусственными отказами: `bench/incidents.py`, результаты в `evidence/incidents/`. +Доставки наружу нет (нет Alertmanager): состояния pending → firing → resolved видны в Prometheus (`/api/v1/alerts`, ряд `ALERTS`), на dashboard (панели «Alerts firing» и таблица) и через `python scripts/obs.py alerts`. Проверка искусственными отказами проводилась в ЛР 6 (`bench/incidents.py` там); в ЛР 7 инциденты уровня 4 не повторялись. diff --git a/docs/WINDOWS.md b/docs/WINDOWS.md index 4a66f58..17e12d4 100644 --- a/docs/WINDOWS.md +++ b/docs/WINDOWS.md @@ -1,4 +1,4 @@ -# Запуск на Windows и сценарий защиты ЛР 6 +# Запуск на Windows и сценарий защиты ЛР 7 Команды — в **PowerShell** из папки проекта (где лежит `compose.yaml`). Переменные `$env:...` действуют до закрытия окна. @@ -6,98 +6,101 @@ | Программа | Зачем | Важно | | --- | --- | --- | -| [Git for Windows](https://git-scm.com/download/win) | clone и Git Bash | путь по умолчанию `C:\Program Files\Git`: оттуда `scripts\*.cmd` запускают `.sh`-хуки | -| [Docker Desktop](https://www.docker.com/products/docker-desktop/) | весь стенд: 9 сервисов ЛР 5 + Collector, Prometheus, Loki, Tempo, Grafana | backend WSL 2; Settings → Resources ≥ 4 CPU и ≥ 10 ГБ RAM (сумма лимитов ~9,5 ГБ, реально занято ~2,5 ГБ) | -| [Python 3.12+](https://www.python.org/downloads/windows/) | secrets, тесты, сценарии, чтение наблюдений | галочка **Add python.exe to PATH** | -| GNU make (необязательно) | `make check/test/...` | `winget install ezwinports.make`; в каждом окне `$env:Path += ";C:\Program Files\Git\usr\bin"` | +| [Git for Windows](https://git-scm.com/download/win) | clone и Git Bash | путь по умолчанию `C:\Program Files\Git`: оттуда `scripts\*.cmd` запускают `.sh`-хуки и проверки | +| [Docker Desktop](https://www.docker.com/products/docker-desktop/) | весь стенд: 16 сервисов (ЛР 6 + OpenBao) | backend WSL 2; Settings → Resources ≥ 4 CPU и ≥ 10 ГБ RAM | +| [Python 3.12+](https://www.python.org/downloads/windows/) | PKI, secrets, оператор OpenBao, тесты | галочка **Add python.exe to PATH** | +| GNU make (необязательно) | `make test/...` | `winget install ezwinports.make`; в каждом окне `$env:Path += ";C:\Program Files\Git\usr\bin"` | -## 2. Развернуть (заранее, нужен интернет) +Если Docker пишет `all predefined address pools have been fully subnetted`, значит, сети старых стендов заняли все подсети. Удалите сети стендов, которые сейчас не нужны: `docker network rm <имя>`. Тома с данными при этом не трогаются, а `docker compose up` создаст сети заново. + +## 2. Развернуть (заранее) ```powershell -git clone https://gitea.privcloud.tech/wfa/mtusi2026lab6 mtusi2026lab6 -cd mtusi2026lab6 +git clone https://gitea.privcloud.tech/wfa/mtusi2026lab7 mtusi2026lab7 +cd mtusi2026lab7 git checkout solution/bvt2302-bodanyuk -python scripts\init_secrets.py # БД, Valkey, S3, RabbitMQ, пароль Grafana -> .\secrets -Copy-Item .env.example .env -docker compose --env-file .env config --quiet -docker compose --env-file .env up -d --build --wait -``` - -Первый запуск качает ~2 ГБ образов (Grafana ~1,9 ГБ в распакованном виде) и собирает образ приложения. Медленный интернет: образы можно скачать заранее в другом месте и перенести `docker save` / `docker load` — теги и digest в `compose.yaml` совпадут. - -Окружение для тестов (один раз): - -```powershell python -m venv .venv .venv\Scripts\python -m pip install --require-hashes --no-deps -r requirements.txt -.venv\Scripts\python -m pip install -r requirements-test.txt -r requirements-dev.txt +.venv\Scripts\python -m pip install -r requirements-test.txt # pytest, httpx2, cryptography (PKI) +$env:PYTHONUTF8 = "1" +.venv\Scripts\python scripts\init_secrets.py # пароли + PKI -> .\secrets +docker compose up -d openbao # стартует запечатанным +.venv\Scripts\python scripts\bao_operator.py bootstrap # init/unseal/политики/секреты +docker compose up -d --build --wait ``` -Стенды ЛР 3–5 занимают порт 8080: `docker compose -p mtusi-lab5 stop`. +Root token и доли unseal окажутся в `%USERPROFILE%\.mtusi-lab7-operator\mtusi-lab7\`: вне папки проекта и вне Git. + +Порты 8443 и 3000 должны быть свободны. Стенды других лабораторных останавливайте через `docker compose -p <проект> stop`, без `down -v`. ## 3. Перед защитой ```powershell $env:PYTHONUTF8 = "1" -docker compose up -d --wait -python tests\smoke.py --base-url http://localhost:8080 # = make test -python scripts\obs.py alerts # пусто = ничего не горит +$env:CA_FILE = (Resolve-Path secrets\pki\public-ca.crt).Path +docker compose up -d openbao; .venv\Scripts\python scripts\bao_operator.py unseal; docker compose up -d --wait +python tests\smoke.py --ca-file $env:CA_FILE # = make test ``` -Grafana: **http://127.0.0.1:3000**, пользователь `admin`, пароль — `Get-Content secrets\grafana_admin_password`. Dashboard «Messenger lab 6» открывается домашней страницей (папка Messenger). +* Grafana: **https://localhost:3000**. Браузер не знает учебный CA, поэтому предупредит о сертификате. Чтобы предупреждения не было, нужно добавить `secrets\pki\public-ca.crt` в «Доверенные корневые центры» текущего пользователя (`certmgr.msc`), а после защиты удалить. +* Пользователь Grafana — `admin`, пароль — `Get-Content secrets\grafana_admin_password`. ## 4. Сценарий защиты README — по шагам -**Шаг 1. С нуля, provisioning, smoke и нагрузка.** +**Шаг 1. Развернуть с нуля и `make test` по HTTPS.** ```powershell -docker compose down -v; Remove-Item -Recurse secrets # ТОЛЬКО если нужен чистый лист: удаляет учебные данные -python scripts\init_secrets.py +docker compose down -v; Remove-Item -Recurse secrets, "$env:USERPROFILE\.mtusi-lab7-operator\mtusi-lab7" # ТОЛЬКО для чистого листа: удаляет учебные данные +.venv\Scripts\python scripts\init_secrets.py +docker compose up -d openbao +.venv\Scripts\python scripts\bao_operator.py bootstrap docker compose up -d --build --wait -python tests\smoke.py --base-url http://localhost:8080 -python tests\load.py --base-url http://localhost:8080 --duration 60 --concurrency 4 +python tests\smoke.py --base-url https://localhost:8443 --ca-file $env:CA_FILE ``` -В Grafana dashboard и три datasource уже есть — ничего не набирается руками (`infra/grafana/provisioning`). Проверка всех запросов dashboard без браузера: `python scripts\check_dashboard.py`. - -**Шаг 2. Свежие метрики, одна трасса и её логи API и worker.** +**Шаг 2. `make test-security`: недоверенный CA отклоняется; ACL и logout.** ```powershell -python scripts\trace_demo.py +python tests\security.py --ca-file $env:CA_FILE +.venv\Scripts\python -m pytest student-tests\test_security.py -k "ingress or plaintext" -v +.venv\Scripts\python -m pytest student-tests\test_api.py -k "foreign_chat or logout or x_user_id" -v ``` -Скрипт отправляет upload со **своим** `traceparent`, ждёт ready и печатает дерево span-ов из Tempo (API SERVER → relay PRODUCER → worker CONSUMER → s3/db) и записи Loki с этим `trace_id` (API `request`, worker `job_done`). В Grafana: Explore → Tempo → вставить trace id → у span-а кнопка «Logs for this span»; в Loki у записи поле `trace_id` ведёт обратно в Tempo. - -**Шаг 3 (уровень 4). Upload → worker в одной трассе; worker остановлен → firing → resolved.** +**Шаг 3. Внутреннее mTLS LB → API.** ```powershell -.venv\Scripts\python -m pytest student-tests\test_observability.py -v # цепочка, retry в той же трассе, логи, labels, секреты -python bench\incidents.py worker-stop # ~5 мин: MessengerQueueLagGrowing firing, затем resolved -python bench\incidents.py db-lock # ~4 мин: блокировка таблицы -> 5xx/latency, trace показывает db span -python bench\incidents.py slow-handler # ~6 мин: контраст - медленный код, БД в норме +scripts\mtls_check.cmd ``` -Вручную то же самое: `docker compose stop worker` → на dashboard растут «Queue depth» и «Oldest job age», через ~2 мин алерт firing (`python scripts\obs.py alerts`) → `docker compose start worker` → backlog уходит, алерт resolved. +По каждой реплике: без сертификата, с чужим CA и с сертификатом `worker` — отказ; с `lb` — 200. В конце печатаются строки лога API `mtls_identity_rejected`. -**Шаг 4. Остановить telemetry backend — API работает, exporter ограничен.** +**Шаг 4. OpenBao, рестарт с сохранением данных, отказ реплик.** ```powershell -python bench\incidents.py backend-down # Tempo+Loki остановлены 3 мин, клиентские ошибки = 0, RSS Collector ограничен -python bench\incidents.py collector-down # сам Collector остановлен 2 мин +scripts\bao_check.cmd # allow/deny + root token в app отсутствует +.venv\Scripts\python scripts\bao_operator.py status +python tests\resilience.py --mode persistence --action-script scripts\restart.cmd --ca-file $env:CA_FILE +python tests\resilience.py --mode failover --action-script scripts\stop-one.cmd --ca-file $env:CA_FILE +bash scripts/restore-api.sh # вернуть остановленную реплику +python tests\resilience.py --mode failover --action-script scripts\stop-one.cmd --ca-file $env:CA_FILE +bash scripts/restore-api.sh ``` -Для 5 (трек 1) — повторить эксперимент: `python bench\track1.py --runs 1 --duration 60 --output evidence\track1-demo` (~15 мин). Готовые результаты: [TRACK1.md](TRACK1.md). +Тест failover сам выбирает реплику, обслужившую запрос. Если второй прогон остановил ту же реплику (видно в `docker compose ps -a api`), повторите его. -## 5. Если что-то пошло не так +Показать запечатанный OpenBao (минута): -| Симптом | Что сделать | -| --- | --- | -| `error during connect … dockerDesktopLinuxEngine` | Docker Desktop не запущен | -| `port is already allocated` на 8080/3000 | другой стенд; или в `.env` `APP_PUBLISH_PORT=8081`, `GRAFANA_PORT=3001` | -| Grafana unhealthy / медленная | `docker stats`: лимит 1 ГБ; `docker compose restart grafana` | -| в Grafana «No data» | подождать 15–30 с (метрики отправляются раз в 5 с); проверить `python scripts\check_dashboard.py` | -| нет трассы по id | spans приходят в Tempo через 2–5 с; `docker compose logs otel-collector` | -| `UnicodeDecodeError` в `tests\*.py` | `$env:PYTHONUTF8 = "1"` | -| локальный `.env` устарел | сравнить с `.env.example` | +```powershell +docker compose restart openbao +.venv\Scripts\python scripts\bao_operator.py status # sealed=True +python tests\smoke.py --ca-file $env:CA_FILE # API работает: секреты в памяти +.venv\Scripts\python scripts\bao_operator.py unseal +``` -Остановить после защиты: `docker compose down` (данные и история телеметрии сохранятся в volumes). +## 5. Подводные камни Windows + +* `PYTHONUTF8=1` обязателен: в путях и выводе есть кириллица. +* Хуки запускаются через `scripts\*.cmd` → Git Bash. Аргументы вида `/run/secrets/...` Git Bash превращает в пути Windows, поэтому скрипты ставят `MSYS_NO_PATHCONV=1`. +* Секреты передаются в контейнеры через stdin. Python в текстовом режиме на Windows пишет `\r\n`, поэтому тесты передают stdin байтами. +* Долгие прогоны (полный `pytest`, сбор доказательств) запускайте отдельным процессом: `powershell -File scripts\bg.ps1 -Log <файл> -Cmd "<команда>"`. Фоновые задачи терминала умирают вместе с ним. +* После перезапуска Docker Desktop OpenBao запечатан: `bao_operator.py unseal`, затем `docker compose up -d --wait`. diff --git a/evidence/argon2/bench.json b/evidence/argon2/bench.json new file mode 100644 index 0000000..f4aa20a --- /dev/null +++ b/evidence/argon2/bench.json @@ -0,0 +1,290 @@ +{ + "when": "2026-11-27T13:50:01Z", + "python": "3.13.16", + "argon2_cffi": "25.1.0", + "cpus_visible": 8, + "cgroup": { + "cpu_max": "100000 100000", + "memory_max": "536870912" + }, + "sequential": [ + { + "m_kib": 19456, + "t": 2, + "p": 1, + "n": 15, + "median_ms": 30.6, + "p95_ms": 47.4, + "cpu_ms_per_hash": 30.4, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=19456,t=2,p=1" + ] + }, + { + "m_kib": 19456, + "t": 3, + "p": 1, + "n": 15, + "median_ms": 47.4, + "p95_ms": 54.7, + "cpu_ms_per_hash": 45.1, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=19456,t=3,p=1" + ] + }, + { + "m_kib": 19456, + "t": 4, + "p": 1, + "n": 15, + "median_ms": 102.3, + "p95_ms": 175.4, + "cpu_ms_per_hash": 62.3, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=19456,t=4,p=1" + ] + }, + { + "m_kib": 32768, + "t": 2, + "p": 1, + "n": 15, + "median_ms": 72.9, + "p95_ms": 82.4, + "cpu_ms_per_hash": 69.8, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=32768,t=2,p=1" + ] + }, + { + "m_kib": 32768, + "t": 3, + "p": 1, + "n": 15, + "median_ms": 144.5, + "p95_ms": 284.0, + "cpu_ms_per_hash": 116.3, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=32768,t=3,p=1" + ] + }, + { + "m_kib": 32768, + "t": 4, + "p": 1, + "n": 15, + "median_ms": 144.6, + "p95_ms": 378.7, + "cpu_ms_per_hash": 135.4, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=32768,t=4,p=1" + ] + }, + { + "m_kib": 47104, + "t": 2, + "p": 1, + "n": 15, + "median_ms": 119.1, + "p95_ms": 291.2, + "cpu_ms_per_hash": 114.6, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=47104,t=2,p=1" + ] + }, + { + "m_kib": 47104, + "t": 3, + "p": 1, + "n": 15, + "median_ms": 144.3, + "p95_ms": 384.1, + "cpu_ms_per_hash": 141.7, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=47104,t=3,p=1" + ] + }, + { + "m_kib": 47104, + "t": 4, + "p": 1, + "n": 15, + "median_ms": 246.7, + "p95_ms": 485.3, + "cpu_ms_per_hash": 215.5, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=47104,t=4,p=1" + ] + }, + { + "m_kib": 65536, + "t": 2, + "p": 1, + "n": 15, + "median_ms": 162.8, + "p95_ms": 368.5, + "cpu_ms_per_hash": 157.4, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=65536,t=2,p=1" + ] + }, + { + "m_kib": 65536, + "t": 3, + "p": 1, + "n": 15, + "median_ms": 233.3, + "p95_ms": 669.8, + "cpu_ms_per_hash": 222.1, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=65536,t=3,p=1" + ] + }, + { + "m_kib": 65536, + "t": 4, + "p": 1, + "n": 15, + "median_ms": 319.5, + "p95_ms": 711.3, + "cpu_ms_per_hash": 261.4, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=65536,t=4,p=1" + ] + } + ], + "concurrent": [ + { + "m_kib": 19456, + "t": 2, + "threads": 1, + "hashes": 6, + "wall_s": 0.22, + "hashes_per_s": 26.8, + "median_ms": 33.6, + "p95_ms": 61.0, + "cpu_utilisation": 0.86, + "ram_mib_hashing": 19.0 + }, + { + "m_kib": 19456, + "t": 2, + "threads": 2, + "hashes": 12, + "wall_s": 0.39, + "hashes_per_s": 30.6, + "median_ms": 74.3, + "p95_ms": 89.3, + "cpu_utilisation": 1.09, + "ram_mib_hashing": 38.0 + }, + { + "m_kib": 19456, + "t": 2, + "threads": 4, + "hashes": 24, + "wall_s": 1.38, + "hashes_per_s": 17.4, + "median_ms": 204.1, + "p95_ms": 289.0, + "cpu_utilisation": 0.86, + "ram_mib_hashing": 76.0 + }, + { + "m_kib": 47104, + "t": 2, + "threads": 1, + "hashes": 6, + "wall_s": 1.4, + "hashes_per_s": 4.3, + "median_ms": 206.5, + "p95_ms": 369.1, + "cpu_utilisation": 0.58, + "ram_mib_hashing": 46.0 + }, + { + "m_kib": 47104, + "t": 2, + "threads": 2, + "hashes": 12, + "wall_s": 1.62, + "hashes_per_s": 7.4, + "median_ms": 286.2, + "p95_ms": 295.9, + "cpu_utilisation": 1.01, + "ram_mib_hashing": 92.0 + }, + { + "m_kib": 47104, + "t": 2, + "threads": 4, + "hashes": 24, + "wall_s": 4.47, + "hashes_per_s": 5.4, + "median_ms": 703.6, + "p95_ms": 988.7, + "cpu_utilisation": 0.86, + "ram_mib_hashing": 184.0 + }, + { + "m_kib": 19456, + "t": 3, + "threads": 1, + "hashes": 6, + "wall_s": 0.68, + "hashes_per_s": 8.8, + "median_ms": 101.2, + "p95_ms": 165.8, + "cpu_utilisation": 0.45, + "ram_mib_hashing": 19.0 + }, + { + "m_kib": 19456, + "t": 3, + "threads": 2, + "hashes": 12, + "wall_s": 0.84, + "hashes_per_s": 14.3, + "median_ms": 114.2, + "p95_ms": 201.5, + "cpu_utilisation": 0.82, + "ram_mib_hashing": 38.0 + }, + { + "m_kib": 19456, + "t": 3, + "threads": 4, + "hashes": 24, + "wall_s": 1.97, + "hashes_per_s": 12.2, + "median_ms": 304.6, + "p95_ms": 409.3, + "cpu_utilisation": 0.92, + "ram_mib_hashing": 76.0 + } + ] +} diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml index ccbe005..c75b242 100644 --- a/infra/otel/collector.yaml +++ b/infra/otel/collector.yaml @@ -17,9 +17,7 @@ # otelcol_exporter_enqueue_failed_*). memory_limiter refuses new data above its limit. # Its own metrics: PUSHED over OTLP/HTTPS to Prometheus (lab 7; the lab 6 pull endpoint :8888 had no # TLS). health_check listens on the container's loopback only. -# -# Traces pipeline variants (lab 6 track 1): this file keeps EVERY span; the overlay -# traces-tail.yaml (passed as a second --config, compose OTEL_COLLECTOR_TRACES) adds tail sampling. +# Every span is kept (the lab 6 track 1 tail-sampling overlay is not part of lab 7). extensions: health_check: diff --git a/infra/otel/traces-all.yaml b/infra/otel/traces-all.yaml deleted file mode 100644 index 91a722a..0000000 --- a/infra/otel/traces-all.yaml +++ /dev/null @@ -1,6 +0,0 @@ -# Overlay for collector.yaml: keep every received span (no tail sampling). Selected by -# OTEL_COLLECTOR_TRACES=traces-all (compose). Lists are replaced, maps are merged by the Collector. -service: - pipelines: - traces: - processors: [memory_limiter, batch] diff --git a/infra/otel/traces-tail.yaml b/infra/otel/traces-tail.yaml deleted file mode 100644 index 134ee8a..0000000 --- a/infra/otel/traces-tail.yaml +++ /dev/null @@ -1,39 +0,0 @@ -# Overlay for collector.yaml: TAIL sampling of traces (track 1 "balanced" configuration, -# docs/TRACK1.md). The decision is taken per trace after decision_wait, when its spans are in: -# keep ALL traces with an error span (status ERROR: HTTP 5xx, failed/retried job, S3/DB error), -# keep ALL slow traces (root to last span >= 250 ms), -# keep 10 % of the rest (probabilistic, by trace id: the same trace -> the same decision). -# Head sampling in the SDK (OTEL_TRACES_SAMPLER_ARG) decides at the first span and cannot know -# whether the request will fail or be slow; tail sampling can, at the price of buffering spans -# in the Collector (num_traces x spans) for decision_wait. -# -# A job is processed seconds after its upload: those spans may arrive after the upload trace was -# decided. decision_cache remembers the decision per trace id, so late spans of a kept trace are -# kept, and late spans of a dropped one are dropped (unless they are errors/slow by themselves: -# then they form a partial trace - a documented limit of the approach). -processors: - tail_sampling: - decision_wait: 5s - num_traces: 20000 - expected_new_traces_per_sec: 200 - decision_cache: - sampled_cache_size: 100000 - non_sampled_cache_size: 100000 - policies: - - name: errors - type: status_code - status_code: - status_codes: [ERROR] - - name: slow - type: latency - latency: - threshold_ms: 250 - - name: baseline - type: probabilistic - probabilistic: - sampling_percentage: 10 - -service: - pipelines: - traces: - processors: [memory_limiter, tail_sampling, batch] diff --git a/migrations/0007_least_privilege.sql b/migrations/0007_least_privilege.sql index 2d951e3..9901136 100644 --- a/migrations/0007_least_privilege.sql +++ b/migrations/0007_least_privilege.sql @@ -38,6 +38,11 @@ GRANT UPDATE ON jobs, attachments TO messenger_jobctl; -- Auditor: read-only checker of the pipeline invariants. GRANT SELECT ON jobs, job_attempts, job_events, outbox, attachments, attachment_variants TO messenger_auditor; +-- job_events (pipeline audit log, no user data): the failure-injection points of the experiments +-- (service.crash_once, FAULT_POINTS) look up their own "fault_injected" marker before crashing, so +-- the services that can crash on purpose may read it. +GRANT SELECT ON job_events TO messenger_api, messenger_relay, messenger_worker; + -- Identity columns of outbox/job_events: inserting roles need the sequences. GRANT USAGE ON SEQUENCE outbox_id_seq, job_events_id_seq TO messenger_api, messenger_relay, messenger_worker, messenger_jobctl; diff --git a/requirements-test.txt b/requirements-test.txt index fea533d..c9a0787 100644 --- a/requirements-test.txt +++ b/requirements-test.txt @@ -4,3 +4,5 @@ httpx2==2.13.1 jsonschema==4.26.0 # Lab 4 tests: generate PNG/JPEG fixtures (valid, corrupt, oversized) on the fly. pillow==12.3.0 +# Lab 7: local PKI (scripts/init_pki.py): CA and service certificates, run on the operator's host. +cryptography==50.0.2 diff --git a/scripts/collect_evidence.py b/scripts/collect_evidence.py index d268d87..148db90 100644 --- a/scripts/collect_evidence.py +++ b/scripts/collect_evidence.py @@ -1,24 +1,18 @@ #!/usr/bin/env python3 -"""Run every check of REPORT.md on the current checkout and save the real output in evidence/. +"""Collect the lab 7 evidence on a RUNNING stand into evidence/ (README defense scenario steps 1-4). - python scripts/collect_evidence.py # ~3 h; the stand must NOT be running yet - python scripts/collect_evidence.py --skip-track1 # without the 45 min track 1 experiment + python scripts/collect_evidence.py [--skip-student-tests] -Intended for a CLEAN CLONE (fresh volumes): it creates secrets and .env, builds and starts the -stand, then runs make check/validate/test/test-persistence/test-failover, the lab 5 defense -scenario (scripts/demo_pipeline.py), lab 6: provisioning check of Grafana, the controlled trace -(scripts/trace_demo.py), every dashboard query (scripts/check_dashboard.py), the own tests, the -level 4 incidents (bench/incidents.py) and the track 1 experiment (bench/track1.py), and records -container states before/after every hook and the real resource limits (docker inspect). Prints no secrets -(hook output is shown by the public tests as suppressed; our scripts print names and states only). -On Windows the hooks are the scripts/*.cmd wrappers (Git Bash) and make needs Git's usr/bin. +Each step writes its own file and goes on after a failure; evidence/SUMMARY.md lists every step with +its command, exit code and file. Nothing secret is printed by the commands used (they print status +codes, key NAMES, PASS/FAIL). Long: start it detached on Windows (scripts/bg.ps1). """ from __future__ import annotations +import argparse import datetime as dt import json import os -import shutil import subprocess import sys import time @@ -26,196 +20,168 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] EVIDENCE = ROOT / "evidence" -WINDOWS = os.name == "nt" -HOOK = ".cmd" if WINDOWS else ".sh" -PYTHON = sys.executable -VENV_PY = str(ROOT / ".venv" / ("Scripts/python.exe" if WINDOWS else "bin/python")) -# Makefile recipes use $(PYTHON) unquoted: pass interpreters WITHOUT spaces in the path. -MAKE_PY = "python" if WINDOWS else "python3" -MAKE_VENV = ".venv/Scripts/python.exe" if WINDOWS else ".venv/bin/python" -ENV = {**os.environ, "PYTHONUTF8": "1"} -if WINDOWS: - ENV["PATH"] = ENV["PATH"] + os.pathsep + r"C:\Program Files\Git\usr\bin" +PY = sys.executable +CA = str(ROOT / "secrets" / "pki" / "public-ca.crt") +WIN = os.name == "nt" +ENV = {**os.environ, "PYTHONUTF8": "1", "MSYS_NO_PATHCONV": "1", "CA_FILE": CA} +results: list[tuple[str, str, int, str, float]] = [] -def now() -> str: - return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") +def hook(name: str) -> str: + return str(ROOT / "scripts" / (name + (".cmd" if WIN else ".sh"))) -def sh(cmd: list[str], timeout: float = 1800, env: dict | None = None) -> tuple[int, str]: +def sh(script: str) -> list[str]: + bash = os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe") if WIN else "sh" + return [bash, str(ROOT / "scripts" / script)] + + +def step(title: str, filename: str, *commands: list[str], timeout: float = 900, append: bool = False) -> int: + path = EVIDENCE / filename + path.parent.mkdir(parents=True, exist_ok=True) started = time.monotonic() - result = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace", - timeout=timeout, env={**ENV, **(env or {})}) - took = time.monotonic() - started - return result.returncode, (result.stdout + result.stderr).rstrip() + f"\n[exit {result.returncode}, {took:.1f} s]\n" + code = 0 + with path.open("a" if append else "w", encoding="utf-8", newline="\n") as out: + if not append: + out.write(f"# {title}\n# {dt.datetime.now(dt.timezone.utc).isoformat(timespec='seconds')}\n") + for command in commands: + out.write(f"\n$ {' '.join(command)}\n") + out.flush() + try: + result = subprocess.run(command, cwd=ROOT, env=ENV, capture_output=True, timeout=timeout) + text = (result.stdout + result.stderr).decode("utf-8", "replace").replace("\r\n", "\n") + out.write(text) + out.write(f"\n[exit {result.returncode}]\n") + code = code or result.returncode + except subprocess.TimeoutExpired: + out.write(f"\n[timeout after {timeout} s]\n") + code = code or 124 + elapsed = time.monotonic() - started + results.append((title, " && ".join(" ".join(c) for c in commands), code, filename, elapsed)) + print(f"{'PASS' if code == 0 else 'FAIL'} {title} ({elapsed:.0f} s) -> evidence/{filename}", flush=True) + return code -class Log: - def __init__(self, name: str, title: str): - self.path = EVIDENCE / name - self.path.parent.mkdir(parents=True, exist_ok=True) - commit = subprocess.run(["git", "log", "-1", "--format=%h %s"], cwd=ROOT, capture_output=True, text=True, - encoding="utf-8").stdout.strip() - self.text = f"# {title}\n# {now()}, commit {commit}\n" - - def run(self, cmd: list[str], shown: str | None = None, **kwargs) -> int: - code, out = sh(cmd, **kwargs) - self.text += f"\n$ {shown or ' '.join(cmd)}\n{out}" - self.save() - print(f" {self.path.name}: {shown or ' '.join(cmd[:4])} -> exit {code}", flush=True) - return code - - def note(self, text: str) -> None: - self.text += f"\n{text}\n" - self.save() - - def save(self) -> None: - self.path.write_text(self.text, encoding="utf-8") +def compose_json(*args: str): + return json.loads(subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, + env=ENV, check=True).stdout) -def states() -> list[str]: - ids = subprocess.run(["docker", "compose", "ps", "-a", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split() - rows = [] - for item in json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, text=True).stdout or "[]"): - st = item["State"] - rows.append(f"{item['Name'].lstrip('/'):24} host={item['Config']['Hostname']:13} {st['Status']:8} " - f"exit={st['ExitCode']:<3} pid={st['Pid']:<6} started={st['StartedAt'][:23]}") - return sorted(rows) +def stand_report() -> None: + """Versions, images, per-service hardening/secrets/ports/limits, running state (no values).""" + config = compose_json("config", "--format", "json") + lines = ["# Стенд: версии, образы, hardening, секреты по сервисам (только имена)", ""] + commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip() + lines.append(f"commit: {commit}") + lines.append("docker: " + subprocess.run(["docker", "version", "--format", "{{.Server.Version}} ({{.Server.Os}}/{{.Server.Arch}})"], + capture_output=True, text=True).stdout.strip()) + info = subprocess.run(["docker", "info", "--format", "{{.NCPU}} CPU, {{.MemTotal}} bytes RAM"], capture_output=True, text=True) + lines.append("docker VM: " + info.stdout.strip()) + lines.append(f"compose project: {config.get('name')}") + lines.append("") + lines.append("| service | image | cap_drop | cap_add | no-new-priv | cpus | memory | published | secrets (names) |") + lines.append("| --- | --- | --- | --- | --- | --- | --- | --- | --- |") + for name, svc in sorted(config["services"].items()): + limits = svc.get("deploy", {}).get("resources", {}).get("limits", {}) + ports = [f"{p.get('host_ip')}:{p.get('published')}" for p in svc.get("ports", [])] + secrets = sorted(s["source"] for s in svc.get("secrets", [])) + lines.append(f"| {name} | {svc.get('image')} | {svc.get('cap_drop')} | {svc.get('cap_add', '')} | " + f"{'no-new-privileges:true' in svc.get('security_opt', [])} | {limits.get('cpus')} | " + f"{int(limits.get('memory', 0)) // 2**20} MiB | {ports} | {', '.join(secrets)} |") + lines.append("") + ps = subprocess.run(["docker", "compose", "ps", "-a", "--format", "{{.Service}}\t{{.Status}}\t{{.Ports}}"], + cwd=ROOT, capture_output=True, text=True, env=ENV).stdout + lines += ["## docker compose ps -a", "", "```", ps.strip(), "```", ""] + users = [] + for service in ("api", "relay", "worker", "lb", "openbao", "otel-collector", "prometheus", "grafana", "loki", "tempo"): + for cid in subprocess.run(["docker", "compose", "ps", "-q", service], cwd=ROOT, capture_output=True, text=True, + env=ENV).stdout.split(): + uid = subprocess.run(["docker", "exec", cid, "id", "-u"], capture_output=True, text=True).stdout.strip() + caps = subprocess.run(["docker", "exec", cid, "sh", "-c", "grep CapEff /proc/1/status"], capture_output=True, + text=True).stdout.split() + alias = subprocess.run(["docker", "exec", cid, "cat", "/tmp/instance_id"], capture_output=True, + text=True, env=ENV).stdout.strip() + users.append(f"| {service} | {cid[:12]} | uid {uid or '? (no shell)'} | CapEff {caps[-1] if caps else '? (distroless)'} | {alias or '-'} |") + lines += ["## Пользователь и capabilities PID 1 (запущенные контейнеры)", "", + "| service | container | user | capabilities | X-Instance-Id alias |", "| --- | --- | --- | --- | --- |", *users, ""] + (EVIDENCE / "stand.md").write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n") + results.append(("стенд: версии/hardening/секреты по сервисам", "docker compose config/ps/inspect/exec", 0, "stand.md", 0)) + print("PASS stand report -> evidence/stand.md", flush=True) -OBS_CHECK = """ -import json, sys, time, urllib.request -sys.path.insert(0, "scripts") -import obs -for _ in range(60): - try: - urllib.request.urlopen(obs.GRAFANA + "/api/health", timeout=5).read(); break - except Exception: - time.sleep(2) -def get(path): - req = urllib.request.Request(obs.GRAFANA + path, headers={"Authorization": obs._auth()}) - return json.loads(urllib.request.urlopen(req, timeout=30).read()) -for uid in ("prometheus", "loki", "tempo"): - print(uid, get(f"/api/datasources/uid/{uid}/health")) -for d in get("/api/search?type=dash-db"): - print("dashboard", d["uid"], d["title"], "folder:", d.get("folderTitle")) -print("prometheus rules:", [r["name"] for g in obs.get("prometheus", "api/v1/rules")["data"]["groups"] for r in g["rules"]]) -""" +def failover_both() -> None: + """test-failover until BOTH replicas have been the stopped one (README: последовательный отказ).""" + stopped: set[str] = set() + filename = "failover.txt" + (EVIDENCE / filename).write_text("# make test-failover: последовательный отказ реплик API\n", encoding="utf-8") + code = 0 + for attempt in range(1, 6): + before = {c for c in subprocess.run(["docker", "compose", "ps", "-q", "api"], cwd=ROOT, capture_output=True, + text=True, env=ENV).stdout.split()} + rc = step(f"failover run {attempt}", filename, + [PY, "tests/resilience.py", "--mode", "failover", "--action-script", hook("stop-one"), "--ca-file", CA], + ["docker", "compose", "ps", "-a", "--format", "{{.Name}} {{.Status}}", "api"], append=True) + results.pop() + code = code or rc + after = {c for c in subprocess.run(["docker", "compose", "ps", "-q", "api"], cwd=ROOT, capture_output=True, + text=True, env=ENV).stdout.split()} + stopped |= {c[:12] for c in before - after} + step("restore", filename, sh("restore-api.sh"), [PY, "scripts/lbctl.py", "wait-up", "2"], append=True) + results.pop() + if len(stopped) >= 2: + break + with (EVIDENCE / filename).open("a", encoding="utf-8") as out: + out.write(f"\nstopped containers over the runs: {sorted(stopped)}\n") + results.append(("make test-failover x N, обе реплики по очереди", "tests/resilience.py --mode failover + restore", + 0 if code == 0 and len(stopped) >= 2 else 1, filename, 0)) def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--skip-student-tests", action="store_true") + args = parser.parse_args() EVIDENCE.mkdir(exist_ok=True) - make = shutil.which("make", path=ENV["PATH"]) or "make" - # 1. Clean clone -> secrets -> build -> start - log = Log("clean-clone.txt", "Clean clone: secrets, config, build, migrations from zero, start, versions") - log.run(["git", "status", "--short", "--branch"]) - log.run([PYTHON, "--version"]); log.run(["docker", "version", "--format", "client {{.Client.Version}} / server {{.Server.Version}}"]) - log.run(["docker", "compose", "version"]); log.run([make, "--version"], shown="make --version") - log.run([PYTHON, "scripts/init_secrets.py"], shown="python scripts/init_secrets.py") - if not (ROOT / ".env").exists(): - shutil.copy(ROOT / ".env.example", ROOT / ".env") - log.note("$ cp .env.example .env") - log.run(["docker", "compose", "--env-file", ".env", "config", "--quiet"]) - log.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--build", "--wait"], timeout=1800) - log.run(["docker", "compose", "ps", "-a", "--format", "table {{.Service}}\t{{.Image}}\t{{.Status}}"]) - log.run(["docker", "compose", "logs", "--no-log-prefix", "migrate"]) - log.run(["docker", "compose", "logs", "--no-log-prefix", "s3-init"]) # bucket + access-model verdicts - log.run([PYTHON, "scripts/lbctl.py", "replicas"]); log.run([PYTHON, "scripts/lbctl.py", "status"]) - log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_users"]) - log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "type", - "durable", "messages", "consumers", "arguments"]) - log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_permissions"]) - # lab 6: telemetry stores up, Grafana provisioned (datasources with fixed UIDs, dashboard) - log.run([PYTHON, "-c", OBS_CHECK], shown="python -c ") - ids = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split() - log.run(["docker", "inspect", "-f", "{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}} " - "memswap={{.HostConfig.MemorySwap}} image={{.Config.Image}}", *ids], shown="docker inspect (limits)") - # venv for validate / own tests - if not Path(VENV_PY).exists(): - log.run([PYTHON, "-m", "venv", ".venv"]) - log.run([VENV_PY, "-m", "pip", "install", "-q", "--require-hashes", "--no-deps", "-r", "requirements.txt"], timeout=1800) - log.run([VENV_PY, "-m", "pip", "install", "-q", "-r", "requirements-test.txt", "-r", "requirements-dev.txt"], timeout=1800) + stand_report() + step("make check", "check.txt", [PY, "scripts/check_contract.py"]) + step("make test (HTTPS, public CA)", "smoke.txt", [PY, "tests/smoke.py", "--base-url", "https://localhost:8443", "--ca-file", CA]) + step("make test-security (недоверенный CA)", "test-security.txt", [PY, "tests/security.py", "--base-url", "https://localhost:8443", "--ca-file", CA]) + step("mTLS LB->API: без cert / чужой CA / неверная identity / lb", "mtls-check.txt", sh("mtls_check.sh")) + step("OpenBao allow/deny, root credential отсутствует в app", "bao-check.txt", sh("bao_check.sh"), + [PY, "scripts/bao_operator.py", "status"]) + step("make test-persistence (рестарт всех процессов, unseal)", "persistence.txt", + ["docker", "compose", "ps", "-a", "--format", "{{.Name}} {{.State}} {{.Status}}"], + [PY, "tests/resilience.py", "--mode", "persistence", "--action-script", hook("restart"), "--ca-file", CA], + ["docker", "compose", "ps", "-a", "--format", "{{.Name}} {{.State}} {{.Status}}"], timeout=600) + failover_both() + argon2_bench() + step("Телеметрия по mTLS: trace + logs", "trace-demo.txt", [PY, "scripts/trace_demo.py", "--output", str(EVIDENCE / "trace-demo-raw.txt")]) + step("Dashboard: все запросы через Grafana (HTTPS)", "dashboard-check.txt", [PY, "scripts/check_dashboard.py"]) + if not args.skip_student_tests: + step("Свои тесты (unit + стенд, в т.ч. test_security.py)", "student-tests.txt", + [PY, "-m", "pytest", "student-tests", "-v", "-p", "no:cacheprovider", "--durations=15"], timeout=5400) + lines = ["# Сводка доказательств lab7", "", f"Собрано: {dt.datetime.now(dt.timezone.utc).isoformat(timespec='seconds')}", "", + "| Шаг | Команда | Код | Файл | Время, с |", "| --- | --- | --- | --- | --- |"] + for title, command, code, filename, elapsed in results: + lines.append(f"| {title} | `{command[:160]}` | {code} | [{filename}]({filename}) | {elapsed:.0f} |") + (EVIDENCE / "SUMMARY.md").write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n") + failed = [r for r in results if r[2] != 0] + print(f"done: {len(results) - len(failed)}/{len(results)} steps OK; evidence/SUMMARY.md") + return 1 if failed else 0 - # 2. make check / validate / test - log = Log("make-check-validate-test.txt", "make check, make validate (venv), make test") - log.run([make, "check", f"PYTHON={MAKE_PY}"], shown="make check") - log.run([make, "validate", f"PYTHON={MAKE_VENV}"], shown=f"make validate PYTHON={MAKE_VENV}") - log.run([make, "test", f"PYTHON={MAKE_PY}"], shown="make test") - # 3. persistence with states before/after - log = Log("test-persistence.txt", "make test-persistence: restart of LB, API replicas, relay, worker, PostgreSQL, " - "Valkey, S3, RabbitMQ") - log.note("Containers BEFORE:\n" + "\n".join(states())) - log.run([make, "test-persistence", f"ACTION_SCRIPT=scripts/restart{HOOK}", f"PYTHON={MAKE_PY}"], - shown=f"make test-persistence ACTION_SCRIPT=scripts/restart{HOOK}") - log.note("Containers AFTER (new pid/started for lb, api-*, relay, worker, postgres, valkey, s3, broker; volumes " - "kept):\n" + "\n".join(states())) - log.run([PYTHON, "scripts/lbctl.py", "wait-up", "2"]) - - # 4. failover: until BOTH replicas have been the stopped one (each run is a real public test) - log = Log("test-failover.txt", "make test-failover with scripts/stop-one: which container is really stopped, restore, repeat") - stopped: set[str] = set() - import urllib.request - for attempt in range(1, 7): - # The public test stops the replica that served its first POST; its request sequence is - # fixed, so with round robin it hits the same replica every time. Shift the rotation by - # (attempt - 1) extra requests so that the other replica becomes the target as well. - for _ in range(attempt - 1): - urllib.request.urlopen("http://127.0.0.1:8080/health/live", timeout=5).read() - before = {r for r in states() if "-api-" in r and " running " in r} - log.note(f"--- run {attempt}; running API replicas BEFORE:\n" + "\n".join(sorted(before))) - log.run([make, "test-failover", f"ACTION_SCRIPT=scripts/stop-one{HOOK}", f"PYTHON={MAKE_PY}"], - shown=f"make test-failover ACTION_SCRIPT=scripts/stop-one{HOOK}") - after = states() - gone = [r for r in after if "-api-" in r and " exited " in r] - log.note("AFTER (the stopped replica, left stopped by the hook):\n" + "\n".join(gone)) - log.run([PYTHON, "scripts/lbctl.py", "status"]) - stopped.update(r.split()[0] for r in gone) - log.run(["sh" if not WINDOWS else r"C:\Program Files\Git\bin\bash.exe", "scripts/restore-api.sh"], - shown="sh scripts/restore-api.sh") - log.run([PYTHON, "scripts/lbctl.py", "wait-up", "2"]) - if len(stopped) >= 2: - break - log.note(f"Replicas stopped by the public test across runs: {sorted(stopped)}") - - # 5a. lab 6 defense steps 2-3: controlled trace + logs; every dashboard query; load - log = Log("trace-demo.txt", "Defense step 2: upload with our own traceparent -> trace in Tempo + logs in Loki") - log.run([PYTHON, "tests/load.py", "--duration", "30", "--concurrency", "4", "--output", "evidence/load.json"]) - log.run([PYTHON, "scripts/trace_demo.py"], shown="python scripts/trace_demo.py", timeout=300) - log = Log("dashboard-check.txt", "Every query of the provisioned dashboard through Grafana /api/ds/query") - log.run([PYTHON, "scripts/check_dashboard.py"], shown="python scripts/check_dashboard.py", timeout=600) - - # 5. lab 5 defense scenario: worker stopped -> 202 -> 409 -> restart api+broker -> worker -> ready - log = Log("demo-pipeline.txt", "Defense steps 2-3: worker stopped, upload 202, content 409, restart API and broker " - "with volumes, worker started, ready + thumbnail") - log.note("Containers BEFORE:\n" + "\n".join(states())) - log.run([VENV_PY, "scripts/demo_pipeline.py"], shown="python scripts/demo_pipeline.py", timeout=900) - log.note("Containers AFTER (api-*, broker restarted; worker stopped and started):\n" + "\n".join(states())) - - # 6. own tests - log = Log("student-tests.txt", "Own tests: unit + stand (pytest -v); failures restored in finally") - log.run([VENV_PY, "-m", "pytest", "student-tests", "-v", "-p", "no:cacheprovider"], shown="python -m pytest student-tests -v", - timeout=5400) - - # 7. lab 6 level 4: incidents under load (alerts firing -> resolved, diagnosis by traces) - log = Log("incidents-runs.txt", "bench/incidents.py all: worker stop, DB lock, slow handler, Tempo+Loki down, " - "Collector down (details: evidence/incidents/*.txt)") - log.run([VENV_PY, "bench/incidents.py", "all"], shown="python bench/incidents.py all", timeout=5400) - log.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "auditor"], shown="docker compose run --rm auditor", - timeout=900) # lab 5 invariants still hold after all of it - - # 8. track 1: price of observability - if "--skip-track1" not in sys.argv: - log = Log("track1-runs.txt", "Track 1: bench/track1.py, off/full/head10/tail x 3 runs, then the summary") - log.run([VENV_PY, "bench/track1.py", "--runs", "3", "--output", "evidence/track1"], - shown="python bench/track1.py --runs 3", timeout=7200) - log.run([PYTHON, "bench/track1_summary.py", "evidence/track1"], shown="python bench/track1_summary.py") - log = Log("final-state.txt", "Final state of the stand") - log.run([PYTHON, "scripts/obs.py", "alerts"], shown="python scripts/obs.py alerts") - log.run(["docker", "compose", "ps", "-a", "--format", "table {{.Service}}\t{{.Status}}"]) - print("done:", EVIDENCE) - return 0 +def argon2_bench() -> None: + """bench/argon2_bench.py inside an API replica (its CPU/RAM limits) -> evidence/argon2/bench.json.""" + target = EVIDENCE / "argon2" / "bench.json" + target.parent.mkdir(parents=True, exist_ok=True) + started = time.monotonic() + with (ROOT / "bench" / "argon2_bench.py").open("rb") as script: + result = subprocess.run(["docker", "compose", "exec", "-T", "api", "python", "-"], cwd=ROOT, env=ENV, + stdin=script, capture_output=True, timeout=900) + target.write_bytes(result.stdout) + results.append(("Argon2id: замер в контейнере API (1 CPU)", "docker compose exec -T api python - < bench/argon2_bench.py", + result.returncode, "argon2/bench.json", time.monotonic() - started)) + print(f"{'PASS' if result.returncode == 0 else 'FAIL'} argon2 bench -> evidence/argon2/bench.json", flush=True) if __name__ == "__main__": - raise SystemExit(main()) + sys.exit(main()) diff --git a/scripts/collect_evidence_resume.py b/scripts/collect_evidence_resume.py deleted file mode 100644 index 5850e97..0000000 --- a/scripts/collect_evidence_resume.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python3 -"""Resume scripts/collect_evidence.py after an interruption, on the SAME clean-clone stand. - - python scripts/collect_evidence_resume.py - -Used once in this work: during the clean-clone run Docker Desktop itself stopped after the own -tests (every later step failed with "cannot connect to the docker API"). This script re-runs, with -the same logging, the tests that failed in that run and the steps that never executed: level 4 -incidents, the read-only audit and the final state. Earlier evidence files are kept unchanged. -""" -from __future__ import annotations - -import subprocess -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "scripts")) -import collect_evidence as ce # noqa: E402 - -FAILED = [ - "student-tests/test_pipeline_flow.py::test_cleanup_racing_a_replay_never_deletes_the_replayed_source", - "student-tests/test_storage_failures.py::test_upload_survives_failover_of_the_serving_replica", - "student-tests/test_storage_failures.py::test_bucket_is_private_outside_the_api", - "student-tests/test_storage_failures.py::test_s3_restart_keeps_objects", -] - - -def main() -> int: - log = ce.Log("student-tests-rerun.txt", "Re-run of the 4 tests that failed in student-tests.txt (Docker Desktop " - "degraded and then stopped at the end of that run)") - log.note("Containers BEFORE:\n" + "\n".join(ce.states())) - log.run([ce.VENV_PY, "-m", "pytest", *FAILED, "-v", "-p", "no:cacheprovider"], - shown="python -m pytest <4 tests> -v", timeout=3600) - - log = ce.Log("incidents-runs.txt", "bench/incidents.py all: worker stop, DB lock, slow handler, Tempo+Loki down, " - "Collector down (details: evidence/incidents/*.txt)") - log.run([ce.VENV_PY, "bench/incidents.py", "all"], shown="python bench/incidents.py all", timeout=5400) - log.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "auditor"], shown="docker compose run --rm auditor", - timeout=900) - - log = ce.Log("final-state.txt", "Final state of the stand") - log.run([ce.PYTHON, "scripts/obs.py", "alerts"], shown="python scripts/obs.py alerts") - log.run(["docker", "compose", "ps", "-a", "--format", "table {{.Service}}\t{{.Status}}"]) - print("done:", ce.EVIDENCE) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/demo_attachments.py b/scripts/demo_attachments.py deleted file mode 100644 index 2e24432..0000000 --- a/scripts/demo_attachments.py +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env python3 -"""Lab 4 defense scenario (kept in lab 5; upload is now 202 queued, the download waits for ready): -upload the fixture, send a message with attachment_ids, -download as the second member and compare SHA-256; the outsider gets 404; an unauthenticated -request straight to S3 (from inside the storage network) is refused, the signed one works. - - python scripts/demo_attachments.py [--base-url http://127.0.0.1:8080] - -Prints requests and answers; never prints tokens or keys. Creates synthetic users. -""" -from __future__ import annotations - -import argparse -import base64 -import hashlib -import json -import subprocess -import sys -import urllib.error -import urllib.request -import uuid -from email.message import Message -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -FIXTURE = ROOT / "tests" / "fixtures" / "sample.png" -PASSWORD = "Demo-password-Ω-12345" - - -class Client: - def __init__(self, base: str): - self.base = base.rstrip("/") - - def call(self, method: str, path: str, *, token: str | None = None, body=None, raw: bytes | None = None, - headers: dict | None = None) -> tuple[int, Message, bytes]: - h = dict(headers or {}) - if token: - h["Authorization"] = "Bearer " + token - data = raw - if body is not None: - data = json.dumps(body, ensure_ascii=False).encode() - h["Content-Type"] = "application/json" - req = urllib.request.Request(self.base + path, data=data, method=method, headers=h) - try: - with urllib.request.urlopen(req, timeout=30) as r: - return r.status, r.headers, r.read() # case-insensitive HTTPMessage - except urllib.error.HTTPError as e: - return e.code, e.headers, e.read() - - -def show(label: str, status: int, headers: Message, payload: bytes, *, binary: bool = False) -> None: - inst = headers.get("X-Instance-Id", "-") - if binary: - text = f"{len(payload)} bytes, Content-Type {headers.get('Content-Type')}" - else: - text = payload.decode("utf-8", "replace")[:300] - print(f" {label:58} -> {status} [X-Instance-Id {inst}] {text}") - - -def user(c: Client, label: str) -> dict: - name = f"{label}_{uuid.uuid4().hex[:8]}" - status, _, body = c.call("POST", "/api/v1/users", body={"username": name, "display_name": label.title(), - "password": PASSWORD}) - assert status == 201, body - basic = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode() - status, _, body = c.call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}) - session = json.loads(body) - return {"id": session["user"]["id"], "token": session["token"], "name": name} - - -def wait_ready(c: Client, actor: dict, attachment_id: str, timeout: float = 60): - import time - deadline = time.monotonic() + timeout - while True: - st, h, b = c.call("GET", f"/api/v1/attachments/{attachment_id}", token=actor["token"]) - if st != 200 or json.loads(b)["status"] in ("ready", "failed") or time.monotonic() > deadline: - return st, h, b - time.sleep(0.3) - - -def main() -> int: - p = argparse.ArgumentParser() - p.add_argument("--base-url", default="http://127.0.0.1:8080") - args = p.parse_args() - c = Client(args.base_url) - content = FIXTURE.read_bytes() - print(f"fixture {FIXTURE.name}: {len(content)} bytes, sha256 {hashlib.sha256(content).hexdigest()}") - alice, bob, eve = user(c, "alice"), user(c, "bob"), user(c, "eve") - print(f"users: alice, bob (members), eve (outsider)") - status, _, body = c.call("POST", "/api/v1/chats", token=alice["token"], - body={"title": "Демо lab5", "member_ids": [alice["id"], bob["id"]]}) - chat = json.loads(body) - - print("\n1. upload -> message -> download by the second member") - st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", token=alice["token"], - raw=content, headers={"Content-Type": "image/png"}) - show("POST /chats/{id}/attachments (alice, raw PNG)", st, h, b) - att = json.loads(b) - st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"], - body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}) - show("POST /chats/{id}/messages text='' attachment_ids=[id]", st, h, b) - st, h, b = wait_ready(c, bob, att["id"]) - show("GET /attachments/{id} (bob) until ready", st, h, b) - st, h, got = c.call("GET", f"/api/v1/attachments/{att['id']}/content", token=bob["token"]) - show("GET /attachments/{id}/content (bob)", st, h, got, binary=True) - same = hashlib.sha256(got).hexdigest() == hashlib.sha256(content).hexdigest() == att["sha256"] - print(f" SHA-256 of the download == fixture == metadata: {same}") - - print("\n2. outsider and direct S3 access") - for suffix in ("", "/content"): - st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", token=eve["token"]) - show(f"GET /attachments/{{id}}{suffix} (eve, not a member)", st, h, b) - key = subprocess.run(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", - "-At", "-c", f"SELECT object_key FROM attachments WHERE id = '{att['id']}'"], - cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip() - print(f" object key in PostgreSQL: {key} (random; not in any API response: " - f"{key not in json.dumps(att)})") - probe = ( - "import urllib.request as u, urllib.error as e, asyncio\n" - "def st(url):\n" - " try: return u.urlopen(url, timeout=3).status\n" - " except e.HTTPError as x: return x.code\n" - f"print('anonymous GET http://s3:8333/messenger-attachments/{key} ->', st('http://s3:8333/messenger-attachments/{key}'))\n" - "print('anonymous LIST http://s3:8333/messenger-attachments?list-type=2 ->', st('http://s3:8333/messenger-attachments?list-type=2'))\n" - "from messenger.config import Settings\nfrom messenger.storage import Storage\n" - "async def m():\n s = Storage(Settings.from_env()); await s.open()\n" - f" print('signed HEAD with the API key pair ->', (await s.head('{key}')).size, 'bytes'); await s.close()\n" - "asyncio.run(m())\n") - out = subprocess.run(["docker", "compose", "exec", "-T", "api", "python", "-c", probe], cwd=ROOT, - capture_output=True, text=True).stdout - for line in out.splitlines(): - print(" (inside network storage) " + line) - print(" S3 is not published on the host at all: only the LB has ports (127.0.0.1:8080, 8404).") - return 0 if same else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/demo_pipeline.py b/scripts/demo_pipeline.py deleted file mode 100644 index 79bb19e..0000000 --- a/scripts/demo_pipeline.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env python3 -"""Lab 5 defense scenario, steps 2-3 (README): worker stopped -> upload 202 -> content 409 while the -rest of the API works -> a message with the attachment is created -> API and broker restarted with -their volumes -> worker started -> the same attachment becomes ready, thumbnail downloadable. - - python scripts/demo_pipeline.py [--base-url http://127.0.0.1:8080] - -Prints every step with HTTP codes, IDs, the outbox row and the queue depth; never prints tokens or -keys. Creates synthetic users. Always starts the worker again at the end. -""" -from __future__ import annotations - -import argparse -import hashlib -import io -import json -import subprocess -import sys -import time -import uuid -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from demo_attachments import FIXTURE, ROOT, Client, show, user, wait_ready # noqa: E402 - - -def compose(*args: str, check: bool = True) -> str: - return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", - check=check, timeout=300).stdout - - -def psql(sql: str) -> str: - return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", sql).strip() - - -def queue_depth() -> str: - """messages/consumers of the jobs queue; rabbitmqctl refreshes these counters every ~5 s.""" - time.sleep(6) - out = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "messages", "consumers") - line = next(l for l in out.splitlines() if l.startswith("messenger.attachment-jobs\t")) - _, messages, consumers = line.split("\t") - return f"messages={messages} consumers={consumers}" - - -def wait_api(c: Client, timeout: float = 120) -> None: - deadline = time.monotonic() + timeout - while time.monotonic() < deadline: - try: - if c.call("GET", "/health/ready")[0] == 200: - return - except OSError: - pass - time.sleep(1) - raise SystemExit("API did not become ready") - - -def step(text: str) -> None: - print(f"\n[{time.strftime('%H:%M:%S')}] {text}") - - -def main() -> int: - p = argparse.ArgumentParser() - p.add_argument("--base-url", default="http://127.0.0.1:8080") - args = p.parse_args() - c = Client(args.base_url) - content = FIXTURE.read_bytes() - alice, bob = user(c, "alice"), user(c, "bob") - _, _, body = c.call("POST", "/api/v1/chats", token=alice["token"], - body={"title": "Демо lab5", "member_ids": [alice["id"], bob["id"]]}) - chat = json.loads(body) - try: - step("1. docker compose stop worker") - compose("stop", "worker") - print(" " + compose("ps", "-a", "--format", "{{.Service}} {{.State}}", "worker").strip()) - - step("2. upload while the worker is stopped") - st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", token=alice["token"], - raw=content, headers={"Content-Type": "image/png"}) - show("POST /chats/{id}/attachments", st, h, b) - att = json.loads(b) - print(f" attachment_id = {att['id']} status = {att['status']}") - for query in ("", "?variant=thumbnail"): - st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}/content{query}", token=bob["token"]) - show(f"GET /attachments/{{id}}/content{query}", st, h, b) - st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=bob["token"], - body={"text": "обычное сообщение работает"}, headers={"Idempotency-Key": uuid.uuid4().hex}) - show("POST /messages (text only)", st, h, b) - st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"], - body={"text": "фото", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}) - show("POST /messages attachment_ids=[queued id]", st, h, b) - message_id = json.loads(b)["id"] - time.sleep(2) - print(" job + outbox in PostgreSQL: " + psql( - "SELECT j.id || ' state=' || j.state || ' attempt=' || j.attempt || ' | outbox published_at=' || " - f"coalesce(o.published_at::text, 'NULL') FROM jobs j JOIN outbox o ON o.job_id = j.id " - f"WHERE j.attachment_id = '{att['id']}'")) - print(" RabbitMQ queue messenger.attachment-jobs: " + queue_depth()) - - step("3. docker compose restart api broker (volumes preserved)") - compose("restart", "api", "broker") - wait_api(c) - time.sleep(3) - print(" RabbitMQ queue after the restart: " + queue_depth()) - st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}", token=bob["token"]) - show("GET /attachments/{id}", st, h, b) - finally: - step("4. docker compose start worker") - compose("start", "worker") - st, h, b = wait_ready(c, bob, att["id"], timeout=90) - show("GET /attachments/{id} until ready", st, h, b) - ready = json.loads(b) - thumb = next(v for v in ready["variants"] if v["name"] == "thumbnail") - st, h, data = c.call("GET", f"/api/v1/attachments/{att['id']}/content?variant=thumbnail", token=bob["token"]) - show("GET /content?variant=thumbnail", st, h, data, binary=True) - from PIL import Image - size = Image.open(io.BytesIO(data)).size - ok = (st == 200 and hashlib.sha256(data).hexdigest() == thumb["sha256"] and size == (256, 160) - and ready["status"] == "ready") - print(f" thumbnail: real JPEG {size[0]}x{size[1]}, sha256 matches metadata: {ok}") - st, h, orig = c.call("GET", f"/api/v1/attachments/{att['id']}/content", token=bob["token"]) - print(f" original unchanged byte for byte: {orig == content}") - print(f" message {message_id} still references it: " - f"{psql(f'SELECT attachment_ids FROM messages WHERE id = {chr(39)}{message_id}{chr(39)}')}") - step("5. job history (jobctl show)") - shown = json.loads(compose("run", "--rm", "--no-deps", "-T", "jobctl", "show", att["id"])) - for e in shown["events"]: - print(f" {e['at']} {e['event']:16} attempt={e['attempt']} actor={e['actor']}") - return 0 if ok and orig == content else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/explain_history.py b/scripts/explain_history.py index 0a929ed..1f32988 100644 --- a/scripts/explain_history.py +++ b/scripts/explain_history.py @@ -89,7 +89,7 @@ EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE offset_page('{CHAT}', {LATE}, 51) def psql(script: str) -> str: result = subprocess.run( - ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-f", "-"], + ["docker", "compose", "exec", "-T", "-u", "postgres", "postgres", "psql", "-d", "messenger", "-X", "-q", "-f", "-"], cwd=ROOT, input=script, capture_output=True, text=True, encoding="utf-8", check=True) return result.stdout diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 31da287..8cc872a 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -1,19 +1,81 @@ -# Модель угроз — заполнить +# Модель угроз — решение lab7 (уровень 3) ## Активы и акторы -TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. +**Активы.** + +| Актив | Где живёт | Почему ценен | +| --- | --- | --- | +| Пароли пользователей | только Argon2id-хеш (PHC: алгоритм, параметры, соль) в `users.password_hash` | раскрытие = вход под чужим именем, в том числе на других сайтах | +| Сессии | Bearer-токен 256 бит у клиента; в Valkey только `session:` | токен = полномочия пользователя до expiry | +| Сообщения и вложения | PostgreSQL (метаданные), SeaweedFS (байты), приватные bucket | конфиденциальность переписки | +| Service identities | leaf-ключи в `./secrets/pki` (каждый сервис видит только свой) | ключ `lb` = право ходить в API в обход ingress | +| Секреты сервисов | пароли ролей БД, ключи S3, пароли RabbitMQ и Valkey: в `./secrets` и в OpenBao KV `messenger/` | прямой доступ к данным | +| Корни доверия | ключи `public-ca`/`internal-ca`, root token и доли unseal OpenBao | выпуск любых identity / чтение всех секретов | +| Телеметрия | Prometheus/Loki/Tempo | не должна содержать пароли, токены и тексты | + +**Акторы и их доступ.** + +* **Участник чата** — легальный пользователь с Bearer-токеном. +* **Посторонний пользователь** — зарегистрирован, но не участник чата. +* **Внешний клиент** — видит только `https://localhost:8443`, может подбирать пароли и подсовывать заголовки (`X-User-Id`, `X-Forwarded-For`). +* **Скомпрометированный сервис** — злоумышленник получил код или ключи одного контейнера (например worker) и действует из его сети с его credentials. +* **Оператор** — владелец хоста. Держит root token, доли unseal и ключи CA. Доверенный актор. + +**Границы учебного стенда.** + +* Один Docker-host; атакующий не root на хосте и не имеет доступа к Docker API (иначе он владеет всем, см. ограничения). +* Сети compose — граница сети. Все внутренние сети, кроме `edge` и `ui`, помечены `internal`. +* Данные синтетические. ## Границы доверия -TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. +``` + public-ca internal-ca (mTLS: allowlist SAN lb) +клиент ──HTTPS:8443──► lb (HAProxy) ────────────────────────────────► api ×2 ──TLS──► postgres (роль messenger_api) + │ ├─TLS──► valkey (ACL user api) +оператор ──HTTPS:3000──► grafana ──mTLS──► prometheus/loki/tempo │ ├─HTTPS─► s3 (ключ messenger-api) +оператор ──docker exec──► openbao (root token/доли из ~/.mtusi-lab7-operator) └─HTTPS─► openbao (AppRole api) +relay ──TLS──► postgres, ──AMQPS──► broker (user relay: только publish), ──HTTPS──► openbao (AppRole relay) +worker ──TLS──► postgres, ──AMQPS──► broker (user worker: только consume), ──HTTPS──► s3, openbao (AppRole worker) +api/relay/worker ──OTLP/HTTPS + client cert──► otel-collector ──mTLS──► prometheus / loki / tempo +``` + +Каждая связь (протокол, порт, CA, identity, права, тесты) описана в [contracts/trust-matrix.md](../contracts/trust-matrix.md). + +* Публичные интерфейсы: только `127.0.0.1/[::1]:8443` (API через LB) и `:3000` (Grafana) — оба HTTPS. +* Секреты выдаются так. Оператор → `./secrets` (файлы) → OpenBao KV (`bao_operator.py`). Сервис приложения при старте → AppRole → свой путь KV. +* Сервисы приложения не монтируют ни одного пароля, только role_id/secret_id и свой сертификат. | Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | | --- | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | TODO | - -На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. +| T1. Перехват/подмена трафика клиента: MITM на пути к ingress или фальшивый сервер с самоподписанным сертификатом | конфиденциальность Basic-пароля и Bearer-токена | только HTTPS 8443 (TLS 1.2+), сертификат `public-ca` с SAN `localhost`; клиент проверяет CA и hostname; открытого 8080 нет | `make test-security` (пустой trust store → ошибка проверки); `test_ingress_verifies_ca_and_hostname` (чужой hostname, внутренний CA → отказ); `test_no_plaintext_entry_point` | CA учебный; доверие к нему — ручная раздача `public-ca.crt`; отзыва (CRL/OCSP) нет | +| T2. Обход LB: процесс в сети `edge` или украденный ключ worker обращается к `api:8443` напрямую и подставляет `X-Forwarded-For`, чтобы обойти лимит входа | только LB говорит с API; клиентский IP честный | mTLS: `CERT_REQUIRED` + только `internal-ca` + allowlist SAN `lb` в `connection_made`; у API нет опубликованных портов; health на loopback; HAProxy перезаписывает `X-Forwarded-For` | `make mtls-check`: без cert / чужой CA с SAN `lb` / cert `worker` → отказ, `lb` → 200, по каждой реплике, TLS 1.3 и 1.2; 8081 снаружи закрыт | кража ключа `lb` = полный обход (ротация и отзыв leaf — уровень 4) | +| T3. Подбор пароля через `POST /auth/sessions` (одного аккаунта или одного пароля по многим аккаунтам) + DoS дорогим Argon2 | пароль нельзя угадать перебором; CPU реплики не выжигается | Argon2id m=19 MiB, t=2, p=1 (замер ~31 мс/хеш, ≤2 хеша параллельно на реплику); лимит неудач 5/60 с на username и 50/300 с на IP в Valkey (общий для реплик), проверка ДО Argon2, 429 + `Retry-After`, верный пароль при блокировке тоже 429 | `test_failed_logins_are_rate_limited_with_retry_after` (5×401 → 429, Retry-After ≤ 60, другой аккаунт не задет); unit `test_limit_per_username/ip` | можно на 60 с заблокировать вход известному username; ботнет с многих IP не ограничен глобально | +| T4. Утечка базы: дамп `users` | пароли не восстанавливаются | только Argon2id-хеш (PHC, соль 16 байт на пароль); одинаковые пароли дают разные хеши | `test_argon2id_hash_carries_salt_and_parameters` | слабый пароль из словаря всё равно подбирается офлайн, только медленнее | +| T5. Посторонний пользователь читает чужой чат или вложение, либо выдаёт себя за другого через `X-User-Id` | доступ только участникам; identity = сессия | Bearer-сессия → `user_id`; членство проверяется в SQL; чужое = 404; `X-User-Id` игнорируется; mTLS не заменяет сессию | `test_api.py::test_foreign_chat_is_indistinguishable_from_missing`, `test_x_user_id_basic_and_garbage_do_not_authenticate`, `test_attachments.py` (чужое → 404), `test_logout_revokes_only_this_token`, `test_sessions.py::test_short_ttl_expires` | — | +| T6. Скомпрометирован worker: пытается читать пользователей/сообщения в БД, писать в чужие таблицы, публиковать задачи, читать секреты API, писать в S3 как admin | наименьшие права worker | роль `messenger_worker` (GRANT только jobs/attempts/attachments/variants/outbox/job_events); RabbitMQ user `worker` только consume; S3 `messenger-worker` без Admin/List; OpenBao policy `worker` = свой путь | `test_postgres_tls_only_and_roles_least_privilege` (worker: users/messages/sessions/DELETE/функция → permission denied); `make bao-check` (worker: чужие пути, запись, sys/* → 403); `s3-init` (worker: ListBuckets пуст) | worker законно читает и пишет все вложения (это его работа) | +| T7. Подслушивание и подмена внутри Docker-сетей: процесс в сети `data`/`queue`/`storage` читает пароли и данные | конфиденциальность внутренних связей | TLS с проверкой сервера на каждой связи: PostgreSQL `verify-full` + `hostssl` only; Valkey `port 0`/`tls-port`; RabbitMQ `listeners.tcp = none`; S3 только HTTPS | `test_postgres_…` (`sslmode=disable` → отказ); `test_valkey_tls_and_acl` (без TLS нет PONG); `test_broker_tls_only…` (5672 закрыт); `test_s3_https…` (http не отвечает) | внутри контейнера остаются loopback-hop'ы (SeaweedFS master/filer, gRPC Loki/Tempo) | +| T8. Утечка секрета в Git, образ или телеметрию | секреты только у оператора и в OpenBao | `./secrets` и `*.key`/`*.pem` в `.gitignore` и `.dockerignore`; Dockerfile копирует только `src`, `migrations`, `openapi.json`; секреты через `/run/secrets` и OpenBao; логи не пишут тела, Authorization, URL с паролями; токен отзывается сразу | `test_no_secret_in_git_or_in_the_image` (значения секретов не найдены `git grep` и в файловой системе образа, `*.key` в образе нет); `test_observability.py::test_no_secrets_or_message_text_in_logs_and_traces` | значения в памяти процессов; root хоста видит `./secrets` | +| T9. Приложение получает «ключ от всего»: root token OpenBao, `BAO_TOKEN`, admin-ключ S3, суперпользователь БД | нет всемогущих credentials в app | AppRole на сервис, scoped policy, `token_no_default_policy`; root token и доли только у оператора; S3 admin только у `s3-init`; superuser БД только через локальный сокет | `make bao-check` (root token и доли не найдены в контейнерах, есть положительный контроль; нет env `*TOKEN*`); `test_compose_policy…` (точный список секретов каждого сервиса) | — | +| T10. Побег/эскалация из контейнера | изоляция хоста | нет `privileged`, host network/PID, docker.sock; `cap_drop: [ALL]` + `no-new-privileges` везде; app/worker uid 10001 с CapEff = 0; лимиты CPU/RAM на всех | `test_running_containers_are_hardened`, `test_compose_policy_limits_ports_secrets_images` | 4 stateful-образа стартуют от root ради `chown` (CHOWN/SETUID/…); read_only и seccomp-профили — уровень 4 | ## Lifecycle и инциденты -TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. +* **Bootstrap.** Порядок такой: + 1. Оператор запускает `scripts/init_secrets.py`: пароли и PKI в `./secrets`. + 2. `docker compose up -d openbao` — OpenBao стартует запечатанным. + 3. `scripts/bao_operator.py bootstrap`: init с тремя долями при пороге 2, unseal, KV, AppRole, политики, запись секретов, выпуск role_id/secret_id в `./secrets/bao`. + 4. `docker compose up -d --wait`. + + Bootstrap credentials сервисов (role_id/secret_id) получает только их собственный контейнер; секрет — это secret_id. Подробно: [docs/OPERATOR.md](../docs/OPERATOR.md). +* **Владельцы.** Ключи CA, root token и доли unseal — у оператора хоста. Доли лежат в `~/.mtusi-lab7-operator//` с правами 0600, вне репозитория и вне контейнеров. В команде каждая доля была бы у отдельного человека, root token — отозван после настройки. +* **Expiry.** + * Токены OpenBao сервисов отзываются через секунды после чтения; их TTL 1 ч — только верхняя граница. + * SecretID живёт 30 дней: `bao_operator.py new-secret-id `, затем пересоздать сервис. + * Leaf-сертификаты живут 365 дней, CA — 5 лет. Перевыпуск: удалить нужный leaf и запустить `init_pki.py`, затем пересоздать сервис. + * Автоматической ротации нет — это уровень 4. +* **Компрометация identity.** Утёк ключ одного сервиса — перевыпустить его leaf (CRL нет: старый leaf формально валиден до истечения, см. остаточный риск T2). Утёк secret_id — выпустить новый. Утёк сам секрет — сменить его в `./secrets` и в OpenBao (`bootstrap`). Это ручной сценарий; доказанная ротация — уровень 4. +* **Sealed или остановленный OpenBao.** Работающие api/relay/worker продолжают обслуживать запросы: секреты у них в памяти, OpenBao нужен только при старте. Новая реплика ждёт до `BAO_STARTUP_TIMEOUT_SECONDS` (60 с), пишет `openbao_unavailable`, затем завершается и перезапускается Docker. После `bao_operator.py unseal` она стартует. Это доказано в `test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones`. +* **Рестарт API.** Новый процесс заново входит по AppRole с тем же secret_id. Unseal не нужен, если сам OpenBao не перезапускался. +* **Scan findings.** Сканирование образов на CVE — требование уровня 4, на уровне 3 не выполнялось. Вместо этого: образы закреплены по digest, Python-пакеты — по sha256-хешам (`requirements.txt`). diff --git a/src/messenger/app.py b/src/messenger/app.py index 5ad080f..fa5fb8a 100644 --- a/src/messenger/app.py +++ b/src/messenger/app.py @@ -281,11 +281,15 @@ async def ready(request: Request) -> JSONResponse: return ok({"status": "ok"}) -async def readiness_problem(app: Starlette) -> str | None: - """None if ready, otherwise the (public, secret-free) reason. Shared by GET /health/ready and the - loopback health listener of the Docker healthcheck (tls.health_listener, lab 7).""" +async def readiness_problem(app: Starlette, core: bool = False) -> str | None: + """None if ready, otherwise the (public, secret-free) reason. Shared by GET /health/ready(/core) + and the loopback health listener of the Docker healthcheck (tls.health_listener, lab 7). + core=True: without S3 (the LB's degraded mode, see ready_core).""" if app.state.draining: return "Сервер завершает работу" + if core: + db_ok, store_ok = await asyncio.gather(app.state.db.ping(), app.state.sessions.ping()) + return None if db_ok and store_ok else "PostgreSQL или хранилище сессий недоступно" db_ok, store_ok, s3_ok = await asyncio.gather(app.state.db.ping(), app.state.sessions.ping(), app.state.storage.ping()) if not db_ok: @@ -302,11 +306,9 @@ async def ready_core(request: Request) -> JSONResponse: If S3 is down for every replica, /health/ready is 503 everywhere; HAProxy then routes to replicas that are at least core-ready, so chats and messages keep working while every attachment request answers 503 itself (see infra/haproxy/haproxy.cfg).""" - if request.app.state.draining: - raise Unavailable("Сервер завершает работу") - db_ok, store_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping()) - if not (db_ok and store_ok): - raise Unavailable("PostgreSQL или хранилище сессий недоступно") + problem = await readiness_problem(request.app, core=True) + if problem is not None: + raise Unavailable(problem) return ok({"status": "ok"}) @@ -672,7 +674,8 @@ def create_app(settings: Settings | None = None) -> Starlette: async def probe(path: str) -> int: if path == "/health/live": return 200 - return 200 if await readiness_problem(app) is None else 503 + problem = await readiness_problem(app, core=path == "/health/ready/core") + return 200 if problem is None else 503 health_server = await tls.health_listener(settings.health_port, probe) try: yield diff --git a/src/messenger/tls.py b/src/messenger/tls.py index 9d064ad..da2aeb1 100644 --- a/src/messenger/tls.py +++ b/src/messenger/tls.py @@ -96,11 +96,14 @@ def protocol_class() -> type[MtlsHttpProtocol]: # ------------------------------------------------------------------ loopback health listener +HEALTH_PATHS = ("/health/live", "/health/ready", "/health/ready/core") + + async def health_listener(port: int, probe: Callable[[str], Awaitable[int]]) -> asyncio.base_events.Server: """Minimal HTTP/1.0 server on 127.0.0.1: for the Docker healthcheck only. - `probe(path)` returns the status code of /health/live or /health/ready (the same checks as the - API endpoints). Any other path gets 404 and nothing else of the API is reachable here. + `probe(path)` returns the status code of /health/live, /health/ready or /health/ready/core (the + same checks as the API endpoints). Any other path gets 404: nothing else of the API is here. """ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: @@ -109,7 +112,7 @@ async def health_listener(port: int, probe: Callable[[str], Awaitable[int]]) -> line = await asyncio.wait_for(reader.readline(), 2) parts = line.decode("latin-1").split() if len(parts) >= 2 and parts[0] == "GET": - status = await probe(parts[1]) if parts[1] in ("/health/live", "/health/ready") else 404 + status = await probe(parts[1]) if parts[1] in HEALTH_PATHS else 404 except Exception: # noqa: BLE001 - a broken probe connection is the prober's problem status = 503 body = b'{"status":"ok"}' if status == 200 else b'{"status":"unavailable"}' diff --git a/student-tests/conftest.py b/student-tests/conftest.py index daf4abe..cd06e37 100644 --- a/student-tests/conftest.py +++ b/student-tests/conftest.py @@ -2,7 +2,8 @@ * `unit/` — pure functions (validation, cursor, auth headers, Argon2id); no services. * `test_*` in this folder — marker `stack`: black-box HTTP against the running compose - stand THROUGH THE LOAD BALANCER (BASE_URL, default http://127.0.0.1:8080) plus + stand THROUGH THE LOAD BALANCER (BASE_URL, default https://localhost:8443, CA_FILE = the public + CA, default secrets/pki/public-ca.crt; certificate AND hostname always verified) plus `docker compose` for database checks (psql inside the postgres container), the HAProxy runtime state (scripts/lbctl.py) and failure injection. Every failure test restores the stopped/paused service or replica in `finally` and waits until HAProxy sees all replicas UP. @@ -23,6 +24,8 @@ import uuid from pathlib import Path from urllib.parse import quote +import ssl + import httpx2 as httpx import pytest from jsonschema import Draft202012Validator @@ -33,7 +36,29 @@ sys.path.insert(0, str(ROOT / "scripts")) import lbctl # noqa: E402 SPEC = json.loads((ROOT / "contracts" / "openapi.json").read_text(encoding="utf-8")) -BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") +BASE_URL = os.environ.get("BASE_URL", "https://localhost:8443").rstrip("/") +# Lab 7: every HTTP call of these tests verifies the server against the PUBLIC CA (+ hostname). +# There is no switch to turn verification off. The wrappers below make it the default of httpx. +CA_FILE = os.environ.get("CA_FILE") or str(ROOT / "secrets" / "pki" / "public-ca.crt") +TLS = ssl.create_default_context(cafile=CA_FILE) + + +class _VerifiedClient(httpx.Client): + def __init__(self, *args, **kwargs): + kwargs.setdefault("verify", TLS) + super().__init__(*args, **kwargs) + + +def _verified(function): + def call(*args, **kwargs): + kwargs.setdefault("verify", TLS) + return function(*args, **kwargs) + return call + + +httpx.Client = _VerifiedClient +for _name in ("get", "post", "put", "delete", "request"): + setattr(httpx, _name, _verified(getattr(httpx, _name))) PASSWORD = "Test-password-Ω-12345" # synthetic; 12+ code points, non-ASCII on purpose REPLICAS = int(os.environ.get("API_REPLICAS", "2")) # replicas the stand normally runs @@ -61,7 +86,9 @@ def compose(*args: str, check: bool = True, timeout: float = 120, stdin: str | N def psql(sql: str) -> str: """Run SQL inside the postgres container (no DB port is published) and return unaligned output.""" - result = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", + # Lab 7: as the superuser over the container's local socket (peer auth of OS user postgres); + # pg_hba refuses the superuser over the network. Tests use it to inspect/break things on purpose. + result = compose("exec", "-T", "-u", "postgres", "postgres", "psql", "-d", "messenger", "-At", "-v", "ON_ERROR_STOP=1", "-c", sql) return result.stdout.strip() @@ -430,9 +457,10 @@ def attachment_row(attachment_id: str) -> dict | None: def probe_inside(replica: dict, path: str) -> int: - """HTTP status of `path` asked inside the replica container itself (bypassing the LB).""" + """HTTP status of `path` asked inside the replica container itself (bypassing the LB) - lab 7: on + the loopback health listener (127.0.0.1:8081), the mTLS port needs the LB's client certificate.""" code = ("import urllib.request as u, urllib.error as e\n" - "try: print(u.urlopen('http://127.0.0.1:8080%s', timeout=3).status)\n" + "try: print(u.urlopen('http://127.0.0.1:8081%s', timeout=3).status)\n" "except e.HTTPError as x: print(x.code)") % path out = subprocess.run(["docker", "exec", replica["id"], "python", "-c", code], capture_output=True, text=True, timeout=30).stdout.strip() diff --git a/student-tests/test_balancing.py b/student-tests/test_balancing.py index 98065ea..ecebb3f 100644 --- a/student-tests/test_balancing.py +++ b/student-tests/test_balancing.py @@ -248,13 +248,17 @@ def test_graceful_shutdown_order_in_logs(api): # ------------------------------------------------------------------ discovery: restart and scaling def test_full_restart_lb_rediscovers_all_replicas(api): actor = api.user("restart") - before = {r["instance"]: r["started_at"] for r in running_replicas()} + # Lab 7: X-Instance-Id is a random alias per PROCESS, so the replicas are compared by container + # id; a restarted process must show a NEW alias (it is not derived from the container). + before = {r["id"]: (r["started_at"], r["instance"]) for r in running_replicas()} run_hook("restart.sh") wait_healthy("postgres", "valkey", "api") wait_stand() - after = {r["instance"]: r["started_at"] for r in running_replicas()} - assert set(after) == set(before) and all(after[h] != before[h] for h in after), "every replica restarted" - assert set(instances_seen(api, actor["token"])) == set(after) # same token, both replicas, no LB restart needed + after = {r["id"]: (r["started_at"], r["instance"]) for r in running_replicas()} + assert set(after) == set(before), "the same containers run again" + assert all(after[c][0] != before[c][0] and after[c][1] != before[c][1] for c in after), "every replica restarted" + seen = set(instances_seen(api, actor["token"])) + assert seen == {alias for _, alias in after.values()} # same token, both replicas, no LB restart needed def test_scale_up_and_down_is_picked_up_without_errors(api): @@ -278,14 +282,24 @@ def test_scale_up_and_down_is_picked_up_without_errors(api): def test_compose_policy_limits_ports_secrets_images(): config = json.loads(compose("config", "--format", "json").stdout) services = config["services"] - # auditor and jobctl (profile "tools") are started on demand and not part of the running stand. + # auditor, jobctl and mtls-check (profile "tools") are started on demand, not part of the stand. assert set(services) == {"postgres", "valkey", "s3", "broker", "migrate", "s3-init", "api", "lb", "relay", "worker", # lab 6: observability - "otel-collector", "prometheus", "loki", "tempo", "grafana"} + "otel-collector", "prometheus", "loki", "tempo", "grafana", + # lab 7: secrets + "openbao"} for name, svc in services.items(): limits = svc.get("deploy", {}).get("resources", {}).get("limits", {}) assert limits.get("cpus") and limits.get("memory"), f"{name}: CPU/RAM limits" assert "container_name" not in svc, f"{name}: container_name prevents scaling" + # lab 7 hardening: nothing privileged, no host namespaces, no Docker socket, no capabilities + assert not svc.get("privileged") and svc.get("network_mode") is None and svc.get("pid") is None, name + assert not any("docker.sock" in str(v.get("source", "")) for v in svc.get("volumes", [])), name + assert svc.get("cap_drop") == ["ALL"] and "no-new-privileges:true" in svc.get("security_opt", []), name + if name in ("postgres", "valkey", "s3", "broker"): # start as root, chown, drop to their user + assert sorted(svc.get("cap_add", [])) == ["CHOWN", "DAC_OVERRIDE", "FOWNER", "SETGID", "SETUID"], name + else: + assert not svc.get("cap_add"), name if name in ("api", "migrate"): assert "build" in svc # built from this repository's source elif name in ("s3-init", "relay", "worker"): @@ -294,39 +308,63 @@ def test_compose_policy_limits_ports_secrets_images(): assert "@sha256:" in svc["image"], f"{name}: image must be pinned by digest" assert services["api"]["deploy"]["replicas"] >= 2 and not services["api"].get("ports") published = {name: svc.get("ports", []) for name, svc in services.items() if svc.get("ports")} - # Published: the LB and (lab 6) the Grafana UI - both on loopback only. No OTLP/store/admin port. + # Published: the HTTPS ingress and the HTTPS Grafana UI - both on loopback only. Nothing else. assert set(published) == {"lb", "grafana"} assert all(p["host_ip"] in ("127.0.0.1", "::1") for ports in published.values() for p in ports) + assert [p["target"] for p in published["lb"]] == [8443, 8443] assert [p["target"] for p in published["grafana"]] == [3000, 3000] secrets = {name: sorted(s["source"] for s in svc.get("secrets", [])) for name, svc in services.items()} s3_keys = sorted(f"s3_{who}_{part}" for who in ("admin", "api", "worker", "auditor") for part in ("access_key_id", "secret_access_key")) - assert secrets == {"postgres": ["postgres_password"], "valkey": ["valkey_password"], "s3": s3_keys, - "migrate": ["database_url"], "s3-init": s3_keys, "lb": [], - "broker": ["rabbitmq_users"], - # the API: its own S3 key pair only (no admin/worker keys, no broker credentials) - "api": ["cache_url", "database_url", "s3_api_access_key_id", "s3_api_secret_access_key"], - # relay: database + its broker user only; worker: + its own S3 key pair - "relay": ["broker_url_relay", "database_url"], - "worker": ["broker_url_worker", "database_url", "s3_worker_access_key_id", - "s3_worker_secret_access_key"], - # lab 6: the telemetry services get no application secret at all - "otel-collector": [], "prometheus": [], "loki": [], "tempo": [], - "grafana": ["grafana_admin_password"]} + ca = "pki_internal_ca" + + def own(*names): + return sorted([*names, ca]) + + assert secrets == { + # stores: their server certificate + what they verify; postgres creates the service roles once + "postgres": sorted(["postgres_password", "pki_postgres_crt", "pki_postgres_key", ca, + *(f"pg_{r}_password" for r in ("migrate", "api", "relay", "worker", "jobctl", "auditor"))]), + "valkey": own("valkey_api_password", "pki_valkey_crt", "pki_valkey_key"), + "s3": own(*s3_keys, "pki_s3_crt", "pki_s3_key"), + "broker": own("rabbitmq_users", "pki_broker_crt", "pki_broker_key"), + # bootstrap jobs: migrate = schema owner only; s3-init = the ONLY holder of the S3 admin key + "migrate": own("database_url_migrate"), + "s3-init": own(*s3_keys), + # the LB: public certificate + its client identity towards the API + "lb": own("pki_ingress_pem", "pki_lb_pem"), + # application services: ONLY their AppRole login + their certificate; every other secret + # comes from OpenBao (no database/cache/broker URL or S3 key file, no token) + "api": own("bao_api_role_id", "bao_api_secret_id", "pki_api_crt", "pki_api_key"), + "relay": own("bao_relay_role_id", "bao_relay_secret_id", "pki_relay_crt", "pki_relay_key"), + "worker": own("bao_worker_role_id", "bao_worker_secret_id", "pki_worker_crt", "pki_worker_key"), + "openbao": own("pki_openbao_crt", "pki_openbao_key"), + # telemetry: certificates only, no application secret + "otel-collector": own("pki_otel_collector_crt", "pki_otel_collector_key"), + "prometheus": own("pki_prometheus_crt", "pki_prometheus_key"), + "loki": own("pki_loki_crt", "pki_loki_key"), + "tempo": own("pki_tempo_crt", "pki_tempo_key"), + "grafana": own("grafana_admin_password", "pki_grafana_crt", "pki_grafana_key", "pki_grafana_ui_crt", + "pki_grafana_ui_key", "pki_public_ca"), + }, secrets + # No CA private key is defined as a secret at all; nothing mounts the operator's material. + assert not [s for s in config.get("secrets", {}) if s.endswith("ca_key") or "root" in s or "unseal" in s] volumes = {name: [v["source"] for v in svc.get("volumes", []) if v["type"] == "volume"] for name, svc in services.items()} assert volumes == {"postgres": ["pgdata"], "valkey": ["valkeydata"], "s3": ["s3data"], "migrate": [], "s3-init": [], "api": [], "lb": [], "broker": ["rabbitmqdata"], "relay": [], "worker": [], "otel-collector": [], "prometheus": ["promdata"], "loki": ["lokidata"], "tempo": ["tempodata"], - "grafana": ["grafanadata"]} + "grafana": ["grafanadata"], "openbao": ["baodata"]} networks = {name: sorted(svc.get("networks", {})) for name, svc in services.items()} assert networks == {"postgres": ["data"], "valkey": ["data"], "s3": ["storage"], "migrate": ["data"], - "s3-init": ["storage"], "api": ["data", "edge", "storage", "telemetry"], "broker": ["queue"], - "relay": ["data", "queue", "telemetry"], "worker": ["data", "queue", "storage", "telemetry"], + "s3-init": ["storage"], "api": ["data", "edge", "storage", "telemetry", "vault"], + "broker": ["queue"], "relay": ["data", "queue", "telemetry", "vault"], + "worker": ["data", "queue", "storage", "telemetry", "vault"], "lb": ["edge"], "otel-collector": ["telemetry"], "prometheus": ["telemetry"], - "loki": ["telemetry"], "tempo": ["telemetry"], "grafana": ["telemetry", "ui"]}, networks + "loki": ["telemetry"], "tempo": ["telemetry"], "grafana": ["telemetry", "ui"], + "openbao": ["vault"]}, networks # the LB cannot reach the stores; the API not the broker; telemetry stores cannot reach the app stores - for network in ("data", "storage", "queue", "telemetry"): + for network in ("data", "storage", "queue", "telemetry", "vault"): assert config["networks"][network].get("internal") is True, network @@ -346,7 +384,7 @@ def test_running_containers_have_limits_and_no_bypass_ports(): def test_migrations_ran_once_by_the_migrate_service(): applied = psql("SELECT version FROM schema_migrations ORDER BY version").split() assert applied == ["0001_init", "0002_idempotency_keys", "0003_post_message_function", "0004_attachments", - "0005_pipeline", "0006_observability"] + "0005_pipeline", "0006_observability", "0007_least_privilege"] migrate = compose("ps", "-a", "--format", "json", "migrate").stdout rows = [json.loads(line) for line in migrate.splitlines() if line.strip()] assert rows and all(r["State"] == "exited" and r["ExitCode"] == 0 for r in rows) diff --git a/student-tests/test_consistency.py b/student-tests/test_consistency.py index 2ddab1d..614ca2b 100644 --- a/student-tests/test_consistency.py +++ b/student-tests/test_consistency.py @@ -21,7 +21,7 @@ from pathlib import Path import pytest import imagegen -from conftest import api_with_env, attachment_row, psql, s3_size +from conftest import TLS, api_with_env, attachment_row, psql, s3_size pytestmark = pytest.mark.stack @@ -52,7 +52,7 @@ def wait_for(condition, timeout: float, what: str) -> None: def raw_upload(token: str, chat_id: str, declared: int, body: bytes, *, wait_answer: float | None) -> bytes: """Hand-made HTTP request: announce `declared` bytes, send only `body`, then either close the socket (client gone) or keep it open and read the answer after `wait_answer` seconds.""" - sock = socket.create_connection(("127.0.0.1", 8080), timeout=30) + sock = TLS.wrap_socket(socket.create_connection(("127.0.0.1", 8443), timeout=30), server_hostname="localhost") head = (f"POST /api/v1/chats/{chat_id}/attachments?filename=x.png HTTP/1.1\r\nHost: localhost\r\n" f"Authorization: Bearer {token}\r\nContent-Type: image/png\r\nContent-Length: {declared}\r\n\r\n") sock.sendall(head.encode() + body) diff --git a/student-tests/test_db.py b/student-tests/test_db.py index 8f9b266..214dbd2 100644 --- a/student-tests/test_db.py +++ b/student-tests/test_db.py @@ -1,13 +1,14 @@ """Database-level guarantees, checked over HTTP and verified directly in PostgreSQL / Valkey.""" from __future__ import annotations +import subprocess import threading import time import uuid import pytest -from conftest import PASSWORD, Api, compose, psql +from conftest import PASSWORD, ROOT, Api, compose, psql pytestmark = pytest.mark.stack @@ -81,7 +82,8 @@ def test_migrations_rerun_is_a_noop(): assert "0004_attachments: already applied, skipped" in result.stdout assert "0005_pipeline: already applied, skipped" in result.stdout assert "0006_observability: already applied, skipped" in result.stdout - assert psql("SELECT count(*) FROM schema_migrations") == "6" + assert "0007_least_privilege: already applied, skipped" in result.stdout + assert psql("SELECT count(*) FROM schema_migrations") == "7" assert psql("SELECT count(*) FROM users") == users_before @@ -112,8 +114,14 @@ def test_secrets_are_not_stored_in_plain_text(api): actor = api.user("store") stored = psql(f"SELECT password_hash FROM users WHERE id = '{actor['id']}'") assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$") and PASSWORD not in stored - token_hex = actor["token"].encode().hex() - keys = compose("exec", "-T", "valkey", "sh", "-c", - 'REDISCLI_AUTH="$(cat /run/secrets/valkey_password)" valkey-cli --scan --pattern "session:*"').stdout.split() - assert keys and all(len(k) == len("session:") + 64 for k in keys) - assert not any(actor["token"] in k or token_hex in k for k in keys) + # Lab 7: Valkey has no all-powerful user any more (default off; `api` may not SCAN/KEYS), so the + # check asks with the API's own ACL user: the session exists ONLY under SHA-256(token). + import hashlib + hashed = "session:" + hashlib.sha256(actor["token"].encode()).hexdigest() + script = ('read -r REDISCLI_AUTH; export REDISCLI_AUTH; read -r k1; read -r k2; ' + 'c="valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost --user api --no-auth-warning"; ' + '$c exists "$k1"; $c exists "$k2"') + pw = (ROOT / "secrets" / "valkey_api_password").read_text(encoding="utf-8").strip() + out = subprocess.run(["docker", "compose", "exec", "-T", "valkey", "sh", "-c", script], cwd=ROOT, capture_output=True, + input=f"{pw}\n{hashed}\nsession:{actor['token']}\n".encode()).stdout.decode().split() + assert out == ["1", "0"], out # hashed key present, raw-token key absent diff --git a/student-tests/test_failures.py b/student-tests/test_failures.py index 899d29b..faa2852 100644 --- a/student-tests/test_failures.py +++ b/student-tests/test_failures.py @@ -81,7 +81,7 @@ def test_locked_table_gives_bounded_503(api, prepared): """A statement stuck behind a lock is stopped by lock_timeout, not after minutes.""" alice, bob, chat, message = prepared locker = subprocess.Popen( - ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c", + ["docker", "compose", "exec", "-T", "-u", "postgres", "postgres", "psql", "-d", "messenger", "-c", "BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(6); COMMIT;"], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) try: diff --git a/student-tests/test_idempotency.py b/student-tests/test_idempotency.py index e704485..0c3a6a3 100644 --- a/student-tests/test_idempotency.py +++ b/student-tests/test_idempotency.py @@ -213,7 +213,7 @@ def test_failure_after_the_key_insert_rolls_everything_back(api, pair): def lock_chat_row(chat: dict, seconds: float) -> subprocess.Popen: sql = (f"BEGIN; SELECT 1 FROM chats WHERE id = '{chat['id']}' FOR UPDATE; " f"SELECT pg_sleep({seconds}); COMMIT;") - return subprocess.Popen(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", + return subprocess.Popen(["docker", "compose", "exec", "-T", "-u", "postgres", "postgres", "psql", "-d", "messenger", "-c", sql], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) diff --git a/student-tests/test_pipeline_flow.py b/student-tests/test_pipeline_flow.py index 8cc7071..2fa6ba6 100644 --- a/student-tests/test_pipeline_flow.py +++ b/student-tests/test_pipeline_flow.py @@ -20,7 +20,7 @@ import pytest from PIL import Image import imagegen -from conftest import (lbctl, attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys, +from conftest import (ROOT, lbctl, attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys, s3_size, service_down, service_with_env, wait_healthy, wait_stand) pytestmark = pytest.mark.stack @@ -343,16 +343,18 @@ def test_bad_message_is_dead_lettered_not_processed(api, pair): """A message that does not match jobs.schema.json (published here with the relay's own broker user) is rejected by the worker into the DLQ; nothing is processed.""" before = queue_depth("messenger.attachment-jobs.dlq") - script = ("import asyncio, aio_pika\n" + script = ("import asyncio, sys, aio_pika\n" + "from messenger.tls import client_context\n" "async def m():\n" - " url = open('/run/secrets/broker_url').read().strip()\n" - " c = await aio_pika.connect(url)\n" + " url = sys.stdin.readline().strip()\n" + " c = await aio_pika.connect(url, ssl_context=client_context('/run/secrets/internal-ca.crt'))\n" " ch = await c.channel(publisher_confirms=True)\n" " ex = await ch.get_exchange('messenger.jobs', ensure=False)\n" " await ex.publish(aio_pika.Message(b'{\"url\":\"http://evil/x.png\"}'), routing_key='attachment.process.v1')\n" " await c.close()\n" "asyncio.run(m())\n") - compose("exec", "-T", "relay", "python", "-c", script) + url = (ROOT / "secrets" / "broker_url_relay").read_text(encoding="utf-8").strip() + compose("exec", "-T", "relay", "python", "-c", script, stdin=url + "\n") wait_for(lambda: queue_depth("messenger.attachment-jobs.dlq") == before + 1, 20, "not dead-lettered") assert '"bad_message"' in compose("logs", "--no-log-prefix", "worker").stdout @@ -438,7 +440,7 @@ def test_queued_staging_is_never_deleted_even_after_retention(api, pair): row = attachment_row(att["id"]) assert row["status"] == "queued" and row["staging_state"] == "present" assert s3_size(row["staging_key"], "staging") == len(SAMPLE) - refused = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c", + refused = compose("exec", "-T", "-u", "postgres", "postgres", "psql", "-d", "messenger", "-c", f"UPDATE attachments SET staging_state = 'deleting' WHERE id = '{att['id']}'", check=False) assert refused.returncode != 0 and "attachments_active_has_source" in refused.stderr diff --git a/student-tests/test_security.py b/student-tests/test_security.py new file mode 100644 index 0000000..b24d536 --- /dev/null +++ b/student-tests/test_security.py @@ -0,0 +1,327 @@ +"""Lab 7, grade 3: negative proofs of the trust matrix (contracts/trust-matrix.md) on the running stand. + +Already covered elsewhere and kept: outsider 404 (test_api.test_foreign_chat_is_indistinguishable...), +X-User-Id ignored, logout/expiry (test_api, test_sessions), no secrets in Loki/Tempo +(test_observability), limits of request sizes (test_api, test_attachments), compose policy incl. +per-service secrets and hardening (test_balancing.test_compose_policy_limits_ports_secrets_images). + +Here: external TLS (wrong hostname / empty trust / plaintext), LB->API mTLS (scripts/mtls_check.sh), +TLS + identities of every dependency (PostgreSQL roles, Valkey ACL, RabbitMQ users, S3 keys, +Collector/Prometheus/Loki/Tempo client certificates), OpenBao policies + sealed behaviour, +Argon2id PHC format, login rate limit (429 + Retry-After), X-Instance-Id alias, non-root/limits of +the running containers, no secrets in Git or in the image. Every test restores what it changes. +""" +from __future__ import annotations + +import json +import re +import socket +import ssl +import subprocess +import time +import uuid + +import httpx2 as httpx +import pytest + +from conftest import BASE_URL, CA_FILE, PASSWORD, REPLICAS, ROOT, TLS, basic, compose, lbctl, psql, wait_healthy, \ + wait_stand + +pytestmark = pytest.mark.stack +SECRETS = ROOT / "secrets" +NO_PATHCONV = {"MSYS_NO_PATHCONV": "1"} + + +def secret(name: str) -> str: + return (SECRETS / name).read_text(encoding="utf-8").strip() + + +def sh(service: str, script: str, stdin: str | None = None, timeout: float = 60) -> subprocess.CompletedProcess: + """Run a shell script inside a running service container; secrets go via stdin, never argv. + Bytes, not text: on Windows a text-mode pipe would turn "\\n" into "\\r\\n" (CR in the password).""" + result = subprocess.run(["docker", "compose", "exec", "-T", service, "sh", "-c", script], cwd=ROOT, + input=(stdin or "").encode("utf-8"), capture_output=True, timeout=timeout) + return subprocess.CompletedProcess(result.args, result.returncode, result.stdout.decode("utf-8", "replace"), + result.stderr.decode("utf-8", "replace")) + + +# ------------------------------------------------------------------ external TLS (client -> LB) +def tls_error(host: str, server_hostname: str, context: ssl.SSLContext) -> str | None: + try: + with socket.create_connection((host, 8443), timeout=5) as raw, \ + context.wrap_socket(raw, server_hostname=server_hostname): + return None + except ssl.SSLCertVerificationError as exc: + return exc.verify_message + + +def test_ingress_verifies_ca_and_hostname(): + assert tls_error("127.0.0.1", "localhost", TLS) is None # right CA + SAN + assert "Hostname mismatch" in (tls_error("127.0.0.1", "evil.example", TLS) or "") # wrong name + empty = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # trusts nothing + assert "unable to get local issuer certificate" in (tls_error("127.0.0.1", "localhost", empty) or "") + internal = ssl.create_default_context(cafile=str(SECRETS / "pki" / "internal-ca.crt")) + assert tls_error("127.0.0.1", "localhost", internal) is not None # internal CA is not the public one + + +def test_no_plaintext_entry_point(): + with socket.create_connection(("127.0.0.1", 8443), timeout=5) as s: # plain HTTP to the TLS port + s.sendall(b"GET /health/live HTTP/1.1\r\nHost: localhost\r\n\r\n") + assert not s.recv(256).startswith(b"HTTP/1.1 200") + for port in (8080, 8404, 9090, 3100, 3200, 4318, 5432, 6379, 5671, 8200, 8333): + with pytest.raises(OSError): + socket.create_connection(("127.0.0.1", port), timeout=2).close() + + +# ------------------------------------------------------------------ LB -> API mTLS +def test_lb_to_api_mtls_refuses_foreign_and_wrong_identity(): + result = subprocess.run(["sh", "scripts/mtls_check.sh"], cwd=ROOT, capture_output=True, text=True, + encoding="utf-8", timeout=180) + assert result.returncode == 0, result.stdout[-3000:] + out = result.stdout + assert f"PASS: mTLS LB->API, {REPLICAS} replica(s), 0 failure(s)" in out + # the allowlist (not the CA chain) refused the worker certificate - the API logged that SAN + assert '"client_san": ["worker"]' in out and '"mtls_identity_rejected"' in out + + +def test_api_has_no_published_port_and_answers_only_mtls(): + for item in lbctl.replicas(all_states=False): + assert not json.loads(subprocess.run(["docker", "inspect", "-f", "{{json .HostConfig.PortBindings}}", item["id"]], + capture_output=True, text=True).stdout or "{}") + + +# ------------------------------------------------------------------ dependencies: TLS + identities +def psql_as(role: str, sql: str, sslmode: str = "verify-full") -> subprocess.CompletedProcess: + """Connect over TCP like a service: TLS verify-full against the internal CA, password via stdin.""" + script = ('read -r PGPASSWORD; export PGPASSWORD; exec psql "host=localhost dbname=messenger user=messenger_%s ' + 'sslmode=%s sslrootcert=/run/secrets/internal-ca.crt" -At -v ON_ERROR_STOP=1 -c "%s"') % (role, sslmode, sql) + return sh("postgres", script, stdin=secret(f"pg_{role}_password") + "\n") + + +def test_postgres_tls_only_and_roles_least_privilege(): + assert psql("SHOW ssl") == "on" + assert psql_as("api", "SELECT 1").stdout.strip() == "1" + assert psql_as("api", "SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()").stdout.strip() == "t" + refused = psql_as("api", "SELECT 1", sslmode="disable") + assert refused.returncode != 0 and "no encryption" in refused.stderr, refused.stderr + # superuser never over the network + su = sh("postgres", 'read -r PGPASSWORD; export PGPASSWORD; psql "host=localhost user=postgres dbname=messenger ' + 'sslmode=require" -c "SELECT 1"', stdin=secret("postgres_password") + "\n") + assert su.returncode != 0 and "pg_hba.conf" in su.stderr + denied = { + "api": ["DELETE FROM messages", "SELECT count(*) FROM job_attempts", "CREATE TABLE x (i int)", + "TRUNCATE users", "UPDATE users SET display_name = 'x'"], + "relay": ["SELECT count(*) FROM users", "SELECT count(*) FROM messages", "DELETE FROM jobs"], + "worker": ["SELECT count(*) FROM users", "SELECT count(*) FROM messages", "SELECT count(*) FROM sessions", + "DELETE FROM attachments", "SELECT post_message_v3(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)"], + "auditor": ["UPDATE jobs SET state = state", "INSERT INTO outbox (job_id, attempt) VALUES (gen_random_uuid(), 1)"], + } + for role, statements in denied.items(): + for sql in statements: + result = psql_as(role, sql) + assert result.returncode != 0 and "permission denied" in result.stderr, (role, sql, result.stderr) + allowed = {"api": "SELECT count(*) FROM users", "relay": "SELECT count(*) FROM outbox", + "worker": "SELECT count(*) FROM jobs", "auditor": "SELECT count(*) FROM attachments"} + for role, sql in allowed.items(): + assert psql_as(role, sql).returncode == 0, role + assert psql("SELECT rolsuper FROM pg_roles WHERE rolname LIKE 'messenger_%'").split() == ["f"] * 6 + + +VALKEY = ('read -r REDISCLI_AUTH; export REDISCLI_AUTH; ' + 'valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost --user api ') + + +def test_valkey_tls_and_acl(): + assert sh("valkey", VALKEY + "ping", stdin=secret("valkey_api_password") + "\n").stdout.strip() == "PONG" + # (DEBUG is disabled server-wide anyway: enable-debug-command defaults to no) + for command in ("flushall", "config get dir", "keys *", "acl list", "set other:key 1", "eval 'return 1' 0"): + out = sh("valkey", VALKEY + command, stdin=secret("valkey_api_password") + "\n").stdout + assert "NOPERM" in out, (command, out) + # no plaintext: the only port speaks TLS; the default user is off + assert "PONG" not in sh("valkey", "valkey-cli -h localhost -p 6379 ping 2>&1; true").stdout + default = sh("valkey", "valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost ping 2>&1; true").stdout + assert "PONG" not in default + + +AMQP_PROBE = r''' +import asyncio, sys, aio_pika +from messenger.tls import client_context +url = sys.stdin.readline().strip() +async def main(): + conn = await aio_pika.connect(url, ssl_context=client_context("/run/secrets/internal-ca.crt"), timeout=5) + ch = await conn.channel() + try: + q = await ch.get_queue("messenger.attachment-jobs", ensure=False) + await q.get(no_ack=False, fail=False) + print("CONSUME_ALLOWED") + except Exception as exc: + print("CONSUME_REFUSED", type(exc).__name__) + await conn.close() +asyncio.run(main()) +''' + + +def test_broker_tls_only_and_users_scoped(): + # relay may not consume (its permission: write to the jobs exchange only) + out = compose("exec", "-T", "relay", "python", "-c", AMQP_PROBE, check=False, + stdin=secret("broker_url_relay") + "\n").stdout + assert "CONSUME_REFUSED" in out, out + # the plaintext AMQP port is closed (listeners.tcp = none) + probe = "import socket\ntry:\n socket.create_connection(('broker', 5672), timeout=3); print('OPEN')\nexcept OSError: print('CLOSED')" + assert compose("exec", "-T", "relay", "python", "-c", probe).stdout.strip() == "CLOSED" + + +def test_s3_https_and_scoped_keys(): + out = compose("run", "--rm", "--no-deps", "s3-init", timeout=180).stdout + assert "api: write final: refused (AccessDenied) -> OK" in out + assert "done: private buckets, least-privilege keys verified" in out + probe = "import urllib.request\ntry:\n urllib.request.urlopen('http://s3:8333/healthz', timeout=3); print('PLAIN')\nexcept Exception: print('NO-PLAINTEXT')" + assert compose("exec", "-T", "worker", "python", "-c", probe).stdout.strip() == "NO-PLAINTEXT" + + +TELEMETRY_PROBE = r''' +import ssl, sys, urllib.request +ca = "/run/secrets/internal-ca.crt" +for url in sys.argv[1:]: + ctx = ssl.create_default_context(cafile=ca) # server verified, but NO client certificate + try: + urllib.request.urlopen(url, timeout=5, context=ctx); print(url, "ACCEPTED") + except Exception as exc: + print(url, "REFUSED", type(exc).__name__) +''' + + +def test_telemetry_endpoints_require_client_certificates(): + # A process WITHOUT a client certificate (the worker's python, no cert loaded) is refused by the + # Collector; the backends are reachable only for the Collector/Grafana/Prometheus identities. + out = compose("exec", "-T", "worker", "python", "-c", TELEMETRY_PROBE, "https://otel-collector:4318/v1/logs").stdout + assert "REFUSED" in out and "ACCEPTED" not in out, out + # Prometheus: a certificate of OUR CA but not in its SAN allowlist (the worker's) is refused + allow = r''' +import ssl, urllib.request +ctx = ssl.create_default_context(cafile="/run/secrets/internal-ca.crt") +ctx.load_cert_chain("/run/secrets/service.crt", "/run/secrets/service.key") +try: + urllib.request.urlopen("https://prometheus:9090/-/ready", timeout=5, context=ctx); print("ACCEPTED") +except Exception as exc: + print("REFUSED", type(exc).__name__) +''' + # the worker is not on the telemetry backends' allowlist; it is on the `telemetry` network + assert "REFUSED" in compose("exec", "-T", "worker", "python", "-c", allow).stdout + + +# ------------------------------------------------------------------ OpenBao +def test_openbao_policies_and_no_root_credential_in_apps(): + result = subprocess.run(["sh", "scripts/bao_check.sh"], cwd=ROOT, capture_output=True, text=True, + encoding="utf-8", timeout=300) + assert result.returncode == 0, result.stdout[-4000:] + assert result.stdout.count("FAIL") == 0 + assert "PASS: OpenBao allow/deny and no root credential in the application" in result.stdout + + +def test_openbao_not_dev_and_persistent(): + status = json.loads(sh("openbao", "bao status -format=json").stdout) + assert status["initialized"] and not status["sealed"] and status["storage_type"] == "raft" + cmd = compose("ps", "--format", "json", "openbao").stdout + assert "-dev" not in json.loads(cmd.splitlines()[0])["Command"] + + +def test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones(api): + """Restart = sealed. Running API replicas keep serving (their secrets are in memory); a NEW replica + cannot get its secrets and never becomes healthy; after the operator's unseal it starts.""" + user = api.user("sealed") + compose("restart", "openbao") + try: + assert json.loads(sh("openbao", "bao status -format=json").stdout)["sealed"] is True + api.call("GET", "/api/v1/users/me", 200, token=user["token"]) # running replicas: fine + compose("up", "-d", "--no-recreate", "--no-deps", "--scale", f"api={REPLICAS + 1}", "api") + time.sleep(15) + logs = compose("logs", "--no-log-prefix", "--since", "30s", "api").stdout + assert "openbao_unavailable" in logs + assert len([r for r in lbctl.replicas(all_states=False) if r["health"] == "healthy"]) == REPLICAS + finally: + subprocess.run(["python", "scripts/bao_operator.py", "unseal"], cwd=ROOT, check=True, capture_output=True) + try: + lbctl.wait_up(REPLICAS + 1, timeout=120) # the new one comes up now + finally: + compose("up", "-d", "--no-recreate", "--no-deps", "--scale", f"api={REPLICAS}", "api") + wait_healthy("api", "relay", "worker", "openbao") + wait_stand() + + +# ------------------------------------------------------------------ passwords, login limit, instance id +def test_argon2id_hash_carries_salt_and_parameters(api): + a, b = api.register("phc"), api.register("phc") + rows = psql("SELECT password_hash FROM users WHERE id IN ('%s', '%s')" % (a["id"], b["id"])).split() + assert len(rows) == 2 + for value in rows: + assert re.fullmatch(r"\$argon2id\$v=19\$m=(\d+),t=(\d+),p=(\d+)\$[A-Za-z0-9+/]{22}\$[A-Za-z0-9+/]{43}", value) + m, t, p = map(int, re.match(r"\$argon2id\$v=19\$m=(\d+),t=(\d+),p=(\d+)", value).groups()) + assert m >= 19456 and t >= 2 and p >= 1 + assert rows[0].split("$")[4] != rows[1].split("$")[4] # same password, different salts + + +def test_failed_logins_are_rate_limited_with_retry_after(api): + user = api.user("ratelimit") + url = BASE_URL + "/api/v1/auth/sessions" + codes = [httpx.post(url, headers={"Authorization": basic(user["username"], "Wrong-password-123")}, timeout=10) + for _ in range(5)] + assert [r.status_code for r in codes] == [401] * 5 + blocked = httpx.post(url, headers={"Authorization": basic(user["username"], "Wrong-password-123")}, timeout=10) + assert blocked.status_code == 429 and blocked.json()["error"]["code"] == "rate_limited" + assert 1 <= int(blocked.headers["Retry-After"]) <= 60 + assert blocked.headers.get("X-Instance-Id") and blocked.headers.get("X-Request-Id") + # even the RIGHT password is 429 while blocked (no oracle), on every replica (shared counter) + for _ in range(4): + assert httpx.post(url, headers={"Authorization": basic(user["username"], PASSWORD)}, timeout=10).status_code == 429 + # another account is not affected + other = api.user("ratelimit2") + assert httpx.post(url, headers={"Authorization": basic(other["username"], PASSWORD)}, timeout=10).status_code == 201 + + +def test_x_instance_id_is_a_random_alias_without_hostname_or_ip(api): + seen = {api.call("GET", "/health/live", 200).headers["X-Instance-Id"] for _ in range(20)} + assert len(seen) == REPLICAS + replicas = lbctl.replicas(all_states=False) + hostnames = {r["hostname"] for r in replicas} + ips = {ip for r in replicas for ip in r["ips"]} + for alias in seen: + assert re.fullmatch(r"i-[0-9a-f]{12}", alias) + assert alias not in hostnames and not any(ip in alias for ip in ips) + assert seen == {r["instance"] for r in replicas} + + +# ------------------------------------------------------------------ hardening, secrets outside Git/images +def test_running_containers_are_hardened(): + ids = compose("ps", "-q").stdout.split() + for item in json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, text=True, check=True).stdout): + name, host = item["Name"], item["HostConfig"] + assert not host["Privileged"] and host["NetworkMode"] != "host" and host["PidMode"] != "host", name + assert host["CapDrop"] == ["ALL"] and "no-new-privileges:true" in host["SecurityOpt"], name + assert host["NanoCpus"] > 0 and host["Memory"] > 0, name + assert not any("docker.sock" in m.get("Source", "") for m in item["Mounts"]), name + for service in ("api", "relay", "worker"): + for cid in compose("ps", "-q", service).stdout.split(): + uid = subprocess.run(["docker", "exec", cid, "id", "-u"], capture_output=True, text=True).stdout.strip() + caps = subprocess.run(["docker", "exec", cid, "sh", "-c", "grep CapEff /proc/1/status"], + capture_output=True, text=True).stdout.split()[-1] + assert uid == "10001" and int(caps, 16) == 0, (service, uid, caps) + + +def test_no_secret_in_git_or_in_the_image(): + tracked = subprocess.run(["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True).stdout.split() + assert not [f for f in tracked if f.startswith("secrets/") or f.endswith((".key", ".pem")) + or ".mtusi-lab7-operator" in f or f.endswith(".env")] + values = [secret("postgres_password"), secret("pg_api_password"), secret("valkey_api_password"), + secret("s3_api_secret_access_key"), secret("rabbitmq_worker_password"), + secret("bao/api_secret_id")] + for value in values: + grep = subprocess.run(["git", "grep", "-q", "-F", value], cwd=ROOT) + assert grep.returncode == 1 # not in any tracked file + image = json.loads(compose("config", "--format", "json").stdout)["services"]["api"]["image"] + script = ('n=0; while read -r v; do grep -rqsF -- "$v" /app /etc /usr/local/lib/python3.13/site-packages/messenger* ' + '&& n=$((n+1)); done; find / -xdev \\( -name "*.key" -o -name "*.pem" \\) -not -path "/proc/*" ' + '-not -path "/usr/*" -not -path "/etc/ssl/*" 2>/dev/null | wc -l; echo "hits=$n"') + out = subprocess.run(["docker", "run", "--rm", "-i", "--entrypoint", "sh", image, "-c", script], + input="\n".join(values) + "\n", capture_output=True, text=True, timeout=120).stdout.split() + assert out[-1] == "hits=0" and out[-2] == "0", out diff --git a/student-tests/test_storage_failures.py b/student-tests/test_storage_failures.py index 2b07503..c537d35 100644 --- a/student-tests/test_storage_failures.py +++ b/student-tests/test_storage_failures.py @@ -81,11 +81,12 @@ def test_bucket_is_private_outside_the_api(api, pair): api.wait_status(alice, att["id"], "ready") key = attachment_row(att["id"])["object_key"] probe = ( - "import urllib.request as u, urllib.error as e, socket\n" + "import urllib.request as u, urllib.error as e, socket, ssl\n" + "ctx = ssl.create_default_context(cafile='/run/secrets/internal-ca.crt')\n" "def st(url):\n" - " try: return u.urlopen(url, timeout=3).status\n" + " try: return u.urlopen(url, timeout=3, context=ctx).status\n" " except e.HTTPError as x: return x.code\n" - f"print(st('http://s3:8333/messenger-attachments/{key}'), st('http://s3:8333/messenger-attachments?list-type=2'))\n" + f"print(st('https://s3:8333/messenger-attachments/{key}'), st('https://s3:8333/messenger-attachments?list-type=2'))\n" "for port in (9333, 8888, 8080):\n" " s = socket.socket(); s.settimeout(2)\n" " print(port, s.connect_ex(('s3', port)))\n") diff --git a/student-tests/unit/test_lab7.py b/student-tests/unit/test_lab7.py new file mode 100644 index 0000000..8603809 --- /dev/null +++ b/student-tests/unit/test_lab7.py @@ -0,0 +1,179 @@ +"""Lab 7 units without services: mTLS identity check, TLS contexts, Argon2id parameters, login limit, +OpenBao client error handling, secret lookup order.""" +from __future__ import annotations + +import asyncio +import ssl +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from messenger import bao, passwords, ratelimit, tls +from messenger.config import ConfigError, Settings + +ROOT = Path(__file__).resolve().parents[2] +PKI = ROOT / "secrets" / "pki" + + +# ------------------------------------------------------------------ mTLS identity allowlist +class FakeSSL: + def __init__(self, sans): + self.sans = sans + + def getpeercert(self): + return {"subjectAltName": tuple(("DNS", s) for s in self.sans)} if self.sans is not None else {} + + +class FakeTransport: + def __init__(self, ssl_object): + self.ssl_object, self.aborted = ssl_object, False + + def get_extra_info(self, name, default=None): + return {"ssl_object": self.ssl_object, "peername": ("10.0.0.9", 4444)}.get(name, default) + + def abort(self): + self.aborted = True + + +def test_dns_names_only_from_subject_alt_name(): + assert tls.dns_names({"subjectAltName": (("DNS", "lb"), ("IP Address", "10.0.0.1"))}) == ["lb"] + assert tls.dns_names(None) == [] and tls.dns_names({}) == [] + + +@pytest.mark.parametrize("sans, allowed", [(["lb"], True), (["worker"], False), (["lb.evil"], False), + ([], False), (None, False)]) +def test_protocol_aborts_every_identity_outside_the_allowlist(sans, allowed, monkeypatch): + monkeypatch.setenv("MTLS_ALLOWED_CLIENTS", "lb") + protocol_cls = tls.protocol_class() + called = [] + monkeypatch.setattr(tls.HttpToolsProtocol, "connection_made", lambda self, transport: called.append(transport)) + transport = FakeTransport(FakeSSL(sans)) + protocol_cls.connection_made(object.__new__(protocol_cls), transport) + assert transport.aborted is (not allowed) + assert bool(called) is allowed + + +def test_protocol_aborts_a_plaintext_transport(monkeypatch): + protocol_cls = tls.protocol_class() + transport = FakeTransport(None) + protocol_cls.connection_made(object.__new__(protocol_cls), transport) + assert transport.aborted + + +def test_allowlist_cannot_be_empty(monkeypatch): + monkeypatch.setenv("MTLS_ALLOWED_CLIENTS", " , ") + with pytest.raises(ValueError): + tls.allowed_clients() + + +@pytest.mark.skipif(not (PKI / "api.crt").exists(), reason="PKI not generated (scripts/init_pki.py)") +def test_server_context_requires_client_certificates_of_the_internal_ca_only(): + ctx = tls.server_context(str(PKI / "api.crt"), str(PKI / "api.key"), str(PKI / "internal-ca.crt")) + assert ctx.verify_mode == ssl.CERT_REQUIRED and ctx.minimum_version == ssl.TLSVersion.TLSv1_2 + subjects = [dict(x[0] for x in c["subject"])["commonName"] for c in ctx.get_ca_certs()] + assert subjects == ["MTUSI lab7 internal CA"] # no system CAs, not the public CA + client = tls.client_context(str(PKI / "internal-ca.crt")) + assert client.check_hostname and client.verify_mode == ssl.CERT_REQUIRED + + +# ------------------------------------------------------------------ Argon2id parameters +def test_argon2_parameters_are_configurable_but_never_below_the_minimum(monkeypatch): + monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z") + monkeypatch.setenv("ARGON2_MEMORY_KIB", "47104") + monkeypatch.setenv("ARGON2_ITERATIONS", "3") + s = Settings.from_env(s3_credentials=False) + assert (s.argon2_memory_kib, s.argon2_iterations, s.argon2_parallelism) == (47104, 3, 1) + for name, bad in (("ARGON2_MEMORY_KIB", "19455"), ("ARGON2_ITERATIONS", "1"), ("ARGON2_PARALLELISM", "0")): + monkeypatch.setenv(name, bad) + with pytest.raises(ConfigError): + Settings.from_env(s3_credentials=False) + monkeypatch.delenv(name) + + +def test_hash_carries_the_configured_parameters_and_old_hashes_still_verify(): + async def run(): + passwords.configure(1) + old = await passwords.hash_password("correct horse battery") + passwords.configure(1, memory_kib=32768, iterations=3) + new = await passwords.hash_password("correct horse battery") + assert new.startswith("$argon2id$v=19$m=32768,t=3,p=1$") + assert await passwords.verify_password(old, "correct horse battery") # params come from the hash + assert await passwords.verify_password(new, "correct horse battery") + passwords.configure(2) + asyncio.run(run()) + + +# ------------------------------------------------------------------ login rate limit (process fallback) +def limiter(user=3, ip=100): + settings = SimpleNamespace(cache_timeout_seconds=0.5, login_user_limit=user, login_user_window_seconds=60, + login_ip_limit=ip, login_ip_window_seconds=300) + return ratelimit.LoginLimiter(settings, client=None) + + +def test_limit_per_username_with_retry_after(): + async def run(): + lim = limiter(user=3) + for _ in range(3): + await lim.check("alice", "1.1.1.1") + await lim.failed("alice", "1.1.1.1") + with pytest.raises(ratelimit.RateLimited) as exc: + await lim.check("alice", "2.2.2.2") # another IP does not help + assert exc.value.status == 429 and exc.value.code == "rate_limited" + assert 1 <= int(exc.value.headers["Retry-After"]) <= 60 + await lim.check("bob", "1.1.1.1") # another user is not blocked + asyncio.run(run()) + + +def test_limit_per_ip_and_reset_on_success(): + async def run(): + lim = limiter(user=100, ip=4) + for i in range(4): + await lim.failed(f"user{i}", "9.9.9.9") + with pytest.raises(ratelimit.RateLimited): + await lim.check("someone-else", "9.9.9.9") # spraying many accounts from one IP + lim2 = limiter(user=2) + await lim2.failed("carol", "1.1.1.1") + await lim2.succeeded("carol") # success resets the username window + await lim2.failed("carol", "1.1.1.1") + await lim2.check("carol", "1.1.1.1") + asyncio.run(run()) + + +# ------------------------------------------------------------------ OpenBao client / secret lookup order +def test_secrets_come_from_openbao_first(monkeypatch): + monkeypatch.setenv("BAO_ADDR", "https://openbao:8200") + monkeypatch.setattr(bao, "_cache", {"database_url": "postgresql://from-bao/x"}) + monkeypatch.setenv("DATABASE_URL", "postgresql://from-env/x") + assert Settings.from_env(s3_credentials=False).database_url == "postgresql://from-bao/x" + monkeypatch.delenv("BAO_ADDR") + assert Settings.from_env(s3_credentials=False).database_url == "postgresql://from-env/x" + + +def test_openbao_refusal_is_a_config_error_without_retry(monkeypatch, tmp_path): + (tmp_path / "r").write_text("role") + (tmp_path / "s").write_text("secret") + monkeypatch.setattr(bao, "_cache", None) + for k, v in {"BAO_ADDR": "https://127.0.0.1:1", "BAO_SECRET_PATH": "messenger/data/api", + "BAO_ROLE_ID_FILE": str(tmp_path / "r"), "BAO_SECRET_ID_FILE": str(tmp_path / "s"), + "BAO_STARTUP_TIMEOUT_SECONDS": "0", "DATABASE_URL": "postgresql://x/y"}.items(): + monkeypatch.setenv(k, v) + with pytest.raises(ConfigError, match="OpenBao unavailable"): # nothing listens: bounded wait, then stop + Settings.from_env(s3_credentials=False) + monkeypatch.delenv("BAO_SECRET_ID_FILE") + monkeypatch.setattr(bao, "_cache", None) + with pytest.raises(ConfigError, match="BAO_SECRET_ID_FILE"): + Settings.from_env(s3_credentials=False) + + +def test_pki_script_never_prints_key_material(tmp_path): + """init_pki.py output names files only (run on a copy so the real ./secrets stays untouched).""" + script = (ROOT / "scripts" / "init_pki.py").read_text(encoding="utf-8") + (tmp_path / "scripts").mkdir() + (tmp_path / "scripts" / "init_pki.py").write_text(script, encoding="utf-8") + out = subprocess.run([sys.executable, str(tmp_path / "scripts" / "init_pki.py")], capture_output=True, text=True, + check=True).stdout + assert "BEGIN" not in out and "PRIVATE" not in out + assert (tmp_path / "secrets" / "pki" / "internal-ca.key").exists() diff --git a/student-tests/unit/test_unit.py b/student-tests/unit/test_unit.py index adf227f..202af75 100644 --- a/student-tests/unit/test_unit.py +++ b/student-tests/unit/test_unit.py @@ -194,14 +194,24 @@ def test_request_fingerprint_ignores_key_order_and_default_attachments(): assert request_fingerprint("x", [one]) != request_fingerprint("x", []) -def test_instance_id_defaults_to_hostname_and_is_validated(monkeypatch): +def test_instance_id_is_a_random_alias_stable_per_process_and_validated(monkeypatch): + """Lab 7: X-Instance-Id is a random alias (no hostname/IP), drawn once per process.""" + import re import socket + from messenger import config monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z") monkeypatch.delenv("INSTANCE_ID", raising=False) - assert Settings.from_env().instance_id == socket.gethostname() + monkeypatch.setattr(config, "_INSTANCE_ID", None) + first = Settings.from_env().instance_id + assert re.fullmatch(r"i-[0-9a-f]{12}", first) and first != socket.gethostname() + assert Settings.from_env().instance_id == first # stable for the life of the process + monkeypatch.setattr(config, "_INSTANCE_ID", None) + assert Settings.from_env().instance_id != first # another process, another alias + monkeypatch.setattr(config, "_INSTANCE_ID", None) monkeypatch.setenv("INSTANCE_ID", "replica-a") assert Settings.from_env().instance_id == "replica-a" for bad in ("with space", "x" * 65, "ip/1"): + monkeypatch.setattr(config, "_INSTANCE_ID", None) monkeypatch.setenv("INSTANCE_ID", bad) with pytest.raises(ConfigError): Settings.from_env() -- 2.54.0 From b3ddcf25dc31bf2be03dbb1de7060ed27f3010c2 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:33:01 +0300 Subject: [PATCH 08/16] =?UTF-8?q?lab7:=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BF=D0=BE=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B3=D0=BE=D0=BD=D1=83=20=D1=81=D0=B2=D0=BE=D0=B8?= =?UTF-8?q?=D1=85=20=D1=82=D0=B5=D1=81=D1=82=D0=BE=D0=B2=20(=D1=82=D0=B0?= =?UTF-8?q?=D0=B9=D0=BC=D0=B0=D1=83=D1=82=20Valkey=20=D1=81=20TLS=201,0=20?= =?UTF-8?q?=D1=81,=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=BF=D0=BE=20alias,=20GET=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=BE=20EXISTS),=20=D1=87=D0=B5=D1=80=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D0=BA=20REPORT,=20=D1=81=D0=B1=D0=BE=D1=80=D1=89=D0=B8=D0=BA?= =?UTF-8?q?=20=D0=B4=D0=BE=D0=BA=D0=B0=D0=B7=D0=B0=D1=82=D0=B5=D0=BB=D1=8C?= =?UTF-8?q?=D1=81=D1=82=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 173 ++++++++++++++++++++++--- compose.yaml | 4 +- scripts/collect_evidence.py | 4 +- student-tests/test_db.py | 3 +- student-tests/test_failures.py | 4 +- student-tests/test_storage_failures.py | 2 +- 6 files changed, 167 insertions(+), 23 deletions(-) diff --git a/REPORT.md b/REPORT.md index 9801db4..d8f45d6 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,178 @@ # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Боданюк Алексей, БВТ2302 +- Целевая оценка; выбранный трек 5: **3** (трек не заявлен) +- Commit/PR: ветка `solution/bvt2302-bodanyuk`; PR «ЛР 7 — БВТ2302 — Боданюк — на 3» (ссылка после публикации) +- Использованные источники, библиотеки и помощь ИИ: + - всё из ЛР 2–6: Python 3.13, Starlette, uvicorn, psycopg 3, redis-py, argon2-cffi, aiobotocore, aio-pika, Pillow, OpenTelemetry SDK 1.45.2; + - новые образы: **OpenBao 2.7.3**; новая библиотека на хосте — **cryptography 50.0.2** (только для `scripts/init_pki.py`); + - документация: [OpenBao AppRole](https://openbao.org/docs/auth/approle/), [policies](https://openbao.org/docs/concepts/policies/), [production hardening](https://openbao.org/docs/internals/security/), [OWASP Password Storage](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html), HAProxy `ssl`/`verifyhost`, PostgreSQL SSL и `pg_hba.conf`, Valkey TLS и ACL, RabbitMQ TLS, OpenTelemetry Collector `confighttp` TLS, Prometheus `web-config` (`client_allowed_sans`), Grafana provisioning `$__file{}`; + - код, тесты, конфигурации и документы написаны с помощью ИИ-ассистента Claude (Anthropic); решения разобраны и объяснимы автором ([docs/DEFENSE.md](docs/DEFENSE.md)). ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Версии (все образы закреплены по тегу **и** digest, см. [compose.yaml](compose.yaml)): + +| Компонент | Версия | +| --- | --- | +| образ приложения | python 3.13.16-slim-bookworm | +| PostgreSQL | 18.6 | +| Valkey | 8.1.3 | +| SeaweedFS | 4.46 | +| RabbitMQ | 4.3.7 | +| HAProxy | 3.2.26 | +| OpenTelemetry Collector contrib | 0.165.0 | +| Prometheus | 3.16.0 | +| Loki | 3.7.10 | +| Tempo | 2.10.10 | +| Grafana | 13.2.6 | +| **OpenBao** | **2.7.3** (`@sha256:b9418c63…`, платформа linux/amd64) | + +Python-пакеты приложения — `requirements.txt` с sha256 (`pip install --require-hashes --no-deps`). + +Prerequisites: Docker с Compose v2, Python 3.12+, Git. Для Windows — [docs/WINDOWS.md](docs/WINDOWS.md). Действия оператора (init/unseal OpenBao, где лежат ключи, что делать после рестарта) — [docs/OPERATOR.md](docs/OPERATOR.md). + +```sh +git clone mtusi2026lab7 && cd mtusi2026lab7 && git checkout solution/bvt2302-bodanyuk +python3 -m venv .venv +.venv/bin/python -m pip install --require-hashes --no-deps -r requirements.txt +.venv/bin/python -m pip install -r requirements-test.txt # pytest, httpx2, jsonschema, pillow, cryptography +.venv/bin/python scripts/init_secrets.py # ./secrets: пароли (по одному на сервис/роль) + PKI (2 CA, сертификаты сервисов) +docker compose up -d openbao # OpenBao стартует ЗАПЕЧАТАННЫМ (не dev) +.venv/bin/python scripts/bao_operator.py bootstrap # ОПЕРАТОР: init 3/2, unseal, KV, AppRole, политики, секреты +docker compose up -d --build --wait # migrate (0001-0007) и s3-init - один раз, exit 0 +make check test test-security CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.venv/bin/python +make mtls-check bao-check PYTHON=.venv/bin/python +make test-persistence ACTION_SCRIPT=scripts/restart.sh CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.venv/bin/python +make test-failover ACTION_SCRIPT=scripts/stop-one.sh CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.venv/bin/python && make restore +.venv/bin/python -m pytest student-tests -v # свои тесты, ~1,5-2 ч на этом ПК +``` + +То же самое для чистого стенда: `make secrets up`, затем `python scripts/collect_evidence.py` (вывод — в `evidence/`). + +* **Действия оператора:** `bootstrap` один раз; `python scripts/bao_operator.py unseal` после **каждого** рестарта OpenBao (хук `scripts/restart.sh` делает это сам). +* Root token и доли unseal создаются в `~/.mtusi-lab7-operator//`, вне репозитория. В отчёте и в выводе скриптов значений нет. +* Grafana: `https://localhost:3000`, `admin` / `secrets/grafana_admin_password`. +* **Безопасная остановка:** `docker compose down` — volumes, включая хранилище OpenBao, остаются. После запуска: `up -d openbao` → `unseal` → `up -d --wait`. +* **Намеренное удаление учебных данных:** `docker compose down -v`, затем удалить `./secrets` и `~/.mtusi-lab7-operator/`. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +```text + public-ca internal-ca: mTLS, allowlist SAN "lb" +client --HTTPS 127.0.0.1:8443--> lb (HAProxy) ------------------------------------> api x2 (8443; health 127.0.0.1:8081) +api --TLS verify-full--> postgres (messenger_api) | --rediss--> valkey (ACL api) | --HTTPS--> s3 (messenger-api) +relay --TLS--> postgres (messenger_relay) | --AMQPS 5671--> broker (user relay: publish) +worker --TLS--> postgres (messenger_worker) | --AMQPS--> broker (user worker: consume) | --HTTPS--> s3 (messenger-worker) +api/relay/worker --HTTPS--> openbao (AppRole , read messenger/data/, revoke-self) [vault, internal] +api/relay/worker --OTLP/HTTPS + client cert--> otel-collector --mTLS--> prometheus / loki / tempo [telemetry] +grafana (HTTPS 127.0.0.1:3000, public-ca) --mTLS--> prometheus / loki / tempo +operator --docker compose exec--> openbao (root token и доли unseal через stdin, из ~/.mtusi-lab7-operator) +``` + +**Что перенесено из lab6** (коммит `6435b6a`, без изменений): весь API, relay, worker, outbox/lease, SeaweedFS, RabbitMQ, телеметрия, миграции 0001–0006, тесты, docs. Бизнес-API и источник истины (PostgreSQL) не менялись. + +**Убрано как лишнее для lab7:** + +* нагрузочные и исследовательские скрипты ЛР 3–6 (`bench/*` трека 1, инциденты, демо по HTTP); +* overlay tail-sampling Collector; +* открытые порты 8080 и 8404. + +**Что изменено и добавлено** (коммиты по шагам, `git log`): + +| Шаг | Что | Где | +| --- | --- | --- | +| PKI | 2 CA + leaf на сервис, SAN = имя compose, ECDSA P-256, 365 дней; ключи CA не монтируются нигде | `scripts/init_pki.py` | +| Внешний HTTPS | HAProxy `bind :8443 ssl crt ingress.pem ssl-min-ver TLSv1.2`; только loopback | `infra/haproxy/haproxy.cfg` | +| mTLS LB → API | uvicorn с `CERT_REQUIRED` + CA `internal-ca`; подкласс протокола сверяет SAN клиента с `MTLS_ALLOWED_CLIENTS=lb` и делает `abort()` до HTTP; health — отдельный listener на loopback | `src/messenger/tls.py`, `__main__.py` | +| TLS к зависимостям | PostgreSQL `ssl=on` + `pg_hba` только `hostssl`; Valkey `port 0`/`tls-port`; RabbitMQ `listeners.tcp = none`/5671; S3 HTTPS; OTLP HTTPS + client cert; Prometheus/Loki/Tempo — `RequireAndVerifyClientCert`; Grafana datasources — mTLS | `infra/*`, `compose.yaml`, `sessions.py`, `storage.py`, `broker.py` | +| Раздельные права | 6 ролей PostgreSQL, GRANT по коду; ACL Valkey; пользователи RabbitMQ; identities S3 (admin только у `s3-init`) | `infra/postgres/`, `migrations/0007_least_privilege.sql`, `infra/valkey/start.sh` | +| OpenBao | raft на volume `baodata`, TLS, audit в stdout; AppRole + policy на сервис; KV v2 `messenger/`; приложение читает секреты из OpenBao, файлов с паролями у api/relay/worker нет | `infra/openbao/`, `scripts/bao_operator.py`, `src/messenger/bao.py`, `config._secret` | +| Argon2id | параметры из env (не ниже m=19456, t=2, p=1), PHC; замер в контейнере API | `passwords.py`, `bench/argon2_bench.py` | +| Лимит входа | неудачи в Valkey, 5/60 с на имя и 50/300 с на IP; 429 + `Retry-After`; проверка до Argon2 | `ratelimit.py`, `app.create_session` | +| Hardening | `cap_drop: [ALL]` + `no-new-privileges` у всех 16 сервисов (у 4 хранилищ ещё CHOWN/DAC_OVERRIDE/FOWNER/SETGID/SETUID для chown и drop to user); app/worker uid 10001, CapEff 0 | `compose.yaml` | +| `X-Instance-Id` | случайный alias `i-<12 hex>` на процесс, без hostname/IP; для оператора лежит в `/tmp/instance_id` контейнера | `config._instance_id`, `scripts/stop-one.sh` | + +Почему так, а не иначе (подробно — [docs/DEFENSE.md](docs/DEFENSE.md)): + +* **Проверка SAN в приложении, а не sidecar.** Реплики масштабируются через `deploy.replicas`, и sidecar к каждой не привязать без отдельных сервисов `api1`/`api2`. Отдельный CA для LB хуже: identity держится на дисциплине выпуска, а не на явном allowlist. +* **OpenBao raft.** В 2.7 backend `file` удалён (`unknown storage type file`). Raft с одним узлом — тоже persistent storage на volume. +* **Токен сервиса отзывается сразу после чтения.** Статические KV на уровне 3 нужны только при старте. Живой токен в памяти ничего не даёт, а только расширяет окно утечки. +* **`CACHE_TIMEOUT_SECONDS` 0,5 → 1,0 с.** В бюджет теперь входит TLS-рукопожатие холодного соединения (см. «Дефекты»). + +### Соответствие `.env.example` реальной конфигурации + +| Переменная `.env.example` | Как в решении | +| --- | --- | +| `APP_HOST`, `APP_PORT` | `0.0.0.0`, **8443** (mTLS); health — `APP_HEALTH_PORT=8081` на loopback | +| `SESSION_TTL_SECONDS`, `IDEMPOTENCY_TTL_SECONDS`, `API_REPLICAS` | как есть (3600, 86400, 2) | +| `DATABASE_URL_FILE`, `CACHE_URL_FILE` | **нет у api/relay/worker**: `database_url`, `cache_url` читаются из OpenBao (`messenger/data/`); `DATABASE_URL_FILE` есть только у `migrate`, `jobctl`, `auditor` | +| `SESSION_STORE` | `valkey` | +| `S3_ENDPOINT` | `https://s3:8333` | +| `S3_REGION`, `S3_BUCKET`, `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS`, `WORKER_CONCURRENCY`, `JOB_MAX_ATTEMPTS`, `JOB_TIMEOUT_SECONDS`, `STAGING_RETENTION_SECONDS` | как в lab6 (+ `S3_STAGING_BUCKET`) | +| `S3_*_FILE` | у api/worker — из OpenBao; файлы только у `s3`, `s3-init`, `auditor` | +| `BROKER_URL_FILE` | из OpenBao (`amqps://...:5671`) | +| `OTEL_SERVICE_NAME` | `messenger-api` / `-relay` / `-worker` | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | `https://otel-collector:4318`, плюс `OTEL_EXPORTER_OTLP_CERTIFICATE`, `..._CLIENT_CERTIFICATE`, `..._CLIENT_KEY` | +| `PUBLIC_BASE_URL` | `https://localhost:8443` (используют тесты) | +| `TLS_CA_FILE` | internal CA для исходящих TLS (S3, Valkey, RabbitMQ) | +| `TLS_CERT_FILE`, `TLS_KEY_FILE` | сертификат и ключ сервиса (`/run/secrets/service.crt/.key`); у API ещё `TLS_CLIENT_CA_FILE` и `MTLS_ALLOWED_CLIENTS` | +| `BAO_ADDR`, `BAO_CACERT` | `https://openbao:8200`, internal CA; плюс `BAO_ROLE_ID_FILE`, `BAO_SECRET_ID_FILE`, `BAO_SECRET_PATH`, `BAO_STARTUP_TIMEOUT_SECONDS` | +| `ARGON2_MEMORY_KIB`, `ARGON2_ITERATIONS`, `ARGON2_PARALLELISM` | 19456, 2, 1 (по замеру) | +| (новое) `LOGIN_RATE_LIMIT_USER[_WINDOW_SECONDS]`, `LOGIN_RATE_LIMIT_IP[_WINDOW_SECONDS]` | 5/60 с, 50/300 с | + +**Критичные зависимости readiness.** PostgreSQL, Valkey и S3, как в lab6. OpenBao в readiness не входит: работающей реплике он не нужен, а новая без него не стартует. Телеметрия и Grafana на readiness не влияют. ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Все файлы — в [evidence/](evidence/), сводка — [evidence/SUMMARY.md](evidence/SUMMARY.md). Прогон из **чистого clone** в отдельной папке: новые secrets и сертификаты, пустые volumes, `COMPOSE_PROJECT_NAME=mtusi-lab7-clean`. Commit и окружение — в [evidence/stand.md](evidence/stand.md). -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +RESULTS_TABLE ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +### Argon2id: выбор параметров замером + +Замер на стенде: `bench/argon2_bench.py` внутри реплики API, с её лимитами (cgroup `cpu.max = 100000 100000` = 1 CPU, 512 MiB), argon2-cffi 25.1.0, p = 1. Сырые данные — [evidence/argon2/bench.json](evidence/argon2/bench.json). + +ARGON2_TABLE + +**Вывод.** Реплика имеет 1 CPU и разрешает 2 хеша одновременно (`PASSWORD_HASH_CONCURRENCY=2`, это 2 × m RAM). Цель — вход не дольше ~100 мс при двух параллельных хешах. Её выполняет только базовая конфигурация OWASP m=19 MiB, t=2, p=1. + +* Следующий шаг по памяти (32 MiB) или по итерациям (t=3) даёт заметно более медленный вход. +* Вариант 46 MiB / t=2 даёт всего несколько хешей в секунду на реплику: вход становится дешёвой DoS-целью. +* Поэтому параметры не повышены. Защита от перебора дополнена лимитом неудачных входов, который срабатывает до Argon2. +* Числа шумные: Docker Desktop, рядом работает стенд. Выбор держится на порядке величин, а не на отдельных миллисекундах. + +### Отказы | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| `restart.sh`: рестарт LB, API ×2, relay, worker, PostgreSQL, Valkey, S3, RabbitMQ, **OpenBao** (+ unseal оператором) | данные и сессия сохранены | PERSIST_RESULT | 0 потерь | +| `stop-one.sh` по очереди для обеих реплик | запросы идут через оставшуюся, повтор без дублей | FAILOVER_RESULT | 0 потерь подтверждённых | +| OpenBao запечатан (`docker compose restart openbao`) | работающие реплики обслуживают; новая не стартует до unseal | `test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones` PASS: запросы 200, новая реплика пишет `openbao_unavailable` и не становится healthy, после unseal поднимается | до unseal оператором | +| 5 неудачных входов одного пользователя | 429 + `Retry-After`, CPU не тратится | `test_failed_logins_are_rate_limited_with_retry_after` PASS | окно 60 с | + +### Дефекты, найденные при проверке (честно) + +1. **`pg_hba.conf` read-only.** Тест ЛР 3 «реплика жива, но не готова» добавляет временную строку `reject` в `pg_hba.conf`. После переноса hba в read-only файл тест падал. Исправлено: postgres при старте копирует `pg_hba.conf` из Git в tmpfs и использует копию. Источник правды остался в Git. +2. **Чтение отметки сбоя.** Внедрение сбоев (`FAULT_POINTS`, только для экспериментов) читает свою отметку из `job_events`, а у сервисов было только INSERT. Тесты конвейера с падением worker висели в `queued`. Исправлено: `GRANT SELECT ON job_events` для api/relay/worker. Это журнал заданий без пользовательских данных; записано в матрице. +3. **Таймаут Valkey 0,5 с мал для TLS.** Только что запущенная реплика один раз не уложилась в 0,5 с на холодном TLS-соединении к Valkey (568 мс, 503 в тесте мягкой остановки). Исправлено: `CACHE_TIMEOUT_SECONDS=1.0`, граница теста отказа Valkey 2,6 с. +4. **`redis-py incr()` = `INCRBY`.** Лимит входа отвечал 503 из-за `NOPERM`. Исправлено: в ACL добавлен `+incrby`. Теперь любая ошибка ACL видна тестом. +5. **`X-Instance-Id` перезаписывался вспомогательным процессом.** Отладочный `docker compose exec api python …` генерировал новый alias и переписывал `/tmp/instance_id`, и `stop-one` не находил реплику. Исправлено: файл пишет только главный процесс сервиса. +6. **CRLF в stdin на Windows.** Тесты, передающие пароль через stdin, на Windows посылали `\r\n`. Исправлено: stdin передаётся байтами. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +* **Уровень 4 не заявлен:** + * нет ротации и отзыва leaf/secret, CRL/OCSP; + * SecretID живёт 30 дней, нет wrapping; + * нет mTLS к брокеру; + * Loki/Tempo проверяют только цепочку CA, без allowlist SAN; + * Grafana в Prometheus может и писать; + * нет read_only/seccomp и сканирования образов; + * лимит входа не защищает от распределённого перебора с многих IP. +* **Root token не отзывается после настройки**, а хранится у оператора. Доли unseal лежат в одной папке, а не у трёх людей. Это учебное упрощение, оно описано. +* **Четыре stateful-образа стартуют от root** ради `chown` и сразу понижают права; оставлен минимальный набор capabilities. +* **Plaintext-hop'ы есть только на loopback** контейнеров (SeaweedFS master/volume/filer, gRPC Loki/Tempo, health 8081). Из сети они недоступны, это проверено тестами. +* **Один Docker-host.** Отказ хоста, единственной БД, LB или OpenBao не переживается. diff --git a/compose.yaml b/compose.yaml index 57335a4..dcb4805 100644 --- a/compose.yaml +++ b/compose.yaml @@ -50,7 +50,9 @@ x-api-env: &api-env DB_POOL_MIN: ${DB_POOL_MIN:-1} DB_POOL_MAX: ${DB_POOL_MAX:-10} DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3} - CACHE_TIMEOUT_SECONDS: ${CACHE_TIMEOUT_SECONDS:-0.5} + # Lab 7: 1.0 s (was 0.5): the budget now includes the TLS handshake of a cold connection to Valkey; + # 0.5 s was exceeded once by a replica that had just started (test_graceful_stop..., 568 ms). + CACHE_TIMEOUT_SECONDS: ${CACHE_TIMEOUT_SECONDS:-1.0} PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-2} # Lab 7: Argon2id parameters, chosen by a measurement on this stand (bench/argon2_bench.py, # REPORT.md); the application refuses values below m=19456 KiB, t=2, p=1. diff --git a/scripts/collect_evidence.py b/scripts/collect_evidence.py index 148db90..2d56150 100644 --- a/scripts/collect_evidence.py +++ b/scripts/collect_evidence.py @@ -154,11 +154,11 @@ def main() -> int: ["docker", "compose", "ps", "-a", "--format", "{{.Name}} {{.State}} {{.Status}}"], timeout=600) failover_both() argon2_bench() - step("Телеметрия по mTLS: trace + logs", "trace-demo.txt", [PY, "scripts/trace_demo.py", "--output", str(EVIDENCE / "trace-demo-raw.txt")]) + step("Телеметрия по mTLS: trace + logs", "trace-demo.txt", [PY, "scripts/trace_demo.py"]) step("Dashboard: все запросы через Grafana (HTTPS)", "dashboard-check.txt", [PY, "scripts/check_dashboard.py"]) if not args.skip_student_tests: step("Свои тесты (unit + стенд, в т.ч. test_security.py)", "student-tests.txt", - [PY, "-m", "pytest", "student-tests", "-v", "-p", "no:cacheprovider", "--durations=15"], timeout=5400) + [PY, "-m", "pytest", "student-tests", "-v", "-p", "no:cacheprovider", "--durations=15"], timeout=14400) lines = ["# Сводка доказательств lab7", "", f"Собрано: {dt.datetime.now(dt.timezone.utc).isoformat(timespec='seconds')}", "", "| Шаг | Команда | Код | Файл | Время, с |", "| --- | --- | --- | --- | --- |"] for title, command, code, filename, elapsed in results: diff --git a/student-tests/test_db.py b/student-tests/test_db.py index 214dbd2..f66f6f0 100644 --- a/student-tests/test_db.py +++ b/student-tests/test_db.py @@ -120,7 +120,8 @@ def test_secrets_are_not_stored_in_plain_text(api): hashed = "session:" + hashlib.sha256(actor["token"].encode()).hexdigest() script = ('read -r REDISCLI_AUTH; export REDISCLI_AUTH; read -r k1; read -r k2; ' 'c="valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost --user api --no-auth-warning"; ' - '$c exists "$k1"; $c exists "$k2"') + # GET, not EXISTS: the ACL of `api` allows only the commands the API uses + 'for k in "$k1" "$k2"; do [ -n "$($c get "$k")" ] && echo 1 || echo 0; done') pw = (ROOT / "secrets" / "valkey_api_password").read_text(encoding="utf-8").strip() out = subprocess.run(["docker", "compose", "exec", "-T", "valkey", "sh", "-c", script], cwd=ROOT, capture_output=True, input=f"{pw}\n{hashed}\nsession:{actor['token']}\n".encode()).stdout.decode().split() diff --git a/student-tests/test_failures.py b/student-tests/test_failures.py index faa2852..d48a8d2 100644 --- a/student-tests/test_failures.py +++ b/student-tests/test_failures.py @@ -1,7 +1,7 @@ """Dependency failures with a VALID session: bounded 503, never anonymous access, recovery afterwards. Every test stops/pauses a real container and restores it in `finally` (service_down). -Timing bounds: DB_TIMEOUT_SECONDS=3 (client deadline), CACHE_TIMEOUT_SECONDS=0.5. +Timing bounds: DB_TIMEOUT_SECONDS=3 (client deadline), CACHE_TIMEOUT_SECONDS=1.0 (lab 7: incl. TLS handshake). Lab 3: requests go through HAProxy. While the outage is being detected the replicas answer 503 themselves; once every replica fails /health/ready, HAProxy answers 503 in the same @@ -20,7 +20,7 @@ from conftest import ROOT, probe_inside, restart_services, running_replicas, ser pytestmark = pytest.mark.stack DB_BOUND = 3.6 # DB_TIMEOUT_SECONDS + network/HTTP overhead -CACHE_BOUND = 1.6 # 2 x CACHE_TIMEOUT_SECONDS + overhead +CACHE_BOUND = 2.6 # 2 x CACHE_TIMEOUT_SECONDS + overhead def timed(api, *args, **kwargs): diff --git a/student-tests/test_storage_failures.py b/student-tests/test_storage_failures.py index c537d35..ae24587 100644 --- a/student-tests/test_storage_failures.py +++ b/student-tests/test_storage_failures.py @@ -64,7 +64,7 @@ def test_upload_survives_failover_of_the_serving_replica(api, pair): data = imagegen.png_of_size(500_000) response = api.upload(alice, chat, data) att, served_by = response.json(), response.headers["x-instance-id"] - replica = next(r for r in running_replicas() if r["hostname"] == served_by) + replica = next(r for r in running_replicas() if r["instance"] == served_by) api.wait_status(bob, att["id"], "ready") with replica_stopped(replica, "kill"): for _ in range(5): -- 2.54.0 From 4c9b0f284bd973cf60611ac42d6dd49a3a100a85 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:51:41 +0300 Subject: [PATCH 09/16] =?UTF-8?q?restart.sh:=20=D0=BE=D0=B4=D0=B8=D0=BD=20?= =?UTF-8?q?docker=20compose=20start=20=D0=B4=D0=BB=D1=8F=20api/relay/worke?= =?UTF-8?q?r/lb=20(=D1=83=D0=BA=D0=BB=D0=B0=D0=B4=D1=8B=D0=B2=D0=B0=D0=B5?= =?UTF-8?q?=D1=82=D1=81=D1=8F=20=D0=B2=2090=20=D1=81=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/restart.sh | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/restart.sh b/scripts/restart.sh index 16b53c9..ad08ece 100644 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -18,9 +18,9 @@ docker compose stop lb api relay worker docker compose restart postgres valkey s3 broker openbao # 3. Operator: unseal (OpenBao is sealed after every start). "$PY" scripts/bao_operator.py unseal -# 4. API replicas (log in to OpenBao again, read their secrets), the LB, then relay and worker. -# HAProxy resolves the new replica addresses through Docker DNS by itself. -docker compose start api -docker compose start lb -docker compose start relay worker +# 4. API replicas (log in to OpenBao again, read their secrets), relay, worker and the LB in ONE +# command: compose starts them in dependency order (lb after api is healthy) and waits for the +# health conditions once, relay/worker in parallel with api (three separate `start` calls cost +# 3 x ~23 s on Windows and exceeded the test's 90 s budget). HAProxy re-resolves the replicas. +docker compose start api relay worker lb echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3, broker and openbao restarted with volumes preserved; openbao unsealed" -- 2.54.0 From 920d9b5694c402188526b8c12e737a081f8ed680 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:06:29 +0300 Subject: [PATCH 10/16] =?UTF-8?q?stop-one:=20alias=20=D1=80=D0=B5=D0=BF?= =?UTF-8?q?=D0=BB=D0=B8=D0=BA=20=D1=87=D0=B8=D1=82=D0=B0=D0=B5=D1=82=D1=81?= =?UTF-8?q?=D1=8F=20=D0=BF=D0=B0=D1=80=D0=B0=D0=BB=D0=BB=D0=B5=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D0=BE,=20docker=20stop=20=D0=B2=20=D1=84=D0=BE=D0=BD?= =?UTF-8?q?=D0=B5=20(=D1=85=D1=83=D0=BA=20<=2010=20=D1=81=20=D0=BD=D0=B0?= =?UTF-8?q?=20Windows);=20check=5Fdashboard=20=D0=BF=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B5=D1=80=D1=8F=D0=B5=D1=82=20Grafana=20=D0=BF=D1=83=D0=B1?= =?UTF-8?q?=D0=BB=D0=B8=D1=87=D0=BD=D1=8B=D0=BC=20CA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/check_dashboard.py | 4 ++-- scripts/collect_evidence.py | 6 +++--- scripts/stop-one.sh | 37 +++++++++++++++++++++++++------------ 3 files changed, 30 insertions(+), 17 deletions(-) diff --git a/scripts/check_dashboard.py b/scripts/check_dashboard.py index a283a6d..e36c10d 100644 --- a/scripts/check_dashboard.py +++ b/scripts/check_dashboard.py @@ -25,7 +25,7 @@ def post(path: str, body: dict) -> dict: request = urllib.request.Request(obs.GRAFANA + path, data=json.dumps(body).encode(), method="POST", headers={"Authorization": obs._auth(), "Content-Type": "application/json"}) try: - with urllib.request.urlopen(request, timeout=60) as response: + with urllib.request.urlopen(request, timeout=60, context=obs.TLS) as response: return json.loads(response.read()) except urllib.error.HTTPError as exc: return json.loads(exc.read() or b"{}") | {"_status": exc.code} @@ -33,7 +33,7 @@ def post(path: str, body: dict) -> dict: def get(path: str) -> dict: request = urllib.request.Request(obs.GRAFANA + path, headers={"Authorization": obs._auth()}) - with urllib.request.urlopen(request, timeout=30) as response: + with urllib.request.urlopen(request, timeout=30, context=obs.TLS) as response: return json.loads(response.read()) diff --git a/scripts/collect_evidence.py b/scripts/collect_evidence.py index 2d56150..a292b53 100644 --- a/scripts/collect_evidence.py +++ b/scripts/collect_evidence.py @@ -120,7 +120,7 @@ def failover_both() -> None: text=True, env=ENV).stdout.split()} rc = step(f"failover run {attempt}", filename, [PY, "tests/resilience.py", "--mode", "failover", "--action-script", hook("stop-one"), "--ca-file", CA], - ["docker", "compose", "ps", "-a", "--format", "{{.Name}} {{.Status}}", "api"], append=True) + ["docker", "compose", "ps", "-a", "api"], append=True) results.pop() code = code or rc after = {c for c in subprocess.run(["docker", "compose", "ps", "-q", "api"], cwd=ROOT, capture_output=True, @@ -149,9 +149,9 @@ def main() -> int: step("OpenBao allow/deny, root credential отсутствует в app", "bao-check.txt", sh("bao_check.sh"), [PY, "scripts/bao_operator.py", "status"]) step("make test-persistence (рестарт всех процессов, unseal)", "persistence.txt", - ["docker", "compose", "ps", "-a", "--format", "{{.Name}} {{.State}} {{.Status}}"], + ["docker", "compose", "ps", "-a"], [PY, "tests/resilience.py", "--mode", "persistence", "--action-script", hook("restart"), "--ca-file", CA], - ["docker", "compose", "ps", "-a", "--format", "{{.Name}} {{.State}} {{.Status}}"], timeout=600) + ["docker", "compose", "ps", "-a"], timeout=600) failover_both() argon2_bench() step("Телеметрия по mTLS: trace + logs", "trace-demo.txt", [PY, "scripts/trace_demo.py"]) diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh index 2e73fe2..22c641d 100644 --- a/scripts/stop-one.sh +++ b/scripts/stop-one.sh @@ -8,7 +8,11 @@ # scripts/restore-api.sh (make restore). # STOP_MODE=stop (default) SIGTERM: readiness 503, 3 s drain, graceful exit (~4 s) # STOP_MODE=kill SIGKILL at once (`docker stop -t 0`): crash of the process -# Returns within 10 s. The test hides the output; run by hand to see it (no secrets printed). +# The test requires the hook to return within 10 s. On Windows one `docker exec` costs ~1.8 s, so +# the aliases are read IN PARALLEL, and `docker stop` runs in the background: Docker marks the +# container as stopped by the user at once (the restart policy will not bring it back), the drain +# and exit happen while the test is already sending requests. WAIT=1 waits for the stop (by hand). +# The test hides the output; run by hand to see it (no secrets printed). set -eu cd "$(dirname "$0")/.." export MSYS_NO_PATHCONV=1 # Git Bash: keep /tmp/instance_id a container path @@ -17,22 +21,31 @@ case "$TARGET_INSTANCE_ID" in *[!A-Za-z0-9._-]*) echo "stop-one: invalid TARGET_INSTANCE_ID" >&2; exit 2 ;; esac mode="${STOP_MODE:-stop}" +case "$mode" in + stop) grace=15 ;; + kill) grace=0 ;; + *) echo "stop-one: STOP_MODE must be stop or kill" >&2; exit 2 ;; +esac -target="" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT # Only RUNNING containers of THIS compose project's service `api` are candidates. for id in $(docker compose ps -q api); do - if [ "$(docker exec "$id" cat /tmp/instance_id 2>/dev/null | tr -d '\r\n')" = "$TARGET_INSTANCE_ID" ]; then - target="$id" - fi + (docker exec "$id" cat /tmp/instance_id 2>/dev/null | tr -d '\r\n' > "$tmp/$id") & +done +wait +target="" +for f in "$tmp"/*; do + [ -f "$f" ] && [ "$(cat "$f")" = "$TARGET_INSTANCE_ID" ] && target="$(basename "$f")" done if [ -z "$target" ]; then echo "stop-one: no running api replica with X-Instance-Id=$TARGET_INSTANCE_ID" >&2 exit 3 fi -name="$(docker inspect -f '{{.Name}}' "$target")" -case "$mode" in - stop) docker stop --time 15 "$target" >/dev/null ;; - kill) docker stop --time 0 "$target" >/dev/null ;; - *) echo "stop-one: STOP_MODE must be stop or kill" >&2; exit 2 ;; -esac -echo "stop-one: $mode $name (X-Instance-Id=$TARGET_INSTANCE_ID) -> $(docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}}' "$target")" +if [ "${WAIT:-0}" = 1 ]; then + docker stop --time "$grace" "$target" >/dev/null + echo "stop-one: $mode $target (X-Instance-Id=$TARGET_INSTANCE_ID) -> $(docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}}' "$target")" +else + nohup docker stop --time "$grace" "$target" >/dev/null 2>&1 & + echo "stop-one: $mode $target (X-Instance-Id=$TARGET_INSTANCE_ID) requested; the container stops in the background" +fi -- 2.54.0 From 6eebbff5eee4cd48a543793d4f94d62d15e5ad79 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:10:40 +0300 Subject: [PATCH 11/16] =?UTF-8?q?api=20healthcheck:=20start=5Fperiod=2030?= =?UTF-8?q?=20=D1=81=20(=D0=B2=D1=85=D0=BE=D0=B4=20=D0=B2=20OpenBao=20?= =?UTF-8?q?=D0=B8=20TLS=20=D0=BF=D1=80=D0=B8=20=D1=85=D0=BE=D0=BB=D0=BE?= =?UTF-8?q?=D0=B4=D0=BD=D0=BE=D0=BC=20=D1=81=D1=82=D0=B0=D1=80=D1=82=D0=B5?= =?UTF-8?q?=20Docker)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compose.yaml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/compose.yaml b/compose.yaml index dcb4805..9082793 100644 --- a/compose.yaml +++ b/compose.yaml @@ -410,7 +410,10 @@ services: interval: 2s timeout: 2s retries: 3 - start_period: 5s + # Lab 7: the start includes the OpenBao login and the first TLS connections; after a cold + # Docker start this took > 11 s once and `up --wait` gave up. Failures inside start_period do + # not count; after the first success a failed replica is still detected in 3 x 2 s. + start_period: 30s depends_on: postgres: condition: service_healthy -- 2.54.0 From d69216785d306c0cb8ca601e2e8b5e471d9b4070 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:24:30 +0300 Subject: [PATCH 12/16] =?UTF-8?q?collect=5Fevidence:=20=D1=81=D0=B4=D0=B2?= =?UTF-8?q?=D0=B8=D0=B3=20round-robin=20=D0=BC=D0=B5=D0=B6=D0=B4=D1=83=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B3=D0=BE=D0=BD=D0=B0=D0=BC=D0=B8=20failov?= =?UTF-8?q?er,=20=D1=80=D0=B5=D0=B6=D0=B8=D0=BC=20--only-failover?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/collect_evidence.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/scripts/collect_evidence.py b/scripts/collect_evidence.py index a292b53..9e00e7a 100644 --- a/scripts/collect_evidence.py +++ b/scripts/collect_evidence.py @@ -13,9 +13,11 @@ import argparse import datetime as dt import json import os +import ssl import subprocess import sys import time +import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] @@ -116,6 +118,15 @@ def failover_both() -> None: (EVIDENCE / filename).write_text("# make test-failover: последовательный отказ реплик API\n", encoding="utf-8") code = 0 for attempt in range(1, 6): + # The test stops the replica that served its first message. After a restore HAProxy's + # round robin is in the same position, so the same replica would be hit every time: shift it + # by `attempt - 1` extra requests through the LB (the public test itself is not touched). + for _ in range(attempt - 1): + try: + urllib.request.urlopen("https://localhost:8443/health/live", timeout=5, + context=ssl.create_default_context(cafile=CA)).read() + except OSError: + pass before = {c for c in subprocess.run(["docker", "compose", "ps", "-q", "api"], cwd=ROOT, capture_output=True, text=True, env=ENV).stdout.split()} rc = step(f"failover run {attempt}", filename, @@ -139,8 +150,20 @@ def failover_both() -> None: def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--skip-student-tests", action="store_true") + parser.add_argument("--only-failover", action="store_true", + help="re-run only the failover series and update its row in SUMMARY.md") args = parser.parse_args() EVIDENCE.mkdir(exist_ok=True) + if args.only_failover: + failover_both() + title, command, code, filename, _ = results[-1] + summary = EVIDENCE / "SUMMARY.md" + row = f"| {title} | `{command}` | {code} | [{filename}]({filename}) | — |" + lines = [row if line.startswith(f"| {title} |") else line + for line in summary.read_text(encoding="utf-8").splitlines()] + summary.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n") + print(f"{'PASS' if code == 0 else 'FAIL'} failover series; SUMMARY.md updated") + return code stand_report() step("make check", "check.txt", [PY, "scripts/check_contract.py"]) step("make test (HTTPS, public CA)", "smoke.txt", [PY, "tests/smoke.py", "--base-url", "https://localhost:8443", "--ca-file", CA]) -- 2.54.0 From c5c9b5c9ab9ab7b55467787f88341d3b2b53c774 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:25:01 +0300 Subject: [PATCH 13/16] =?UTF-8?q?evidence:=20=D0=BF=D0=B5=D1=80=D0=B2?= =?UTF-8?q?=D1=8B=D0=B9=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=80=20Argon2=20(dev-?= =?UTF-8?q?=D1=81=D1=82=D0=B5=D0=BD=D0=B4)=20=D0=BF=D0=BE=D0=B4=20=D0=BE?= =?UTF-8?q?=D1=82=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=BC=20=D0=B8=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=B5=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- evidence/argon2/{bench.json => bench-run1-dev.json} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename evidence/argon2/{bench.json => bench-run1-dev.json} (100%) diff --git a/evidence/argon2/bench.json b/evidence/argon2/bench-run1-dev.json similarity index 100% rename from evidence/argon2/bench.json rename to evidence/argon2/bench-run1-dev.json -- 2.54.0 From 783aa354562346ae6acf17f5d5c8eb36160d62e5 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:22:52 +0300 Subject: [PATCH 14/16] =?UTF-8?q?=D1=82=D0=B5=D1=81=D1=82=D1=8B=20=D0=B8?= =?UTF-8?q?=20healthcheck=20=D1=83=D1=81=D1=82=D0=BE=D0=B9=D1=87=D0=B8?= =?UTF-8?q?=D0=B2=D0=B5=D0=B5=20=D0=BA=20=D0=BC=D0=B5=D0=B4=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=BD=D0=BE=D0=BC=D1=83=20=D1=85=D0=BE=D1=81=D1=82=D1=83?= =?UTF-8?q?:=20=D0=B2=D1=80=D0=B5=D0=BC=D1=8F=20=D0=BF=D1=80=D0=BE=D0=B1?= =?UTF-8?q?=D1=8B=20=D0=B2=D0=BD=D1=83=D1=82=D1=80=D0=B8=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BD=D1=82=D0=B5=D0=B9=D0=BD=D0=B5=D1=80=D0=B0,=20healthcheck?= =?UTF-8?q?=20timeout=205=20=D1=81,=20=D0=B4=D0=BE=D1=87=D0=B8=D1=82=D1=8B?= =?UTF-8?q?=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20TLS-=D0=BE=D1=82=D0=B2=D0=B5?= =?UTF-8?q?=D1=82=D0=B0,=20grace=20=D1=83=D0=B1=D0=BE=D1=80=D1=89=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0=2015=20=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 35 +++++++++++++++++++++++++++++-- compose.yaml | 8 ++++--- student-tests/conftest.py | 25 +++++++++++++++------- student-tests/test_balancing.py | 10 ++++----- student-tests/test_consistency.py | 20 +++++++++++++++--- 5 files changed, 77 insertions(+), 21 deletions(-) diff --git a/REPORT.md b/REPORT.md index d8f45d6..2432ac7 100644 --- a/REPORT.md +++ b/REPORT.md @@ -133,9 +133,40 @@ RESULTS_TABLE ### Argon2id: выбор параметров замером -Замер на стенде: `bench/argon2_bench.py` внутри реплики API, с её лимитами (cgroup `cpu.max = 100000 100000` = 1 CPU, 512 MiB), argon2-cffi 25.1.0, p = 1. Сырые данные — [evidence/argon2/bench.json](evidence/argon2/bench.json). +Замер на стенде: `bench/argon2_bench.py` внутри реплики API, с её лимитами (cgroup `cpu.max = 100000 100000` = 1 CPU, 512 MiB), argon2-cffi 25.1.0, p = 1. Сырые данные — [evidence/argon2/bench-run1-dev.json](evidence/argon2/bench-run1-dev.json) и [evidence/argon2/bench.json](evidence/argon2/bench.json). -ARGON2_TABLE +Последовательно, по одному хешу (N = 15 на точку; мс): + +| m, KiB (MiB) | t | замер 1 (dev): медиана / p95 | замер 2 (чистый clone): медиана / p95 | CPU на хеш, мс (1 / 2) | +| --- | --- | --- | --- | --- | +| 19456 (19) | 2 **выбрано** | 30.6 / 47.4 | 154.0 / 270.1 | 30.4 / 87.9 | +| 19456 (19) | 3 | 47.4 / 54.7 | 210.4 / 391.7 | 45.1 / 143.6 | +| 19456 (19) | 4 | 102.3 / 175.4 | 265.5 / 486.4 | 62.3 / 195.0 | +| 32768 (32) | 2 | 72.9 / 82.4 | 245.6 / 601.1 | 69.8 / 205.4 | +| 32768 (32) | 3 | 144.5 / 284.0 | 461.3 / 732.6 | 116.3 / 292.8 | +| 32768 (32) | 4 | 144.6 / 378.7 | 431.4 / 942.8 | 135.4 / 356.6 | +| 47104 (46) | 2 | 119.1 / 291.2 | 496.6 / 778.5 | 114.6 / 335.1 | +| 47104 (46) | 3 | 144.3 / 384.1 | 598.8 / 937.3 | 141.7 / 433.5 | +| 47104 (46) | 4 | 246.7 / 485.3 | 915.5 / 2236.4 | 215.5 / 635.7 | +| 65536 (64) | 2 | 162.8 / 368.5 | 699.4 / 1298.1 | 157.4 / 474.5 | +| 65536 (64) | 3 | 233.3 / 669.8 | 703.0 / 1489.6 | 222.1 / 580.9 | +| 65536 (64) | 4 | 319.5 / 711.3 | 1199.7 / 1682.2 | 261.4 / 731.5 | + +Параллельно (K потоков хешируют одновременно; 6 хешей на поток) — пропускная способность одной реплики = сколько входов в секунду она может проверить: + +| m, KiB | t | K | хешей/с (1 / 2) | медиана, мс (1 / 2) | p95, мс (1 / 2) | RAM на хеши, MiB | +| --- | --- | --- | --- | --- | --- | --- | +| 19456 | 2 | 1 | 26.8 / 12.1 | 33.6 / 75.2 | 61.0 / 105.4 | 19.0 | +| 19456 | 2 | 2 | 30.6 / 7.8 | 74.3 / 212.3 | 89.3 / 373.0 | 38.0 | +| 19456 | 2 | 4 | 17.4 / 7.5 | 204.1 / 480.6 | 289.0 / 972.2 | 76.0 | +| 47104 | 2 | 1 | 4.3 / 1.8 | 206.5 / 501.0 | 369.1 / 807.2 | 46.0 | +| 47104 | 2 | 2 | 7.4 / 2.4 | 286.2 / 805.2 | 295.9 / 1043.5 | 92.0 | +| 47104 | 2 | 4 | 5.4 / 2.5 | 703.6 / 1496.4 | 988.7 / 1900.7 | 184.0 | +| 19456 | 3 | 1 | 8.8 / 3.6 | 101.2 / 278.5 | 165.8 / 374.2 | 19.0 | +| 19456 | 3 | 2 | 14.3 / 5.6 | 114.2 / 345.8 | 201.5 / 516.2 | 38.0 | +| 19456 | 3 | 4 | 12.2 / 5.8 | 304.6 / 650.2 | 409.3 / 881.8 | 76.0 | + +Замер 1: 2026-11-27T13:50:01Z, dev-стенд; замер 2: 2026-11-28T12:21:11Z, чистый стенд. Оба — в контейнере API, cgroup `cpu.max` 100000 100000, `memory.max` 536870912; argon2-cffi 25.1.0, Python 3.13.16. Абсолютные числа различаются в 2–5 раз (Docker Desktop, разная фоновая нагрузка хоста), **соотношения между точками сохраняются**. **Вывод.** Реплика имеет 1 CPU и разрешает 2 хеша одновременно (`PASSWORD_HASH_CONCURRENCY=2`, это 2 × m RAM). Цель — вход не дольше ~100 мс при двух параллельных хешах. Её выполняет только базовая конфигурация OWASP m=19 MiB, t=2, p=1. diff --git a/compose.yaml b/compose.yaml index 9082793..a38b82e 100644 --- a/compose.yaml +++ b/compose.yaml @@ -408,7 +408,9 @@ services: healthcheck: test: ["CMD", "python", "-m", "messenger.healthcheck"] interval: 2s - timeout: 2s + # 5 s: starting the Python probe alone took > 2 s on a loaded Windows host (lab 7 clean run), + # which kept a healthy replica "unhealthy". The probe's own HTTP timeout stays 2 s. + timeout: 5s retries: 3 # Lab 7: the start includes the OpenBao login and the first TLS connections; after a cold # Docker start this took > 11 s once and `up --wait` gave up. Failures inside start_period do @@ -496,7 +498,7 @@ services: healthcheck: test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"] interval: 5s - timeout: 3s + timeout: 5s retries: 3 start_period: 10s depends_on: @@ -543,7 +545,7 @@ services: healthcheck: test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"] interval: 5s - timeout: 3s + timeout: 5s retries: 3 start_period: 10s depends_on: diff --git a/student-tests/conftest.py b/student-tests/conftest.py index cd06e37..1967b20 100644 --- a/student-tests/conftest.py +++ b/student-tests/conftest.py @@ -456,12 +456,21 @@ def attachment_row(attachment_id: str) -> dict | None: return json.loads(out) if out else None -def probe_inside(replica: dict, path: str) -> int: - """HTTP status of `path` asked inside the replica container itself (bypassing the LB) - lab 7: on - the loopback health listener (127.0.0.1:8081), the mTLS port needs the LB's client certificate.""" - code = ("import urllib.request as u, urllib.error as e\n" - "try: print(u.urlopen('http://127.0.0.1:8081%s', timeout=3).status)\n" - "except e.HTTPError as x: print(x.code)") % path +def probe_inside_timed(replica: dict, path: str) -> tuple[int, float]: + """(HTTP status, seconds) of `path` asked inside the replica container itself (bypassing the LB) - + lab 7: on the loopback health listener (127.0.0.1:8081), the mTLS port needs the LB's client + certificate. The time is measured INSIDE the container around the request only: `docker exec` + and the Python start-up (seconds on a loaded Windows host) are the test tool's cost, not the + replica's responsiveness.""" + code = ("import time, urllib.request as u, urllib.error as e\n" + "t = time.perf_counter()\n" + "try: s = u.urlopen('http://127.0.0.1:8081%s', timeout=5).status\n" + "except e.HTTPError as x: s = x.code\n" + "print(s, round(time.perf_counter() - t, 3))") % path out = subprocess.run(["docker", "exec", replica["id"], "python", "-c", code], capture_output=True, text=True, - timeout=30).stdout.strip() - return int(out or 0) + timeout=60).stdout.split() + return (int(out[0]), float(out[1])) if len(out) == 2 else (0, 99.0) + + +def probe_inside(replica: dict, path: str) -> int: + return probe_inside_timed(replica, path)[0] diff --git a/student-tests/test_balancing.py b/student-tests/test_balancing.py index ecebb3f..b332362 100644 --- a/student-tests/test_balancing.py +++ b/student-tests/test_balancing.py @@ -15,7 +15,7 @@ import uuid import httpx2 as httpx import pytest -from conftest import BASE_URL, REPLICAS, Api, compose, lbctl, probe_inside, psql, replica_stopped, run_hook, \ +from conftest import BASE_URL, REPLICAS, Api, compose, lbctl, probe_inside_timed, psql, replica_stopped, run_hook, \ running_replicas, wait_healthy, wait_stand pytestmark = pytest.mark.stack @@ -109,10 +109,10 @@ def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position time.sleep(0.1) detected = time.monotonic() - started for _ in range(3): # the process stays responsive (event loop never blocked) ... - started_probe = time.monotonic() - assert probe_inside(replica, "/health/live") == 200 - assert probe_inside(replica, "/health/ready") == 503 # ... but not ready - assert time.monotonic() - started_probe < 4.5, "replica froze while its dependencies were unreachable" + live, live_s = probe_inside_timed(replica, "/health/live") + ready, ready_s = probe_inside_timed(replica, "/health/ready") + assert live == 200 and ready == 503 # ... but not ready + assert live_s + ready_s < 4.5, ("replica froze while its dependencies were unreachable", live_s, ready_s) seen = instances_seen(api, actor["token"], 40) assert replica["instance"] not in seen and len(seen) == 40 for i in range(20): # writes keep working, only through the ready replicas diff --git a/student-tests/test_consistency.py b/student-tests/test_consistency.py index 614ca2b..4f023de 100644 --- a/student-tests/test_consistency.py +++ b/student-tests/test_consistency.py @@ -60,7 +60,19 @@ def raw_upload(token: str, chat_id: str, declared: int, body: bytes, *, wait_ans sock.close() return b"" time.sleep(wait_answer) - answer = sock.recv(65536) + answer = b"" + sock.settimeout(5) + try: + while chunk := sock.recv(65536): # lab 7: TLS delivers headers and body in separate records + answer += chunk + if b"\r\n\r\n" in answer: + head, _, body = answer.partition(b"\r\n\r\n") + length = next((int(line.split(b":", 1)[1]) for line in head.split(b"\r\n") + if line.lower().startswith(b"content-length:")), None) + if length is not None and len(body) >= length: + break + except (TimeoutError, OSError): + pass sock.close() return answer @@ -84,14 +96,16 @@ def test_crash_after_staging_before_job_is_cleaned_by_janitor(api): (object first) and then the intent row; no job, no message ever existed.""" alice = api.user("alice") chat = api.chat(alice) - with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"): + # grace 15 s: the checks below go through docker exec (seconds each on a loaded host) and must + # see the orphan BEFORE the janitor may remove it. + with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="15", JANITOR_INTERVAL_SECONDS="1"): assert api.upload(alice, chat, SAMPLE, 503).json()["error"]["code"] == "unavailable" [(attachment_id, status, key)] = rows_of_chat(chat["id"]) assert status == "pending" and s3_size(key, "staging") == len(SAMPLE) # the orphan-to-be exists assert jobs_of(attachment_id) == (0, 0) # no job, no outbox row api.call("GET", f"/api/v1/attachments/{attachment_id}", 404, token=alice["token"]) # invisible api.post_message(alice, chat, {"text": "", "attachment_ids": [attachment_id]}, 404) # not attachable - wait_for(lambda: rows_of_chat(chat["id"]) == [], 30, "janitor did not remove the stale intent") + wait_for(lambda: rows_of_chat(chat["id"]) == [], 60, "janitor did not remove the stale intent") assert s3_size(key, "staging") is None # object removed first # Normal configuration again: an upload in the same chat works and is not touched. att = api.upload(alice, chat, SAMPLE).json() -- 2.54.0 From f2bd580c2f1ee6473034e6f8bd03f44dbc67c73c Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:09:58 +0300 Subject: [PATCH 15/16] =?UTF-8?q?Valkey:=20=D0=BE=D0=B3=D1=80=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D1=87=D0=B5=D0=BD=D0=BD=D1=8B=D0=B9=20=D0=BF=D1=83=D0=BB?= =?UTF-8?q?=20TLS-=D1=81=D0=BE=D0=B5=D0=B4=D0=B8=D0=BD=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B9,=20=D0=BF=D1=80=D0=BE=D0=B3=D1=80=D0=B5=D1=82=D1=8B?= =?UTF-8?q?=D0=B9=20=D0=B4=D0=BE=20readiness=20(=D0=B2=D1=81=D0=BF=D0=BB?= =?UTF-8?q?=D0=B5=D1=81=D0=BA=20=D0=BF=D0=B0=D1=80=D0=B0=D0=BB=D0=BB=D0=B5?= =?UTF-8?q?=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D1=81=D0=BE=D0=B2=20=D0=BD=D0=B5=20=D0=BE=D1=82=D0=BA=D1=80?= =?UTF-8?q?=D1=8B=D0=B2=D0=B0=D0=B5=D1=82=20=D0=BD=D0=BE=D0=B2=D1=8B=D0=B5?= =?UTF-8?q?=20=D1=80=D1=83=D0=BA=D0=BE=D0=BF=D0=BE=D0=B6=D0=B0=D1=82=D0=B8?= =?UTF-8?q?=D1=8F)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/messenger/app.py | 2 ++ src/messenger/config.py | 2 ++ src/messenger/sessions.py | 21 ++++++++++++++++++--- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/messenger/app.py b/src/messenger/app.py index fa5fb8a..b339b34 100644 --- a/src/messenger/app.py +++ b/src/messenger/app.py @@ -652,6 +652,8 @@ def create_app(settings: Settings | None = None) -> Starlette: await db.open() await storage.open() await staging.open() + if hasattr(sessions, "warm"): + await sessions.warm() # lab 7: TLS connections to Valkey opened before readiness log.info("dependencies_configured", extra={"fields": { "session_store": sessions.name, "session_ttl_s": settings.session_ttl_seconds, "db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds, diff --git a/src/messenger/config.py b/src/messenger/config.py index 10e471a..46de462 100644 --- a/src/messenger/config.py +++ b/src/messenger/config.py @@ -137,6 +137,7 @@ class Settings: db_pool_max: int = 10 db_timeout_seconds: float = 3.0 cache_timeout_seconds: float = 0.5 + cache_pool_size: int = 8 hash_concurrency: int = 2 instance_id: str = "local" drain_seconds: float = 0.0 @@ -240,6 +241,7 @@ class Settings: db_pool_max=db_pool_max, db_timeout_seconds=_float("DB_TIMEOUT_SECONDS", 3.0, 0.5, 30.0), cache_timeout_seconds=_float("CACHE_TIMEOUT_SECONDS", 0.5, 0.05, 10.0), + cache_pool_size=_int("CACHE_POOL_SIZE", 8, 1, 200), hash_concurrency=_int("PASSWORD_HASH_CONCURRENCY", 2, 1, 16), instance_id=_instance_id(), # After SIGTERM: readiness is 503 but requests are still served for this long, diff --git a/src/messenger/sessions.py b/src/messenger/sessions.py index 4804789..a3ac8ed 100644 --- a/src/messenger/sessions.py +++ b/src/messenger/sessions.py @@ -27,7 +27,7 @@ import secrets from typing import Protocol from redis import exceptions as redis_errors -from redis.asyncio import Redis +from redis.asyncio import BlockingConnectionPool, Redis from redis.backoff import NoBackoff from redis.retry import Retry @@ -113,14 +113,23 @@ class ValkeySessionStore: # Lab 7: TLS to Valkey, server verified by the internal CA AND hostname (SAN valkey). tls = {"ssl_ca_certs": settings.tls_ca_file or None, "ssl_cert_reqs": "required", "ssl_check_hostname": True, "ssl_min_version": ssl.TLSVersion.TLSv1_2} - self.client = Redis.from_url( + # Lab 7: a BOUNDED pool, warmed at start (warm()). With TLS every new connection costs a + # handshake; a burst of 24 parallel requests on a fresh replica opened 24 connections at once + # and some handshakes missed CACHE_TIMEOUT_SECONDS (503, test_concurrent_same_key...). Now at + # most CACHE_POOL_SIZE connections exist, they are opened before the replica is ready, and a + # burst waits (<= the same timeout) for a free one instead of opening new ones. + self.pool_size = settings.cache_pool_size + pool = BlockingConnectionPool.from_url( settings.cache_url, + max_connections=self.pool_size, + timeout=self.timeout, # wait for a free connection, then 503 socket_timeout=self.timeout, socket_connect_timeout=self.timeout, - retry=Retry(NoBackoff(), 0), # no hidden retries: a failure is reported at once decode_responses=False, **tls, ) + self.client = Redis(connection_pool=pool, + retry=Retry(NoBackoff(), 0)) # no hidden retries: a failure is reported at once def _key(self, token: str) -> str: return self.PREFIX + token_hash(token).hex() @@ -159,6 +168,12 @@ class ValkeySessionStore: except Unavailable: return False + async def warm(self) -> None: + """Open the whole pool now (parallel PINGs take one connection each): the TLS handshakes + happen at start-up, before the replica reports ready, not in the first burst of requests.""" + results = await asyncio.gather(*(self.ping() for _ in range(self.pool_size))) + log.info("session_store_warmed", extra={"fields": {"connections": self.pool_size, "ok": sum(results)}}) + async def close(self) -> None: await self.client.aclose() -- 2.54.0 From b2990d8be586ff451b548bce859476d88444ee6a Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:53:53 +0300 Subject: [PATCH 16/16] =?UTF-8?q?lab7:=20=D0=B4=D0=BE=D0=BA=D0=B0=D0=B7?= =?UTF-8?q?=D0=B0=D1=82=D0=B5=D0=BB=D1=8C=D1=81=D1=82=D0=B2=D0=B0=20=D0=B8?= =?UTF-8?q?=D0=B7=20=D1=87=D0=B8=D1=81=D1=82=D0=BE=D0=B3=D0=BE=20clone=20(?= =?UTF-8?q?evidence/,=20425=20passed,=2012/12=20=D1=88=D0=B0=D0=B3=D0=BE?= =?UTF-8?q?=D0=B2),=20REPORT=20=D0=BF=D0=BE=20=D1=80=D0=B5=D0=B0=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D0=BE=D0=BC=D1=83=20=D0=BF=D1=80=D0=BE=D0=B3=D0=BE?= =?UTF-8?q?=D0=BD=D1=83,=20=D1=83=D1=82=D0=BE=D1=87=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D1=8B=20=D1=86=D0=B8=D1=84=D1=80=D1=8B=20Argon2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 101 +++++--- docs/DEFENSE.md | 2 +- evidence/SUMMARY.md | 18 ++ evidence/argon2/bench.json | 290 ++++++++++++++++++++++ evidence/bao-check.txt | 98 ++++++++ evidence/check.txt | 7 + evidence/dashboard-check.txt | 42 ++++ evidence/failover.txt | 67 +++++ evidence/mtls-check.txt | 39 +++ evidence/persistence.txt | 52 ++++ evidence/smoke.txt | 7 + evidence/stand.md | 64 +++++ evidence/student-tests.txt | 459 +++++++++++++++++++++++++++++++++++ evidence/test-security.txt | 7 + evidence/trace-demo.txt | 46 ++++ security/THREAT_MODEL.md | 2 +- 16 files changed, 1271 insertions(+), 30 deletions(-) create mode 100644 evidence/SUMMARY.md create mode 100644 evidence/argon2/bench.json create mode 100644 evidence/bao-check.txt create mode 100644 evidence/check.txt create mode 100644 evidence/dashboard-check.txt create mode 100644 evidence/failover.txt create mode 100644 evidence/mtls-check.txt create mode 100644 evidence/persistence.txt create mode 100644 evidence/smoke.txt create mode 100644 evidence/stand.md create mode 100644 evidence/student-tests.txt create mode 100644 evidence/test-security.txt create mode 100644 evidence/trace-demo.txt diff --git a/REPORT.md b/REPORT.md index 2432ac7..675ba36 100644 --- a/REPORT.md +++ b/REPORT.md @@ -45,7 +45,7 @@ make check test test-security CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.v make mtls-check bao-check PYTHON=.venv/bin/python make test-persistence ACTION_SCRIPT=scripts/restart.sh CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.venv/bin/python make test-failover ACTION_SCRIPT=scripts/stop-one.sh CA_FILE="$PWD/secrets/pki/public-ca.crt" PYTHON=.venv/bin/python && make restore -.venv/bin/python -m pytest student-tests -v # свои тесты, ~1,5-2 ч на этом ПК +.venv/bin/python -m pytest student-tests -v # свои тесты, ~30-60 мин на этом ПК ``` То же самое для чистого стенда: `make secrets up`, затем `python scripts/collect_evidence.py` (вывод — в `evidence/`). @@ -107,7 +107,7 @@ operator --docker compose exec--> openbao (root token и доли unseal чер | `APP_HOST`, `APP_PORT` | `0.0.0.0`, **8443** (mTLS); health — `APP_HEALTH_PORT=8081` на loopback | | `SESSION_TTL_SECONDS`, `IDEMPOTENCY_TTL_SECONDS`, `API_REPLICAS` | как есть (3600, 86400, 2) | | `DATABASE_URL_FILE`, `CACHE_URL_FILE` | **нет у api/relay/worker**: `database_url`, `cache_url` читаются из OpenBao (`messenger/data/`); `DATABASE_URL_FILE` есть только у `migrate`, `jobctl`, `auditor` | -| `SESSION_STORE` | `valkey` | +| `SESSION_STORE` | `valkey`; плюс `CACHE_TIMEOUT_SECONDS=1.0` (TLS-рукопожатие) и `CACHE_POOL_SIZE=8` (пул, прогретый до readiness) | | `S3_ENDPOINT` | `https://s3:8333` | | `S3_REGION`, `S3_BUCKET`, `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS`, `WORKER_CONCURRENCY`, `JOB_MAX_ATTEMPTS`, `JOB_TIMEOUT_SECONDS`, `STAGING_RETENTION_SECONDS` | как в lab6 (+ `S3_STAGING_BUCKET`) | | `S3_*_FILE` | у api/worker — из OpenBao; файлы только у `s3`, `s3-init`, `auditor` | @@ -127,7 +127,31 @@ operator --docker compose exec--> openbao (root token и доли unseal чер Все файлы — в [evidence/](evidence/), сводка — [evidence/SUMMARY.md](evidence/SUMMARY.md). Прогон из **чистого clone** в отдельной папке: новые secrets и сертификаты, пустые volumes, `COMPOSE_PROJECT_NAME=mtusi-lab7-clean`. Commit и окружение — в [evidence/stand.md](evidence/stand.md). -RESULTS_TABLE +Прогон: commit `f2bd580`, 2026-11-28. Все 12 шагов сборщика — код 0. + +| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | +| --- | --- | --- | --- | +| Публичный smoke по HTTPS с проверяемым CA и hostname | `make test BASE_URL=https://localhost:8443 CA_FILE=/secrets/pki/public-ca.crt` | `PASS: lab7 public API scenario` (полный сценарий ЛР 1–6: пользователи, чаты, идемпотентность, файл → thumbnail, logout) | [smoke.txt](evidence/smoke.txt) | +| Недоверенный CA отклоняется | `make test-security` | `PASS: trusted HTTPS works; untrusted CA rejected` | [test-security.txt](evidence/test-security.txt) | +| Чужой hostname, внутренний CA снаружи, нет открытого входа | `pytest student-tests/test_security.py -k "ingress or plaintext"` | Hostname mismatch → ошибка проверки; порты 8080/8404/5432/6379/5671/8200/8333/… закрыты | [student-tests.txt](evidence/student-tests.txt) | +| Сертификаты создаются локально документированным bootstrap | `scripts/init_secrets.py` → `init_pki.py` в чистом clone | 2 CA + leaf на сервис созданы на хосте; в Git и образе ключей нет (`test_no_secret_in_git_or_in_the_image`) | [stand.md](evidence/stand.md), [student-tests.txt](evidence/student-tests.txt) | +| LB → **каждая** API-реплика: обязательное mTLS, отказ без cert / чужой CA / неверная identity | `make mtls-check` (`scripts/mtls_check.sh`) | по 2 репликам × TLS 1.3/1.2: без cert, `foreign-ca SAN=lb`, `internal-ca SAN=worker` → refused; `SAN=lb` → 200; открытый HTTP на 8443 и порт 8081 снаружи → нет; в логе API `mtls_identity_rejected "client_san": ["worker"]` | [mtls-check.txt](evidence/mtls-check.txt) | +| Прямого обхода публичным портом API нет | `test_api_has_no_published_port_and_answers_only_mtls`, `test_compose_policy_limits_ports_secrets_images` | у API нет PortBindings; опубликованы только lb 8443 и grafana 3000 на 127.0.0.1/::1 | [student-tests.txt](evidence/student-tests.txt), [stand.md](evidence/stand.md) | +| TLS с проверкой сервера к DB, Valkey, S3, broker, Collector, backends; раздельные права | `pytest student-tests/test_security.py -k "postgres or valkey or broker or s3 or telemetry"` | PG: `ssl=on`, `sslmode=disable` → отказ, superuser по сети → отказ, 15 запрещённых запросов → `permission denied`; Valkey: NOPERM на FLUSHALL/CONFIG/KEYS/ACL/EVAL; RabbitMQ: relay не читает очередь, 5672 закрыт; S3: `api: write final: refused`; Collector без cert → отказ; worker с cert того же CA в Prometheus → отказ | [student-tests.txt](evidence/student-tests.txt), матрица — [contracts/trust-matrix.md](contracts/trust-matrix.md) | +| Телеметрия работает через mTLS | `scripts/trace_demo.py`, `scripts/check_dashboard.py` | trace API → relay → worker → S3/DB и логи с trace_id: 7/7 PASS; все запросы dashboard: `queries failed: 0` | [trace-demo.txt](evidence/trace-demo.txt), [dashboard-check.txt](evidence/dashboard-check.txt) | +| OpenBao в стенде, не dev, persistent storage | `bao_operator.py status`, `test_openbao_not_dev_and_persistent` | `initialized=True sealed=False storage=raft version=2.7.3`; команда без `-dev`; после рестарта данные на месте (persistence PASS) | [bao-check.txt](evidence/bao-check.txt) | +| api/relay/worker: сервисная аутентификация + scoped policy; нет root token / unseal / всемогущего токена | `make bao-check` | 3 × 16 проверок allow/deny: свой путь — 200, чужие пути, запись, `sys/*`, `auth/token/create` → 403, отозванный токен → 403; root token и 3 доли не найдены в `/run/secrets`, `/app`, `/tmp`, окружении PID 1 (положительный контроль находит свой role_id); env без `*TOKEN*`. Итого 66 PASS, 0 FAIL | [bao-check.txt](evidence/bao-check.txt) | +| Sealed OpenBao: работающие реплики живут, новые ждут unseal | `test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones` | PASS | [student-tests.txt](evidence/student-tests.txt) | +| Argon2id: соль и параметры в хеше, ≥ 19 MiB / t=2 / p=1, обосновано замером | `test_argon2id_hash_carries_salt_and_parameters`; `make argon2-bench` | `$argon2id$v=19$m=19456,t=2,p=1$<соль>$<хеш>`, разные соли у одинаковых паролей; замер — раздел «Эксперименты» | [argon2/bench.json](evidence/argon2/bench.json), [bench-run1-dev.json](evidence/argon2/bench-run1-dev.json) | +| Ограничение частоты входа 429 + Retry-After | `test_failed_logins_are_rate_limited_with_retry_after` | 5 × 401 → 429 `rate_limited`, `Retry-After` 1–60; верный пароль во время блокировки тоже 429; другой аккаунт — 201 | [student-tests.txt](evidence/student-tests.txt) | +| Ограничение размера запросов | `test_api.py::test_oversized_body_and_wrong_content_type`, `test_attachments.py::test_size_limit_through_the_load_balancer` | 413 до чтения тела; 10 MiB проходит через LB | [student-tests.txt](evidence/student-tests.txt) | +| Посторонний, logout/expiry, X-User-Id | `test_api.py`, `test_sessions.py`, `test_idempotency.py::test_outsider_and_revoked_session_never_see_the_stored_result` | чужое → 404; после logout и истечения TTL → 401; X-User-Id игнорируется | [student-tests.txt](evidence/student-tests.txt) | +| Контейнеры без privileged/host network/docker.sock; app и worker non-root, без capabilities, с лимитами | `test_running_containers_are_hardened`, `test_compose_policy…`, `stand.md` | у всех `CapDrop=[ALL]`, `no-new-privileges`, лимиты CPU/RAM; api/relay/worker uid 10001, `CapEff=0` | [stand.md](evidence/stand.md), [student-tests.txt](evidence/student-tests.txt) | +| Секреты не в Git, образе, телеметрии | `test_no_secret_in_git_or_in_the_image`, `test_observability.py::test_no_secrets_or_message_text_in_logs_and_traces` | значения секретов не найдены `git grep` и в файловой системе образа; в Loki/Tempo нет пароля, токена и текста | [student-tests.txt](evidence/student-tests.txt) | +| `X-Instance-Id` без hostname/IP | `test_x_instance_id_is_a_random_alias_without_hostname_or_ip` | `i-<12 hex>`, не совпадает с hostname/IP контейнеров | [student-tests.txt](evidence/student-tests.txt) | +| Рестарт с сохранением данных (шаг 4 защиты) | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS за 65 с: рестарт LB, API ×2, relay, worker, PostgreSQL, Valkey, S3, RabbitMQ, OpenBao + unseal; `docker compose ps` до и после | [persistence.txt](evidence/persistence.txt) | +| Последовательный отказ API-реплик (шаг 4 защиты) | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` × 2 + `make restore` | остановлены обе реплики по очереди (`17c5883f5d19`, `87d05ecea97d`): 117 и 120 записей, 0 неудачных, восстановление 1,75 и 1,79 с | [failover.txt](evidence/failover.txt) | +| Всё из ЛР 2–6 сохранено | `pytest student-tests` (unit + стенд) | **425 passed, 4 skipped** (djpeg не установлен на Windows-хосте), 32 мин; в том числе 17 тестов `test_security.py` | [student-tests.txt](evidence/student-tests.txt) | ## Эксперименты и отказы @@ -139,34 +163,36 @@ RESULTS_TABLE | m, KiB (MiB) | t | замер 1 (dev): медиана / p95 | замер 2 (чистый clone): медиана / p95 | CPU на хеш, мс (1 / 2) | | --- | --- | --- | --- | --- | -| 19456 (19) | 2 **выбрано** | 30.6 / 47.4 | 154.0 / 270.1 | 30.4 / 87.9 | -| 19456 (19) | 3 | 47.4 / 54.7 | 210.4 / 391.7 | 45.1 / 143.6 | -| 19456 (19) | 4 | 102.3 / 175.4 | 265.5 / 486.4 | 62.3 / 195.0 | -| 32768 (32) | 2 | 72.9 / 82.4 | 245.6 / 601.1 | 69.8 / 205.4 | -| 32768 (32) | 3 | 144.5 / 284.0 | 461.3 / 732.6 | 116.3 / 292.8 | -| 32768 (32) | 4 | 144.6 / 378.7 | 431.4 / 942.8 | 135.4 / 356.6 | -| 47104 (46) | 2 | 119.1 / 291.2 | 496.6 / 778.5 | 114.6 / 335.1 | -| 47104 (46) | 3 | 144.3 / 384.1 | 598.8 / 937.3 | 141.7 / 433.5 | -| 47104 (46) | 4 | 246.7 / 485.3 | 915.5 / 2236.4 | 215.5 / 635.7 | -| 65536 (64) | 2 | 162.8 / 368.5 | 699.4 / 1298.1 | 157.4 / 474.5 | -| 65536 (64) | 3 | 233.3 / 669.8 | 703.0 / 1489.6 | 222.1 / 580.9 | -| 65536 (64) | 4 | 319.5 / 711.3 | 1199.7 / 1682.2 | 261.4 / 731.5 | +| 19456 (19) | 2 **выбрано** | 30.6 / 47.4 | 50.6 / 64.9 | 30.4 / 47.8 | +| 19456 (19) | 3 | 47.4 / 54.7 | 106.1 / 172.3 | 45.1 / 57.4 | +| 19456 (19) | 4 | 102.3 / 175.4 | 87.9 / 152.6 | 62.3 / 78.5 | +| 32768 (32) | 2 | 72.9 / 82.4 | 109.9 / 277.4 | 69.8 / 82.5 | +| 32768 (32) | 3 | 144.5 / 284.0 | 144.1 / 371.5 | 116.3 / 126.9 | +| 32768 (32) | 4 | 144.6 / 378.7 | 165.8 / 294.4 | 135.4 / 143.4 | +| 47104 (46) | 2 | 119.1 / 291.2 | 167.8 / 249.6 | 114.6 / 140.0 | +| 47104 (46) | 3 | 144.3 / 384.1 | 166.3 / 516.5 | 141.7 / 157.7 | +| 47104 (46) | 4 | 246.7 / 485.3 | 210.6 / 586.1 | 215.5 / 209.4 | +| 65536 (64) | 2 | 162.8 / 368.5 | 162.0 / 379.4 | 157.4 / 157.2 | +| 65536 (64) | 3 | 233.3 / 669.8 | 264.1 / 601.4 | 222.1 / 233.3 | +| 65536 (64) | 4 | 319.5 / 711.3 | 301.6 / 1100.1 | 261.4 / 279.5 | -Параллельно (K потоков хешируют одновременно; 6 хешей на поток) — пропускная способность одной реплики = сколько входов в секунду она может проверить: +Параллельно (K потоков хешируют одновременно, по 6 хешей на поток). Пропускная способность одной реплики = сколько входов в секунду она может проверить: | m, KiB | t | K | хешей/с (1 / 2) | медиана, мс (1 / 2) | p95, мс (1 / 2) | RAM на хеши, MiB | | --- | --- | --- | --- | --- | --- | --- | -| 19456 | 2 | 1 | 26.8 / 12.1 | 33.6 / 75.2 | 61.0 / 105.4 | 19.0 | -| 19456 | 2 | 2 | 30.6 / 7.8 | 74.3 / 212.3 | 89.3 / 373.0 | 38.0 | -| 19456 | 2 | 4 | 17.4 / 7.5 | 204.1 / 480.6 | 289.0 / 972.2 | 76.0 | -| 47104 | 2 | 1 | 4.3 / 1.8 | 206.5 / 501.0 | 369.1 / 807.2 | 46.0 | -| 47104 | 2 | 2 | 7.4 / 2.4 | 286.2 / 805.2 | 295.9 / 1043.5 | 92.0 | -| 47104 | 2 | 4 | 5.4 / 2.5 | 703.6 / 1496.4 | 988.7 / 1900.7 | 184.0 | -| 19456 | 3 | 1 | 8.8 / 3.6 | 101.2 / 278.5 | 165.8 / 374.2 | 19.0 | -| 19456 | 3 | 2 | 14.3 / 5.6 | 114.2 / 345.8 | 201.5 / 516.2 | 38.0 | -| 19456 | 3 | 4 | 12.2 / 5.8 | 304.6 / 650.2 | 409.3 / 881.8 | 76.0 | +| 19456 | 2 | 1 | 26.8 / 32.0 | 33.6 / 29.7 | 61.0 / 40.7 | 19.0 | +| 19456 | 2 | 2 | 30.6 / 28.8 | 74.3 / 83.0 | 89.3 / 89.6 | 38.0 | +| 19456 | 2 | 4 | 17.4 / 17.4 | 204.1 / 205.0 | 289.0 / 291.6 | 76.0 | +| 47104 | 2 | 1 | 4.3 / 5.5 | 206.5 / 176.9 | 369.1 / 309.5 | 46.0 | +| 47104 | 2 | 2 | 7.4 / 8.2 | 286.2 / 224.2 | 295.9 / 305.3 | 92.0 | +| 47104 | 2 | 4 | 5.4 / 5.0 | 703.6 / 799.9 | 988.7 / 980.1 | 184.0 | +| 19456 | 3 | 1 | 8.8 / 22.1 | 101.2 / 43.9 | 165.8 / 53.1 | 19.0 | +| 19456 | 3 | 2 | 14.3 / 19.0 | 114.2 / 106.5 | 201.5 / 156.0 | 38.0 | +| 19456 | 3 | 4 | 12.2 / 11.5 | 304.6 / 385.3 | 409.3 / 407.5 | 76.0 | -Замер 1: 2026-11-27T13:50:01Z, dev-стенд; замер 2: 2026-11-28T12:21:11Z, чистый стенд. Оба — в контейнере API, cgroup `cpu.max` 100000 100000, `memory.max` 536870912; argon2-cffi 25.1.0, Python 3.13.16. Абсолютные числа различаются в 2–5 раз (Docker Desktop, разная фоновая нагрузка хоста), **соотношения между точками сохраняются**. +Замер 1: 2026-11-27T13:50:01Z, dev-стенд; замер 2: 2026-11-28T14:18:18Z, чистый стенд. Оба — в контейнере API: cgroup `cpu.max` 100000 100000, `memory.max` 536870912; argon2-cffi 25.1.0, Python 3.13.16. + +Ещё один промежуточный замер на чистом стенде шёл, пока хост был загружен посторонним процессом на 85–100 % CPU. Там медиана m=19 MiB / t=2 была 154 мс; его сырой файл перезаписан финальным замером. Абсолютные числа меняются в 2–5 раз от фоновой нагрузки хоста, **соотношения между точками сохраняются**. **Вывод.** Реплика имеет 1 CPU и разрешает 2 хеша одновременно (`PASSWORD_HASH_CONCURRENCY=2`, это 2 × m RAM). Цель — вход не дольше ~100 мс при двух параллельных хешах. Её выполняет только базовая конфигурация OWASP m=19 MiB, t=2, p=1. @@ -179,8 +205,8 @@ RESULTS_TABLE | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| `restart.sh`: рестарт LB, API ×2, relay, worker, PostgreSQL, Valkey, S3, RabbitMQ, **OpenBao** (+ unseal оператором) | данные и сессия сохранены | PERSIST_RESULT | 0 потерь | -| `stop-one.sh` по очереди для обеих реплик | запросы идут через оставшуюся, повтор без дублей | FAILOVER_RESULT | 0 потерь подтверждённых | +| `restart.sh`: рестарт LB, API ×2, relay, worker, PostgreSQL, Valkey, S3, RabbitMQ, **OpenBao** (+ unseal оператором) | данные и сессия сохранены | PASS за 65 с, тот же токен, сообщения и файл на месте (`evidence/persistence.txt`) | 0 потерь | +| `stop-one.sh` по очереди для обеих реплик | запросы идут через оставшуюся, повтор без дублей | обе реплики по очереди: 117 и 120 записей, 0 неудачных попыток, первая успешная запись после отказа через 1,75 и 1,79 с (`evidence/failover.txt`) | 0 потерь подтверждённых | | OpenBao запечатан (`docker compose restart openbao`) | работающие реплики обслуживают; новая не стартует до unseal | `test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones` PASS: запросы 200, новая реплика пишет `openbao_unavailable` и не становится healthy, после unseal поднимается | до unseal оператором | | 5 неудачных входов одного пользователя | 429 + `Retry-After`, CPU не тратится | `test_failed_logins_are_rate_limited_with_retry_after` PASS | окно 60 с | @@ -193,6 +219,25 @@ RESULTS_TABLE 5. **`X-Instance-Id` перезаписывался вспомогательным процессом.** Отладочный `docker compose exec api python …` генерировал новый alias и переписывал `/tmp/instance_id`, и `stop-one` не находил реплику. Исправлено: файл пишет только главный процесс сервиса. 6. **CRLF в stdin на Windows.** Тесты, передающие пароль через stdin, на Windows посылали `\r\n`. Исправлено: stdin передаётся байтами. +Ещё шесть дефектов нашёл первый прогон из чистого clone (13 падений из 425). Часть совпала с перегрузкой хоста посторонним процессом на 85–100 % CPU, поэтому прогон был повторён полностью. В итоговом прогоне — 0 падений. + +7. **Всплеск TLS-соединений к Valkey.** + * Что было: 24 параллельных запроса на свежей реплике открывали 24 новых TLS-соединения, часть рукопожатий не укладывалась в таймаут → 503 (`test_concurrent_same_key…`, требование ЛР 3 «все 201»). + * Исправлено: ограниченный пул (`CACHE_POOL_SIZE=8`), прогретый до readiness (`sessions.warm`). +8. **`restart.sh` дольше 90 с.** Три отдельных `docker compose start` ждали healthcheck по ~23 с каждый. Исправлено: один `start api relay worker lb` (80 → 65 с). +9. **`stop-one.sh` дольше 10 с.** + * Что было: `docker exec` на Windows стоит ~1,8 с на реплику, плюс синхронный `docker stop` с drain. + * Исправлено: alias реплик читаются параллельно, `docker stop` запускается в фоне. Docker сразу помечает контейнер остановленным пользователем, поэтому restart policy его не поднимет. +10. **Healthcheck и `start_period` API.** + * Что было: под нагрузкой старт Python-пробы занимал > 2 с, и здоровая реплика оставалась `unhealthy`; после холодного старта Docker `up --wait` сдавался раньше, чем API успевал войти в OpenBao. + * Исправлено: `timeout: 5s`, `start_period: 30s`. Обнаружение упавшей реплики после старта осталось 3 × 2 с. +11. **`check_dashboard.py` без нашего CA.** Скрипт обращался к Grafana без публичного CA. Исправлено: `context=obs.TLS`. +12. **Хрупкие тесты.** + * Время «реплика не замерла» включало `docker exec` → теперь меряется внутри контейнера. + * Ручной upload по TLS читал только первую TLS-запись → теперь дочитывает ответ. + * Grace уборщика 3 с был короче самих проверок через `docker exec` → 15 с. + * Сборщик доказательств ронял одну и ту же реплику из-за положения round-robin → теперь сдвигает его между прогонами. + ## Ограничения и следующие шаги * **Уровень 4 не заявлен:** diff --git a/docs/DEFENSE.md b/docs/DEFENSE.md index cecc20c..d5df8d5 100644 --- a/docs/DEFENSE.md +++ b/docs/DEFENSE.md @@ -75,6 +75,6 @@ * **mTLS:** «Подпись CA — это пропуск, allowlist SAN — список допущенных ролей, сессия — права пользователя.» * **PostgreSQL:** «Шесть ролей, никто из сервисов не суперпользователь, `pg_hba` принимает только `hostssl`; GRANT выписаны по коду, а worker не видит даже таблицу users.» * **OpenBao:** «Не dev, raft на volume, TLS. AppRole на каждый сервис, токен живёт секунды, root token и доли — у оператора вне репозитория.» -* **Argon2id:** «Параметры m=19 MiB, t=2, p=1 выбраны замером в контейнере API с лимитом 1 CPU. Это ~31 мс на вход; более тяжёлые давали 70–250 мс и 4–14 входов в секунду на реплику, то есть дешёвый DoS.» +* **Argon2id:** «Параметры m=19 MiB, t=2, p=1 выбраны замером в контейнере API с лимитом 1 CPU. Это 30–50 мс на вход при 1 CPU; более тяжёлые давали 70–250 мс и 2–14 входов в секунду на реплику, то есть дешёвый DoS.» * **Лимит входа:** «Счётчик неудач в Valkey, общий для реплик, проверяется до Argon2; при блокировке даже верный пароль получает 429, иначе блокировка подсказывала бы, что пароль угадан.» * **Hardening:** «Везде `cap_drop: ALL` и `no-new-privileges`, app/worker с uid 10001 и нулевыми capabilities; наружу только 8443 и 3000, оба HTTPS на loopback.» diff --git a/evidence/SUMMARY.md b/evidence/SUMMARY.md new file mode 100644 index 0000000..68ee3a9 --- /dev/null +++ b/evidence/SUMMARY.md @@ -0,0 +1,18 @@ +# Сводка доказательств lab7 + +Собрано: 2026-11-28T14:51:20+00:00 + +| Шаг | Команда | Код | Файл | Время, с | +| --- | --- | --- | --- | --- | +| стенд: версии/hardening/секреты по сервисам | `docker compose config/ps/inspect/exec` | 0 | [stand.md](stand.md) | 0 | +| make check | `.venv\Scripts\python.exe scripts/check_contract.py` | 0 | [check.txt](check.txt) | 4 | +| make test (HTTPS, public CA) | `.venv\Scripts\python.exe tests/smoke.py --base-url https://localhost:8443 --ca-file C:\Users\wfa2` | 0 | [smoke.txt](smoke.txt) | 5 | +| make test-security (недоверенный CA) | `.venv\Scripts\python.exe tests/security.py --base-url https://localhost:8443 --ca-file C:\Users\w` | 0 | [test-security.txt](test-security.txt) | 1 | +| mTLS LB->API: без cert / чужой CA / неверная identity / lb | `C:\Program Files\Git\bin\bash.exe scripts\mtls_check.sh` | 0 | [mtls-check.txt](mtls-check.txt) | 4 | +| OpenBao allow/deny, root credential отсутствует в app | `C:\Program Files\Git\bin\bash.exe scripts\bao_check.sh && C:\Users\wfa22\Desktop\Высоконагруженны` | 0 | [bao-check.txt](bao-check.txt) | 20 | +| make test-persistence (рестарт всех процессов, unseal) | `docker compose ps -a && .venv\Scripts\python.exe tests/resilience.py --mode persistence --action-` | 0 | [persistence.txt](persistence.txt) | 65 | +| make test-failover x N, обе реплики по очереди | `tests/resilience.py --mode failover + restore` | 0 | [failover.txt](failover.txt) | 0 | +| Argon2id: замер в контейнере API (1 CPU) | `docker compose exec -T api python - < bench/argon2_bench.py` | 0 | [argon2/bench.json](argon2/bench.json) | 52 | +| Телеметрия по mTLS: trace + logs | `.venv\Scripts\python.exe scripts/trace_demo.py` | 0 | [trace-demo.txt](trace-demo.txt) | 7 | +| Dashboard: все запросы через Grafana (HTTPS) | `.venv\Scripts\python.exe scripts/check_dashboard.py` | 0 | [dashboard-check.txt](dashboard-check.txt) | 2 | +| Свои тесты (unit + стенд, в т.ч. test_security.py) | `.venv\Scripts\python.exe -m pytest student-tests -v -p no:cacheprovider --durations=15` | 0 | [student-tests.txt](student-tests.txt) | 1923 | diff --git a/evidence/argon2/bench.json b/evidence/argon2/bench.json new file mode 100644 index 0000000..918420f --- /dev/null +++ b/evidence/argon2/bench.json @@ -0,0 +1,290 @@ +{ + "when": "2026-11-28T14:18:18Z", + "python": "3.13.16", + "argon2_cffi": "25.1.0", + "cpus_visible": 8, + "cgroup": { + "cpu_max": "100000 100000", + "memory_max": "536870912" + }, + "sequential": [ + { + "m_kib": 19456, + "t": 2, + "p": 1, + "n": 15, + "median_ms": 50.6, + "p95_ms": 64.9, + "cpu_ms_per_hash": 47.8, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=19456,t=2,p=1" + ] + }, + { + "m_kib": 19456, + "t": 3, + "p": 1, + "n": 15, + "median_ms": 106.1, + "p95_ms": 172.3, + "cpu_ms_per_hash": 57.4, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=19456,t=3,p=1" + ] + }, + { + "m_kib": 19456, + "t": 4, + "p": 1, + "n": 15, + "median_ms": 87.9, + "p95_ms": 152.6, + "cpu_ms_per_hash": 78.5, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=19456,t=4,p=1" + ] + }, + { + "m_kib": 32768, + "t": 2, + "p": 1, + "n": 15, + "median_ms": 109.9, + "p95_ms": 277.4, + "cpu_ms_per_hash": 82.5, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=32768,t=2,p=1" + ] + }, + { + "m_kib": 32768, + "t": 3, + "p": 1, + "n": 15, + "median_ms": 144.1, + "p95_ms": 371.5, + "cpu_ms_per_hash": 126.9, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=32768,t=3,p=1" + ] + }, + { + "m_kib": 32768, + "t": 4, + "p": 1, + "n": 15, + "median_ms": 165.8, + "p95_ms": 294.4, + "cpu_ms_per_hash": 143.4, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=32768,t=4,p=1" + ] + }, + { + "m_kib": 47104, + "t": 2, + "p": 1, + "n": 15, + "median_ms": 167.8, + "p95_ms": 249.6, + "cpu_ms_per_hash": 140.0, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=47104,t=2,p=1" + ] + }, + { + "m_kib": 47104, + "t": 3, + "p": 1, + "n": 15, + "median_ms": 166.3, + "p95_ms": 516.5, + "cpu_ms_per_hash": 157.7, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=47104,t=3,p=1" + ] + }, + { + "m_kib": 47104, + "t": 4, + "p": 1, + "n": 15, + "median_ms": 210.6, + "p95_ms": 586.1, + "cpu_ms_per_hash": 209.4, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=47104,t=4,p=1" + ] + }, + { + "m_kib": 65536, + "t": 2, + "p": 1, + "n": 15, + "median_ms": 162.0, + "p95_ms": 379.4, + "cpu_ms_per_hash": 157.2, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=65536,t=2,p=1" + ] + }, + { + "m_kib": 65536, + "t": 3, + "p": 1, + "n": 15, + "median_ms": 264.1, + "p95_ms": 601.4, + "cpu_ms_per_hash": 233.3, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=65536,t=3,p=1" + ] + }, + { + "m_kib": 65536, + "t": 4, + "p": 1, + "n": 15, + "median_ms": 301.6, + "p95_ms": 1100.1, + "cpu_ms_per_hash": 279.5, + "hash_example_prefix": [ + "argon2id", + "v=19", + "m=65536,t=4,p=1" + ] + } + ], + "concurrent": [ + { + "m_kib": 19456, + "t": 2, + "threads": 1, + "hashes": 6, + "wall_s": 0.19, + "hashes_per_s": 32.0, + "median_ms": 29.7, + "p95_ms": 40.7, + "cpu_utilisation": 0.99, + "ram_mib_hashing": 19.0 + }, + { + "m_kib": 19456, + "t": 2, + "threads": 2, + "hashes": 12, + "wall_s": 0.42, + "hashes_per_s": 28.8, + "median_ms": 83.0, + "p95_ms": 89.6, + "cpu_utilisation": 1.04, + "ram_mib_hashing": 38.0 + }, + { + "m_kib": 19456, + "t": 2, + "threads": 4, + "hashes": 24, + "wall_s": 1.38, + "hashes_per_s": 17.4, + "median_ms": 205.0, + "p95_ms": 291.6, + "cpu_utilisation": 0.88, + "ram_mib_hashing": 76.0 + }, + { + "m_kib": 47104, + "t": 2, + "threads": 1, + "hashes": 6, + "wall_s": 1.09, + "hashes_per_s": 5.5, + "median_ms": 176.9, + "p95_ms": 309.5, + "cpu_utilisation": 0.6, + "ram_mib_hashing": 46.0 + }, + { + "m_kib": 47104, + "t": 2, + "threads": 2, + "hashes": 12, + "wall_s": 1.46, + "hashes_per_s": 8.2, + "median_ms": 224.2, + "p95_ms": 305.3, + "cpu_utilisation": 0.99, + "ram_mib_hashing": 92.0 + }, + { + "m_kib": 47104, + "t": 2, + "threads": 4, + "hashes": 24, + "wall_s": 4.76, + "hashes_per_s": 5.0, + "median_ms": 799.9, + "p95_ms": 980.1, + "cpu_utilisation": 0.82, + "ram_mib_hashing": 184.0 + }, + { + "m_kib": 19456, + "t": 3, + "threads": 1, + "hashes": 6, + "wall_s": 0.27, + "hashes_per_s": 22.1, + "median_ms": 43.9, + "p95_ms": 53.1, + "cpu_utilisation": 0.94, + "ram_mib_hashing": 19.0 + }, + { + "m_kib": 19456, + "t": 3, + "threads": 2, + "hashes": 12, + "wall_s": 0.63, + "hashes_per_s": 19.0, + "median_ms": 106.5, + "p95_ms": 156.0, + "cpu_utilisation": 1.0, + "ram_mib_hashing": 38.0 + }, + { + "m_kib": 19456, + "t": 3, + "threads": 4, + "hashes": 24, + "wall_s": 2.09, + "hashes_per_s": 11.5, + "median_ms": 385.3, + "p95_ms": 407.5, + "cpu_utilisation": 0.83, + "ram_mib_hashing": 76.0 + } + ] +} diff --git a/evidence/bao-check.txt b/evidence/bao-check.txt new file mode 100644 index 0000000..4f7aefd --- /dev/null +++ b/evidence/bao-check.txt @@ -0,0 +1,98 @@ +# OpenBao allow/deny, root credential отсутствует в app +# 2026-11-28T14:15:50+00:00 + +$ C:\Program Files\Git\bin\bash.exe scripts\bao_check.sh +== api +service api: OpenBao https://openbao:8200 (TLS verified against /run/secrets/internal-ca.crt) + PASS allow AppRole login with the service's role_id/secret_id -> HTTP 200 + token policies=['api'] ttl=3600s renewable=True + PASS allow read own path messenger/data/api -> HTTP 200 + keys: ['cache_url', 'database_url', 's3_access_key_id', 's3_secret_access_key'] + PASS allow token lookup-self -> HTTP 200 + PASS deny read other service's path messenger/data/relay -> HTTP 403 + PASS deny read other service's path messenger/data/worker -> HTTP 403 + PASS deny write own path messenger/data/api -> HTTP 403 + PASS deny list messenger/metadata -> HTTP 403 + PASS deny write policy sys/policies/acl/api -> HTTP 403 + PASS deny read policy list sys/policies/acl -> HTTP 403 + PASS deny create a child token auth/token/create -> HTTP 403 + PASS deny enable an auth method sys/auth/userpass -> HTTP 403 + PASS deny read sys/mounts -> HTTP 403 + PASS allow revoke-self -> HTTP 204 + PASS deny use the token after revoke-self (lookup-self) -> HTTP 403 + PASS deny read own path with the revoked token -> HTTP 403 + PASS deny AppRole login with a wrong secret_id -> HTTP 400 +PASS: OpenBao policy of api, 0 failure(s) +== relay +service relay: OpenBao https://openbao:8200 (TLS verified against /run/secrets/internal-ca.crt) + PASS allow AppRole login with the service's role_id/secret_id -> HTTP 200 + token policies=['relay'] ttl=3600s renewable=True + PASS allow read own path messenger/data/relay -> HTTP 200 + keys: ['broker_url', 'database_url'] + PASS allow token lookup-self -> HTTP 200 + PASS deny read other service's path messenger/data/api -> HTTP 403 + PASS deny read other service's path messenger/data/worker -> HTTP 403 + PASS deny write own path messenger/data/relay -> HTTP 403 + PASS deny list messenger/metadata -> HTTP 403 + PASS deny write policy sys/policies/acl/relay -> HTTP 403 + PASS deny read policy list sys/policies/acl -> HTTP 403 + PASS deny create a child token auth/token/create -> HTTP 403 + PASS deny enable an auth method sys/auth/userpass -> HTTP 403 + PASS deny read sys/mounts -> HTTP 403 + PASS allow revoke-self -> HTTP 204 + PASS deny use the token after revoke-self (lookup-self) -> HTTP 403 + PASS deny read own path with the revoked token -> HTTP 403 + PASS deny AppRole login with a wrong secret_id -> HTTP 400 +PASS: OpenBao policy of relay, 0 failure(s) +== worker +service worker: OpenBao https://openbao:8200 (TLS verified against /run/secrets/internal-ca.crt) + PASS allow AppRole login with the service's role_id/secret_id -> HTTP 200 + token policies=['worker'] ttl=3600s renewable=True + PASS allow read own path messenger/data/worker -> HTTP 200 + keys: ['broker_url', 'database_url', 's3_access_key_id', 's3_secret_access_key'] + PASS allow token lookup-self -> HTTP 200 + PASS deny read other service's path messenger/data/api -> HTTP 403 + PASS deny read other service's path messenger/data/relay -> HTTP 403 + PASS deny write own path messenger/data/worker -> HTTP 403 + PASS deny list messenger/metadata -> HTTP 403 + PASS deny write policy sys/policies/acl/worker -> HTTP 403 + PASS deny read policy list sys/policies/acl -> HTTP 403 + PASS deny create a child token auth/token/create -> HTTP 403 + PASS deny enable an auth method sys/auth/userpass -> HTTP 403 + PASS deny read sys/mounts -> HTTP 403 + PASS allow revoke-self -> HTTP 204 + PASS deny use the token after revoke-self (lookup-self) -> HTTP 403 + PASS deny read own path with the revoked token -> HTTP 403 + PASS deny AppRole login with a wrong secret_id -> HTTP 400 +PASS: OpenBao policy of worker, 0 failure(s) + +== root credential / unseal material in the application containers (values compared, never printed) + PASS api: no *TOKEN*/*UNSEAL*/*ROOT* environment variable + PASS control: own role_id found by the same search (/run/secrets/bao_role_id) + PASS api: root-token absent (/run/secrets, /app, /tmp, PID 1 environment) + PASS api: unseal-share-1 absent (/run/secrets, /app, /tmp, PID 1 environment) + PASS api: unseal-share-2 absent (/run/secrets, /app, /tmp, PID 1 environment) + PASS api: unseal-share-3 absent (/run/secrets, /app, /tmp, PID 1 environment) + api /run/secrets: bao_role_id bao_secret_id internal-ca.crt service.crt service.key + PASS relay: no *TOKEN*/*UNSEAL*/*ROOT* environment variable + PASS control: own role_id found by the same search (/run/secrets/bao_role_id) + PASS relay: root-token absent (/run/secrets, /app, /tmp, PID 1 environment) + PASS relay: unseal-share-1 absent (/run/secrets, /app, /tmp, PID 1 environment) + PASS relay: unseal-share-2 absent (/run/secrets, /app, /tmp, PID 1 environment) + PASS relay: unseal-share-3 absent (/run/secrets, /app, /tmp, PID 1 environment) + relay /run/secrets: bao_role_id bao_secret_id internal-ca.crt service.crt service.key + PASS worker: no *TOKEN*/*UNSEAL*/*ROOT* environment variable + PASS control: own role_id found by the same search (/run/secrets/bao_role_id) + PASS worker: root-token absent (/run/secrets, /app, /tmp, PID 1 environment) + PASS worker: unseal-share-1 absent (/run/secrets, /app, /tmp, PID 1 environment) + PASS worker: unseal-share-2 absent (/run/secrets, /app, /tmp, PID 1 environment) + PASS worker: unseal-share-3 absent (/run/secrets, /app, /tmp, PID 1 environment) + worker /run/secrets: bao_role_id bao_secret_id internal-ca.crt service.crt service.key +PASS: OpenBao allow/deny and no root credential in the application + +[exit 0] + +$ .venv\Scripts\python.exe scripts/bao_operator.py status +bao-operator: initialized=True sealed=False storage=raft version=2.7.3 operator_dir=C:\Users\wfa22\.mtusi-lab7-operator\mtusi-lab7-clean + +[exit 0] diff --git a/evidence/check.txt b/evidence/check.txt new file mode 100644 index 0000000..c913eb5 --- /dev/null +++ b/evidence/check.txt @@ -0,0 +1,7 @@ +# make check +# 2026-11-28T14:15:37+00:00 + +$ .venv\Scripts\python.exe scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + +[exit 0] diff --git a/evidence/dashboard-check.txt b/evidence/dashboard-check.txt new file mode 100644 index 0000000..bda2f1a --- /dev/null +++ b/evidence/dashboard-check.txt @@ -0,0 +1,42 @@ +# Dashboard: все запросы через Grafana (HTTPS) +# 2026-11-28T14:19:16+00:00 + +$ .venv\Scripts\python.exe scripts/check_dashboard.py +dashboard messenger-lab6 "Messenger lab 6: API, worker, queue, SLO" (provisioned), window 30 min +== API: requests, errors, latency (all replicas) + [timeseries] Requests per second by route: A: 10 series/446 points + [timeseries] Error ratio (5xx and 4xx / all business requests): A: 1 series/67 points; B: 1 series/67 points + [timeseries] Latency p50 / p95 / p99 (all routes, all replicas): A: 1 series/67 points; B: 1 series/67 points; C: 1 series/67 points + [timeseries] p95 by route: A: 10 series/446 points + [timeseries] Requests in flight by replica: A: 42 series/851 points +== Worker and queue + [timeseries] Jobs handled per second by outcome: A: 1 series/47 points + [timeseries] Job duration p50 / p95 / p99 (succeeded): A: 1 series/47 points; B: 1 series/47 points; C: 1 series/47 points + [timeseries] Time to ready p50 / p95 / p99 (uploads): A: 1 series/47 points; B: 1 series/47 points; C: 1 series/47 points + [timeseries] Queue depth (PostgreSQL) and outbox: A: 2 series/136 points; B: 2 series/136 points + [timeseries] Oldest job age / oldest due outbox row: A: 1 series/68 points; B: 1 series/68 points + [timeseries] Worker saturation (busy / capacity): A: 1 series/66 points +== Database pool and resources + [timeseries] DB pool: used / max, waiting requests: A: 3 series/204 points; B: 3 series/204 points; C: 3 series/204 points + [timeseries] DB unit of work p95 by service: A: 3 series/202 points + [timeseries] DB pool wait p95 by service: A: 3 series/202 points + [timeseries] Container CPU (cores): A: 48 series/375 points; B: 1 series/69 points + [timeseries] Container memory: A: 48 series/1042 points; B: 1 series/70 points +== SLO (docs/SLO.md) and alerts + [stat] Availability, last 1 h (target 99 %): A: 1 series/70 points + [stat] Requests under 250 ms, last 5 min (target 95 %): A: 1 series/67 points + [stat] Uploads ready within 30 s, last 1 h (target 99 %): A: 1 series/70 points + [stat] Alerts firing: A: 1 series/121 points + [table] Alerts (pending / firing): A: no data +== Telemetry pipeline (Collector, SDK) + [timeseries] Collector: spans accepted / sent / failed per second: A: 1 series/66 points; B: 1 series/66 points; C: 1 series/66 points; D: no data + [timeseries] Collector: logs and metric points per second: A: 1 series/67 points; B: no data; C: 1 series/67 points; D: no data + [timeseries] Collector: exporter queues: A: 3 series/210 points; B: 3 series/210 points + [timeseries] SDK: spans recorded vs exported (all processes): A: 3 series/161 points; B: 3 series/161 points + [timeseries] Telemetry components up: A: 3 series/209 points +== Logs and traces + [logs] Application logs (Loki): warnings and errors: A: 1 series/100 points + [table] Recent upload traces (Tempo): A: 1 series/12 points +queries failed: 0 + +[exit 0] diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 0000000..34ddb8c --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1,67 @@ +# make test-failover: последовательный отказ реплик API + +$ .venv\Scripts\python.exe tests/resilience.py --mode failover --action-script scripts\stop-one.cmd --ca-file secrets\pki\public-ca.crt +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 117, "failed_attempts": 0, "first_recovery_seconds": 1.748} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. + +[exit 0] + +$ docker compose ps -a api +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab7-clean-api-1 mtusi-messenger:lab7 "python -m messenger" api 3 minutes ago Exited (0) 9 seconds ago +mtusi-lab7-clean-api-2 mtusi-messenger:lab7 "python -m messenger" api 3 minutes ago Up 26 seconds (healthy) 8080/tcp, 8443/tcp + +[exit 0] + +$ C:\Program Files\Git\bin\bash.exe scripts\restore-api.sh +mtusi-lab7-clean-api-1 Up 6 seconds (healthy) +mtusi-lab7-clean-api-2 Up 35 seconds (healthy) + Container mtusi-lab7-clean-api-2 Running + Container mtusi-lab7-clean-api-1 Starting + Container mtusi-lab7-clean-api-1 Started + Container mtusi-lab7-clean-api-1 Waiting + Container mtusi-lab7-clean-api-2 Waiting + Container mtusi-lab7-clean-api-1 Healthy + Container mtusi-lab7-clean-api-2 Healthy + +[exit 0] + +$ .venv\Scripts\python.exe scripts/lbctl.py wait-up 2 +2 API replica(s) UP in HAProxy after 1.1 s: ['i-5f67386b096f', 'i-7bcf23aa0693'] + +[exit 0] + +$ .venv\Scripts\python.exe tests/resilience.py --mode failover --action-script scripts\stop-one.cmd --ca-file secrets\pki\public-ca.crt +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 120, "failed_attempts": 0, "first_recovery_seconds": 1.787} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. + +[exit 0] + +$ docker compose ps -a api +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab7-clean-api-1 mtusi-messenger:lab7 "python -m messenger" api 3 minutes ago Up 28 seconds (healthy) 8080/tcp, 8443/tcp +mtusi-lab7-clean-api-2 mtusi-messenger:lab7 "python -m messenger" api 3 minutes ago Exited (0) 10 seconds ago + +[exit 0] + +$ C:\Program Files\Git\bin\bash.exe scripts\restore-api.sh +mtusi-lab7-clean-api-1 Up 37 seconds (healthy) +mtusi-lab7-clean-api-2 Up 7 seconds (healthy) + Container mtusi-lab7-clean-api-1 Running + Container mtusi-lab7-clean-api-2 Starting + Container mtusi-lab7-clean-api-2 Started + Container mtusi-lab7-clean-api-1 Waiting + Container mtusi-lab7-clean-api-2 Waiting + Container mtusi-lab7-clean-api-1 Healthy + Container mtusi-lab7-clean-api-2 Healthy + +[exit 0] + +$ .venv\Scripts\python.exe scripts/lbctl.py wait-up 2 +2 API replica(s) UP in HAProxy after 1.1 s: ['i-5f67386b096f', 'i-83def22f481a'] + +[exit 0] + +stopped containers over the runs: ['17c5883f5d19', '87d05ecea97d'] diff --git a/evidence/mtls-check.txt b/evidence/mtls-check.txt new file mode 100644 index 0000000..20165be --- /dev/null +++ b/evidence/mtls-check.txt @@ -0,0 +1,39 @@ +# mTLS LB->API: без cert / чужой CA / неверная identity / lb +# 2026-11-28T14:15:47+00:00 + +$ C:\Program Files\Git\bin\bash.exe scripts\mtls_check.sh +API replicas behind DNS name `api`: 2 + +replica 172.26.0.3:8443 + PASS TLS 1.3 client cert none -> refused closed by the server after the handshake (no HTTP response) + PASS TLS 1.3 client cert foreign-ca SAN=lb -> refused closed by the server after the handshake (no HTTP response) + PASS TLS 1.3 client cert internal-ca SAN=worker -> refused closed by the server after the handshake (no HTTP response) + PASS TLS 1.3 client cert internal-ca SAN=lb -> 200 HTTP 200; server cert SAN api verified + PASS TLS 1.2 client cert none -> refused server closed the connection during the handshake (no HTTP response) + PASS TLS 1.2 client cert foreign-ca SAN=lb -> refused server closed the connection during the handshake (no HTTP response) + PASS TLS 1.2 client cert internal-ca SAN=worker -> refused server closed the connection during the handshake (no HTTP response) + PASS TLS 1.2 client cert internal-ca SAN=lb -> 200 HTTP 200; server cert SAN api verified + PASS plaintext HTTP to the mTLS port -> no HTTP answer (TLS-only listener) + PASS loopback health port from outside -> ConnectionRefusedError + +replica 172.26.0.4:8443 + PASS TLS 1.3 client cert none -> refused closed by the server after the handshake (no HTTP response) + PASS TLS 1.3 client cert foreign-ca SAN=lb -> refused closed by the server after the handshake (no HTTP response) + PASS TLS 1.3 client cert internal-ca SAN=worker -> refused closed by the server after the handshake (no HTTP response) + PASS TLS 1.3 client cert internal-ca SAN=lb -> 200 HTTP 200; server cert SAN api verified + PASS TLS 1.2 client cert none -> refused server closed the connection during the handshake (no HTTP response) + PASS TLS 1.2 client cert foreign-ca SAN=lb -> refused server closed the connection during the handshake (no HTTP response) + PASS TLS 1.2 client cert internal-ca SAN=worker -> refused server closed the connection during the handshake (no HTTP response) + PASS TLS 1.2 client cert internal-ca SAN=lb -> 200 HTTP 200; server cert SAN api verified + PASS plaintext HTTP to the mTLS port -> no HTTP answer (TLS-only listener) + PASS loopback health port from outside -> ConnectionRefusedError + +PASS: mTLS LB->API, 2 replica(s), 0 failure(s) + +API log since 2026-11-28T14:15:47Z, identity allowlist refusals (cases 1-2 are dropped by TLS and never logged): +{"ts": "2026-11-28T14:15:49.594Z", "level": "warning", "logger": "messenger.tls", "event": "mtls_identity_rejected", "client_san": ["worker"], "peer": "172.26.0.5", "allowed": ["lb"]} +{"ts": "2026-11-28T14:15:49.691Z", "level": "warning", "logger": "messenger.tls", "event": "mtls_identity_rejected", "client_san": ["worker"], "peer": "172.26.0.5", "allowed": ["lb"]} +{"ts": "2026-11-28T14:15:49.309Z", "level": "warning", "logger": "messenger.tls", "event": "mtls_identity_rejected", "client_san": ["worker"], "peer": "172.26.0.5", "allowed": ["lb"]} +{"ts": "2026-11-28T14:15:49.438Z", "level": "warning", "logger": "messenger.tls", "event": "mtls_identity_rejected", "client_san": ["worker"], "peer": "172.26.0.5", "allowed": ["lb"]} + +[exit 0] diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 0000000..381d618 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,52 @@ +# make test-persistence (рестарт всех процессов, unseal) +# 2026-11-28T14:16:10+00:00 + +$ docker compose ps -a +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab7-clean-api-1 mtusi-messenger:lab7 "python -m messenger" api About a minute ago Up About a minute (healthy) 8080/tcp, 8443/tcp +mtusi-lab7-clean-api-2 mtusi-messenger:lab7 "python -m messenger" api About a minute ago Up About a minute (healthy) 8080/tcp, 8443/tcp +mtusi-lab7-clean-broker-1 rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5 "docker-entrypoint.s…" broker 16 hours ago Up 14 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp +mtusi-lab7-clean-grafana-1 grafana/grafana:13.2.6@sha256:b21409d7951ddcfd63a4b49083e4ef2cc35bc1437d071813bf82bfb238b00bca "/run.sh" grafana 16 hours ago Up 14 minutes (healthy) 127.0.0.1:3000->3000/tcp, [::1]:3000->3000/tcp +mtusi-lab7-clean-lb-1 haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 "docker-entrypoint.s…" lb 16 hours ago Up 14 minutes (healthy) 127.0.0.1:8443->8443/tcp, [::1]:8443->8443/tcp +mtusi-lab7-clean-loki-1 grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7 "/usr/bin/loki -conf…" loki 16 hours ago Up 14 minutes 3100/tcp +mtusi-lab7-clean-migrate-1 mtusi-messenger:lab7 "python -m messenger…" migrate 5 minutes ago Exited (0) 5 minutes ago +mtusi-lab7-clean-openbao-1 openbao/openbao:2.7.3@sha256:b9418c63e2185157d8ee8689a8a93265d5aadad677d6320156172bd42ad3b10b "docker-entrypoint.s…" openbao 16 hours ago Up 14 minutes (healthy) 8200/tcp +mtusi-lab7-clean-otel-collector-1 otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea "/otelcol-contrib --…" otel-collector 16 hours ago Up 14 minutes 4317-4318/tcp, 55679/tcp +mtusi-lab7-clean-postgres-1 postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c "docker-entrypoint.s…" postgres 16 hours ago Up About a minute (healthy) 5432/tcp +mtusi-lab7-clean-prometheus-1 prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06 "/bin/prometheus --c…" prometheus 16 hours ago Up 14 minutes (healthy) 9090/tcp +mtusi-lab7-clean-relay-1 mtusi-messenger:lab7 "python -m messenger…" relay 5 minutes ago Up 5 minutes (healthy) 8080/tcp +mtusi-lab7-clean-s3-1 chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62 "/bin/sh /etc/seawee…" s3 16 hours ago Up 14 minutes (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp +mtusi-lab7-clean-s3-init-1 mtusi-messenger:lab7 "python -m messenger…" s3-init 5 minutes ago Exited (0) 5 minutes ago +mtusi-lab7-clean-tempo-1 grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38 "/tempo -config.file…" tempo 16 hours ago Up 14 minutes +mtusi-lab7-clean-valkey-1 valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 "/bin/sh /etc/valkey…" valkey 16 hours ago Up 3 minutes (healthy) 6379/tcp +mtusi-lab7-clean-worker-1 mtusi-messenger:lab7 "python -m messenger…" worker 5 minutes ago Up 5 minutes (healthy) 8080/tcp + +[exit 0] + +$ .venv\Scripts\python.exe tests/resilience.py --mode persistence --action-script scripts\restart.cmd --ca-file secrets\pki\public-ca.crt +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. + +[exit 0] + +$ docker compose ps -a +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab7-clean-api-1 mtusi-messenger:lab7 "python -m messenger" api 2 minutes ago Up 8 seconds (healthy) 8080/tcp, 8443/tcp +mtusi-lab7-clean-api-2 mtusi-messenger:lab7 "python -m messenger" api 2 minutes ago Up 7 seconds (healthy) 8080/tcp, 8443/tcp +mtusi-lab7-clean-broker-1 rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5 "docker-entrypoint.s…" broker 16 hours ago Up 53 seconds (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp +mtusi-lab7-clean-grafana-1 grafana/grafana:13.2.6@sha256:b21409d7951ddcfd63a4b49083e4ef2cc35bc1437d071813bf82bfb238b00bca "/run.sh" grafana 16 hours ago Up 15 minutes (healthy) 127.0.0.1:3000->3000/tcp, [::1]:3000->3000/tcp +mtusi-lab7-clean-lb-1 haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 "docker-entrypoint.s…" lb 16 hours ago Up 1 second (health: starting) 127.0.0.1:8443->8443/tcp, [::1]:8443->8443/tcp +mtusi-lab7-clean-loki-1 grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7 "/usr/bin/loki -conf…" loki 16 hours ago Up 15 minutes 3100/tcp +mtusi-lab7-clean-migrate-1 mtusi-messenger:lab7 "python -m messenger…" migrate 7 minutes ago Exited (0) 28 seconds ago +mtusi-lab7-clean-openbao-1 openbao/openbao:2.7.3@sha256:b9418c63e2185157d8ee8689a8a93265d5aadad677d6320156172bd42ad3b10b "docker-entrypoint.s…" openbao 16 hours ago Up 53 seconds (healthy) 8200/tcp +mtusi-lab7-clean-otel-collector-1 otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea "/otelcol-contrib --…" otel-collector 16 hours ago Up 15 minutes 4317-4318/tcp, 55679/tcp +mtusi-lab7-clean-postgres-1 postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c "docker-entrypoint.s…" postgres 16 hours ago Up 54 seconds (healthy) 5432/tcp +mtusi-lab7-clean-prometheus-1 prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06 "/bin/prometheus --c…" prometheus 16 hours ago Up 15 minutes (healthy) 9090/tcp +mtusi-lab7-clean-relay-1 mtusi-messenger:lab7 "python -m messenger…" relay 7 minutes ago Up 28 seconds (healthy) 8080/tcp +mtusi-lab7-clean-s3-1 chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62 "/bin/sh /etc/seawee…" s3 16 hours ago Up 34 seconds (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp +mtusi-lab7-clean-s3-init-1 mtusi-messenger:lab7 "python -m messenger…" s3-init 7 minutes ago Exited (0) 8 seconds ago +mtusi-lab7-clean-tempo-1 grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38 "/tempo -config.file…" tempo 16 hours ago Up 15 minutes +mtusi-lab7-clean-valkey-1 valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 "/bin/sh /etc/valkey…" valkey 16 hours ago Up 54 seconds (healthy) 6379/tcp +mtusi-lab7-clean-worker-1 mtusi-messenger:lab7 "python -m messenger…" worker 7 minutes ago Up 6 seconds (healthy) 8080/tcp + +[exit 0] diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 0000000..506f24f --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,7 @@ +# make test (HTTPS, public CA) +# 2026-11-28T14:15:41+00:00 + +$ .venv\Scripts\python.exe tests/smoke.py --base-url https://localhost:8443 --ca-file secrets\pki\public-ca.crt +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. + +[exit 0] diff --git a/evidence/stand.md b/evidence/stand.md new file mode 100644 index 0000000..2fd1139 --- /dev/null +++ b/evidence/stand.md @@ -0,0 +1,64 @@ +# Стенд: версии, образы, hardening, секреты по сервисам (только имена) + +commit: f2bd580c2f1ee6473034e6f8bd03f44dbc67c73c +docker: 29.8.0 (linux/amd64) +docker VM: 8 CPU, 15686336512 bytes RAM +compose project: mtusi-lab7-clean + +| service | image | cap_drop | cap_add | no-new-priv | cpus | memory | published | secrets (names) | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| api | mtusi-messenger:lab7 | ['ALL'] | | True | 1 | 512 MiB | [] | bao_api_role_id, bao_api_secret_id, pki_api_crt, pki_api_key, pki_internal_ca | +| broker | rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5 | ['ALL'] | ['CHOWN', 'DAC_OVERRIDE', 'FOWNER', 'SETGID', 'SETUID'] | True | 1 | 512 MiB | [] | pki_broker_crt, pki_broker_key, pki_internal_ca, rabbitmq_users | +| grafana | grafana/grafana:13.2.6@sha256:b21409d7951ddcfd63a4b49083e4ef2cc35bc1437d071813bf82bfb238b00bca | ['ALL'] | | True | 1 | 1024 MiB | ['127.0.0.1:3000', '::1:3000'] | grafana_admin_password, pki_grafana_crt, pki_grafana_key, pki_grafana_ui_crt, pki_grafana_ui_key, pki_internal_ca, pki_public_ca | +| lb | haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 | ['ALL'] | | True | 1 | 128 MiB | ['127.0.0.1:8443', '::1:8443'] | pki_ingress_pem, pki_internal_ca, pki_lb_pem | +| loki | grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7 | ['ALL'] | | True | 1 | 512 MiB | [] | pki_internal_ca, pki_loki_crt, pki_loki_key | +| migrate | mtusi-messenger:lab7 | ['ALL'] | | True | 0.5 | 256 MiB | [] | database_url_migrate, pki_internal_ca | +| openbao | openbao/openbao:2.7.3@sha256:b9418c63e2185157d8ee8689a8a93265d5aadad677d6320156172bd42ad3b10b | ['ALL'] | | True | 0.5 | 256 MiB | [] | pki_internal_ca, pki_openbao_crt, pki_openbao_key | +| otel-collector | otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea | ['ALL'] | | True | 1 | 512 MiB | [] | pki_internal_ca, pki_otel_collector_crt, pki_otel_collector_key | +| postgres | postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c | ['ALL'] | ['CHOWN', 'DAC_OVERRIDE', 'FOWNER', 'SETGID', 'SETUID'] | True | 2 | 1024 MiB | [] | pg_api_password, pg_auditor_password, pg_jobctl_password, pg_migrate_password, pg_relay_password, pg_worker_password, pki_internal_ca, pki_postgres_crt, pki_postgres_key, postgres_password | +| prometheus | prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06 | ['ALL'] | | True | 1 | 512 MiB | [] | pki_internal_ca, pki_prometheus_crt, pki_prometheus_key | +| relay | mtusi-messenger:lab7 | ['ALL'] | | True | 0.5 | 256 MiB | [] | bao_relay_role_id, bao_relay_secret_id, pki_internal_ca, pki_relay_crt, pki_relay_key | +| s3 | chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62 | ['ALL'] | ['CHOWN', 'DAC_OVERRIDE', 'FOWNER', 'SETGID', 'SETUID'] | True | 1 | 1024 MiB | [] | pki_internal_ca, pki_s3_crt, pki_s3_key, s3_admin_access_key_id, s3_admin_secret_access_key, s3_api_access_key_id, s3_api_secret_access_key, s3_auditor_access_key_id, s3_auditor_secret_access_key, s3_worker_access_key_id, s3_worker_secret_access_key | +| s3-init | mtusi-messenger:lab7 | ['ALL'] | | True | 0.5 | 256 MiB | [] | pki_internal_ca, s3_admin_access_key_id, s3_admin_secret_access_key, s3_api_access_key_id, s3_api_secret_access_key, s3_auditor_access_key_id, s3_auditor_secret_access_key, s3_worker_access_key_id, s3_worker_secret_access_key | +| tempo | grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38 | ['ALL'] | | True | 1 | 512 MiB | [] | pki_internal_ca, pki_tempo_crt, pki_tempo_key | +| valkey | valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 | ['ALL'] | ['CHOWN', 'DAC_OVERRIDE', 'FOWNER', 'SETGID', 'SETUID'] | True | 0.5 | 256 MiB | [] | pki_internal_ca, pki_valkey_crt, pki_valkey_key, valkey_api_password | +| worker | mtusi-messenger:lab7 | ['ALL'] | | True | 2 | 1536 MiB | [] | bao_worker_role_id, bao_worker_secret_id, pki_internal_ca, pki_worker_crt, pki_worker_key | + +## docker compose ps -a + +``` +api Up 49 seconds (healthy) 8080/tcp, 8443/tcp +api Up 48 seconds (healthy) 8080/tcp, 8443/tcp +broker Up 13 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp +grafana Up 13 minutes (healthy) 127.0.0.1:3000->3000/tcp, [::1]:3000->3000/tcp +lb Up 13 minutes (healthy) 127.0.0.1:8443->8443/tcp, [::1]:8443->8443/tcp +loki Up 13 minutes 3100/tcp +migrate Exited (0) 5 minutes ago +openbao Up 13 minutes (healthy) 8200/tcp +otel-collector Up 13 minutes 4317-4318/tcp, 55679/tcp +postgres Up About a minute (healthy) 5432/tcp +prometheus Up 13 minutes (healthy) 9090/tcp +relay Up 5 minutes (healthy) 8080/tcp +s3 Up 13 minutes (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp +s3-init Exited (0) 4 minutes ago +tempo Up 13 minutes +valkey Up 2 minutes (healthy) 6379/tcp +worker Up 4 minutes (healthy) 8080/tcp +``` + +## Пользователь и capabilities PID 1 (запущенные контейнеры) + +| service | container | user | capabilities | X-Instance-Id alias | +| --- | --- | --- | --- | --- | +| api | 17c5883f5d19 | uid 10001 | CapEff 0000000000000000 | i-1c2252476ea2 | +| api | 87d05ecea97d | uid 10001 | CapEff 0000000000000000 | i-7a9bc4eb5903 | +| relay | 638e500712f8 | uid 10001 | CapEff 0000000000000000 | i-f6d48092a828 | +| worker | 7b83b29d9feb | uid 10001 | CapEff 0000000000000000 | i-5751896bbdd1 | +| lb | ae03174dae61 | uid 99 | CapEff 0000000000000000 | - | +| openbao | 51aa7f9765f9 | uid 100 | CapEff 0000000000000000 | - | +| otel-collector | 1acf642bfd4f | uid OCI runtime exec failed: exec failed: unable to start container process: exec: "id": executable file not found in $PATH | CapEff $PATH | OCI runtime exec failed: exec failed: unable to start container process: exec: "cat": executable file not found in $PATH | +| prometheus | 8583fee78ae1 | uid 65534 | CapEff 0000000000000000 | - | +| grafana | 294735cabfeb | uid 472 | CapEff 0000000000000000 | - | +| loki | 163ba071b6b3 | uid OCI runtime exec failed: exec failed: unable to start container process: exec: "id": executable file not found in $PATH | CapEff $PATH | OCI runtime exec failed: exec failed: unable to start container process: exec: "cat": executable file not found in $PATH | +| tempo | fa42af48bede | uid OCI runtime exec failed: exec failed: unable to start container process: exec: "id": executable file not found in $PATH | CapEff $PATH | OCI runtime exec failed: exec failed: unable to start container process: exec: "cat": executable file not found in $PATH | + diff --git a/evidence/student-tests.txt b/evidence/student-tests.txt new file mode 100644 index 0000000..f5989cc --- /dev/null +++ b/evidence/student-tests.txt @@ -0,0 +1,459 @@ +# Свои тесты (unit + стенд, в т.ч. test_security.py) +# 2026-11-28T14:19:18+00:00 + +$ .venv\Scripts\python.exe -m pytest student-tests -v -p no:cacheprovider --durations=15 +============================= test session starts ============================= +platform win32 -- Python 3.14.6, pytest-9.1.1, pluggy-1.7.0 -- .venv\Scripts\python.exe +rootdir: . +plugins: anyio-4.15.1 +collecting ... collected 429 items + +student-tests/test_api.py::test_register_never_returns_password_and_login_returns_bearer PASSED [ 0%] +student-tests/test_api.py::test_duplicate_username_is_409 PASSED [ 0%] +student-tests/test_api.py::test_bad_password_on_registration_is_400[short-11ch] PASSED [ 0%] +student-tests/test_api.py::test_bad_password_on_registration_is_400[ ] PASSED [ 0%] +student-tests/test_api.py::test_bad_password_on_registration_is_400[ \t \n \t \n \t \n ] PASSED [ 1%] +student-tests/test_api.py::test_bad_password_on_registration_is_400[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 1%] +student-tests/test_api.py::test_edge_passwords_register_and_login[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 1%] +student-tests/test_api.py::test_edge_passwords_register_and_login[with:colons:inside] PASSED [ 1%] +student-tests/test_api.py::test_edge_passwords_register_and_login[Twelve chars] PASSED [ 2%] +student-tests/test_api.py::test_wrong_password_and_unknown_user_give_the_same_401 PASSED [ 2%] +student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic \xe9] PASSED [ 2%] +student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic !!!] PASSED [ 2%] +student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic bm9fY29sb24=] PASSED [ 3%] +student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic //46eA==] PASSED [ 3%] +student-tests/test_api.py::test_malformed_basic_is_401_not_500[Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 3%] +student-tests/test_api.py::test_malformed_basic_is_401_not_500[] PASSED [ 3%] +student-tests/test_api.py::test_logout_revokes_only_this_token PASSED [ 3%] +student-tests/test_api.py::test_x_user_id_basic_and_garbage_do_not_authenticate PASSED [ 4%] +student-tests/test_api.py::test_malformed_json_is_400[{] PASSED [ 4%] +student-tests/test_api.py::test_malformed_json_is_400[] PASSED [ 4%] +student-tests/test_api.py::test_malformed_json_is_400[[]] PASSED [ 4%] +student-tests/test_api.py::test_malformed_json_is_400[null] PASSED [ 5%] +student-tests/test_api.py::test_malformed_json_is_400[{"username": "abc_def", "display_name": NaN, "password": "Twelve-chars"}] PASSED [ 5%] +student-tests/test_api.py::test_malformed_json_is_400[{"username": "abc_def", "display_name": "x", "password": "Twelve-chars"}{"a": 1}] PASSED [ 5%] +student-tests/test_api.py::test_malformed_json_is_400[{"username": "abc_def", "display_name": "\ud800", "password": "Twelve-chars"}] PASSED [ 5%] +student-tests/test_api.py::test_invalid_registration_fields_are_400[body0] PASSED [ 6%] +student-tests/test_api.py::test_invalid_registration_fields_are_400[body1] PASSED [ 6%] +student-tests/test_api.py::test_invalid_registration_fields_are_400[body2] PASSED [ 6%] +student-tests/test_api.py::test_invalid_registration_fields_are_400[body3] PASSED [ 6%] +student-tests/test_api.py::test_invalid_registration_fields_are_400[body4] PASSED [ 6%] +student-tests/test_api.py::test_invalid_registration_fields_are_400[body5] PASSED [ 7%] +student-tests/test_api.py::test_unicode_limits_are_code_points_and_nul_is_stored PASSED [ 7%] +student-tests/test_api.py::test_oversized_body_and_wrong_content_type PASSED [ 7%] +student-tests/test_api.py::test_chat_validation PASSED [ 7%] +student-tests/test_api.py::test_foreign_chat_is_indistinguishable_from_missing PASSED [ 8%] +student-tests/test_api.py::test_chat_list_order_pagination_and_isolation PASSED [ 8%] +student-tests/test_api.py::test_history_pages_without_loss_or_duplicates PASSED [ 8%] +student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=0] PASSED [ 8%] +student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=101] PASSED [ 9%] +student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=abc] PASSED [ 9%] +student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=1&limit=2] PASSED [ 9%] +student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=] PASSED [ 9%] +student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=garbage] PASSED [ 10%] +student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=djF8bXx4fDF8Mg] PASSED [ 10%] +student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=djF8bXx4fDk5OTk5OTk5OTk5OTk5OTk5OTk5fHk=] PASSED [ 10%] +student-tests/test_api.py::test_cursor_bound_to_chat PASSED [ 10%] +student-tests/test_api.py::test_read_after_write PASSED [ 10%] +student-tests/test_api.py::test_malformed_cursor_values_are_400_on_both_lists PASSED [ 11%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[\xff] PASSED [ 11%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"first","TEXT":"second"}] PASSED [ 11%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"a","text":"b"}] PASSED [ 11%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":123}] PASSED [ 12%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"valid"}}] PASSED [ 12%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"valid"}]] PASSED [ 12%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x"} {}] PASSED [ 12%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x","sender_id":"11111111-1111-4111-8111-111111111111"}] PASSED [ 13%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x","attachment_ids":null}] PASSED [ 13%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x","attachment_ids":["nope"]}] PASSED [ 13%] +student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":" \n\t "}] PASSED [ 13%] +student-tests/test_api.py::test_ff_byte_body_on_registration_is_contract_error PASSED [ 13%] +student-tests/test_api.py::test_text_is_stored_verbatim_and_length_counts_raw_text PASSED [ 14%] +student-tests/test_api.py::test_unknown_attachment_ids_are_404 PASSED [ 14%] +student-tests/test_api.py::test_member_ids_are_compared_as_uuids_not_strings PASSED [ 14%] +student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer \xe9] PASSED [ 14%] +student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer .] PASSED [ 15%] +student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer a b] PASSED [ 15%] +student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer \xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9] PASSED [ 15%] +student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[bearer\taaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 15%] +student-tests/test_api.py::test_login_with_a_body_is_rejected PASSED [ 16%] +student-tests/test_api.py::test_password_range_is_12_to_128_code_points PASSED [ 16%] +student-tests/test_api.py::test_every_api_response_carries_instance_and_request_id PASSED [ 16%] +student-tests/test_api.py::test_unicode_whitespace_only_strings_are_400[\xa0] PASSED [ 16%] +student-tests/test_api.py::test_unicode_whitespace_only_strings_are_400[\u2003\u2003] PASSED [ 17%] +student-tests/test_api.py::test_unicode_whitespace_only_strings_are_400[ \xa0\t\u3000] PASSED [ 17%] +student-tests/test_api.py::test_odd_registration_bodies_are_400_and_the_api_survives[{"username":"num_probe","display_name":"x","password":1e1000}] PASSED [ 17%] +student-tests/test_api.py::test_odd_registration_bodies_are_400_and_the_api_survives[{"username":"ff_probe","display_name":"x","password":"12345678901\xff"}] PASSED [ 17%] +student-tests/test_api.py::test_odd_registration_bodies_are_400_and_the_api_survives[{"username":"num_probe","display_name":1,"password":"Twelve-chars-ok"}] PASSED [ 17%] +student-tests/test_api.py::test_more_than_100_members_is_400 PASSED [ 18%] +student-tests/test_api.py::test_cursor_of_one_list_is_rejected_by_the_other PASSED [ 18%] +student-tests/test_attachments.py::test_png_and_jpeg_roundtrip_byte_for_byte PASSED [ 18%] +student-tests/test_attachments.py::test_metadata_reveals_no_storage_details PASSED [ 18%] +student-tests/test_attachments.py::test_original_is_not_stored_on_api_containers PASSED [ 19%] +student-tests/test_attachments.py::test_outsider_and_unknown_get_404 PASSED [ 19%] +student-tests/test_attachments.py::test_attachment_ids_are_checked_per_chat PASSED [ 19%] +student-tests/test_attachments.py::test_message_with_attachments_and_history PASSED [ 19%] +student-tests/test_attachments.py::test_idempotent_replay_with_attachments PASSED [ 20%] +student-tests/test_attachments.py::test_message_body_validation[{"attachment_ids":["%(a)s"]}] PASSED [ 20%] +student-tests/test_attachments.py::test_message_body_validation[{"text":null,"attachment_ids":["%(a)s"]}] PASSED [ 20%] +student-tests/test_attachments.py::test_message_body_validation[{"text":1,"attachment_ids":["%(a)s"]}] PASSED [ 20%] +student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":null}] PASSED [ 20%] +student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":"%(a)s"}] PASSED [ 21%] +student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":{}}] PASSED [ 21%] +student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":["%(a)s","%] PASSED [ 21%] +student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":["%(a)s",1]] PASSED [ 21%] +student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":["not-a-uui] PASSED [ 22%] +student-tests/test_attachments.py::test_message_body_validation[{"text":"","attachment_ids":[]}] PASSED [ 22%] +student-tests/test_attachments.py::test_message_body_validation[{"text":" "}] PASSED [ 22%] +student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":[],"sender_] PASSED [ 22%] +student-tests/test_attachments.py::test_at_most_ten_attachments PASSED [ 23%] +student-tests/test_attachments.py::test_size_limit_through_the_load_balancer PASSED [ 23%] +student-tests/test_attachments.py::test_pixel_limit_before_decoding PASSED [ 23%] +student-tests/test_attachments.py::test_exactly_40_megapixels_is_accepted PASSED [ 23%] +student-tests/test_attachments.py::test_bad_content_is_415[png: first 33 bytes of the fixture] PASSED [ 24%] +student-tests/test_attachments.py::test_bad_content_is_415[png: truncated] PASSED [ 24%] +student-tests/test_attachments.py::test_bad_content_is_415[png: corrupt IDAT, valid CRC] PASSED [ 24%] +student-tests/test_attachments.py::test_bad_content_is_415[png: fewer rows than IHDR] PASSED [ 24%] +student-tests/test_attachments.py::test_bad_content_is_415[png: flipped byte] PASSED [ 24%] +student-tests/test_attachments.py::test_bad_content_is_415[png: bytes after IEND] PASSED [ 25%] +student-tests/test_attachments.py::test_bad_content_is_415[jpeg: no scan data after SOS] PASSED [ 25%] +student-tests/test_attachments.py::test_bad_content_is_415[jpeg: truncated] PASSED [ 25%] +student-tests/test_attachments.py::test_bad_content_is_415[review: png row filter 5] PASSED [ 25%] +student-tests/test_attachments.py::test_bad_content_is_415[review: png row filter 0xff] PASSED [ 26%] +student-tests/test_attachments.py::test_bad_content_is_415[review: png IDAT not-a-zlib-stream] PASSED [ 26%] +student-tests/test_attachments.py::test_bad_content_is_415[review: jpeg 27 bytes, no tables/scan] PASSED [ 26%] +student-tests/test_attachments.py::test_bad_content_is_415[review: jpeg SOS component not in SOF] PASSED [ 26%] +student-tests/test_attachments.py::test_bad_content_is_415[mime: png bytes declared jpeg] PASSED [ 27%] +student-tests/test_attachments.py::test_bad_content_is_415[mime: jpeg bytes declared png] PASSED [ 27%] +student-tests/test_attachments.py::test_bad_content_is_415[mime: gif declared png] PASSED [ 27%] +student-tests/test_attachments.py::test_bad_content_is_415[mime: html declared png] PASSED [ 27%] +student-tests/test_attachments.py::test_bad_content_is_415[type: text/plain] PASSED [ 27%] +student-tests/test_attachments.py::test_bad_content_is_415[type: octet-stream] PASSED [ 28%] +student-tests/test_attachments.py::test_bad_content_is_415[type: multipart] PASSED [ 28%] +student-tests/test_attachments.py::test_bad_content_is_415[type: missing] PASSED [ 28%] +student-tests/test_attachments.py::test_empty_body_is_400 PASSED [ 28%] +student-tests/test_attachments.py::test_bad_filename_is_400[missing] PASSED [ 29%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=] PASSED [ 29%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=%20%20%20] PASSED [ 29%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=.] PASSED [ 29%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=..] PASSED [ 30%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=a%2Fb.png] PASSED [ 30%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=a%5Cb.png] PASSED [ 30%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=a%00b.png] PASSED [ 30%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=c1%C2%85.png] PASSED [ 31%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=tab%09.png] PASSED [ 31%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=photo%E2%80%AEgnp.exe] PASSED [ 31%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=%FF%FE.png] PASSED [ 31%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=a.png&filename=b.png] PASSED [ 31%] +student-tests/test_attachments.py::test_bad_filename_is_400[filename=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 32%] +student-tests/test_attachments.py::test_unicode_filename_is_kept_and_safely_exposed PASSED [ 32%] +student-tests/test_attachments.py::test_variant_parameter PASSED [ 32%] +student-tests/test_balancing.py::test_one_session_is_served_by_every_real_replica PASSED [ 32%] +student-tests/test_balancing.py::test_write_on_one_replica_is_read_on_the_other PASSED [ 33%] +student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[0-pg_hba] PASSED [ 33%] +student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[0-network] PASSED [ 33%] +student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[1-pg_hba] PASSED [ 33%] +student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[1-network] PASSED [ 34%] +student-tests/test_balancing.py::test_graceful_stop_of_each_replica_loses_no_request[0] PASSED [ 34%] +student-tests/test_balancing.py::test_graceful_stop_of_each_replica_loses_no_request[1] PASSED [ 34%] +student-tests/test_balancing.py::test_killed_replica_bounded_errors_recovery_and_no_duplicates[0] PASSED [ 34%] +student-tests/test_balancing.py::test_killed_replica_bounded_errors_recovery_and_no_duplicates[1] PASSED [ 34%] +student-tests/test_balancing.py::test_graceful_shutdown_order_in_logs PASSED [ 35%] +student-tests/test_balancing.py::test_full_restart_lb_rediscovers_all_replicas PASSED [ 35%] +student-tests/test_balancing.py::test_scale_up_and_down_is_picked_up_without_errors PASSED [ 35%] +student-tests/test_balancing.py::test_compose_policy_limits_ports_secrets_images PASSED [ 35%] +student-tests/test_balancing.py::test_running_containers_have_limits_and_no_bypass_ports PASSED [ 36%] +student-tests/test_balancing.py::test_migrations_ran_once_by_the_migrate_service PASSED [ 36%] +student-tests/test_consistency.py::test_interrupted_and_stalled_uploads_leave_nothing PASSED [ 36%] +student-tests/test_consistency.py::test_crash_after_staging_before_job_is_cleaned_by_janitor PASSED [ 36%] +student-tests/test_consistency.py::test_lost_answer_after_job_commit_still_becomes_ready PASSED [ 37%] +student-tests/test_consistency.py::test_fresh_pending_upload_is_not_touched_by_janitor PASSED [ 37%] +student-tests/test_db.py::test_registration_race_exactly_one_201_and_seven_409 PASSED [ 37%] +student-tests/test_db.py::test_create_chat_rolls_back_after_the_chat_row_was_inserted PASSED [ 37%] +student-tests/test_db.py::test_migrations_rerun_is_a_noop PASSED [ 37%] +student-tests/test_db.py::test_100_messages_from_10_clients_keep_order_and_cursor_walk PASSED [ 38%] +student-tests/test_db.py::test_secrets_are_not_stored_in_plain_text PASSED [ 38%] +student-tests/test_explain.py::test_late_page_uses_index_range_not_filter PASSED [ 38%] +student-tests/test_failures.py::test_valkey_failure[stop] PASSED [ 38%] +student-tests/test_failures.py::test_valkey_failure[pause] PASSED [ 39%] +student-tests/test_failures.py::test_postgres_failure[stop] PASSED [ 39%] +student-tests/test_failures.py::test_postgres_failure[pause] PASSED [ 39%] +student-tests/test_failures.py::test_locked_table_gives_bounded_503 PASSED [ 39%] +student-tests/test_failures.py::test_logout_during_valkey_outage_is_never_lost PASSED [ 40%] +student-tests/test_idempotency.py::test_replay_returns_the_same_201_and_message_from_every_replica PASSED [ 40%] +student-tests/test_idempotency.py::test_other_body_with_the_same_key_is_409_and_keeps_the_original PASSED [ 40%] +student-tests/test_idempotency.py::test_key_order_and_missing_attachment_ids_are_the_same_body PASSED [ 40%] +student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[] PASSED [ 41%] +student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 41%] +student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[\u043a\u043b\u044e\u0447] PASSED [ 41%] +student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a b] PASSED [ 41%] +student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a/b] PASSED [ 41%] +student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a,b] PASSED [ 42%] +student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a\tb] PASSED [ 42%] +student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[*] PASSED [ 42%] +student-tests/test_idempotency.py::test_repeated_key_header_is_400 PASSED [ 42%] +student-tests/test_idempotency.py::test_longest_key_and_every_allowed_character PASSED [ 43%] +student-tests/test_idempotency.py::test_scope_is_user_plus_chat_plus_key PASSED [ 43%] +student-tests/test_idempotency.py::test_outsider_and_revoked_session_never_see_the_stored_result PASSED [ 43%] +student-tests/test_idempotency.py::test_concurrent_same_key_through_different_replicas_creates_exactly_one PASSED [ 43%] +student-tests/test_idempotency.py::test_concurrent_same_key_different_bodies_one_wins PASSED [ 44%] +student-tests/test_idempotency.py::test_failure_after_the_key_insert_rolls_everything_back PASSED [ 44%] +student-tests/test_idempotency.py::test_client_timeout_then_retry_with_the_same_key_gives_the_committed_message PASSED [ 44%] +student-tests/test_idempotency.py::test_lock_timeout_is_a_transient_503_that_is_not_recorded PASSED [ 44%] +student-tests/test_idempotency.py::test_replay_after_the_serving_replica_is_stopped PASSED [ 44%] +student-tests/test_observability.py::test_upload_is_one_trace_api_relay_worker_s3_db PASSED [ 45%] +student-tests/test_observability.py::test_retry_is_visible_in_the_same_trace PASSED [ 45%] +student-tests/test_observability.py::test_logs_of_api_and_worker_are_joined_by_trace_id PASSED [ 45%] +student-tests/test_observability.py::test_no_ids_or_raw_paths_in_metric_labels PASSED [ 45%] +student-tests/test_observability.py::test_no_secrets_or_message_text_in_logs_and_traces PASSED [ 46%] +student-tests/test_observability.py::test_history_survives_restart_of_the_stores PASSED [ 46%] +student-tests/test_pipeline_flow.py::test_upload_is_202_queued_then_ready_with_contract_variants PASSED [ 46%] +student-tests/test_pipeline_flow.py::test_queued_attachment_is_attachable_failed_is_not PASSED [ 46%] +student-tests/test_pipeline_flow.py::test_worker_stopped_upload_202_content_409_restart_api_and_broker_then_ready PASSED [ 47%] +student-tests/test_pipeline_flow.py::test_broker_down_commit_to_publish_gap_is_closed_by_the_outbox PASSED [ 47%] +student-tests/test_pipeline_flow.py::test_relay_down_job_waits_in_outbox_not_lost PASSED [ 47%] +student-tests/test_pipeline_flow.py::test_crash_after_publish_before_confirm_is_recorded_gives_a_harmless_duplicate PASSED [ 47%] +student-tests/test_pipeline_flow.py::test_duplicate_and_reordered_deliveries_are_noops PASSED [ 48%] +student-tests/test_pipeline_flow.py::test_worker_crash_before_side_effect_lease_expires_and_job_completes PASSED [ 48%] +student-tests/test_pipeline_flow.py::test_worker_crash_after_s3_write_before_commit_republishes_without_duplicates PASSED [ 48%] +student-tests/test_pipeline_flow.py::test_worker_crash_after_commit_before_ack_redelivery_is_noop PASSED [ 48%] +student-tests/test_pipeline_flow.py::test_transient_errors_are_retried_with_jittered_backoff PASSED [ 48%] +student-tests/test_pipeline_flow.py::test_retry_exhausted_failed_registry_then_replay PASSED [ 49%] +student-tests/test_pipeline_flow.py::test_permanent_error_fails_at_once_without_retries PASSED [ 49%] +student-tests/test_pipeline_flow.py::test_memory_and_time_limits_of_the_worker PASSED [ 49%] +student-tests/test_pipeline_flow.py::test_bad_message_is_dead_lettered_not_processed PASSED [ 49%] +student-tests/test_pipeline_flow.py::test_hung_worker_loses_its_lease_and_cannot_publish PASSED [ 50%] +student-tests/test_pipeline_flow.py::test_graceful_worker_stop_finishes_the_running_attempt PASSED [ 50%] +student-tests/test_pipeline_flow.py::test_concurrency_is_bounded_by_prefetch PASSED [ 50%] +student-tests/test_pipeline_flow.py::test_queued_staging_is_never_deleted_even_after_retention PASSED [ 50%] +student-tests/test_pipeline_flow.py::test_retention_deletes_failed_staging_then_replay_is_refused PASSED [ 51%] +student-tests/test_pipeline_flow.py::test_cleanup_racing_a_replay_never_deletes_the_replayed_source PASSED [ 51%] +student-tests/test_pipeline_flow.py::test_reprocess_of_a_not_ready_upload_is_refused PASSED [ 51%] +student-tests/test_pipeline_flow.py::test_zz_invariants_hold_after_all_scenarios PASSED [ 51%] +student-tests/test_security.py::test_ingress_verifies_ca_and_hostname PASSED [ 51%] +student-tests/test_security.py::test_no_plaintext_entry_point PASSED [ 52%] +student-tests/test_security.py::test_lb_to_api_mtls_refuses_foreign_and_wrong_identity PASSED [ 52%] +student-tests/test_security.py::test_api_has_no_published_port_and_answers_only_mtls PASSED [ 52%] +student-tests/test_security.py::test_postgres_tls_only_and_roles_least_privilege PASSED [ 52%] +student-tests/test_security.py::test_valkey_tls_and_acl PASSED [ 53%] +student-tests/test_security.py::test_broker_tls_only_and_users_scoped PASSED [ 53%] +student-tests/test_security.py::test_s3_https_and_scoped_keys PASSED [ 53%] +student-tests/test_security.py::test_telemetry_endpoints_require_client_certificates PASSED [ 53%] +student-tests/test_security.py::test_openbao_policies_and_no_root_credential_in_apps PASSED [ 54%] +student-tests/test_security.py::test_openbao_not_dev_and_persistent PASSED [ 54%] +student-tests/test_security.py::test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones PASSED [ 54%] +student-tests/test_security.py::test_argon2id_hash_carries_salt_and_parameters PASSED [ 54%] +student-tests/test_security.py::test_failed_logins_are_rate_limited_with_retry_after PASSED [ 55%] +student-tests/test_security.py::test_x_instance_id_is_a_random_alias_without_hostname_or_ip PASSED [ 55%] +student-tests/test_security.py::test_running_containers_are_hardened PASSED [ 55%] +student-tests/test_security.py::test_no_secret_in_git_or_in_the_image PASSED [ 55%] +student-tests/test_sessions.py::test_short_ttl_expires[valkey] PASSED [ 55%] +student-tests/test_sessions.py::test_short_ttl_expires[postgres] PASSED [ 56%] +student-tests/test_sessions.py::test_restart_does_not_extend_ttl PASSED [ 56%] +student-tests/test_sessions.py::test_postgres_session_store PASSED [ 56%] +student-tests/test_storage_failures.py::test_s3_outage_is_503_and_text_keeps_working[stop] PASSED [ 56%] +student-tests/test_storage_failures.py::test_s3_outage_is_503_and_text_keeps_working[pause] PASSED [ 57%] +student-tests/test_storage_failures.py::test_upload_survives_failover_of_the_serving_replica PASSED [ 57%] +student-tests/test_storage_failures.py::test_bucket_is_private_outside_the_api PASSED [ 57%] +student-tests/test_storage_failures.py::test_s3_restart_keeps_objects PASSED [ 57%] +student-tests/unit/test_images.py::test_public_fixture_is_accepted PASSED [ 58%] +student-tests/unit/test_images.py::test_valid_png_kinds[rgba] PASSED [ 58%] +student-tests/unit/test_images.py::test_valid_png_kinds[palette] PASSED [ 58%] +student-tests/unit/test_images.py::test_valid_png_kinds[1bit] PASSED [ 58%] +student-tests/unit/test_images.py::test_valid_png_kinds[gray] PASSED [ 58%] +student-tests/unit/test_images.py::test_valid_png_kinds[noise] PASSED [ 59%] +student-tests/unit/test_images.py::test_valid_png_kinds[1x1] PASSED [ 59%] +student-tests/unit/test_images.py::test_interlaced_png_is_accepted PASSED [ 59%] +student-tests/unit/test_images.py::test_broken_png_is_415[first 33 bytes of the fixture] PASSED [ 59%] +student-tests/unit/test_images.py::test_broken_png_is_415[truncated (no IEND)] PASSED [ 60%] +student-tests/unit/test_images.py::test_broken_png_is_415[truncated in IDAT] PASSED [ 60%] +student-tests/unit/test_images.py::test_broken_png_is_415[flipped byte -> CRC error] PASSED [ 60%] +student-tests/unit/test_images.py::test_broken_png_is_415[garbage IDAT with valid CRC] PASSED [ 60%] +student-tests/unit/test_images.py::test_broken_png_is_415[fewer rows than IHDR] PASSED [ 61%] +student-tests/unit/test_images.py::test_broken_png_is_415[bytes after IEND (polyglot)] PASSED [ 61%] +student-tests/unit/test_images.py::test_broken_png_is_415[text] PASSED [ 61%] +student-tests/unit/test_images.py::test_broken_png_is_415[gif] PASSED [ 61%] +student-tests/unit/test_images.py::test_broken_png_is_415[two bytes of a signature] PASSED [ 62%] +student-tests/unit/test_images.py::test_pixel_limit_is_checked_from_the_header PASSED [ 62%] +student-tests/unit/test_images.py::test_png_verification_is_streaming_and_fast PASSED [ 62%] +student-tests/unit/test_images.py::test_jpeg_header_is_parsed_incrementally PASSED [ 62%] +student-tests/unit/test_images.py::test_valid_jpeg[base] SKIPPED (dj...) [ 62%] +student-tests/unit/test_images.py::test_valid_jpeg[prog] SKIPPED (dj...) [ 63%] +student-tests/unit/test_images.py::test_broken_jpeg_is_415[no scan data after SOS-] SKIPPED [ 63%] +student-tests/unit/test_images.py::test_broken_jpeg_is_415[truncated-] SKIPPED [ 63%] +student-tests/unit/test_images.py::test_good_filenames[photo.png] PASSED [ 63%] +student-tests/unit/test_images.py::test_good_filenames[\u0444\u043e\u0442\u043e \u043e\u0442\u043f\u0443\u0441\u043a\u0430.jpg] PASSED [ 64%] +student-tests/unit/test_images.py::test_good_filenames[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 64%] +student-tests/unit/test_images.py::test_good_filenames[emoji \U0001f468\u200d\U0001f469\u200d\U0001f467.png] PASSED [ 64%] +student-tests/unit/test_images.py::test_good_filenames[ x ] PASSED [ 64%] +student-tests/unit/test_images.py::test_good_filenames[..x] PASSED [ 65%] +student-tests/unit/test_images.py::test_bad_filenames[] PASSED [ 65%] +student-tests/unit/test_images.py::test_bad_filenames[ ] PASSED [ 65%] +student-tests/unit/test_images.py::test_bad_filenames[\u3000] PASSED [ 65%] +student-tests/unit/test_images.py::test_bad_filenames[.] PASSED [ 65%] +student-tests/unit/test_images.py::test_bad_filenames[..] PASSED [ 66%] +student-tests/unit/test_images.py::test_bad_filenames[a/b.png] PASSED [ 66%] +student-tests/unit/test_images.py::test_bad_filenames[a\\b.png] PASSED [ 66%] +student-tests/unit/test_images.py::test_bad_filenames[a\x00b] PASSED [ 66%] +student-tests/unit/test_images.py::test_bad_filenames[c1\x85.png] PASSED [ 67%] +student-tests/unit/test_images.py::test_bad_filenames[tab\t.png] PASSED [ 67%] +student-tests/unit/test_images.py::test_bad_filenames[del\x7f.png] PASSED [ 67%] +student-tests/unit/test_images.py::test_bad_filenames[x\u2028y] PASSED [ 67%] +student-tests/unit/test_images.py::test_bad_filenames[photo\u202egnp.exe] PASSED [ 68%] +student-tests/unit/test_images.py::test_bad_filenames[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 68%] +student-tests/unit/test_images.py::test_filename_must_be_single_and_present PASSED [ 68%] +student-tests/unit/test_images.py::test_query_must_be_valid_utf8 PASSED [ 68%] +student-tests/unit/test_lab7.py::test_dns_names_only_from_subject_alt_name PASSED [ 68%] +student-tests/unit/test_lab7.py::test_protocol_aborts_every_identity_outside_the_allowlist[sans0-True] PASSED [ 69%] +student-tests/unit/test_lab7.py::test_protocol_aborts_every_identity_outside_the_allowlist[sans1-False] PASSED [ 69%] +student-tests/unit/test_lab7.py::test_protocol_aborts_every_identity_outside_the_allowlist[sans2-False] PASSED [ 69%] +student-tests/unit/test_lab7.py::test_protocol_aborts_every_identity_outside_the_allowlist[sans3-False] PASSED [ 69%] +student-tests/unit/test_lab7.py::test_protocol_aborts_every_identity_outside_the_allowlist[None-False] PASSED [ 70%] +student-tests/unit/test_lab7.py::test_protocol_aborts_a_plaintext_transport PASSED [ 70%] +student-tests/unit/test_lab7.py::test_allowlist_cannot_be_empty PASSED [ 70%] +student-tests/unit/test_lab7.py::test_server_context_requires_client_certificates_of_the_internal_ca_only PASSED [ 70%] +student-tests/unit/test_lab7.py::test_argon2_parameters_are_configurable_but_never_below_the_minimum PASSED [ 71%] +student-tests/unit/test_lab7.py::test_hash_carries_the_configured_parameters_and_old_hashes_still_verify PASSED [ 71%] +student-tests/unit/test_lab7.py::test_limit_per_username_with_retry_after PASSED [ 71%] +student-tests/unit/test_lab7.py::test_limit_per_ip_and_reset_on_success PASSED [ 71%] +student-tests/unit/test_lab7.py::test_secrets_come_from_openbao_first PASSED [ 72%] +student-tests/unit/test_lab7.py::test_openbao_refusal_is_a_config_error_without_retry PASSED [ 72%] +student-tests/unit/test_lab7.py::test_pki_script_never_prints_key_material PASSED [ 72%] +student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size0-256-expected0] PASSED [ 72%] +student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size1-256-expected1] PASSED [ 72%] +student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size2-256-expected2] PASSED [ 73%] +student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size3-256-expected3] PASSED [ 73%] +student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size4-256-expected4] PASSED [ 73%] +student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size5-256-expected5] PASSED [ 73%] +student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size6-256-expected6] PASSED [ 74%] +student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size7-1280-expected7] PASSED [ 74%] +student-tests/unit/test_pipeline.py::test_center_square PASSED [ 74%] +student-tests/unit/test_pipeline.py::test_public_fixture_variants_match_the_contract PASSED [ 74%] +student-tests/unit/test_pipeline.py::test_small_image_is_not_upscaled_but_crop_is PASSED [ 75%] +student-tests/unit/test_pipeline.py::test_big_image_is_bounded_by_1280 PASSED [ 75%] +student-tests/unit/test_pipeline.py::test_exif_orientation_is_applied_and_dropped PASSED [ 75%] +student-tests/unit/test_pipeline.py::test_alpha_is_composited_on_white_for_jpeg_and_kept_for_webp PASSED [ 75%] +student-tests/unit/test_pipeline.py::test_metadata_is_not_copied PASSED [ 75%] +student-tests/unit/test_pipeline.py::test_png_modes_are_processed[RGBA] PASSED [ 76%] +student-tests/unit/test_pipeline.py::test_png_modes_are_processed[P] PASSED [ 76%] +student-tests/unit/test_pipeline.py::test_png_modes_are_processed[1] PASSED [ 76%] +student-tests/unit/test_pipeline.py::test_png_modes_are_processed[L] PASSED [ 76%] +student-tests/unit/test_pipeline.py::test_png_modes_are_processed[LA] PASSED [ 77%] +student-tests/unit/test_pipeline.py::test_png_modes_are_processed[RGB] PASSED [ 77%] +student-tests/unit/test_pipeline.py::test_16_bit_grey_is_scaled_not_clipped PASSED [ 77%] +student-tests/unit/test_pipeline.py::test_pipeline_versions_differ_in_bytes_not_in_geometry PASSED [ 77%] +student-tests/unit/test_pipeline.py::test_pixel_limit_is_checked_before_decoding PASSED [ 78%] +student-tests/unit/test_pipeline.py::test_child_process_protocol_round_trip PASSED [ 78%] +student-tests/unit/test_pipeline.py::test_encoded_message_matches_jobs_schema_and_carries_ids_only PASSED [ 78%] +student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change0] PASSED [ 78%] +student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change1] PASSED [ 79%] +student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change2] PASSED [ 79%] +student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change3] PASSED [ 79%] +student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change4] PASSED [ 79%] +student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change5] PASSED [ 79%] +student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change6] PASSED [ 80%] +student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change7] PASSED [ 80%] +student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change8] PASSED [ 80%] +student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change9] PASSED [ 80%] +student-tests/unit/test_pipeline.py::test_garbage_is_rejected PASSED [ 81%] +student-tests/unit/test_pipeline.py::test_backoff_is_full_jitter_and_capped PASSED [ 81%] +student-tests/unit/test_pipeline.py::test_pipeline_settings PASSED [ 81%] +student-tests/unit/test_telemetry.py::test_server_span_continues_incoming_traceparent PASSED [ 81%] +student-tests/unit/test_telemetry.py::test_without_traceparent_a_new_root_trace_is_started PASSED [ 82%] +student-tests/unit/test_telemetry.py::test_5xx_is_an_error_4xx_is_not PASSED [ 82%] +student-tests/unit/test_telemetry.py::test_health_probes_get_no_span_and_unknown_paths_one_label PASSED [ 82%] +student-tests/unit/test_telemetry.py::test_http_metric_attributes_are_low_cardinality_and_buckets_fit_seconds PASSED [ 82%] +student-tests/unit/test_telemetry.py::test_job_message_carries_traceparent_in_the_schema_field PASSED [ 82%] +student-tests/unit/test_telemetry.py::test_log_records_carry_trace_context_and_fields PASSED [ 83%] +student-tests/unit/test_telemetry.py::test_successful_probe_lines_are_not_exported_failed_ones_are PASSED [ 83%] +student-tests/unit/test_telemetry.py::test_child_span_only_inside_a_traced_operation PASSED [ 83%] +student-tests/unit/test_unit.py::test_valid_passwords[Twelve-chars] PASSED [ 83%] +student-tests/unit/test_unit.py::test_valid_passwords[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 84%] +student-tests/unit/test_unit.py::test_valid_passwords[\u043f\u0430\u0440\u043e\u043b\u044c:\u0441:\u0434\u0432\u043e\u0435\u0442\u043e\u0447\u0438\u044f\u043c\u0438] PASSED [ 84%] +student-tests/unit/test_unit.py::test_valid_passwords[\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600] PASSED [ 84%] +student-tests/unit/test_unit.py::test_valid_passwords[a b c d e f g] PASSED [ 84%] +student-tests/unit/test_unit.py::test_invalid_passwords[short-11ch] PASSED [ 85%] +student-tests/unit/test_unit.py::test_invalid_passwords[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 85%] +student-tests/unit/test_unit.py::test_invalid_passwords[ ] PASSED [ 85%] +student-tests/unit/test_unit.py::test_invalid_passwords[\t\n\u3000\t\n\u3000\t\n\u3000\t\n\u3000\t\n\u3000] PASSED [ 85%] +student-tests/unit/test_unit.py::test_invalid_passwords[\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800] PASSED [ 86%] +student-tests/unit/test_unit.py::test_invalid_passwords[None] PASSED [ 86%] +student-tests/unit/test_unit.py::test_invalid_passwords[123456789012] PASSED [ 86%] +student-tests/unit/test_unit.py::test_text_may_contain_nul_but_not_lone_surrogates PASSED [ 86%] +student-tests/unit/test_unit.py::test_cursor_roundtrip_and_binding PASSED [ 86%] +student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|253402300800000000|11111111-1111-4111-8111-111111111111] PASSED [ 87%] +student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|9999999999999999999|11111111-1111-4111-8111-111111111111] PASSED [ 87%] +student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|-1|11111111-1111-4111-8111-111111111111] PASSED [ 87%] +student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|1|not-a-uuid] PASSED [ 87%] +student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|1|11111111-1111-4111-8111-11111111111G] PASSED [ 88%] +student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v2|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|1|11111111-1111-4111-8111-111111111111] PASSED [ 88%] +student-tests/unit/test_unit.py::test_time_helpers_are_exact PASSED [ 88%] +student-tests/unit/test_unit.py::test_basic_is_parsed_and_password_may_contain_colons PASSED [ 88%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[None] PASSED [ 89%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[] PASSED [ 89%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic] PASSED [ 89%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic \xe9] PASSED [ 89%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic !!!!] PASSED [ 89%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic bm8tY29sb24=] PASSED [ 90%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic //46cHc=] PASSED [ 90%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic OnBhc3N3b3Jk] PASSED [ 90%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic YWxpY2U6] PASSED [ 90%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic 0JDQu9C40YHQsDpwdw==] PASSED [ 91%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 91%] +student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA] PASSED [ 91%] +student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[None] PASSED [ 91%] +student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[] PASSED [ 92%] +student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer] PASSED [ 92%] +student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer short] PASSED [ 92%] +student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!] PASSED [ 92%] +student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Basic YWxpY2U6cGFzc3dvcmQtMTIz] PASSED [ 93%] +student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Token aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 93%] +student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer \xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9] PASSED [ 93%] +student-tests/unit/test_unit.py::test_bearer_ok PASSED [ 93%] +student-tests/unit/test_unit.py::test_argon2id_hash_and_verify PASSED [ 93%] +student-tests/unit/test_unit.py::test_s3_settings_are_validated_and_contract_limits_cannot_be_raised PASSED [ 94%] +student-tests/unit/test_unit.py::test_settings_read_secret_files_and_contract_names PASSED [ 94%] +student-tests/unit/test_unit.py::test_valid_idempotency_keys[a] PASSED [ 94%] +student-tests/unit/test_unit.py::test_valid_idempotency_keys[kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk] PASSED [ 94%] +student-tests/unit/test_unit.py::test_valid_idempotency_keys[A-Za-z0-9._:-] PASSED [ 95%] +student-tests/unit/test_unit.py::test_valid_idempotency_keys[2026-10-16T10:00:00.1] PASSED [ 95%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[None] PASSED [ 95%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[] PASSED [ 95%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk] PASSED [ 96%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[\u043a\u043b\u044e\u0447] PASSED [ 96%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a b] PASSED [ 96%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a/b] PASSED [ 96%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a,b] PASSED [ 96%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a\tb] PASSED [ 97%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a\x00b] PASSED [ 97%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[*] PASSED [ 97%] +student-tests/unit/test_unit.py::test_invalid_idempotency_keys[\xe9] PASSED [ 97%] +student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[{"text":"a","text":"b"}] PASSED [ 98%] +student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[{"a":{"x":1,"x":2}}] PASSED [ 98%] +student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[\xff] PASSED [ 98%] +student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[{"text":"x"} {}] PASSED [ 98%] +student-tests/unit/test_unit.py::test_attachment_ids_absent_equals_empty_and_is_validated PASSED [ 99%] +student-tests/unit/test_unit.py::test_request_fingerprint_ignores_key_order_and_default_attachments PASSED [ 99%] +student-tests/unit/test_unit.py::test_instance_id_is_a_random_alias_stable_per_process_and_validated PASSED [ 99%] +student-tests/unit/test_unit.py::test_idempotency_ttl_cannot_be_below_24_hours PASSED [ 99%] +student-tests/unit/test_unit.py::test_message_write_path_setting PASSED [100%] + +============================ slowest 15 durations ============================= +61.16s call student-tests/test_balancing.py::test_full_restart_lb_rediscovers_all_replicas +60.93s call student-tests/test_sessions.py::test_restart_does_not_extend_ttl +56.99s call student-tests/test_storage_failures.py::test_s3_outage_is_503_and_text_keeps_working[stop] +55.48s call student-tests/test_sessions.py::test_postgres_session_store +54.64s call student-tests/test_observability.py::test_history_survives_restart_of_the_stores +52.70s call student-tests/test_pipeline_flow.py::test_worker_crash_after_s3_write_before_commit_republishes_without_duplicates +52.46s call student-tests/test_pipeline_flow.py::test_hung_worker_loses_its_lease_and_cannot_publish +50.53s call student-tests/test_pipeline_flow.py::test_worker_stopped_upload_202_content_409_restart_api_and_broker_then_ready +49.34s call student-tests/test_consistency.py::test_crash_after_staging_before_job_is_cleaned_by_janitor +48.36s call student-tests/test_pipeline_flow.py::test_memory_and_time_limits_of_the_worker +45.57s call student-tests/test_pipeline_flow.py::test_cleanup_racing_a_replay_never_deletes_the_replayed_source +43.27s call student-tests/test_pipeline_flow.py::test_graceful_worker_stop_finishes_the_running_attempt +41.90s call student-tests/test_pipeline_flow.py::test_queued_staging_is_never_deleted_even_after_retention +41.54s call student-tests/test_pipeline_flow.py::test_retry_exhausted_failed_registry_then_replay +41.46s call student-tests/test_storage_failures.py::test_s3_restart_keeps_objects +================= 425 passed, 4 skipped in 1919.83s (0:31:59) ================= + +[exit 0] diff --git a/evidence/test-security.txt b/evidence/test-security.txt new file mode 100644 index 0000000..8380a3c --- /dev/null +++ b/evidence/test-security.txt @@ -0,0 +1,7 @@ +# make test-security (недоверенный CA) +# 2026-11-28T14:15:46+00:00 + +$ .venv\Scripts\python.exe tests/security.py --base-url https://localhost:8443 --ca-file secrets\pki\public-ca.crt +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. + +[exit 0] diff --git a/evidence/trace-demo.txt b/evidence/trace-demo.txt new file mode 100644 index 0000000..696b8a5 --- /dev/null +++ b/evidence/trace-demo.txt @@ -0,0 +1,46 @@ +# Телеметрия по mTLS: trace + logs +# 2026-11-28T14:19:09+00:00 + +$ .venv\Scripts\python.exe scripts/trace_demo.py +upload: HTTP 202, status=queued, X-Request-Id=trace-demo-68ea29f5, X-Instance-Id=i-83def22f481a, X-Trace-Id=fcefd6efe84d1bd8a5c933e4b6b7f66d +sent traceparent: 00-fcefd6efe84d1bd8a5c933e4b6b7f66d-69c3a1cf82244c3e-01 +attachment f3fa88b3-5dbb-42b5-b1f5-a57d60c35f15: ready, variants=['thumbnail', 'crop', 'optimized'] + +Tempo: trace fcefd6efe84d1bd8a5c933e4b6b7f66d, 19 spans ++ 0.0 ms 37.6 ms [messenger-api] SERVER POST /api/v1/chats/{chat_id}/attachments {"http.route": "/api/v1/chats/{chat_id}/attachments", "http.response.status_code": "202"} + + 1.2 ms 2.4 ms [messenger-api] CLIENT db ensure_member {"db.client.connection.wait_time_ms": 0.572} + + 5.7 ms 5.1 ms [messenger-api] CLIENT db create_intent {"db.client.connection.wait_time_ms": 0.531} + + 11.2 ms 16.0 ms [messenger-api] CLIENT s3 put + + 27.6 ms 8.6 ms [messenger-api] CLIENT db enqueue {"db.client.connection.wait_time_ms": 0.651} + + 88.4 ms 5.7 ms [messenger-relay] PRODUCER messenger.jobs publish {"messenger.job.attempt": "1"} + + 94.5 ms 763.7 ms [messenger-worker] CONSUMER messenger.attachment-jobs process {"messenger.job.attempt": "1", "messenger.job.outcome": "succeeded"} + + 94.7 ms 12.1 ms [messenger-worker] CLIENT db jobs.claim {"db.client.connection.wait_time_ms": 0.55} + + 107.0 ms 9.7 ms [messenger-worker] INTERNAL s3 download + + 107.1 ms 8.6 ms [messenger-worker] CLIENT s3 get + + 117.0 ms 679.8 ms [messenger-worker] INTERNAL image render + + 797.1 ms 27.9 ms [messenger-worker] CLIENT s3 put + + 798.9 ms 25.6 ms [messenger-worker] CLIENT s3 put + + 800.4 ms 23.1 ms [messenger-worker] CLIENT s3 put + + 802.3 ms 23.5 ms [messenger-worker] CLIENT s3 put + + 826.1 ms 17.9 ms [messenger-worker] CLIENT db jobs.complete {"db.client.connection.wait_time_ms": 0.641} + + 844.3 ms 3.5 ms [messenger-worker] CLIENT db delete_staging {"db.client.connection.wait_time_ms": 0.581} + + 848.0 ms 3.3 ms [messenger-worker] CLIENT s3 delete + + 851.6 ms 5.6 ms [messenger-worker] CLIENT db delete_staging {"db.client.connection.wait_time_ms": 0.67} + +Loki: 4 log records with trace_id=fcefd6efe84d1bd8a5c933e4b6b7f66d + messenger-api attachment_queued span_id=c63846abe775f110 request_id=trace-demo-68ea29f5 + messenger-api request span_id=c63846abe775f110 request_id=trace-demo-68ea29f5 route=/api/v1/chats/{chat_id}/attachments status=202 + messenger-worker staging_deleted span_id=c5745bf8195fd208 + messenger-worker job_done span_id=c5745bf8195fd208 job_id=b42f1fef-a3aa-408f-a3af-f5383bcb587c outcome=succeeded + +Checks: + [PASS] API SERVER span continues our traceparent (parent = our span id) + [PASS] relay PRODUCER is inside the upload trace (ancestor = API SERVER span) + [PASS] worker CONSUMER is a child of the PRODUCER + [PASS] worker wrote to S3 inside the job (s3 put spans) + [PASS] worker committed the result (db jobs.complete span) + [PASS] API log record of the request has this trace_id and our X-Request-Id + [PASS] worker log record (job_done) has this trace_id +services in logs: ['messenger-api', 'messenger-worker'] + +[exit 0] diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 8cc872a..7c6cdd9 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -51,7 +51,7 @@ api/relay/worker ──OTLP/HTTPS + client cert──► otel-collector ──mT | --- | --- | --- | --- | --- | | T1. Перехват/подмена трафика клиента: MITM на пути к ingress или фальшивый сервер с самоподписанным сертификатом | конфиденциальность Basic-пароля и Bearer-токена | только HTTPS 8443 (TLS 1.2+), сертификат `public-ca` с SAN `localhost`; клиент проверяет CA и hostname; открытого 8080 нет | `make test-security` (пустой trust store → ошибка проверки); `test_ingress_verifies_ca_and_hostname` (чужой hostname, внутренний CA → отказ); `test_no_plaintext_entry_point` | CA учебный; доверие к нему — ручная раздача `public-ca.crt`; отзыва (CRL/OCSP) нет | | T2. Обход LB: процесс в сети `edge` или украденный ключ worker обращается к `api:8443` напрямую и подставляет `X-Forwarded-For`, чтобы обойти лимит входа | только LB говорит с API; клиентский IP честный | mTLS: `CERT_REQUIRED` + только `internal-ca` + allowlist SAN `lb` в `connection_made`; у API нет опубликованных портов; health на loopback; HAProxy перезаписывает `X-Forwarded-For` | `make mtls-check`: без cert / чужой CA с SAN `lb` / cert `worker` → отказ, `lb` → 200, по каждой реплике, TLS 1.3 и 1.2; 8081 снаружи закрыт | кража ключа `lb` = полный обход (ротация и отзыв leaf — уровень 4) | -| T3. Подбор пароля через `POST /auth/sessions` (одного аккаунта или одного пароля по многим аккаунтам) + DoS дорогим Argon2 | пароль нельзя угадать перебором; CPU реплики не выжигается | Argon2id m=19 MiB, t=2, p=1 (замер ~31 мс/хеш, ≤2 хеша параллельно на реплику); лимит неудач 5/60 с на username и 50/300 с на IP в Valkey (общий для реплик), проверка ДО Argon2, 429 + `Retry-After`, верный пароль при блокировке тоже 429 | `test_failed_logins_are_rate_limited_with_retry_after` (5×401 → 429, Retry-After ≤ 60, другой аккаунт не задет); unit `test_limit_per_username/ip` | можно на 60 с заблокировать вход известному username; ботнет с многих IP не ограничен глобально | +| T3. Подбор пароля через `POST /auth/sessions` (одного аккаунта или одного пароля по многим аккаунтам) + DoS дорогим Argon2 | пароль нельзя угадать перебором; CPU реплики не выжигается | Argon2id m=19 MiB, t=2, p=1 (замер 30–50 мс/хеш при 1 CPU, ≤2 хеша параллельно на реплику); лимит неудач 5/60 с на username и 50/300 с на IP в Valkey (общий для реплик), проверка ДО Argon2, 429 + `Retry-After`, верный пароль при блокировке тоже 429 | `test_failed_logins_are_rate_limited_with_retry_after` (5×401 → 429, Retry-After ≤ 60, другой аккаунт не задет); unit `test_limit_per_username/ip` | можно на 60 с заблокировать вход известному username; ботнет с многих IP не ограничен глобально | | T4. Утечка базы: дамп `users` | пароли не восстанавливаются | только Argon2id-хеш (PHC, соль 16 байт на пароль); одинаковые пароли дают разные хеши | `test_argon2id_hash_carries_salt_and_parameters` | слабый пароль из словаря всё равно подбирается офлайн, только медленнее | | T5. Посторонний пользователь читает чужой чат или вложение, либо выдаёт себя за другого через `X-User-Id` | доступ только участникам; identity = сессия | Bearer-сессия → `user_id`; членство проверяется в SQL; чужое = 404; `X-User-Id` игнорируется; mTLS не заменяет сессию | `test_api.py::test_foreign_chat_is_indistinguishable_from_missing`, `test_x_user_id_basic_and_garbage_do_not_authenticate`, `test_attachments.py` (чужое → 404), `test_logout_revokes_only_this_token`, `test_sessions.py::test_short_ttl_expires` | — | | T6. Скомпрометирован worker: пытается читать пользователей/сообщения в БД, писать в чужие таблицы, публиковать задачи, читать секреты API, писать в S3 как admin | наименьшие права worker | роль `messenger_worker` (GRANT только jobs/attempts/attachments/variants/outbox/job_events); RabbitMQ user `worker` только consume; S3 `messenger-worker` без Admin/List; OpenBao policy `worker` = свой путь | `test_postgres_tls_only_and_roles_least_privilege` (worker: users/messages/sessions/DELETE/функция → permission denied); `make bao-check` (worker: чужие пути, запись, sys/* → 403); `s3-init` (worker: ListBuckets пуст) | worker законно читает и пишет все вложения (это его работа) | -- 2.54.0