Files
mtusi2026lab7/student-tests/rotation.py

250 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""lab7, уровень 4: ротация секрета и leaf-сертификата без пересборки, отзыв старой identity,
отзыв токенов, поведение при sealed OpenBao. Всё под фоновой нагрузкой через HTTPS.
python student-tests/rotation.py # все сценарии (~6 минут)
python student-tests/rotation.py --scenario sealed
Сценарии:
db-password — scripts/lab7.py rotate-db-password api: KV (текущий+предыдущий) → ALTER ROLE.
Ожидаем: 0 ошибок под нагрузкой; API подхватывает новую версию; новое соединение
с прежним паролем отклоняется; после рестарта API работает на новом пароле.
cert — rotate-cert lb (новый ключ и серийный, reload HAProxy) → revoke-cert lb (CRL).
Ожидаем: трафик идёт; API отвергает ОТОЗВАННЫЙ прежний сертификат lb (новое
соединение), принимает новый.
token — оператор отзывает все токены cert auth: приложение получает 403 на чтении KV,
входит заново сертификатом и продолжает работать.
sealed — seal OpenBao: работающие реплики обслуживают запросы на кэше секретов;
перезапущенная реплика НЕ стартует (fail closed), LB ведёт трафик на живую;
unseal → реплика поднимается сама.
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import threading
import time
from pathlib import Path
from common import ROOT, Api, Report
C = ["docker", "compose", "--env-file", ".env"]
OPS = [sys.executable, str(ROOT / "scripts" / "lab7.py")]
def sh(args: list[str], check: bool = True, input: str | None = None) -> str:
p = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace",
input=input)
if check and p.returncode != 0:
raise RuntimeError(f"{' '.join(args[:5])}: {(p.stderr or p.stdout).strip()[-400:]}")
return p.stdout
def audit(*sections: str) -> tuple[int, str]:
p = subprocess.run(C + ["--profile", "ops", "run", "--rm", "sectest", "student-tests/tls_audit.py", "--only",
*sections], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace")
return p.returncode, p.stdout
def logs_since(service: str, since: str, needle: str) -> list[dict]:
out = sh(C + ["logs", "--no-color", "--since", since, service], check=False)
res = []
for line in out.splitlines():
js = line[line.find("{"):] if "{" in line else ""
if needle in js:
try:
res.append(json.loads(js))
except ValueError:
pass
return res
class Load:
"""Фон: вход + сообщения + чтение. Считает коды ответов."""
def __init__(self, api: Api):
self.api, self.stop, self.codes, self.lock = api, threading.Event(), {}, threading.Lock()
self.u = api.new_user("rot")
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "rot", "member_ids": [self.u["id"]]},
token=self.u["token"])
self.chat = chat["id"]
self.ts = [threading.Thread(target=self.run, args=(i,), daemon=True) for i in range(3)]
def run(self, i):
while not self.stop.is_set():
if i == 0:
s = self.api.call("POST", f"/api/v1/chats/{self.chat}/messages", {"text": "r"}, token=self.u["token"])[0]
elif i == 1:
s = self.api.call("GET", f"/api/v1/chats/{self.chat}/messages?limit=5", token=self.u["token"])[0]
else:
s = self.api.login(self.u["username"], self.u["password"])[0]
time.sleep(2) # вход дорогой и ограничен по IP
with self.lock:
self.codes[s] = self.codes.get(s, 0) + 1
time.sleep(0.1)
def start(self):
for t in self.ts:
t.start()
return self
def take(self) -> dict:
with self.lock:
c, self.codes = dict(self.codes), {}
return c
def finish(self):
self.stop.set()
for t in self.ts:
t.join(10)
def errors(codes: dict) -> int:
return sum(v for k, v in codes.items() if k >= 500 or k == 0)
def operator_dir() -> Path:
"""Ключи unseal и root token живут вне репозитория (scripts/lab7.py bootstrap)."""
return Path(os.getenv("MTUSI_OPERATOR_DIR", str(Path.home() / ".mtusi-lab7")))
def utc_now() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# ============================================================ db-password
def scenario_db(api: Api, rep: Report) -> None:
print("== Ротация пароля БД роли api под нагрузкой")
load = Load(api).start()
time.sleep(5)
load.take()
since = utc_now()
out = sh(OPS + ["rotate-db-password", "api"])
print(" " + "\n ".join(line for line in out.splitlines() if line.strip().startswith(("kv/", "ALTER", "api"))))
time.sleep(40) # > SECRETS_REFRESH_SECONDS × 2
codes = load.take()
rot = logs_since("api", since, "secrets.rotated")
rep.check(len(rot) >= 1, f"API подхватил новую версию секретов: {[r.get('msg') for r in rot][:2]}")
rep.check(errors(codes) == 0 and sum(codes.values()) > 0, f"под нагрузкой во время ротации: {codes}")
rc, out = audit("db-rotation")
print(" " + "\n ".join(line for line in out.splitlines() if "rotation" in line))
rep.check(rc == 0, "прежний пароль отклоняется для новых соединений, текущий принимается")
sh(C + ["restart", "api"])
for _ in range(40):
if api.call("GET", "/health/ready")[0] == 200:
break
time.sleep(2)
time.sleep(3)
load.take()
time.sleep(8)
codes = load.take()
load.finish()
rep.check(errors(codes) == 0 and codes.get(201, 0) > 0,
f"после рестарта API (только новый пароль, образ тот же): {codes}")
# ============================================================ cert
def scenario_cert(api: Api, rep: Report) -> None:
print("== Ротация leaf-сертификата lb и отзыв прежнего")
load = Load(api).start()
time.sleep(3)
load.take()
out = sh(OPS + ["rotate-cert", "lb"])
issued = [line for line in out.splitlines() if "issued lb" in line]
print(" ", issued[-1].strip() if issued else out[-200:])
time.sleep(5)
codes = load.take()
rep.check(errors(codes) == 0, f"трафик через LB после reload с новым сертификатом: {codes}")
out = sh(OPS + ["revoke-cert", "lb"])
rev = [line for line in out.splitlines() if "revoked lb" in line]
print(" ", rev[-1].strip() if rev else out[-200:])
time.sleep(8) # API перечитывает CRL (TLS_CRL_RELOAD_SECONDS=5)
rc, out = audit("lb")
lines = [line for line in out.splitlines() if "lb→api" in line]
print(" " + "\n ".join(line for line in lines if "отозванный" in line or "разрешена" in line))
rep.check(any("отозванный" in line and line.strip().startswith("ok") for line in lines),
"API отвергает новое соединение с ОТОЗВАННЫМ прежним сертификатом lb")
rep.check(rc == 0, "вся матрица LB → API после ротации: разрешён только действующий lb")
codes = load.take()
load.finish()
rep.check(errors(codes) == 0, f"трафик через LB после отзыва прежнего сертификата: {codes}")
# ============================================================ token
def scenario_token(api: Api, rep: Report) -> None:
print("== Отзыв токенов OpenBao приложения")
load = Load(api).start()
since = utc_now()
token = json.loads((operator_dir() / "openbao-init.json").read_text(encoding="utf-8"))["root_token"]
p = subprocess.run(C + ["exec", "-T", "-e", "BAO_TOKEN", "openbao", "bao", "token", "revoke", "-mode=path",
"auth/cert/"], cwd=ROOT, capture_output=True, text=True,
env={**os.environ, "BAO_TOKEN": token})
rep.check(p.returncode == 0, "оператор отозвал все токены, выданные cert auth")
time.sleep(40)
relog = logs_since("api", since, "secrets.login")
fail = logs_since("api", since, "secrets.refresh_failed")
codes = load.take()
load.finish()
rep.check(len(relog) >= 1, f"API вошёл заново сертификатом ({len(relog)} входов), неудачных чтений: {len(fail)}")
rep.check(errors(codes) == 0, f"запросы во время отзыва: {codes}")
# ============================================================ sealed
def scenario_sealed(api: Api, rep: Report) -> None:
print("== OpenBao sealed: работающие реплики живут на кэше, новые не стартуют")
load = Load(api).start()
since = utc_now()
sh(OPS + ["seal"])
t0 = time.monotonic()
time.sleep(35)
codes = load.take()
fails = logs_since("api", since, "secrets.refresh_failed")
rep.check(errors(codes) == 0 and codes.get(201, 0) > 0,
f"35 c при sealed OpenBao: {codes} (секреты из кэша процесса)")
rep.check(len(fails) >= 1, f"обновление секретов падает и это видно в логах: {len(fails)} событий")
cid = sh(C + ["ps", "-q", "api"]).split()[0]
sh(["docker", "restart", "-t", "5", cid])
time.sleep(45)
state = sh(["docker", "inspect", "-f", "{{.State.Health.Status}} {{.State.Status}} {{.RestartCount}}", cid]).strip()
codes = load.take()
rep.check(not state.startswith("healthy"), f"перезапущенная реплика без OpenBao не готова: {state}")
rep.check(errors(codes) == 0, f"LB ведёт трафик на живую реплику: {codes}")
sh(OPS + ["unseal"])
t1 = time.monotonic()
healthy = None
for _ in range(60):
st = sh(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid], check=False).strip()
if st == "healthy":
healthy = time.monotonic() - t1
break
time.sleep(3)
codes = load.take()
load.finish()
rep.check(healthy is not None, f"после unseal реплика поднялась сама за {healthy or 0:.0f} c "
f"(OpenBao был sealed {t1 - t0:.0f} c)")
rep.check(errors(codes) == 0, f"запросы во время восстановления: {codes}")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--base-url", default="https://localhost:8443")
ap.add_argument("--scenario", choices=["all", "db-password", "cert", "token", "sealed"], default="all")
a = ap.parse_args()
api, rep = Api(a.base_url), Report()
for name, fn in (("db-password", scenario_db), ("cert", scenario_cert), ("token", scenario_token),
("sealed", scenario_sealed)):
if a.scenario in ("all", name):
t = time.monotonic()
try:
fn(api, rep)
finally:
if name == "sealed":
subprocess.run(OPS + ["unseal"], cwd=ROOT, capture_output=True)
print(f" [{name}: {time.monotonic() - t:.0f}s]")
rep.finish()
if __name__ == "__main__":
main()