Files
mtusi2026lab7/student-tests/test_lifecycle.py

282 lines
14 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.
#!/usr/bin/env python3
"""lab7 уровень 4: жизненный цикл secrets/сертификатов ПОД НАГРУЗКОЙ, без пересборки образов.
python3 student-tests/test_lifecycle.py [--only db,s3,cert,sealed,tokens,renewal] [--json evidence/lifecycle.json]
Каждый сценарий: фоновая нагрузка (загрузки + сообщения через HTTPS) → операторское действие → проверка, что
клиентских ошибок нет (или их число ограничено и объяснено), все загрузки дошли до ready, старый credential
отклоняется НОВЫМ подключением. ВНИМАНИЕ: тест меняет стенд (ротации, seal/unseal, масштабирование api).
"""
import argparse
import json
import os
import shlex
import shutil
import subprocess
import sys
import threading
import time
from pathlib import Path
from common import BASE_URL, DC, ROOT, Client, Failure, check, login, new_user, upload, wait_status
from secretcopy import copy_secrets
ENV = dict(os.environ, NO_PROXY="127.0.0.1,localhost", no_proxy="127.0.0.1,localhost")
RESULTS = []
def case(name):
def deco(fn):
RESULTS.append([name, fn, None, None])
return fn
return deco
def run(cmd, timeout=600, check_rc=True):
r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, timeout=timeout, env=ENV)
if check_rc and r.returncode != 0:
raise Failure("%s → %d: %s" % (" ".join(cmd[:4]), r.returncode, (r.stderr or r.stdout)[-400:]))
return r
def py(script, *args, timeout=600):
out = run([sys.executable, str(ROOT / "scripts" / script)] + list(args), timeout=timeout).stdout
start = out.find("{")
return json.loads(out[start:]) if start >= 0 else out
def dc(*args, timeout=300, check_rc=True):
return run(shlex.split(DC) + list(args), timeout=timeout, check_rc=check_rc)
def logs(service, since):
return dc("logs", "--no-log-prefix", "--since", since, service, check_rc=False).stdout.splitlines()
def utc():
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
class Load:
"""Фоновая нагрузка: каждый цикл — сообщение + (каждый 2-й) загрузка картинки. Считает ошибки клиента."""
def __init__(self, period=0.4):
self.c = Client(BASE_URL, timeout=20)
self.u = new_user(self.c, "lc")
login(self.c, self.u)
self.chat = self.c.call("POST", "/api/v1/chats", 201, actor=self.u, schema="Chat",
body={"title": "lifecycle", "member_ids": [self.u["id"]]})["json"]
self.period, self.stop, self.atts = period, threading.Event(), []
self.ok = self.err = 0
self.errors = []
self.t = threading.Thread(target=self.loop, daemon=True)
def loop(self):
i = 0
while not self.stop.is_set():
i += 1
try:
self.c.call("POST", "/api/v1/chats/%s/messages" % self.chat["id"], 201, actor=self.u,
body={"text": "lc %d" % i}, headers={"Idempotency-Key": "lc-%d-%f" % (i, time.time())})
if i % 2 == 0:
att, _ = upload(self.c, self.u, self.chat)
self.atts.append(att["id"])
self.ok += 1
except Exception as e: # noqa: BLE001
self.err += 1
self.errors.append("%s %s" % (time.strftime("%H:%M:%S"), str(e)[:120]))
time.sleep(self.period)
def __enter__(self):
self.t.start()
return self
def __exit__(self, *exc):
self.stop.set()
self.t.join(30)
def settle(self, timeout=180):
ready = 0
for a in self.atts:
att = wait_status(self.c, self.u, a, ("ready", "failed"), timeout=timeout)
ready += att["status"] == "ready"
return ready
@case("db: ротация пароля роли БД worker (blue/green) под нагрузкой — без ошибок и потерь")
def _():
with Load() as ld:
time.sleep(3)
res = py("rotate_credentials.py", "db", "worker")
time.sleep(5)
ready = ld.settle()
check(res["old_credential_check"].startswith("REJECTED"), "old db password still works: %s" % res)
check(res["services_switched_after_s"] is not None, "workers did not switch: %s" % res)
check(ld.err == 0, "client errors: %s" % ld.errors[:3])
check(ready == len(ld.atts), "ready %d of %d" % (ready, len(ld.atts)))
return ("%s → %s, KV v%s, переход за %s с, закрыто %s сессий старой роли; старый пароль: %s; нагрузка: %d ok / %d err,"
" вложений ready %d/%d" % (res["old_role"], res["new_role"], res["kv_version"], res["services_switched_after_s"],
res["old_sessions_terminated"], res["old_credential_check"][:30], ld.ok, ld.err,
ready, len(ld.atts)))
@case("s3: ротация ключа S3 identity api (два ключа на время перехода) под нагрузкой")
def _():
with Load() as ld:
time.sleep(3)
res = py("rotate_credentials.py", "s3", "api")
time.sleep(3)
ready = ld.settle()
check(res["old_credential_check"].startswith("REJECTED"), "old key still works: %s" % res)
check(res["services_switched_after_s"] is not None, "replicas did not confirm switch: %s" % res)
check(ld.err == 0, "client errors: %s" % ld.errors[:3])
check(ready == len(ld.atts), "ready %d of %d" % (ready, len(ld.atts)))
return "KV v%s, %d реплик перешли за %s с; старый ключ: %s; нагрузка %d ok / %d err; ready %d/%d" % (
res["kv_version"], res["replicas"], res["services_switched_after_s"], res["old_credential_check"], ld.ok, ld.err,
ready, len(ld.atts))
@case("cert: ротация leaf LB + отзыв старого (CRL) под нагрузкой; старый сертификат отклонён новым подключением")
def _():
old = ROOT / "secrets" / "test" / "old-lb"
if old.exists():
shutil.rmtree(old)
old.mkdir(parents=True)
copy_secrets([("tls/lb/" + n, "test/old-lb/" + n) for n in ("tls.crt", "tls.key", "tls.pem")], mode=0o600)
since = utc()
with Load(period=0.2) as ld:
time.sleep(3)
res = py("rotate_cert.py", "lb")
time.sleep(6)
ready = ld.settle()
probe = dc("--profile", "tests", "run", "--rm", "-T", "probe", "student-tests/internal_security.py", "--only", "lb",
timeout=300, check_rc=False)
line = [x for x in probe.stdout.splitlines() if "после ротации" in x]
check(line and line[0].startswith("PASS"), "probe: %s" % probe.stdout[-600:])
revoked_closed = sum('"mtls_revoked_closed"' in x for x in logs("api", since))
check(ld.err <= 2, "client errors during reload: %s" % ld.errors)
return ("serial %s → %s, CRL+reload за %s с (%s); нагрузка %d ok / %d err; ready %d/%d; старый cert → отказ "
"(probe), живых соединений со старым cert закрыто API: %d" % (
res["pki"]["old_serial"][:10], res["pki"]["new_serial"][:10], res["total_s"], ",".join(res["reloaded"][:2]),
ld.ok, ld.err, ready, len(ld.atts), revoked_closed))
def api_containers():
return [x for x in dc("ps", "-q", "api").stdout.split() if x]
def health(cid):
return subprocess.run(["docker", "inspect", "-f", "{{.State.Status}}/{{if .State.Health}}{{.State.Health.Status}}{{end}}",
cid], capture_output=True, text=True).stdout.strip()
@case("sealed: OpenBao запечатан — работающие API обслуживают; новая реплика НЕ стартует; после unseal — стартует")
def _():
since = utc()
run([sys.executable, str(ROOT / "scripts" / "bao_admin.py"), "seal"])
try:
with Load() as ld:
time.sleep(20) # > BAO_REFRESH_SECONDS: реплики заметили sealed
before = set(api_containers())
dc("up", "-d", "--no-recreate", "--scale", "api=3", "api", timeout=120)
new = [c for c in api_containers() if c not in before]
check(len(new) == 1, "scale-up did not add a replica: %s" % new)
time.sleep(25)
st_sealed = health(new[0])
check(not st_sealed.endswith("healthy") or st_sealed.endswith("unhealthy"),
"new replica became healthy while sealed: %s" % st_sealed)
run([sys.executable, str(ROOT / "scripts" / "bao_admin.py"), "unseal"])
t0 = time.monotonic()
while time.monotonic() - t0 < 120 and not health(new[0]).endswith("/healthy"):
time.sleep(1)
st_after = health(new[0])
recover = round(time.monotonic() - t0, 1)
time.sleep(3)
finally:
s = run([sys.executable, str(ROOT / "scripts" / "bao_admin.py"), "status"], check_rc=False).stdout
if '"sealed": true' in s:
run([sys.executable, str(ROOT / "scripts" / "bao_admin.py"), "unseal"], check_rc=False)
dc("up", "-d", "--no-recreate", "--scale", "api=2", "api", timeout=120, check_rc=False)
# Удалённая реплика уходит из server-template LB по DNS (hold obsolete 5 с) — даём LB перестроиться, чтобы
# переходное окно scale-down не попало в нагрузку следующего сценария (см. REPORT, «Ограничения»).
time.sleep(8)
lines = logs("api", since)
unavailable = sum('"bao_unavailable"' in x for x in lines)
check(st_after.endswith("/healthy"), "new replica not healthy after unseal: %s" % st_after)
check(ld.err == 0, "client errors while sealed: %s" % ld.errors[:3])
check(unavailable > 0, "no bao_unavailable events logged")
return ("sealed 45 с: нагрузка %d ok / %d err (реплики на кэшированных секретах); новая реплика при sealed: %s; "
"после unseal healthy за %s с; событий bao_unavailable: %d" % (ld.ok, ld.err, st_sealed, recover, unavailable))
@case("tokens: отзыв токенов api → 403 → новый вход по SecretID; ротация SecretID без рестарта")
def _():
since = utc()
with Load() as ld:
r1 = py("bao_admin.py", "revoke-tokens", "api")
time.sleep(35) # 2 × BAO_REFRESH_SECONDS + backoff
r2 = py("bao_admin.py", "rotate-secret-id", "api")
py("bao_admin.py", "revoke-tokens", "api") # заставить войти с НОВЫМ SecretID
time.sleep(35)
lines = logs("api", since)
denied = sum('"bao_denied"' in x for x in lines)
logins = sum('"bao_login"' in x for x in lines)
check(ld.err == 0, "client errors: %s" % ld.errors[:3])
check(denied >= 2 and logins >= 4, "denied=%d logins=%d" % (denied, logins))
toks = py("bao_admin.py", "tokens", "api")["tokens"]
return ("отозвано %d токенов → bao_denied %d, повторных входов %d (в т.ч. с новым SecretID: старый уничтожен=%s); "
"нагрузка %d ok / %d err; действующих токенов api: %d (TTL ≤ %s с)" % (
r1["tokens_revoked"], denied, logins, r2["old_secret_id_destroyed"], ld.ok, ld.err, len(toks),
max(t["creation_ttl"] for t in toks) if toks else 0))
@case("renewal: токены продлеваются на 2/3 TTL (renew-self), у max TTL — новый вход; TTL рабочего токена 5 мин")
def _():
# Продление — на 2/3 TTL (≈ 200 с после входа). Если сервисы только что перезапущены/вошли заново (persistence,
# отзыв токенов выше), ждём первое продление, но не дольше 260 с.
deadline = time.monotonic() + 260
while True:
lines = dc("logs", "--no-log-prefix", "api", "worker", check_rc=False).stdout.splitlines()
renew = [json.loads(x) for x in lines if '"bao_token_renewed"' in x]
if renew or time.monotonic() > deadline:
break
time.sleep(10)
logins = [json.loads(x) for x in lines if '"bao_login"' in x]
toks = py("bao_admin.py", "tokens", "worker")["tokens"]
check(toks and all(t["creation_ttl"] <= 300 for t in toks), "worker token TTL: %s" % toks)
check(renew, "no renewals logged yet (стенд работает < 4 мин?)")
ttls = sorted({r.get("token_ttl_s") for r in renew})
return "продлений: %d (выданный TTL после продления, с: %s), входов: %d; токены worker: TTL %s, last_renewal есть у %d" % (
len(renew), ttls[:6], len(logins), [t["ttl"] for t in toks], sum(1 for t in toks if t.get("last_renewal")))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--only", default="")
ap.add_argument("--json")
a = ap.parse_args()
only = [x for x in a.only.split(",") if x]
print("## lab7 lifecycle under load (%s, %s)" % (BASE_URL, time.strftime("%Y-%m-%d %H:%M:%S")))
p = f = 0
for row in RESULTS:
if only and row[0].split(":")[0] not in only:
continue
t0 = time.monotonic()
try:
row[3] = row[1]() or ""
row[2] = "PASS"
p += 1
except Exception as e: # noqa: BLE001
row[2], row[3] = "FAIL", str(e)[:800]
f += 1
print("%s %s (%.0fs)\n %s" % (row[2], row[0], time.monotonic() - t0, row[3]), flush=True)
print("summary: %d passed, %d failed" % (p, f))
if a.json:
Path(a.json).write_text(json.dumps([{"check": r[0], "result": r[2], "detail": r[3]} for r in RESULTS if r[2]],
ensure_ascii=False, indent=1))
sys.exit(1 if f else 0)
if __name__ == "__main__":
main()