ЛР7: TLS/mTLS по матрице доверия, OpenBao, Argon2id, ротация и отрицательные тесты
This commit is contained in:
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Прогон проверок lab7 (и унаследованных lab2–6) с сохранением вывода в evidence/ (Windows/macOS/Linux).
|
||||
Стенд поднят и распечатан: python scripts/lab7.py bootstrap (или unseal после рестарта Docker)
|
||||
|
||||
python student-tests/collect_evidence.py # основной набор (~35 минут)
|
||||
python student-tests/collect_evidence.py --only smoke,tls-audit # выборочно
|
||||
python student-tests/collect_evidence.py --extra # + инциденты lab6 и тесты lab4
|
||||
|
||||
Каждый шаг пишет evidence/<имя>.txt (команда, время, stdout/stderr, код выхода).
|
||||
Ошибка одного шага не останавливает остальные; в конце — сводка PASS/FAIL.
|
||||
HTTPS проверяется по нашему CA: secrets/ca.crt (CA_FILE). Проверка сертификата нигде не отключается.
|
||||
Hook-и: на Windows scripts/*.cmd, иначе scripts/*.sh. Секреты не печатаются.
|
||||
"""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
EVIDENCE = ROOT / "evidence"
|
||||
PY = sys.executable
|
||||
WIN = os.name == "nt"
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
SAMPLE_SHA = hashlib.sha256((ROOT / "tests/fixtures/sample.png").read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def hook(name: str) -> str:
|
||||
return str(ROOT / "scripts" / (name + (".cmd" if WIN else ".sh")))
|
||||
|
||||
|
||||
# Публичные tests/ читают JSON без явной кодировки: на Windows (cp1251) это падает.
|
||||
# UTF-8 mode Python для всех дочерних процессов, сами тесты не меняем.
|
||||
CA = str(ROOT / "secrets" / "ca.crt")
|
||||
ENV = {**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8", "CA_FILE": os.environ.get("CA_FILE", CA)}
|
||||
|
||||
|
||||
def run(cmd: list[str], log, timeout: int = 900) -> int:
|
||||
log.write(f"\n$ {' '.join(cmd)}\n")
|
||||
log.flush()
|
||||
try:
|
||||
p = subprocess.run(cmd, cwd=ROOT, env=ENV, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True, encoding="utf-8", errors="replace", timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
log.write("TIMEOUT\n")
|
||||
return 124
|
||||
log.write(p.stdout)
|
||||
log.write(f"[exit {p.returncode}]\n")
|
||||
return p.returncode
|
||||
|
||||
|
||||
def ports_closed(log) -> int:
|
||||
"""Наружу (127.0.0.1) только TLS-вход lb (8443/8444/8445) и Grafana HTTPS (3000).
|
||||
PostgreSQL, Redis, брокер, MinIO, OpenBao, otel-gw/Collector, Prometheus/Loki/Tempo, health API — закрыты."""
|
||||
bad = 0
|
||||
for port in (5432, 6379, 9000, 9001, 8200, 8201, 4317, 4318, 8888, 13133, 9090, 3100, 3200, 8081, 8404, 8080):
|
||||
s = socket.socket()
|
||||
s.settimeout(1)
|
||||
try:
|
||||
s.connect(("127.0.0.1", port))
|
||||
log.write(f"127.0.0.1:{port} OPEN <- не должно быть\n")
|
||||
bad += 1
|
||||
except OSError as exc:
|
||||
log.write(f"127.0.0.1:{port} closed ({type(exc).__name__}) ok\n")
|
||||
finally:
|
||||
s.close()
|
||||
return bad
|
||||
|
||||
|
||||
def drain(log, limit: int = 600) -> int:
|
||||
"""Ждать, пока в очереди не останется queued/processing (не дольше limit секунд)."""
|
||||
import json
|
||||
t0 = time.monotonic()
|
||||
while time.monotonic() - t0 < limit:
|
||||
out = subprocess.run(COMPOSE + ["exec", "-T", "worker", "python", "-m", "app.tools", "queue"], cwd=ROOT,
|
||||
capture_output=True, text=True, encoding="utf-8", errors="replace").stdout
|
||||
try:
|
||||
jobs = json.loads(out.strip().splitlines()[-1])["jobs_by_status"]
|
||||
except (ValueError, IndexError, KeyError):
|
||||
jobs = {}
|
||||
busy = jobs.get("queued", 0) + jobs.get("processing", 0)
|
||||
if jobs and busy == 0:
|
||||
log.write(f"queue drained in {time.monotonic() - t0:.1f} s: {jobs}\n")
|
||||
return 0
|
||||
time.sleep(3)
|
||||
log.write(f"queue NOT drained in {limit} s\n")
|
||||
return 1
|
||||
|
||||
|
||||
TRIVY = "aquasec/trivy:0.58.1"
|
||||
SCAN_IMAGES = ["postgres:16.4-alpine", "redis:8.6.8", "openbao/openbao:2.6.4", "haproxy:3.0.5-alpine",
|
||||
"pgsty/minio:RELEASE.2026-08-04T00-00-00Z", "grafana/grafana:11.4.0"]
|
||||
|
||||
|
||||
def trivy(image: str, severity: str) -> list[str]:
|
||||
return ["docker", "run", "--rm", "-v", "/var/run/docker.sock:/var/run/docker.sock",
|
||||
"-v", "mtusi-trivy-cache:/root/.cache/", TRIVY, "image", "--scanners", "vuln",
|
||||
"--severity", severity, "--no-progress", image]
|
||||
|
||||
|
||||
def steps(base: str, extra: bool):
|
||||
t = ["--base-url", base]
|
||||
w = COMPOSE + ["exec", "-T", "worker", "python", "-m"] # служебные команды — identity worker
|
||||
yield "check", [[PY, "scripts/check_contract.py"]]
|
||||
yield "stand", [COMPOSE + ["ps"], COMPOSE + ["config", "--images"], [PY, "scripts/lab7.py", "status"]]
|
||||
# уровень 3: публичные проверки по HTTPS с нашим CA
|
||||
yield "smoke", [[PY, "tests/smoke.py", *t, "--ca-file", CA]]
|
||||
yield "security", [[PY, "tests/security.py", *t, "--ca-file", CA]]
|
||||
# матрица доверия: каждая связь — правильная identity / чужая identity того же CA / чужой CA /
|
||||
# без сертификата / plaintext / неверный SAN; права ролей в БД, S3, брокере, OpenBao
|
||||
yield "tls-audit", [COMPOSE + ["--profile", "ops", "run", "--rm", "sectest", "student-tests/tls_audit.py"]]
|
||||
yield "security-neg", [[PY, "student-tests/security_neg.py", *t]]
|
||||
yield "ports", ["PORTS"]
|
||||
yield "student-tests", [[PY, "student-tests/run.py", *t], [PY, "student-tests/idempotency.py", *t]]
|
||||
yield "attachments", [[PY, "student-tests/attachments.py", *t]]
|
||||
yield "s3-private", [COMPOSE + ["exec", "-T", "api", "python", "-m", "app.tools", "private-check"]]
|
||||
yield "worker-limits", [w + ["app.tools", "limits-selftest"]]
|
||||
for sc in ("worker-down", "broker-down", "redelivery", "crash-ack", "retry-replay"):
|
||||
yield f"jobs-{sc}", [[PY, "student-tests/jobs.py", *t, "--scenario", sc]]
|
||||
yield "jobs-registry", [w + ["app.replay", "--list"], w + ["app.replay", "--dlq"], w + ["app.tools", "queue"],
|
||||
COMPOSE + ["--profile", "fault", "stop", "api-fault", "worker-fault"]]
|
||||
yield "telemetry-config", [
|
||||
COMPOSE + ["ps", "otel-gw", "otel-collector", "prometheus", "loki", "tempo", "grafana"],
|
||||
COMPOSE + ["exec", "-T", "prometheus", "promtool", "check", "config", "/etc/prometheus/prometheus.yml"],
|
||||
COMPOSE + ["exec", "-T", "prometheus", "promtool", "check", "rules", "/etc/prometheus/rules/messenger.yml"],
|
||||
COMPOSE + ["logs", "--tail", "15", "otel-collector"]]
|
||||
yield "observability", [[PY, "student-tests/observability.py", *t]]
|
||||
yield "load", [[PY, "tests/load.py", *t, "--ca-file", CA, "--duration", "60", "--concurrency", "8",
|
||||
"--output", "evidence/load.json"], "SLEEP", "SLEEP",
|
||||
[PY, "student-tests/snapshot.py", "--minutes", "2"]]
|
||||
yield "no-local-file", [COMPOSE + ["exec", "-T", "--index", str(i), "api", "python", "-m", "app.tools",
|
||||
"find-local", SAMPLE_SHA] for i in (1, 2)] + [
|
||||
w + ["app.tools", "find-local", SAMPLE_SHA]]
|
||||
yield "queue-drain", ["DRAIN", w + ["app.tools", "queue"]]
|
||||
if extra:
|
||||
yield "orphans", [COMPOSE + ["--profile", "fault", "up", "-d", "api-fault"], "SLEEP",
|
||||
[PY, "student-tests/orphans.py", *t, "--fault-url", "https://localhost:8445"],
|
||||
COMPOSE + ["--profile", "fault", "stop", "api-fault"]]
|
||||
yield "upload-memory", [[PY, "student-tests/upload_memory.py", *t, "--concurrency", "10",
|
||||
"--output", "evidence/upload-memory-10.json"]]
|
||||
yield "queue-drain-2", ["DRAIN"]
|
||||
for sc in ("worker", "db", "telemetry"):
|
||||
yield f"incident-{sc}", [[PY, "student-tests/incidents.py", *t, "--scenario", sc]]
|
||||
# уровень 4: ротация secret и leaf-сертификата без пересборки, отзыв, отзыв токенов, sealed OpenBao
|
||||
yield "rotation", [[PY, "student-tests/rotation.py", *t], [PY, "scripts/lab7.py", "status"]]
|
||||
yield "metrics-snapshot", [[PY, "student-tests/snapshot.py", "--minutes", "30"]]
|
||||
# перезапуск всего стенда (OpenBao → unseal оператором → хранилища, API, worker, LB) и отказ реплик
|
||||
yield "persistence", [COMPOSE + ["ps"], [PY, "tests/resilience.py", "--mode", "persistence",
|
||||
"--action-script", hook("restart"), *t, "--ca-file", CA],
|
||||
COMPOSE + ["ps"]]
|
||||
yield "failover", [[PY, "tests/resilience.py", "--mode", "failover", "--action-script", hook("stop-one"), *t,
|
||||
"--ca-file", CA],
|
||||
[hook("restore-api")], "SLEEP",
|
||||
[PY, "tests/resilience.py", "--mode", "failover", "--action-script", hook("stop-one"), *t,
|
||||
"--ca-file", CA],
|
||||
[hook("restore-api")]]
|
||||
# dependency/image scan: разбор применимости — в REPORT.md
|
||||
yield "scan-pip-audit", [["docker", "run", "--rm", "--entrypoint", "sh", "-v",
|
||||
f"{ROOT / 'requirements.txt'}:/tmp/requirements.txt:ro", "python:3.12.7-slim-bookworm",
|
||||
"-c", "pip install -q --root-user-action=ignore pip-audit==2.7.3 >/dev/null && "
|
||||
"pip-audit -r /tmp/requirements.txt --progress-spinner off; true"]]
|
||||
yield "scan-trivy-app", [trivy("mtusi-messenger:lab7", "HIGH,CRITICAL")]
|
||||
yield "scan-trivy-infra", [trivy(img, "CRITICAL") for img in SCAN_IMAGES]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="https://localhost:8443")
|
||||
ap.add_argument("--only", default="")
|
||||
ap.add_argument("--extra", action="store_true", help="+ orphans/upload-memory/инциденты lab6 (~15 минут)")
|
||||
args = ap.parse_args()
|
||||
only = {x.strip() for x in args.only.split(",") if x.strip()}
|
||||
EVIDENCE.mkdir(exist_ok=True)
|
||||
commit = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True,
|
||||
text=True).stdout.strip() or "no-git"
|
||||
summary = []
|
||||
for name, cmds in steps(args.base_url, args.extra or bool(only)):
|
||||
if only and name not in only:
|
||||
continue
|
||||
path = EVIDENCE / f"{name}.txt"
|
||||
print(f"== {name} -> {path.relative_to(ROOT)}")
|
||||
with open(path, "w", encoding="utf-8") as log:
|
||||
log.write(f"# {name}\n# date: {dt.datetime.now().isoformat(timespec='seconds')} commit: {commit}\n")
|
||||
failed = 0
|
||||
for cmd in cmds:
|
||||
if cmd == "SLEEP":
|
||||
time.sleep(8)
|
||||
continue
|
||||
if cmd == "DRAIN":
|
||||
failed += drain(log)
|
||||
continue
|
||||
if cmd == "PORTS":
|
||||
failed += ports_closed(log)
|
||||
continue
|
||||
code = run(cmd, log)
|
||||
failed += 1 if code else 0
|
||||
status = "PASS" if not failed else f"FAIL ({failed})"
|
||||
summary.append((name, status))
|
||||
print(" ", status)
|
||||
print("\nSummary:")
|
||||
for name, status in summary:
|
||||
print(f" {name:20} {status}")
|
||||
sys.exit(0 if all(s == "PASS" for _, s in summary) else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user