forked from mtusi2026/mtusi2026lab7
Перенесён минимум 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.
89 lines
4.7 KiB
Python
89 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Level 4: rotation of one working secret without image rebuild or restart: the DB password of role app_worker.
|
|
|
|
1. background traffic (messages + 1 upload/s) through HTTPS for the whole test
|
|
2. operator: scripts/bao.sh rotate-worker-db -> ALTER ROLE app_worker + new KV version messenger/worker
|
|
3. both workers pick up the new version from OpenBao (refresh <= BAO_REFRESH_SECONDS) and switch the pool
|
|
4. existing app_worker sessions are terminated in PostgreSQL: the pool must reconnect WITH THE NEW password
|
|
5. old password refused, new password accepted (probe from inside the network); uploads keep reaching ready
|
|
Passwords are held in memory only for the probes and are never printed.
|
|
|
|
python3 student-tests/test_secret_rotation.py (needs the operator OpenBao material: scripts/bao.sh)
|
|
"""
|
|
import os
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
|
|
from openloop import Load
|
|
from stand import ROOT, Client, check, compose, log, run, sql, upload, wait_status
|
|
|
|
PROBE = ("import os,psycopg\n"
|
|
"try:\n"
|
|
" psycopg.connect('postgresql://app_worker@postgres:5432/messenger', password=os.environ['PW'],"
|
|
" sslmode='verify-full', sslrootcert='/run/secrets/ca.crt', connect_timeout=5).close(); print('accepted')\n"
|
|
"except psycopg.Error as e:\n print('rejected: ' + str(e).splitlines()[0][-60:])\n")
|
|
|
|
|
|
def probe(password):
|
|
out = subprocess.run(["docker", "compose", "run", "--rm", "--no-deps", "-e", "PW", "--entrypoint", "python",
|
|
"worker", "-c", PROBE], cwd=ROOT, env={**os.environ, "PW": password},
|
|
capture_output=True, text=True).stdout
|
|
return [line for line in out.splitlines() if line.startswith(("accepted", "rejected"))][-1]
|
|
|
|
|
|
def worker_logs(since):
|
|
return compose("logs", "--since", since, "worker")
|
|
|
|
|
|
def main():
|
|
c = Client()
|
|
alice, _bob, _eve, chat = c.bootstrap()
|
|
load = Load("https://localhost:8443", users=2, threads=32)
|
|
stop, summary = threading.Event(), {}
|
|
thread = threading.Thread(target=lambda: summary.update(load.run(5, 900, 1, stop_event=stop)), daemon=True)
|
|
thread.start()
|
|
old = (ROOT / "secrets/bootstrap/db_worker_password").read_text().strip()
|
|
check(probe(old) == "accepted", "old password must work before the rotation")
|
|
before = int(sql("SELECT count(*) FROM pg_stat_activity WHERE usename = 'app_worker'")[0][0])
|
|
log("before: old password accepted, %d app_worker connections open" % before)
|
|
|
|
t0 = time.time()
|
|
out = subprocess.run(["sh", "scripts/bao.sh", "rotate-worker-db"], cwd=ROOT, capture_output=True, text=True)
|
|
check(out.returncode == 0, "rotation script failed: %s" % out.stderr[-200:])
|
|
log(out.stdout.strip().splitlines()[-1])
|
|
new = (ROOT / "secrets/bootstrap/db_worker_password").read_text().strip()
|
|
check(new != old, "password must change")
|
|
|
|
deadline = time.time() + 60
|
|
while time.time() < deadline:
|
|
logs = worker_logs("90s")
|
|
if logs.count("db_credentials_rotated") >= 2:
|
|
break
|
|
time.sleep(3)
|
|
check(logs.count("db_credentials_rotated") >= 2, "both workers must switch to the new secret version")
|
|
log("both workers loaded the new KV version and switched the pool (%.0f s after rotation)" % (time.time() - t0))
|
|
|
|
sql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'app_worker'")
|
|
log("terminated all existing app_worker sessions: the pools must reconnect with the new password")
|
|
atts = [upload(c, alice, chat, filename="rotation-%d.png" % i) for i in range(3)]
|
|
for att in atts:
|
|
wait_status(c, alice, att["id"], ("ready",), 90)
|
|
after = int(sql("SELECT count(*) FROM pg_stat_activity WHERE usename = 'app_worker'")[0][0])
|
|
log("3 uploads after the forced reconnect are ready; %d app_worker connections open again" % after)
|
|
check(after > 0, "workers must reconnect")
|
|
old_result, new_result = probe(old), probe(new)
|
|
log("probe: old password -> %s | new password -> %s" % (old_result, new_result))
|
|
check(old_result.startswith("rejected") and new_result == "accepted", "old refused, new accepted")
|
|
failed = sql("SELECT count(*) FROM attachment_jobs WHERE state = 'failed' AND updated_at > to_timestamp(%d)" % t0)[0][0]
|
|
stop.set()
|
|
thread.join(60)
|
|
log("traffic: %s requests, unexpected errors %s, uploads %s; failed jobs since rotation: %s" % (
|
|
summary.get("requests"), summary.get("server_errors_unexpected"), summary["by_kind"]["upload"]["n"], failed))
|
|
check(summary.get("server_errors_unexpected") == 0 and failed == "0", "no errors and no failed jobs")
|
|
print("PASS: app_worker password rotated via OpenBao without rebuild/restart; old password revoked")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main)
|