forked from mtusi2026/mtusi2026lab7
lab7: тесты безопасности и перевод своих тестов на HTTPS, документы (trust-matrix, THREAT_MODEL, OPERATOR, DEFENSE, WINDOWS, PR), сборщик доказательств, чистка legacy bench
This commit is contained in:
+151
-185
@@ -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())
|
||||
|
||||
Reference in New Issue
Block a user