Files
mtusi2026lab7/scripts/collect_evidence.py
T

188 lines
11 KiB
Python

#!/usr/bin/env python3
"""Collect the lab 7 evidence on a RUNNING stand into evidence/ (README defense scenario steps 1-4).
python scripts/collect_evidence.py [--skip-student-tests]
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 subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence"
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 hook(name: str) -> str:
return str(ROOT / "scripts" / (name + (".cmd" if WIN else ".sh")))
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()
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
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 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)
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)
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"])
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=14400)
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
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__":
sys.exit(main())