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] =?UTF-8?q?lab7:=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20=D0=B1?= =?UTF-8?q?=D0=B5=D0=B7=D0=BE=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D0=B8=20=D0=B8=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B2=D0=BE=D0=B4=20?= =?UTF-8?q?=D1=81=D0=B2=D0=BE=D0=B8=D1=85=20=D1=82=D0=B5=D1=81=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=BD=D0=B0=20HTTPS,=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=D1=8B=20(trust-matrix,=20THREAT=5FMODEL,=20O?= =?UTF-8?q?PERATOR,=20DEFENSE,=20WINDOWS,=20PR),=20=D1=81=D0=B1=D0=BE?= =?UTF-8?q?=D1=80=D1=89=D0=B8=D0=BA=20=D0=B4=D0=BE=D0=BA=D0=B0=D0=B7=D0=B0?= =?UTF-8?q?=D1=82=D0=B5=D0=BB=D1=8C=D1=81=D1=82=D0=B2,=20=D1=87=D0=B8?= =?UTF-8?q?=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()