forked from mtusi2026/mtusi2026lab7
Name restarting both the LB and the replicas when the LB has no ready replica, state the measured 25 s bound of the LB metrics port, narrow the missing files of a held identity to its certificate, and cover refusals and signals during CRL issue with fast tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1647 lines
60 KiB
Python
1647 lines
60 KiB
Python
"""Методы стенда команд ротации (change `rotation-revocation`, «Уточнения
|
||
verify», W7): `infra/rotation/rotation.py`, класс `Stand` на подменённом
|
||
`run` — настоящие argv, stdin и разбор ответов docker, openssl, pki.sh, bao.py
|
||
и runtime API LB; порядок команд проверяет `test_rotation.py`.
|
||
|
||
Каждый тест краснит мутацию своего метода: перечень мутаций и итог —
|
||
`evidence/security/rotation-revocation.md`, «Правки verify».
|
||
"""
|
||
|
||
import importlib.util
|
||
import json
|
||
import os
|
||
import re
|
||
import signal
|
||
import subprocess
|
||
import sys
|
||
import tomllib
|
||
from collections.abc import Callable
|
||
from pathlib import Path
|
||
from types import ModuleType
|
||
from typing import Any
|
||
|
||
import pytest
|
||
|
||
from src.config.settings import BASE_DIR
|
||
|
||
SCRIPT = BASE_DIR / "infra" / "rotation" / "rotation.py"
|
||
|
||
|
||
def _load() -> ModuleType:
|
||
spec = importlib.util.spec_from_file_location("rotation_stand", SCRIPT)
|
||
assert spec is not None and spec.loader is not None
|
||
module = importlib.util.module_from_spec(spec)
|
||
sys.modules.setdefault("rotation_stand", module)
|
||
spec.loader.exec_module(module)
|
||
return module
|
||
|
||
|
||
rotation = _load()
|
||
OLD = "2026-12-01T02:00:00.000000001Z"
|
||
NEW = "2026-12-01T03:00:00.000000002Z"
|
||
PEM = "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"
|
||
KEY = "-----BEGIN PRIVATE KEY-----\nBBBB\n-----END PRIVATE KEY-----\n"
|
||
|
||
|
||
class Call:
|
||
def __init__(self, args: list[str], kwargs: dict[str, Any]) -> None:
|
||
self.text = " ".join(args)
|
||
self.args = args
|
||
self.stdin = kwargs.get("stdin")
|
||
self.env = kwargs.get("env") or {}
|
||
self.kwargs = kwargs
|
||
|
||
|
||
class RunStand(rotation.Stand): # type: ignore[misc]
|
||
"""`run` отвечает по первому правилу, чья подстрока есть в argv: ответ —
|
||
(код, stdout, stderr) или функция от вызова."""
|
||
|
||
def __init__(self, tmp_path: Path) -> None:
|
||
super().__init__()
|
||
self.pki_dir = tmp_path
|
||
self.calls: list[Call] = []
|
||
self.rules: list[tuple[str, Any]] = []
|
||
self.clock = 0.0
|
||
(tmp_path / "ca.crt").write_text("CA")
|
||
(tmp_path / "crl.pem").write_text("CRL")
|
||
|
||
def on(self, part: str, answer: Any) -> None:
|
||
self.rules.insert(0, (part, answer))
|
||
|
||
def run(self, args: list[str], **kwargs: Any) -> Any:
|
||
call = Call(args, kwargs)
|
||
self.calls.append(call)
|
||
answer: Any = (0, "", "")
|
||
for part, rule in self.rules:
|
||
if part in call.text:
|
||
answer = rule(call) if callable(rule) else rule
|
||
break
|
||
if isinstance(answer, str):
|
||
answer = (0, answer, "")
|
||
code, out, err = answer
|
||
if kwargs.get("output") is not None:
|
||
kwargs["output"].write(out + err)
|
||
kwargs["output"].flush()
|
||
return subprocess.CompletedProcess(args, code, out, err)
|
||
|
||
def texts(self, part: str) -> list[str]:
|
||
return [call.text for call in self.calls if part in call.text]
|
||
|
||
def services(self, **states: Any) -> None:
|
||
"""Сервис → строки docker inspect: (состояние, health, старт) или их
|
||
список; журнал — по id контейнера."""
|
||
ids: dict[str, dict[str, Any]] = {}
|
||
table: dict[str, list[str]] = {}
|
||
for number, (name, rows) in enumerate(states.items()):
|
||
service = name.replace("_", "-")
|
||
table[service] = []
|
||
for index, (status, health, started) in enumerate(
|
||
rows if isinstance(rows, list) else [rows],
|
||
):
|
||
key = f"{number:032x}{index:032x}"
|
||
table[service].append(key)
|
||
ids[key] = {
|
||
"id": key,
|
||
"status": status,
|
||
"health": health,
|
||
"started": started,
|
||
"oneoff": "False",
|
||
}
|
||
self.ids = table
|
||
self.on(
|
||
"compose ps -a -q --no-trunc",
|
||
lambda call: "\n".join(table.get(call.args[-1], [])),
|
||
)
|
||
self.on(
|
||
"docker inspect -f",
|
||
lambda call: "\n".join(
|
||
json.dumps(ids[key]) for key in call.args[4:]
|
||
),
|
||
)
|
||
|
||
|
||
@pytest.fixture
|
||
def stand(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> RunStand:
|
||
"""Часы идут от сна: сроки проверяются без ожидания."""
|
||
made = RunStand(tmp_path)
|
||
|
||
def sleep(seconds: float) -> None:
|
||
made.clock += seconds
|
||
|
||
monkeypatch.setattr(rotation.time, "sleep", sleep)
|
||
monkeypatch.setattr(rotation.time, "monotonic", lambda: made.clock)
|
||
made.started = 0.0
|
||
return made
|
||
|
||
|
||
# процессы --------------------------------------------------------------------
|
||
|
||
|
||
def test_run_is_a_process_of_its_own_session() -> None:
|
||
"""Ctrl+C терминала дочерний процесс не получает; stdin — только данные,
|
||
без них пуст; окружение дополняется."""
|
||
result = rotation.Stand().run(
|
||
[
|
||
sys.executable,
|
||
"-c",
|
||
"import os, sys; print(os.getsid(0) == os.getpid(), "
|
||
"os.environ['PROBE'], repr(sys.stdin.read()))",
|
||
],
|
||
env={"PROBE": "here"},
|
||
)
|
||
assert result.stdout.strip() == "True here ''"
|
||
result = rotation.Stand().run(
|
||
[sys.executable, "-c", "import sys; print(sys.stdin.read())"],
|
||
stdin="data",
|
||
)
|
||
assert result.stdout.strip() == "data"
|
||
|
||
|
||
def test_run_does_not_inherit_stdin(tmp_path: Path) -> None:
|
||
"""Ввод оператора (или труба, из которой запущен скрипт) дочернему
|
||
процессу не достаётся."""
|
||
source = tmp_path / "stdin"
|
||
source.write_text("typed by the operator")
|
||
saved = os.dup(0)
|
||
with source.open() as file:
|
||
os.dup2(file.fileno(), 0)
|
||
try:
|
||
result = rotation.Stand().run(
|
||
[sys.executable, "-c", "import sys; print(sys.stdin.read())"],
|
||
)
|
||
finally:
|
||
os.dup2(saved, 0)
|
||
os.close(saved)
|
||
assert result.stdout.strip() == ""
|
||
|
||
|
||
def test_run_output_file_and_lock(tmp_path: Path) -> None:
|
||
"""Замена реплик: вывод — в файл (труба убитой команды оборвала бы её), а
|
||
блокировку держит и она, пока не кончится."""
|
||
first = rotation.Stand()
|
||
first.pki_dir = tmp_path
|
||
first.lock()
|
||
ready, go = tmp_path / "ready", tmp_path / "go"
|
||
code = (
|
||
"import os, sys, time\n"
|
||
f"open({str(ready)!r}, 'w').close()\n"
|
||
f"while not os.path.exists({str(go)!r}): time.sleep(0.02)\n"
|
||
"print('finished')\n"
|
||
)
|
||
proc = subprocess.Popen( # noqa: S603
|
||
[sys.executable, "-c", code],
|
||
pass_fds=(first.lock_file,),
|
||
)
|
||
try:
|
||
while not ready.exists():
|
||
pass
|
||
# команда кончилась (убита), её замена реплик — нет
|
||
os.close(first.lock_file)
|
||
second = rotation.Stand()
|
||
second.pki_dir = tmp_path
|
||
with pytest.raises(rotation.NotReady):
|
||
second.lock()
|
||
finally:
|
||
go.touch()
|
||
proc.wait()
|
||
second.lock()
|
||
with (tmp_path / "out").open("w+") as file:
|
||
second.run(
|
||
[
|
||
sys.executable,
|
||
"-c",
|
||
f"import os; print('text', os.fstat({second.lock_file}).st_size"
|
||
" >= 0)",
|
||
],
|
||
output=file,
|
||
keep=second.lock_file,
|
||
)
|
||
file.seek(0)
|
||
assert file.read().strip() == "text True"
|
||
|
||
|
||
@pytest.mark.parametrize("number", ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"])
|
||
def test_main_defers_every_signal(
|
||
number: str,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
"""Закрытие терминала — SIGHUP: без обработчика команда обрывалась бы на
|
||
полпути."""
|
||
handlers: dict[int, Any] = {}
|
||
monkeypatch.setattr(
|
||
rotation.signal,
|
||
"signal",
|
||
lambda signum, handler: handlers.update({int(signum): handler}),
|
||
)
|
||
monkeypatch.setattr(rotation.Stand, "lock", lambda _self: None)
|
||
seen: list[str] = []
|
||
|
||
def command(stand: Any, _identity: str) -> None:
|
||
stand.begin_change("issue")
|
||
handlers[getattr(signal, number)](getattr(signal, number), None)
|
||
seen.append("finished")
|
||
|
||
monkeypatch.setattr(rotation, "cmd_leaf", command)
|
||
assert rotation.main(["leaf", "relay"]) == 0
|
||
assert seen == ["finished"]
|
||
|
||
|
||
def test_tool_failure_names_command(stand: RunStand) -> None:
|
||
stand.on("pki.sh revoke", (1, "a\nb\n", "c\nd\n"))
|
||
with pytest.raises(rotation.Failed) as error:
|
||
stand.pki("revoke", "relay")
|
||
assert str(error.value) == "pki.sh revoke: exit 1: b | c | d"
|
||
assert stand.calls[-1].env["PKI_STAND_DIR"] == str(stand.pki_dir)
|
||
assert "BAO_ADDRESS" in stand.calls[-1].env
|
||
|
||
|
||
def test_compose_failure_hides_output(stand: RunStand) -> None:
|
||
"""Вывод compose в ошибку не попадает: в нём бывают значения."""
|
||
stand.on("compose up", (1, "PASSWORD=secret", "secret"))
|
||
with pytest.raises(rotation.Failed) as error:
|
||
stand.compose_ok("up", "-d", "valkey", stdin="secret")
|
||
assert "secret" not in str(error.value)
|
||
assert "exit 1" in str(error.value)
|
||
|
||
|
||
# PKI -------------------------------------------------------------------------
|
||
|
||
|
||
def _pair(stand: RunStand, name: str = "haproxy.pem") -> None:
|
||
(stand.pki_dir / name).write_text(PEM + KEY)
|
||
stand.on("openssl verify", (0, "OK", ""))
|
||
stand.on("-pubkey", "PUBLIC\n")
|
||
stand.on("pkey -in", "PUBLIC\n")
|
||
|
||
|
||
def test_verify_material_leaf(stand: RunStand) -> None:
|
||
"""Пара для LB: цепочка по CA и CRL каталога стенда и соответствие ключа —
|
||
до отправки (пару другого CA LB принял бы)."""
|
||
_pair(stand)
|
||
assert stand.verify_material("haproxy.pem") == PEM + KEY
|
||
(verify,) = stand.texts("openssl verify")
|
||
path = stand.pki_dir
|
||
assert verify.endswith(
|
||
f"verify -CAfile {path}/ca.crt -crl_check -CRLfile {path}/crl.pem "
|
||
f"{path}/haproxy.pem",
|
||
)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("part", "answer", "reason"),
|
||
[
|
||
("openssl verify", (2, "", "error 23"), "does not verify"),
|
||
("pkey -in", "ANOTHER\n", "key does not match"),
|
||
("pkey -in", (1, "PUBLIC\n", ""), "key does not match"),
|
||
],
|
||
)
|
||
def test_verify_material_refuses_leaf(
|
||
part: str,
|
||
answer: Any,
|
||
reason: str,
|
||
stand: RunStand,
|
||
) -> None:
|
||
_pair(stand)
|
||
stand.on(part, answer)
|
||
with pytest.raises(rotation.Failed) as error:
|
||
stand.verify_material("haproxy.pem")
|
||
assert reason in str(error.value)
|
||
assert "BEGIN" not in str(error.value)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("answer", "good"),
|
||
[
|
||
((0, "", "verify OK\n"), True),
|
||
((0, "verify OK\n", ""), True),
|
||
((0, "", "verify failure\n"), False),
|
||
((1, "", "verify OK\n"), False),
|
||
((0, "", ""), False),
|
||
],
|
||
)
|
||
def test_verify_material_crl(answer: Any, good: bool, stand: RunStand) -> None:
|
||
"""CRL чужого CA openssl не считает ошибкой кода: решает «verify OK»."""
|
||
stand.on(" crl -in", answer)
|
||
if good:
|
||
assert stand.verify_material("crl.pem") == "CRL"
|
||
else:
|
||
with pytest.raises(rotation.Failed, match="not a CRL of the stand"):
|
||
stand.verify_material("crl.pem")
|
||
assert f"-CAfile {stand.pki_dir}/ca.crt" in stand.calls[-1].text
|
||
|
||
|
||
def test_lb_install_verifies_first(
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
sent: list[str] = []
|
||
|
||
def refuse(_name: str) -> str:
|
||
raise rotation.Failed("bad")
|
||
|
||
monkeypatch.setattr(stand, "lb", lambda text: sent.append(text) or "")
|
||
monkeypatch.setattr(stand, "verify_material", refuse)
|
||
for action in (
|
||
lambda: stand.lb_install_leaf("haproxy"),
|
||
stand.lb_install_crl,
|
||
stand.broker_install_crl,
|
||
):
|
||
with pytest.raises(rotation.Failed, match="bad"):
|
||
action()
|
||
assert sent == []
|
||
assert stand.calls == []
|
||
|
||
|
||
def test_status_names_revoked(stand: RunStand) -> None:
|
||
stand.on(
|
||
"pki.sh status",
|
||
"leaf relay: serial 1, not after x (90 days, REVOKED), sha256 A\n"
|
||
"leaf cleaner: serial 2, not after x (9 days, REVOKED, held until "
|
||
"make rotate_leaf IDENTITY=cleaner), sha256 B\n"
|
||
"leaf worker: serial 3, not after x (90 days, ok), sha256 C\n"
|
||
"leaf api-client: serial 4, not after x (90 days, ok), sha256 D\n"
|
||
"older leaf worker: 2 still valid and not revoked\n"
|
||
"CRL: next update x (30 days, ok), revoked 5\n",
|
||
)
|
||
stand.read_status()
|
||
assert stand.revoked == {"relay", "cleaner"}
|
||
assert stand.stopped() == {"relay", "cleaner"}
|
||
assert stand.left_alone({"relay", "worker", "api"}) == {"worker", "api"}
|
||
assert stand.older() == {"worker": 2}
|
||
assert stand.missing == set()
|
||
# каталог стенда создан заново: удержанной identity leaf не выдан
|
||
stand.on(
|
||
"pki.sh status",
|
||
"leaf relay: MISSING, held until infra/pki/pki.sh rotate relay (x)\n"
|
||
"leaf cleaner: MISSING (x)\n",
|
||
)
|
||
stand.read_status()
|
||
assert stand.missing == {"relay"}
|
||
assert stand.revoked == set()
|
||
stand.on("pki.sh status", (1, "", "no CA"))
|
||
with pytest.raises(rotation.NotReady, match="PKI is not ready"):
|
||
stand.read_status()
|
||
|
||
|
||
# состояние -------------------------------------------------------------------
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("rows", "problem"),
|
||
[
|
||
([], "has no container"),
|
||
(("running", "healthy", NEW), None),
|
||
(("running", None, NEW), None),
|
||
(("running", "unhealthy", NEW), "is unhealthy"),
|
||
(("running", "starting", NEW), "is starting"),
|
||
(("exited", "healthy", NEW), "is exited"),
|
||
(
|
||
[("running", "healthy", NEW), ("restarting", "healthy", NEW)],
|
||
"is restarting",
|
||
),
|
||
],
|
||
)
|
||
def test_service_problem(
|
||
rows: Any,
|
||
problem: str | None,
|
||
stand: RunStand,
|
||
) -> None:
|
||
stand.services(relay=rows)
|
||
got = stand.service_problem("relay")
|
||
assert got == (f"relay {problem}" if problem else None)
|
||
|
||
|
||
def _ready(stand: RunStand, **states: Any) -> None:
|
||
stand.services(
|
||
**{
|
||
"relay": ("running", None, NEW),
|
||
"haproxy": ("running", "healthy", NEW),
|
||
"rabbitmq": ("running", "healthy", NEW),
|
||
"openbao": ("running", "healthy", NEW),
|
||
"api": [("running", "healthy", NEW)] * 2,
|
||
**states,
|
||
},
|
||
)
|
||
stand.on("grep -c install-crl", "2\n")
|
||
stand.on("rolling-update.sh", "preconditions hold\n")
|
||
stand.on(
|
||
"exec -T haproxy bash",
|
||
lambda call: (
|
||
"Uptime: 1\n" if call.stdin == "show info\n" else SHOW_STAT
|
||
),
|
||
)
|
||
stand.seal_state = lambda: { # type: ignore[method-assign]
|
||
"initialized": True,
|
||
"sealed": False,
|
||
}
|
||
|
||
|
||
SHOW_STAT = (
|
||
"# pxname,svname,scur,status,addr\n"
|
||
"entry,FRONTEND,1,OPEN,\n"
|
||
"api,api-1,0,UP,10.0.0.1:8080\n"
|
||
"api,api-2,0,DOWN,10.0.0.2:8080\n"
|
||
"api,api-3,0,MAINT (resolution),\n"
|
||
"api,BACKEND,0,UP,\n"
|
||
"other,other-1,0,UP,10.0.0.9:8080\n"
|
||
"health,BACKEND,0,UP,\n"
|
||
)
|
||
|
||
|
||
def test_require_ready(stand: RunStand) -> None:
|
||
_ready(stand)
|
||
stand.require(
|
||
{"relay", "haproxy", "rabbitmq", "openbao", "api"},
|
||
replicas=True,
|
||
openbao=True,
|
||
)
|
||
assert stand.down == set()
|
||
(check,) = [c for c in stand.calls if "rolling-update.sh" in c.text]
|
||
assert check.env == {
|
||
"ROLLOUT_BUILD": "0",
|
||
"ROLLOUT_MIGRATE": "0",
|
||
"ROLLOUT_COMMIT": "",
|
||
"ROLLOUT_CHECK": "1",
|
||
}
|
||
|
||
|
||
@pytest.mark.parametrize("name", ["ca.crt", "crl.pem"])
|
||
def test_require_files(name: str, stand: RunStand) -> None:
|
||
_ready(stand)
|
||
(stand.pki_dir / name).unlink()
|
||
stand.missing = {"relay"}
|
||
with pytest.raises(rotation.NotReady, match=f"no {name}"):
|
||
stand.require(set())
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("state", "text"),
|
||
[
|
||
({"initialized": True, "sealed": True}, "make bao_unseal"),
|
||
({"initialized": False, "sealed": True}, "make bao_init"),
|
||
({}, "make bao_init"),
|
||
(OSError("refused"), "does not answer"),
|
||
],
|
||
)
|
||
def test_require_openbao(state: Any, text: str, stand: RunStand) -> None:
|
||
_ready(stand)
|
||
|
||
def seal_state() -> dict[str, Any]:
|
||
if isinstance(state, Exception):
|
||
raise state
|
||
return state
|
||
|
||
stand.seal_state = seal_state # type: ignore[method-assign]
|
||
with pytest.raises(rotation.NotReady, match=text):
|
||
stand.require({"relay"}, openbao=True)
|
||
# команде без OpenBao он не нужен
|
||
stand.require({"relay"})
|
||
|
||
|
||
def test_require_lb_and_broker(stand: RunStand) -> None:
|
||
_ready(stand)
|
||
stand.on("exec -T haproxy bash", "")
|
||
for services, replicas in (({"haproxy"}, False), (set(), True)):
|
||
with pytest.raises(rotation.NotReady, match="HAProxy runtime API"):
|
||
stand.require(services, replicas=replicas)
|
||
_ready(stand)
|
||
stand.on("grep -c install-crl", (1, "0\n", ""))
|
||
with pytest.raises(rotation.NotReady, match="restart rabbitmq"):
|
||
stand.require({"rabbitmq"})
|
||
stand.require({"relay"})
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("rows", "replaced", "ok"),
|
||
[
|
||
(("running", "unhealthy", NEW), True, True),
|
||
(("running", "starting", NEW), True, True),
|
||
(("restarting", None, NEW), True, True),
|
||
(("exited", None, NEW), True, False),
|
||
([], True, False),
|
||
([("running", None, NEW), ("exited", None, NEW)], True, False),
|
||
(("running", "unhealthy", NEW), False, False),
|
||
(("restarting", None, NEW), False, False),
|
||
],
|
||
)
|
||
def test_require_of_replaced_service(
|
||
rows: Any,
|
||
replaced: bool,
|
||
ok: bool,
|
||
stand: RunStand,
|
||
) -> None:
|
||
"""Повтор после сбоя: сервис, который команда заменит сама, может быть
|
||
неисправен, но не остановлен; у остальных нужна исправность."""
|
||
_ready(stand, relay=rows)
|
||
names = {"relay"} if replaced else set()
|
||
if ok:
|
||
stand.require({"relay"}, replaced=names)
|
||
assert stand.down == {"relay"}
|
||
else:
|
||
with pytest.raises(rotation.NotReady, match="run make run_docker"):
|
||
stand.require({"relay"}, replaced=names)
|
||
|
||
|
||
@pytest.mark.parametrize("status", ["restarting", "exited"])
|
||
def test_require_of_revoked_owner(status: str, stand: RunStand) -> None:
|
||
"""Владельца остановил отзыв: `rotate_leaf` его и вернёт; другой сервис с
|
||
отозванным leaf — с подсказкой."""
|
||
_ready(stand, rabbitmq=(status, None, NEW))
|
||
stand.require({"rabbitmq"}, owner="rabbitmq")
|
||
assert stand.down == {"rabbitmq"}
|
||
assert stand.texts("grep -c install-crl") == []
|
||
stand.down.clear()
|
||
stand.revoked = {"rabbitmq"}
|
||
with pytest.raises(
|
||
rotation.NotReady,
|
||
match="make rotate_leaf IDENTITY=rabbitmq",
|
||
):
|
||
stand.require({"rabbitmq"})
|
||
_ready(stand, rabbitmq=[])
|
||
with pytest.raises(rotation.NotReady, match="has no container"):
|
||
stand.require({"rabbitmq"}, owner="rabbitmq")
|
||
|
||
|
||
LB_HINT = (
|
||
"run make run_docker first; if the LB still has no ready replica: docker "
|
||
"compose restart haproxy api"
|
||
)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("service", "revoked", "hint"),
|
||
[
|
||
("relay", set(), "run make run_docker first"),
|
||
("relay", {"relay"}, "run make rotate_leaf IDENTITY=relay first"),
|
||
("worker", {"relay"}, "run make run_docker first"),
|
||
# LB без реплик: отозванную api-client вернёт её leaf, свой — тоже
|
||
(
|
||
"haproxy",
|
||
{"api-client"},
|
||
"run make rotate_leaf IDENTITY=api-client first",
|
||
),
|
||
(
|
||
"haproxy",
|
||
{"haproxy"},
|
||
"run make rotate_leaf IDENTITY=haproxy first",
|
||
),
|
||
# rotate_leaf api (и ingress) ждёт LB: подсказка вела бы по кругу
|
||
("haproxy", set(), LB_HINT),
|
||
("haproxy", {"api"}, LB_HINT),
|
||
("haproxy", {"ingress"}, LB_HINT),
|
||
(
|
||
"haproxy",
|
||
{"api", "api-client"},
|
||
"run make rotate_leaf IDENTITY=api-client first",
|
||
),
|
||
(
|
||
"haproxy",
|
||
{"api-client", "haproxy"},
|
||
"run make rotate_leaf IDENTITY=api-client first",
|
||
),
|
||
("api", {"api"}, "run make rotate_leaf IDENTITY=api first"),
|
||
("relay", {"api-client"}, "run make run_docker first"),
|
||
("haproxy", {"relay"}, LB_HINT),
|
||
("haproxy", {"mallory"}, LB_HINT),
|
||
("relay", {"mallory"}, "run make run_docker first"),
|
||
],
|
||
)
|
||
def test_hint(
|
||
service: str,
|
||
revoked: set[str],
|
||
hint: str,
|
||
stand: RunStand,
|
||
) -> None:
|
||
"""Подсказка ведёт к выходу, а не по кругу (сценарий «Отозванная identity
|
||
реплик после остановки»)."""
|
||
name = service.replace("-", "_")
|
||
_ready(stand, **{name: ("running", "unhealthy", NEW)})
|
||
stand.revoked = revoked
|
||
with pytest.raises(rotation.NotReady) as error:
|
||
stand.require({service})
|
||
assert str(error.value) == f"{service} is unhealthy: {hint}"
|
||
|
||
|
||
def test_recreated_stand_directory(stand: RunStand) -> None:
|
||
"""Сценарий «Каталог стенда создан заново»: файлов удержанной identity нет
|
||
— отказ любой команды раньше всего, и на исправном работающем стенде тоже;
|
||
цепочка — та же, что печатает pki.sh."""
|
||
_ready(stand)
|
||
stand.missing = {"relay", "cleaner"}
|
||
for services in (set(), {"haproxy"}, {"relay"}):
|
||
with pytest.raises(rotation.NotReady) as error:
|
||
stand.require(services, replaced={"relay"}, owner="relay")
|
||
assert str(error.value) == (
|
||
"no files of the revoked cleaner, relay in the stand directory: "
|
||
"run infra/pki/pki.sh rotate cleaner; infra/pki/pki.sh rotate "
|
||
"relay; make stop; make bao_unseal; make run_docker; make "
|
||
"pki_renew"
|
||
)
|
||
assert stand.calls == []
|
||
script = (BASE_DIR / "infra" / "pki" / "pki.sh").read_text()
|
||
assert f"$(held_missing){'; '.join(rotation.RECREATED_STEPS)}" in script
|
||
|
||
|
||
@pytest.mark.parametrize("missing", ["worker", "openbao", "api"])
|
||
@pytest.mark.parametrize(
|
||
"command",
|
||
[
|
||
"leaf relay",
|
||
"leaf openbao",
|
||
"leaf api",
|
||
"revoke relay",
|
||
"renew",
|
||
"secret postgres/worker",
|
||
],
|
||
)
|
||
def test_command_in_a_recreated_stand_directory(
|
||
command: str,
|
||
missing: str,
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Сценарий «Каталог стенда создан заново»: сертификата удержанной нет —
|
||
каждая команда читает статус PKI и отказывает с цепочкой до изменений: код
|
||
2, кроме чтения статуса не запущено ничего, `.env` прежний."""
|
||
_ready(stand, worker=("running", None, NEW))
|
||
stand.on(
|
||
"pki.sh status",
|
||
f"leaf {missing}: MISSING, held until infra/pki/pki.sh rotate "
|
||
f"{missing} (x)\n",
|
||
)
|
||
stand.env_file = stand.pki_dir / ".env"
|
||
env = "POSTGRES_WORKER_PASSWORD=0123456789abcdef\n"
|
||
stand.env_file.write_text(env)
|
||
monkeypatch.delenv("POSTGRES_WORKER_PASSWORD", raising=False)
|
||
name, *args = command.split()
|
||
call = getattr(rotation, f"cmd_{name}")
|
||
assert rotation.execute(stand, lambda: call(stand, *args)) == 2 # noqa: PLR2004
|
||
steps = "; ".join(rotation.RECREATED_STEPS)
|
||
assert capsys.readouterr().out == (
|
||
f"rotation: no files of the revoked {missing} in the stand directory: "
|
||
f"run infra/pki/pki.sh rotate {missing}; {steps}; nothing changed\n"
|
||
)
|
||
assert stand.changed is False
|
||
assert [c.text.split("pki.sh ")[-1] for c in stand.calls] == ["status"]
|
||
assert stand.env_file.read_text() == env
|
||
|
||
|
||
def _rollout_refuses(stand: RunStand) -> None:
|
||
stand.on("rolling-update.sh", (2, "", "error: replica x is not UP\n"))
|
||
|
||
|
||
def test_require_replicas_refused(stand: RunStand) -> None:
|
||
"""Предусловие замены не выполнено, а LB обслуживает хоть одна реплика —
|
||
код 2 со строкой скрипта."""
|
||
_ready(stand)
|
||
_rollout_refuses(stand)
|
||
with pytest.raises(rotation.NotReady, match="replica x is not UP"):
|
||
stand.require({"api"}, replicas=True)
|
||
|
||
|
||
def test_require_replicas_down(stand: RunStand) -> None:
|
||
"""Ни одной реплики в LB: заменять поочерёдно нечего, перезапуск всех."""
|
||
_ready(stand, api=[("running", "unhealthy", NEW)] * 2)
|
||
_rollout_refuses(stand)
|
||
down = SHOW_STAT.replace("api,api-1,0,UP", "api,api-1,0,DOWN")
|
||
stand.on(
|
||
"exec -T haproxy bash",
|
||
lambda call: "Uptime: 1\n" if call.stdin == "show info\n" else down,
|
||
)
|
||
stand.require({"api"}, replaced={"api"}, replicas=True)
|
||
assert stand.down == {"api"}
|
||
before = len(stand.texts("rolling-update.sh"))
|
||
stand.services(api=[("running", "healthy", OLD)] * 2)
|
||
stand.restart = lambda name: stand.calls.append( # type: ignore[method-assign]
|
||
Call(["restarted", name], {}),
|
||
)
|
||
stand.replace_replicas()
|
||
assert len(stand.texts("rolling-update.sh")) == before
|
||
assert stand.texts("restarted api")
|
||
assert stand.down == set()
|
||
# следующая замена в той же команде — снова поочерёдная
|
||
stand.on("rolling-update.sh", "12 rolling-update: x done: 2 replicas\n")
|
||
stand.replace_replicas()
|
||
assert len(stand.texts("rolling-update.sh")) == before + 1
|
||
|
||
|
||
def test_require_replicas_unhealthy_but_replaceable(stand: RunStand) -> None:
|
||
"""Реплика `unhealthy`, но предусловия поочерёдной замены выполнены —
|
||
замена поочерёдная, а не перезапуск всех разом."""
|
||
_ready(
|
||
stand,
|
||
api=[("running", "healthy", NEW), ("running", "unhealthy", NEW)],
|
||
)
|
||
stand.require({"api"}, replaced={"api"}, replicas=True)
|
||
assert stand.down == set()
|
||
|
||
|
||
def test_require_replicas_of_revoked_owner(stand: RunStand) -> None:
|
||
"""`api-client` отозвана, и часть реплик её лишилась: поочерёдная замена
|
||
невозможна, новый leaf им даёт перезапуск."""
|
||
_ready(stand, api=[("running", "healthy", NEW), ("exited", None, NEW)])
|
||
_rollout_refuses(stand)
|
||
stand.require({"api"}, owner="api", replicas=True)
|
||
assert stand.down == {"api"}
|
||
|
||
|
||
def test_require_replicas_needs_lb_answer(stand: RunStand) -> None:
|
||
_ready(stand)
|
||
_rollout_refuses(stand)
|
||
stand.on(
|
||
"exec -T haproxy bash",
|
||
lambda call: "Uptime: 1\n" if call.stdin == "show info\n" else "",
|
||
)
|
||
with pytest.raises(rotation.NotReady, match="does not answer"):
|
||
stand.require({"api"}, replicas=True)
|
||
|
||
|
||
def test_replicas_up_counts_servers_only(stand: RunStand) -> None:
|
||
_ready(stand)
|
||
assert stand.replicas_up() == 1
|
||
|
||
|
||
# реплики и перезапуск --------------------------------------------------------
|
||
|
||
|
||
def test_replace_replicas(
|
||
stand: RunStand,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Замена — без сборки и миграций, с блокировкой команды; строка итога —
|
||
в вывод."""
|
||
stand.lock_file = 7
|
||
stand.on(
|
||
"rolling-update.sh",
|
||
"1 rolling-update: start\n2 rolling-update: done: 2 replicas\n",
|
||
)
|
||
stand.replace_replicas()
|
||
(call,) = stand.calls
|
||
assert call.env == {
|
||
"ROLLOUT_BUILD": "0",
|
||
"ROLLOUT_MIGRATE": "0",
|
||
"ROLLOUT_COMMIT": "",
|
||
"ROLLOUT_CHECK": "0",
|
||
}
|
||
assert call.kwargs["keep"] == 7 # noqa: PLR2004
|
||
assert call.kwargs["output"] is not None
|
||
assert "api: done: 2 replicas" in capsys.readouterr().out
|
||
|
||
|
||
def test_replace_replicas_failure(stand: RunStand) -> None:
|
||
stand.on(
|
||
"rolling-update.sh",
|
||
(1, "1 rolling-update: start\n", "2 rolling-update: error: x\nend\n"),
|
||
)
|
||
with pytest.raises(rotation.Failed) as error:
|
||
stand.replace_replicas()
|
||
assert "exit 1" in str(error.value)
|
||
assert "error: x" in str(error.value)
|
||
|
||
|
||
RECORD = '{"event": "Started relay"}\n'
|
||
|
||
|
||
def test_wait_ready(stand: RunStand) -> None:
|
||
"""Готов — контейнер, стартовавший заново, работает, healthy, а процесс
|
||
без healthcheck написал запись старта."""
|
||
states = [
|
||
[("running", None, OLD)],
|
||
[("restarting", None, NEW)],
|
||
[],
|
||
[("running", None, NEW)],
|
||
[("running", None, NEW)],
|
||
]
|
||
logs = ["", RECORD]
|
||
|
||
def step(call: Call) -> str:
|
||
stand.services(relay=states.pop(0) if states else [])
|
||
stand.on("compose ps -a -q --no-trunc", step)
|
||
return "\n".join(stand.ids["relay"])
|
||
|
||
stand.on("compose ps -a -q --no-trunc", step)
|
||
stand.on("docker logs", lambda _call: logs.pop(0))
|
||
stand.wait_ready("relay", {OLD})
|
||
assert states == []
|
||
assert logs == []
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"rows",
|
||
[
|
||
[("running", None, OLD)],
|
||
[("running", "unhealthy", NEW)],
|
||
[("running", "starting", NEW)],
|
||
[("exited", None, NEW)],
|
||
[("running", None, NEW), ("running", None, OLD)],
|
||
[],
|
||
],
|
||
)
|
||
def test_wait_ready_times_out(rows: Any, stand: RunStand) -> None:
|
||
stand.services(relay=rows)
|
||
stand.on("docker logs", RECORD)
|
||
with pytest.raises(rotation.Failed, match="relay is not ready"):
|
||
stand.wait_ready("relay", {OLD})
|
||
assert stand.clock >= rotation.READY_TIMEOUT_SECONDS
|
||
|
||
|
||
def test_wait_ready_needs_the_record(stand: RunStand) -> None:
|
||
"""Без записи старта процесс не готов, даже если контейнер работает; у
|
||
сервиса с healthcheck и у чужого процесса запись не нужна."""
|
||
stand.services(
|
||
relay=("running", None, NEW),
|
||
api=("running", "healthy", NEW),
|
||
otel_collector=("running", None, NEW),
|
||
)
|
||
stand.on("docker logs", '{"event": "Loaded process secrets"}')
|
||
with pytest.raises(rotation.Failed):
|
||
stand.wait_ready("relay", {OLD})
|
||
stand.wait_ready("api", {OLD})
|
||
stand.wait_ready("otel-collector", {OLD})
|
||
|
||
|
||
def test_restart_waits_for_dependents(
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
"""Перезапуск шлюза перезапускает и его хранилище: ждут оба, «заново» —
|
||
относительно старта до перезапуска."""
|
||
stand.services(
|
||
otel_gateway=("running", "healthy", OLD),
|
||
otel_collector=("running", None, NEW),
|
||
)
|
||
waited: list[tuple[str, set[str]]] = []
|
||
monkeypatch.setattr(
|
||
stand,
|
||
"wait_ready",
|
||
lambda name, before: waited.append((name, before)),
|
||
)
|
||
stand.restart("otel-gateway")
|
||
assert stand.texts("compose restart") == [
|
||
"docker compose restart otel-gateway",
|
||
]
|
||
assert waited == [("otel-gateway", {OLD}), ("otel-collector", {NEW})]
|
||
stand.on("compose restart", (1, "", ""))
|
||
with pytest.raises(rotation.Failed):
|
||
stand.restart("otel-gateway")
|
||
|
||
|
||
# владелец --------------------------------------------------------------------
|
||
|
||
|
||
def _written(stand: RunStand, identity: str, moment: str) -> None:
|
||
path = stand.pki_dir / f"{identity}.crt"
|
||
path.write_text(PEM)
|
||
stamp = rotation.parse_time(moment).timestamp()
|
||
os.utime(path, (stamp, stamp))
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("rows", "current"),
|
||
[
|
||
(("running", None, NEW), True),
|
||
(("running", None, OLD), False),
|
||
([("running", None, NEW), ("running", None, OLD)], False),
|
||
([], False),
|
||
],
|
||
)
|
||
def test_owner_current_by_start(
|
||
rows: Any,
|
||
current: bool,
|
||
stand: RunStand,
|
||
) -> None:
|
||
"""Перезапускаемый владелец — на новом leaf, если все его контейнеры
|
||
запущены позже файла."""
|
||
_written(stand, "relay", "2026-12-01T02:30:00Z")
|
||
stand.services(relay=rows)
|
||
stand.on("-serial", "serial=01AB\n")
|
||
assert stand.owner_current("relay") is current
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("served", "current"),
|
||
[("01AB", True), ("1AB", True), ("01AC", False), ("", False)],
|
||
)
|
||
def test_owner_current_by_served_serial(
|
||
served: str,
|
||
current: bool,
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
"""LB и брокер — по серийному номеру, который они отдают: они не
|
||
перезапускаются."""
|
||
for identity in ("haproxy", "rabbitmq"):
|
||
_written(stand, identity, OLD)
|
||
stand.services(
|
||
haproxy=("running", "healthy", NEW),
|
||
rabbitmq=("running", "healthy", NEW),
|
||
)
|
||
stand.on("-serial", "serial=01AB\n")
|
||
stand.on("exec -T haproxy bash", f"Filename: x\nSerial: {served}\n")
|
||
monkeypatch.setattr(stand, "broker_serial", lambda: served)
|
||
assert stand.owner_current("haproxy") is current
|
||
assert stand.owner_current("rabbitmq") is current
|
||
(call,) = [c for c in stand.calls if "exec -T haproxy" in c.text]
|
||
assert call.stdin == "show ssl cert /run/secrets/haproxy.pem\n"
|
||
|
||
|
||
@pytest.mark.parametrize("identity", ["migrate", "bao-operator"])
|
||
def test_owner_current_without_process(
|
||
identity: str,
|
||
stand: RunStand,
|
||
) -> None:
|
||
assert stand.owner_current(identity) is True
|
||
assert stand.calls == []
|
||
|
||
|
||
def test_apply_owner(
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
done: list[str] = []
|
||
monkeypatch.setattr(stand, "lb_install_leaf", lambda n: done.append(n))
|
||
monkeypatch.setattr(
|
||
stand,
|
||
"broker_install_leaf",
|
||
lambda: done.append("broker"),
|
||
)
|
||
monkeypatch.setattr(
|
||
stand,
|
||
"replace_replicas",
|
||
lambda: done.append("replicas"),
|
||
)
|
||
monkeypatch.setattr(
|
||
stand,
|
||
"restart",
|
||
lambda name: done.append(f"restart {name}") or 1.0,
|
||
)
|
||
for identity in ("haproxy", "ingress", "rabbitmq", "api", "api-client"):
|
||
stand.apply_owner(identity)
|
||
stand.apply_owner("relay")
|
||
stand.apply_owner("migrate")
|
||
assert done == [
|
||
"haproxy",
|
||
"ingress",
|
||
"broker",
|
||
"replicas",
|
||
"replicas",
|
||
"restart relay",
|
||
]
|
||
|
||
|
||
# брокер ----------------------------------------------------------------------
|
||
|
||
|
||
def test_broker_install_leaf(stand: RunStand) -> None:
|
||
"""Ключ — только stdin; после пары сброс кэша OTP, иначе узел ещё до двух
|
||
минут отдавал бы прежнюю."""
|
||
(stand.pki_dir / "rabbitmq.crt").write_text(PEM)
|
||
(stand.pki_dir / "rabbitmq.key").write_text(KEY)
|
||
stand.on("-serial", "serial=01AB\n")
|
||
stand.broker_install_leaf()
|
||
install, clear = stand.calls[0], stand.calls[1]
|
||
assert install.text.endswith("--install-leaf")
|
||
assert install.stdin == PEM + KEY
|
||
assert "BEGIN" not in install.text
|
||
assert clear.text.endswith("rabbitmqctl -q eval ssl:clear_pem_cache().")
|
||
stand.on("--install-leaf", (1, "", "x\nkey does not match\n"))
|
||
with pytest.raises(rotation.Failed, match="key does not match"):
|
||
stand.broker_install_leaf()
|
||
|
||
|
||
def test_broker_install_crl(
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
monkeypatch.setattr(stand, "verify_material", lambda name: f"PEM {name}")
|
||
stand.broker_install_crl()
|
||
(call,) = stand.calls
|
||
assert call.text.endswith("start.sh --install-crl")
|
||
assert call.stdin == "PEM crl.pem"
|
||
|
||
|
||
LISTING = (
|
||
"<rabbit@localhost.1.2.0>\trelay\tnew\n"
|
||
"<rabbit@localhost.1.3.0>\trelay\told\n"
|
||
"ok\n"
|
||
)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("keep", "closed"),
|
||
[
|
||
(
|
||
None,
|
||
'"<rabbit@localhost.1.2.0>", "<rabbit@localhost.1.3.0>"',
|
||
),
|
||
("new", '"<rabbit@localhost.1.3.0>"'),
|
||
],
|
||
)
|
||
def test_broker_close(keep: str | None, closed: str, stand: RunStand) -> None:
|
||
"""Отзыв закрывает все соединения пользователя, ротация — не новые. Учёт
|
||
соединений, а не `list_connections`: тот ждёт каждое входящее."""
|
||
stand.on("list_of_user", LISTING)
|
||
pids = stand.broker_close("relay", keep)
|
||
listing, closing = stand.texts("rabbitmqctl -q eval")
|
||
assert 'list_of_user(<<"relay">>)' in listing
|
||
assert "list_connections" not in listing
|
||
assert ("peer_cert_validity" in listing) is (keep is not None)
|
||
assert f"S <- [{closed}]" in closing
|
||
assert "close_connection" in closing
|
||
assert ", ".join(f'"{pid}"' for pid in pids) == closed
|
||
|
||
|
||
def test_broker_close_nothing(stand: RunStand) -> None:
|
||
stand.on("list_of_user", "ok\n")
|
||
assert stand.broker_close("relay", None) == []
|
||
assert len(stand.calls) == 1
|
||
stand.on("list_of_user", (69, "", "node is down\n"))
|
||
with pytest.raises(rotation.Failed, match="node is down"):
|
||
stand.broker_close("relay", None)
|
||
|
||
|
||
def test_broker_late(
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Сценарий «Соединение, начатое до отзыва»: закрытие повторяется до конца
|
||
сроков входа брокера, последнее — после них, для каждого пользователя."""
|
||
passes: list[tuple[float, str, str | None]] = []
|
||
|
||
def close(user: str, keep: str | None) -> list[str]:
|
||
passes.append((stand.clock, user, keep))
|
||
# закрываемое остаётся в учёте и в следующем проходе
|
||
return ["pid"] if len(passes) in (5, 7) else []
|
||
|
||
stand.clock = 100.0
|
||
monkeypatch.setattr(stand, "broker_close", close)
|
||
stand.broker_late({"worker": None, "relay": "new"}, 95.0)
|
||
assert {(user, keep) for _, user, keep in passes} == {
|
||
("relay", "new"),
|
||
("worker", None),
|
||
}
|
||
moments = sorted({moment for moment, _, _ in passes})
|
||
assert moments[0] == 100.0 # noqa: PLR2004
|
||
assert moments[-1] >= 95.0 + rotation.BROKER_LATE_SECONDS
|
||
assert moments[-2] < 95.0 + rotation.BROKER_LATE_SECONDS
|
||
gaps = [b - a for a, b in zip(moments, moments[1:], strict=False)]
|
||
assert max(gaps) <= 1
|
||
assert [user for moment, user, _ in passes if moment == moments[-1]] == [
|
||
"relay",
|
||
"worker",
|
||
]
|
||
assert "closed: 1" in capsys.readouterr().out
|
||
|
||
|
||
def test_broker_late_covers_the_broker_limits() -> None:
|
||
"""Сроки брокера на вход — умолчания (5 с TLS, 10 с AMQP): конфигурация
|
||
стенда их не меняет, а закрытие ждёт дольше их суммы."""
|
||
assert rotation.BROKER_LATE_SECONDS > 5 + 10
|
||
for name in ("rabbitmq.conf", "advanced.config"):
|
||
text = (BASE_DIR / "infra" / "rabbitmq" / name).read_text()
|
||
assert "handshake_timeout" not in text
|
||
|
||
|
||
def test_apply_crl_closes_late_connections(
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
"""Отсчёт — от нового CRL у брокера; поздние соединения — последний шаг."""
|
||
done: list[str] = []
|
||
late: list[tuple[dict[str, Any], float]] = []
|
||
|
||
def crl() -> None:
|
||
stand.clock += 3
|
||
done.append("crl")
|
||
|
||
monkeypatch.setattr(stand, "broker_install_crl", crl)
|
||
monkeypatch.setattr(stand, "broker_close", lambda *_a: [])
|
||
monkeypatch.setattr(
|
||
stand,
|
||
"restart",
|
||
lambda name: done.append(name),
|
||
)
|
||
monkeypatch.setattr(
|
||
stand,
|
||
"broker_late",
|
||
lambda users, at: late.append((users, at)),
|
||
)
|
||
stand.apply_crl({"rabbitmq", "otel-gateway"}, {"relay": None})
|
||
assert done == ["crl", "otel-gateway"]
|
||
assert late == [({"relay": None}, 3.0)]
|
||
assert stand.phase == "late connections"
|
||
late.clear()
|
||
stand.apply_crl({"otel-gateway"}, {"relay": None})
|
||
stand.apply_crl({"rabbitmq"}, {"cleaner": None})
|
||
assert late == []
|
||
|
||
|
||
# PostgreSQL ------------------------------------------------------------------
|
||
|
||
|
||
def test_close_sessions(
|
||
stand: RunStand,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Сценарий «Вход, начатый до смены пароля»: закрываются и сессии роли, и
|
||
входы без роли, начатые раньше смены; повтор — пока не останется."""
|
||
answers = ["3\n", "1\n", "0\n"]
|
||
stand.on("exec -T postgres", lambda _call: answers.pop(0))
|
||
stand.close_sessions("cleaner", "T1")
|
||
assert answers == []
|
||
for call in stand.calls:
|
||
sql = call.stdin
|
||
assert sql.startswith("SELECT count(pg_terminate_backend(pid))")
|
||
where = sql.split("WHERE ", 1)[1]
|
||
assert where == (
|
||
"backend_start < 'T1'::timestamptz AND "
|
||
"backend_type = 'client backend' AND "
|
||
"(usename = 'cleaner' OR "
|
||
"(usename IS NULL AND state = 'starting'));"
|
||
)
|
||
assert "SELECT" not in call.text
|
||
assert "closed: 3, left: 0" in capsys.readouterr().out
|
||
|
||
|
||
def test_close_sessions_left(stand: RunStand) -> None:
|
||
stand.on("exec -T postgres", "2\n")
|
||
with pytest.raises(rotation.Failed, match="2 sessions of role api"):
|
||
stand.close_sessions("api", "T1")
|
||
stand.on("exec -T postgres", (1, "", "FATAL"))
|
||
with pytest.raises(rotation.Failed):
|
||
stand.close_sessions("api", "T1")
|
||
|
||
|
||
# секрет ----------------------------------------------------------------------
|
||
|
||
|
||
def _outcomes(
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
outcomes: list[tuple[str, str]],
|
||
) -> None:
|
||
def login(*_args: Any) -> dict[str, str]:
|
||
old, new = outcomes.pop(0) if len(outcomes) > 1 else outcomes[0]
|
||
return {"old": old, "new": new}
|
||
|
||
monkeypatch.setattr(stand, "login_outcomes", login)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("path", "refusal"),
|
||
[
|
||
("postgres/api", "28P01"),
|
||
("valkey/api", "WRONGPASS"),
|
||
("s3/api", "InvalidAccessKeyId"),
|
||
],
|
||
)
|
||
def test_check_values(
|
||
path: str,
|
||
refusal: str,
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
"""Отказ — именно этого хранилища: другая причина (сеть, TLS) ничего не
|
||
доказывает; ключу S3 даётся срок дойти до шлюза."""
|
||
_outcomes(stand, monkeypatch, [("ok", "ok"), (refusal, "ok")])
|
||
stand.check_values(path, {}, {})
|
||
assert stand.clock > 0
|
||
for wrong in (
|
||
("ok", "ok"),
|
||
("TimeoutError", "ok"),
|
||
(refusal, refusal),
|
||
(refusal, "TimeoutError"),
|
||
):
|
||
_outcomes(stand, monkeypatch, [wrong])
|
||
began = stand.clock
|
||
with pytest.raises(rotation.Failed, match="previous value"):
|
||
stand.check_values(path, {}, {})
|
||
assert stand.clock - began >= rotation.KEY_GONE_TIMEOUT_SECONDS
|
||
|
||
|
||
def test_login_outcomes(stand: RunStand) -> None:
|
||
"""Значения — только stdin одноразового контейнера сервиса."""
|
||
stand.on("compose run", 'warning\n{"old": "28P01", "new": "ok"}\n')
|
||
got = stand.login_outcomes(
|
||
"postgres/cleaner",
|
||
{"password": "old-value"},
|
||
{"password": "new-value"},
|
||
)
|
||
assert got == {"old": "28P01", "new": "ok"}
|
||
(call,) = stand.calls
|
||
assert call.args[2:9] == [
|
||
"run",
|
||
"--rm",
|
||
"--no-deps",
|
||
"-T",
|
||
"--entrypoint",
|
||
"python",
|
||
"cleaner",
|
||
]
|
||
assert "-value" not in call.text
|
||
assert json.loads(call.stdin) == {
|
||
"name": "cleaner",
|
||
"old": {"password": "old-value"},
|
||
"new": {"password": "new-value"},
|
||
}
|
||
|
||
|
||
def _loaded(version: int, path: str = "postgres/api") -> str:
|
||
record = {"event": "Loaded process secrets", "versions": {path: version}}
|
||
return json.dumps(record) + "\n"
|
||
|
||
|
||
def test_apply_secret(
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
"""Реплики — поочерёдной заменой, остальные — перезапуском; затем запись
|
||
каждого контейнера с нужной версией."""
|
||
done: list[str] = []
|
||
monkeypatch.setattr(
|
||
stand,
|
||
"replace_replicas",
|
||
lambda: done.append("replicas"),
|
||
)
|
||
monkeypatch.setattr(stand, "restart", lambda name: done.append(name))
|
||
stand.services(
|
||
api=[("running", "healthy", NEW)] * 2,
|
||
worker=("running", None, NEW),
|
||
)
|
||
first, second = stand.ids["api"]
|
||
logs = {first: [_loaded(5)], second: ["", _loaded(4), _loaded(5)]}
|
||
|
||
def log(call: Call) -> str:
|
||
assert call.args[:4] == ["docker", "logs", "--since", NEW]
|
||
found = logs.get(call.args[-1], [_loaded(5)])
|
||
return found.pop(0) if len(found) > 1 else found[0]
|
||
|
||
stand.on("docker logs", log)
|
||
stand.apply_secret("api", "postgres/api", 5)
|
||
assert logs[second] == [_loaded(5)]
|
||
stand.apply_secret("worker", "postgres/api", 5)
|
||
assert done == ["replicas", "worker"]
|
||
for text in (_loaded(4), _loaded(5, "s3/api"), ""):
|
||
logs[second] = [text]
|
||
with pytest.raises(rotation.Failed, match="did not load"):
|
||
stand.apply_secret("api", "postgres/api", 5)
|
||
stand.services(worker=[])
|
||
with pytest.raises(rotation.Failed, match="did not load"):
|
||
stand.apply_secret("worker", "postgres/api", 5)
|
||
|
||
|
||
def _kv(versions: dict[str, Any], differs: set[str]) -> str:
|
||
lines = [
|
||
f"kv messenger/{path}: version {version.number}, "
|
||
+ ("differs" if path in differs else "unchanged")
|
||
+ f", created {version.created}"
|
||
for path, version in versions.items()
|
||
]
|
||
return "\n".join([*lines, "seed: 0 of 9 paths written"])
|
||
|
||
|
||
def _versions(number: int, created: str = OLD) -> dict[str, Any]:
|
||
return dict.fromkeys(
|
||
rotation.SECRETS,
|
||
rotation.KvVersion(number, created),
|
||
)
|
||
|
||
|
||
def test_kv_state(stand: RunStand) -> None:
|
||
versions = _versions(3)
|
||
stand.on("seed --check", _kv(versions, {"postgres/worker"}))
|
||
assert stand.kv_state() == (versions, {"postgres/worker"})
|
||
stand.on(
|
||
"seed --check",
|
||
_kv(versions, set()).replace(
|
||
f"s3/api: version 3, unchanged, created {OLD}",
|
||
"s3/api: version None, differs, created None",
|
||
),
|
||
)
|
||
absent = rotation.KvVersion(0, "")
|
||
assert stand.kv_state() == (versions | {"s3/api": absent}, {"s3/api"})
|
||
# пути нет — версии нет, и позже старта процесса она быть не может
|
||
assert absent.newer_than(OLD) is False
|
||
versions.pop("s3/api")
|
||
stand.on("seed --check", _kv(versions, set()))
|
||
with pytest.raises(rotation.Failed):
|
||
stand.kv_state()
|
||
|
||
|
||
def test_seed(stand: RunStand) -> None:
|
||
stand.on(
|
||
"bao.py seed",
|
||
"kv messenger/s3/api: version 4, written\n"
|
||
"kv messenger/postgres/api: version 2, unchanged\n",
|
||
)
|
||
assert stand.seed() == {"s3/api": 4}
|
||
|
||
|
||
def _lag_stand(stand: RunStand, logs: dict[str, str]) -> None:
|
||
stand.services(
|
||
api=[("running", "healthy", NEW)] * 2,
|
||
relay=("running", None, NEW),
|
||
worker=("restarting", None, NEW),
|
||
cleaner=("running", None, NEW),
|
||
)
|
||
|
||
def log(call: Call) -> str:
|
||
for name, ids in stand.ids.items():
|
||
if call.args[-1] in ids:
|
||
index = ids.index(call.args[-1])
|
||
return logs.get(f"{name}{index}", logs.get(name, ""))
|
||
raise AssertionError(call.text)
|
||
|
||
stand.on("docker logs", log)
|
||
|
||
|
||
def _record(**versions: int) -> str:
|
||
found = {
|
||
name.replace("__", "/"): value for name, value in versions.items()
|
||
}
|
||
return (
|
||
json.dumps({"event": "Loaded process secrets", "versions": found})
|
||
+ "\n"
|
||
)
|
||
|
||
|
||
def test_lagging(stand: RunStand) -> None:
|
||
"""Отстаёт процесс, чья запись — не версия KV его пути (хоть одна реплика);
|
||
неработающий прочитает KV при старте."""
|
||
# запись сильнее времени: версии созданы позже старта
|
||
versions = _versions(2, "2026-12-01T04:00:00Z")
|
||
good = {
|
||
"api": _record(postgres__api=2, valkey__api=2, s3__api=2),
|
||
"relay": _record(postgres__relay=2),
|
||
"cleaner": _record(postgres__cleaner=2, s3__cleaner=2),
|
||
"worker": _record(postgres__worker=1, s3__worker=1),
|
||
}
|
||
_lag_stand(stand, good)
|
||
assert stand.lagging(versions) == {}
|
||
assert stand.clock == 0
|
||
late = _record(postgres__api=1, valkey__api=2, s3__api=2)
|
||
_lag_stand(
|
||
stand,
|
||
{**good, "api1": late, "cleaner": _record(postgres__cleaner=2)},
|
||
)
|
||
assert stand.lagging(versions) == {
|
||
"api": {"postgres/api"},
|
||
"cleaner": {"s3/cleaner"},
|
||
}
|
||
# отстала первая реплика, а не последняя
|
||
_lag_stand(stand, {**good, "api0": late})
|
||
assert stand.lagging(versions) == {"api": {"postgres/api"}}
|
||
_lag_stand(stand, {**good, "relay": _record(postgres__relay=3)})
|
||
assert stand.lagging(versions) == {"relay": {"postgres/relay"}}
|
||
|
||
|
||
def test_lagging_without_the_record(stand: RunStand) -> None:
|
||
"""Сценарий «Запись о загрузке вытеснена из журнала»: записи нет —
|
||
процесс, запущенный раньше версии, отстал (после срока старта), а
|
||
запущенный позже прочитал её: долго работающая реплика с вытесненной
|
||
записью не отстаёт и ждать её незачем."""
|
||
_lag_stand(stand, {})
|
||
assert stand.lagging(_versions(2, OLD)) == {}
|
||
assert stand.clock == 0
|
||
later = "2026-12-01T03:00:00.000001Z"
|
||
versions = _versions(2, OLD)
|
||
versions["postgres/relay"] = rotation.KvVersion(3, later)
|
||
versions["postgres/api"] = rotation.KvVersion(3, later)
|
||
assert stand.lagging(versions) == {
|
||
"api": {"postgres/api"},
|
||
"relay": {"postgres/relay"},
|
||
}
|
||
assert stand.clock >= rotation.LOADED_TIMEOUT_SECONDS
|
||
|
||
|
||
def test_lagging_waits_for_the_record(stand: RunStand) -> None:
|
||
"""Процесс, запущенный раньше версии, ещё стартует: запись появится, и
|
||
решает она, а не время — обе стороны."""
|
||
versions = _versions(2, "2026-12-01T04:00:00Z")
|
||
other = {
|
||
"api": _record(postgres__api=2, valkey__api=2, s3__api=2),
|
||
"cleaner": _record(postgres__cleaner=2, s3__cleaner=2),
|
||
}
|
||
for loaded, want in ((2, {}), (1, {"relay": {"postgres/relay"}})):
|
||
answers = ["", "", _record(postgres__relay=loaded)]
|
||
_lag_stand(stand, other)
|
||
stand.services(
|
||
api=[("running", "healthy", NEW)] * 2,
|
||
relay=("running", None, NEW),
|
||
cleaner=("running", None, NEW),
|
||
)
|
||
(relay,) = stand.ids["relay"]
|
||
|
||
def log(
|
||
call: Call,
|
||
relay: str = relay,
|
||
answers: list[str] = answers,
|
||
) -> str:
|
||
if call.args[-1] == relay:
|
||
return answers.pop(0)
|
||
name = next(n for n, i in stand.ids.items() if call.args[-1] in i)
|
||
return other[name]
|
||
|
||
stand.on("docker logs", log)
|
||
began = stand.clock
|
||
assert stand.lagging(versions) == want
|
||
assert answers == []
|
||
assert 0 < stand.clock - began < rotation.LOADED_TIMEOUT_SECONDS
|
||
|
||
|
||
def test_outdated_prints_names_only(
|
||
stand: RunStand,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""`make run_docker` перезапускает то, что напечатано: только имена, без
|
||
процессов с отозванной identity."""
|
||
versions = _versions(4)
|
||
|
||
def lagging(given: dict[str, Any]) -> dict[str, set[str]]:
|
||
assert given == versions
|
||
return {"worker": {"x"}, "api": {"x"}, "cleaner": {"x"}}
|
||
|
||
stand.on(
|
||
"pki.sh status",
|
||
"leaf cleaner: serial 2, not after x (9 days, REVOKED), sha256 B\n",
|
||
)
|
||
monkeypatch.setattr(stand, "kv_state", lambda: (versions, set()))
|
||
monkeypatch.setattr(stand, "lagging", lagging)
|
||
code = rotation.execute(stand, lambda: rotation.cmd_outdated(stand))
|
||
assert code == 0
|
||
assert capsys.readouterr().out == "api\nworker\n"
|
||
|
||
|
||
def test_storage_steps(stand: RunStand) -> None:
|
||
"""Аргументы одноразовых шагов: bootstrap — с кодом, пересоздание с новым
|
||
`.env`; ключи S3 — вместе только в режиме ротации."""
|
||
stand.one_off("postgres-bootstrap")
|
||
stand.s3_bootstrap_keep()
|
||
stand.recreate_valkey()
|
||
assert [call.text for call in stand.calls] == [
|
||
"docker compose up --no-deps --no-build --force-recreate "
|
||
"--exit-code-from postgres-bootstrap postgres-bootstrap",
|
||
"docker compose run --rm --no-deps -T -e S3_KEEP_STALE_KEYS=1 "
|
||
"s3-bootstrap apply",
|
||
"docker compose up -d --no-deps --force-recreate --wait valkey",
|
||
]
|
||
steps: list[Callable[[], None]] = [
|
||
lambda: stand.one_off("s3-bootstrap"),
|
||
stand.s3_bootstrap_keep,
|
||
stand.recreate_valkey,
|
||
]
|
||
stand.on("compose", (1, "", ""))
|
||
for step in steps:
|
||
with pytest.raises(rotation.Failed):
|
||
step()
|
||
|
||
|
||
def test_database_time(stand: RunStand) -> None:
|
||
stand.on("exec -T postgres", " 2026-12-01 03:00:00+00\n")
|
||
assert stand.database_time() == "2026-12-01 03:00:00+00"
|
||
assert stand.calls[0].stdin == "SELECT clock_timestamp();"
|
||
|
||
|
||
def test_env_symlink_and_indent(tmp_path: Path) -> None:
|
||
"""`.env` — ссылка: меняется файл, на который она ведёт, ссылка остаётся;
|
||
строка с отступом — та же переменная, вторая такая — отказ."""
|
||
target = tmp_path / "real.env"
|
||
target.write_text("A=1\nNAME=0123456789\n")
|
||
link = tmp_path / ".env"
|
||
link.symlink_to(target)
|
||
rotation.replace_env_values(link, {"NAME": "abcdefghij"})
|
||
assert link.is_symlink()
|
||
assert target.read_text() == "A=1\nNAME=abcdefghij\n"
|
||
target.write_text("NAME=0123456789\n NAME=9876543210\n")
|
||
with pytest.raises(rotation.NotReady, match="2 lines in .env"):
|
||
rotation.env_value(link, "NAME")
|
||
with pytest.raises(rotation.NotReady, match="2 lines in .env"):
|
||
rotation.replace_env_values(link, {"NAME": "x"})
|
||
target.write_text("\tNAME=0123456789\n")
|
||
assert rotation.env_value(link, "NAME") == "0123456789"
|
||
|
||
|
||
def test_s3_grpc_allowlist() -> None:
|
||
"""gRPC шлюза S3 CRL не читает: ни одна identity списка к нему не
|
||
допущена (имя — разовой пробы `make s3_check`)."""
|
||
text = (BASE_DIR / "infra" / "s3" / "security.toml").read_text()
|
||
grpc = tomllib.loads(text)["grpc"]
|
||
# ключ действует только в секции слушателя шлюза
|
||
assert set(grpc) == {"ca", "s3"}
|
||
names = grpc["s3"]["allowed_commonNames"].split(",")
|
||
identities = (BASE_DIR / "infra" / "pki" / "identities.conf").read_text()
|
||
listed = {
|
||
line.split()[0]
|
||
for line in identities.splitlines()
|
||
if line.strip() and not line.startswith("#")
|
||
}
|
||
assert names == ["s3-grpc-probe"]
|
||
assert not set(names) & listed
|
||
|
||
|
||
def test_lb_metrics_port_serves_one_request() -> None:
|
||
"""Порт метрик LB: простаивающее keep-alive runtime API не видит, и отзыв
|
||
его не закрыл бы — соединение на один запрос."""
|
||
text = (BASE_DIR / "infra" / "haproxy" / "haproxy.cfg").read_text()
|
||
section = re.split(r"^(?=\S)", text, flags=re.M)
|
||
(monitor,) = [s for s in section if s.startswith("frontend monitor")]
|
||
assert re.search(r"^\s+option httpclose$", monitor, re.M)
|
||
# рукопожатие, начатое до CRL, проверяется прежним: его срок — свой
|
||
assert re.search(r"^\s+timeout client-hs 5s$", monitor, re.M)
|
||
assert "timeout http-request" not in monitor
|
||
assert re.search(r"^\s+timeout http-request 10s$", text, re.M)
|
||
|
||
|
||
# run_docker -------------------------------------------------------------------
|
||
|
||
STUB = """#!/bin/sh
|
||
echo "$*" >>"$CALLS"
|
||
case "$*" in
|
||
*"rotation.py idle") exit "${IDLE:-0}" ;;
|
||
*"rotation.py outdated") echo "$STALE"; exit "${OUTDATED:-0}" ;;
|
||
esac
|
||
"""
|
||
|
||
|
||
@pytest.mark.parametrize("jobs", ["-j1", "-j4"])
|
||
@pytest.mark.parametrize(
|
||
("env", "code", "restarted"),
|
||
[
|
||
({}, 0, None),
|
||
({"STALE": "relay\nworker"}, 0, "restart relay worker"),
|
||
({"STALE": "broken", "OUTDATED": "1"}, 2, None),
|
||
({"IDLE": "2"}, 2, None),
|
||
],
|
||
)
|
||
def test_run_docker(
|
||
jobs: str,
|
||
env: dict[str, str],
|
||
code: int,
|
||
restarted: str | None,
|
||
tmp_path: Path,
|
||
) -> None:
|
||
"""Рецепт `run_docker` на подставных docker, python и pki.sh в копии
|
||
Makefile: идёт команда ротации — ничего не начато, и с `make -j` тоже (ни
|
||
`.env`, ни CRL); отставшие от версии KV перезапущены и названы; сверка не
|
||
удалась — ненулевой код."""
|
||
(tmp_path / "Makefile").write_text((BASE_DIR / "Makefile").read_text())
|
||
(tmp_path / "config.toml").touch()
|
||
calls, stub = tmp_path / "calls", tmp_path / "stub"
|
||
calls.touch()
|
||
stub.write_text(STUB)
|
||
stub.chmod(0o755)
|
||
result = subprocess.run( # noqa: S603
|
||
[ # noqa: S607
|
||
"make",
|
||
jobs,
|
||
"run_docker",
|
||
f"DC={stub} compose",
|
||
f"PYTHON={stub}",
|
||
f"PKI={stub} pki.sh",
|
||
"ENV_FILLED=true",
|
||
"ENV_APPEND_MISSING=cat",
|
||
f"PKI_OPERATOR_DIR={tmp_path / 'operator'}",
|
||
f"PKI_STAND_DIR={tmp_path / 'stand'}",
|
||
],
|
||
cwd=tmp_path,
|
||
env={
|
||
"PATH": os.environ["PATH"],
|
||
"HOME": str(tmp_path),
|
||
"CALLS": str(calls),
|
||
**env,
|
||
},
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
assert result.returncode == code, result.stdout + result.stderr
|
||
done = calls.read_text().splitlines()
|
||
assert done[0].endswith("infra/rotation/rotation.py idle")
|
||
if "IDLE" in env:
|
||
assert len(done) == 1
|
||
assert not (tmp_path / ".env").exists()
|
||
return
|
||
assert (tmp_path / ".env").exists()
|
||
order = ["pki.sh stand", "compose up -d openbao", "compose up -d"]
|
||
assert [line for line in done if line in order] == order
|
||
at = [n for n, line in enumerate(done) if line.endswith(" outdated")]
|
||
assert len(at) == 1
|
||
assert at[0] > done.index("compose up -d")
|
||
restarts = [line for line in done if line.startswith("compose restart")]
|
||
assert restarts == ([f"compose {restarted}"] if restarted else [])
|
||
if restarted:
|
||
assert "old secret versions: relay worker" in result.stdout
|
||
|
||
|
||
def test_rolling_update_asks_first() -> None:
|
||
"""Цель `rolling_update` сначала спрашивает, не идёт ли команда ротации;
|
||
скрипт — нет: его зовёт и сама команда, которая держит блокировку."""
|
||
makefile = (BASE_DIR / "Makefile").read_text()
|
||
assert re.search(r"^rolling_update: rotation_idle$", makefile, re.M)
|
||
assert "rotation.py" not in (
|
||
BASE_DIR / "scripts" / "rolling-update.sh"
|
||
).read_text().replace("rotation-revocation", "")
|