Files
mtusi2026lab7/student-tests/test_cert_rotation.py
T
alenchha 861e7722b5
Skeleton contracts / contracts (pull_request) Canceled after 0s
Application stand (lab7) / stand (pull_request) Canceled after 0s
ЛР 7 — БВТ2301 — Курлова — на 4
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия:
- внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial;
- TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL),
  Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA;
- OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь;
- роли БД, S3-политики и права брокера по принципу минимальных прав;
- Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS;
- hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия;
- отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
2026-11-16 10:49:13 +03:00

89 lines
4.6 KiB
Python

#!/usr/bin/env python3
"""Level 4: rotation of a leaf certificate WITHOUT rebuilding images, revocation of the old identity, expiry.
Leaf: lb-client (identity lb.client.messenger), the only client allowed by the API replicas.
1. background HTTPS traffic through nginx for the whole test (errors are counted)
2. scripts/pki.sh issue lb-client new key + serial, files overwritten in place (bind-mounted secrets)
3. nginx -s reload new upstream connections present the new certificate; no image build,
no container recreate
4. old and new certificate both still accepted (old is valid until revoked)
5. scripts/pki.sh revoke-serial <old> appended to revoked-serials.txt; the API re-reads it within ~1 s
6. old certificate -> refused (reason=revoked in the API log), new -> 200, expired copy -> refused by TLS
7. public smoke afterwards
New connections are what proves revocation: established keep-alive/TLS sessions are not re-checked, so nginx's
upstream keep-alive (4 s) is the upper bound for an already open connection of the old identity.
python3 student-tests/test_cert_rotation.py
"""
import json
import shutil
import subprocess
import threading
import time
from openloop import Load
from stand import ROOT, check, compose, log, run
PKI = ROOT / "secrets/pki"
def sh(*args):
return subprocess.run(["sh", *args], cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip()
def probe(host, *certs):
out = compose("run", "--rm", "--no-deps", "-v", "./secrets/pki:/pki:ro", "-v", "./student-tests:/audit:ro",
"--entrypoint", "python", "worker", "/audit/mtls_probe.py", host, *certs)
return {r["cert"]: r for r in (json.loads(line) for line in out.splitlines() if line.startswith("{"))}
def main():
load = Load("https://localhost:8443", users=2, threads=32)
stop, summary = threading.Event(), {}
thread = threading.Thread(target=lambda: summary.update(load.run(10, 900, stop_event=stop)), daemon=True)
thread.start()
time.sleep(5)
old = sh("scripts/pki.sh", "serial", "lb-client")
log("current lb-client serial %s" % old)
t0 = time.time()
log(sh("scripts/pki.sh", "issue", "lb-client").splitlines()[0])
shutil.copy(PKI / "lb-client.crt.previous", PKI / "lb-client-old.crt")
shutil.copy(PKI / "lb-client.key.previous", PKI / "lb-client-old.key")
new = sh("scripts/pki.sh", "serial", "lb-client")
check(new != old, "a new serial must be issued")
compose("exec", "-T", "nginx", "nginx", "-s", "reload")
log("nginx reloaded with the new client certificate (%.1f s after issue)" % (time.time() - t0))
if not (PKI / "lb-client-expired.crt").exists():
sh("scripts/pki.sh", "expired", "lb-client")
before = probe("api-1", "lb-client-old", "lb-client")
check(before["lb-client-old"]["verdict"] == "accepted" and before["lb-client"]["verdict"] == "accepted",
"both certificates valid before revocation: %s" % before)
log("before revocation: old=%s new=%s" % (before["lb-client-old"]["detail"], before["lb-client"]["detail"]))
log(sh("scripts/pki.sh", "revoke-serial", old))
time.sleep(2)
for api in ("api-1", "api-2"):
after = probe(api, "lb-client-old", "lb-client", "lb-client-expired")
check(after["lb-client-old"]["verdict"] == "rejected", "%s: revoked old cert must be refused" % api)
check(after["lb-client"]["verdict"] == "accepted", "%s: new cert must work" % api)
check(after["lb-client-expired"]["verdict"] == "rejected", "%s: expired cert must be refused" % api)
log("%s after revocation: old -> %s | new -> %s | expired -> %s" % (
api, after["lb-client-old"]["detail"], after["lb-client"]["detail"], after["lb-client-expired"]["detail"]))
logs = compose("logs", "--since", "2m", "api-1", "api-2")
check("reason=revoked" in logs and old in logs.upper(), "API must log the revoked serial")
log("API log: mtls_client_rejected reason=revoked serial=%s" % old)
time.sleep(5)
stop.set()
thread.join(60)
bad = summary.get("server_errors_unexpected")
log("traffic during rotation: %s requests, %s ok, unexpected errors %s" % (
summary.get("requests"), summary.get("ok"), bad))
check(bad == 0, "rotation must not break traffic")
out = subprocess.run(["make", "test", "CA_FILE=%s" % (PKI / "ca.crt")], cwd=ROOT, capture_output=True, text=True)
check(out.returncode == 0, "smoke after rotation")
log(out.stdout.strip().splitlines()[-1])
print("PASS: lb-client rotated (%s -> %s) without image rebuild, old serial revoked, expired cert refused" % (old, new))
if __name__ == "__main__":
run(main)