lab7: тесты безопасности и перевод своих тестов на HTTPS, документы (trust-matrix, THREAT_MODEL, OPERATOR, DEFENSE, WINDOWS, PR), сборщик доказательств, чистка legacy bench

This commit is contained in:
Alexey Bodanyuk
2026-11-27 17:43:14 +03:00
parent 05df1695fe
commit 84dbdb4735
44 changed files with 1644 additions and 2686 deletions
+151 -185
View File
@@ -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 <Grafana: health of datasources prometheus/loki/tempo, dashboards>")
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())
-50
View File
@@ -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())
-138
View File
@@ -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())
-132
View File
@@ -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())
+1 -1
View File
@@ -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