forked from mtusi2026/mtusi2026lab7
feat: rotate and revoke credentials on the running stand
Add operator commands for leaf and secret rotation, identity revocation and CRL renewal without rebuilding images, and a drill under load. A rejected PostgreSQL role password is now 503 instead of 500. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,882 @@
|
||||
"""Команды оператора ротации, отзыва и продления (change
|
||||
`rotation-revocation`, design, решения 2–9, 12; спек `credential-lifecycle`):
|
||||
`infra/rotation/rotation.py`.
|
||||
|
||||
- Таблица identity → владелец, применение, проверяющие = `identities.conf` и
|
||||
`secrets` compose; таблица путей = `bao.SEED`, переменные — `.env.example` и
|
||||
мосты compose. Контроль: изменённая копия краснит с именем.
|
||||
- Правка `.env`: только строка известной переменной, права прежние, дубликат и
|
||||
отсутствие — отказ без записи; значения в вывод не попадают.
|
||||
- Порядок шагов ротации leaf, отзыва, продления и секрета по видам хранилищ —
|
||||
на подставном стенде; сбой фазы — код 1 с её именем, предусловие — код 2 без
|
||||
изменений, сигнал до первого изменения — 130, после — отложен.
|
||||
- Runtime API LB: тело `set ssl`, отказ `set` или `commit` — `abort` и сбой.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from src.config.settings import BASE_DIR
|
||||
|
||||
SCRIPT = BASE_DIR / "infra" / "rotation" / "rotation.py"
|
||||
IDENTITIES = BASE_DIR / "infra" / "pki" / "identities.conf"
|
||||
COMPOSE = BASE_DIR / "docker-compose.yml"
|
||||
ENV_EXAMPLE = BASE_DIR / ".env.example"
|
||||
|
||||
|
||||
def _load() -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location("rotation_script", SCRIPT)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules.setdefault("rotation_script", module)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
rotation = _load()
|
||||
|
||||
|
||||
def _identities() -> dict[str, str]:
|
||||
"""Имя строки списка → форма файлов."""
|
||||
rows = {}
|
||||
for raw in IDENTITIES.read_text(encoding="utf-8").splitlines():
|
||||
line = raw.split("#", 1)[0].strip()
|
||||
if line:
|
||||
name, _profile, _sans, form = line.split()
|
||||
rows[name] = form
|
||||
return rows
|
||||
|
||||
|
||||
def _compose() -> dict[str, Any]:
|
||||
return yaml.safe_load(COMPOSE.read_text(encoding="utf-8"))["services"]
|
||||
|
||||
|
||||
def _table_problems(
|
||||
leaves: dict[str, Any],
|
||||
services: dict[str, Any],
|
||||
identities: dict[str, str],
|
||||
) -> list[str]:
|
||||
secrets = {
|
||||
name: {str(item) for item in spec.get("secrets") or []}
|
||||
for name, spec in services.items()
|
||||
}
|
||||
problems = [
|
||||
f"identity {name}: not in both tables"
|
||||
for name in sorted(set(leaves) ^ set(identities))
|
||||
]
|
||||
for name in sorted(set(leaves) & set(identities)):
|
||||
owner, how, checkers = leaves[name]
|
||||
files = (
|
||||
{f"{name}.pem"}
|
||||
if identities[name] == "bundle"
|
||||
else {f"{name}.crt", f"{name}.key"}
|
||||
)
|
||||
holders = {s for s, held in secrets.items() if files & held}
|
||||
want = {owner} if owner else set()
|
||||
if holders != want:
|
||||
problems.append(f"identity {name}: owner {owner} != {holders}")
|
||||
elif owner and not files <= secrets[owner]:
|
||||
problems.append(f"identity {name}: {owner} lacks its files")
|
||||
if how not in (*rotation.APPLY_ORDER, "manual", "none"):
|
||||
problems.append(f"identity {name}: apply {how}")
|
||||
for checker in checkers:
|
||||
if checker not in services:
|
||||
problems.append(f"identity {name}: no service {checker}")
|
||||
elif "crl.pem" not in secrets[checker] and checker != "openbao":
|
||||
problems.append(
|
||||
f"identity {name}: {checker} has no crl.pem",
|
||||
)
|
||||
if checker not in rotation.CRL_ORDER:
|
||||
problems.append(f"checker {checker}: not in CRL_ORDER")
|
||||
used = {c for leaf in leaves.values() for c in leaf.checkers}
|
||||
problems += [
|
||||
f"service {name}: reads crl.pem and checks nobody"
|
||||
for name, held in secrets.items()
|
||||
if "crl.pem" in held and name != "migrate" and name not in used
|
||||
]
|
||||
return problems
|
||||
|
||||
|
||||
def test_leaf_table_matches_list_and_compose() -> None:
|
||||
assert not _table_problems(rotation.LEAVES, _compose(), _identities())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", ["owner", "checker", "identity", "unused"])
|
||||
def test_leaf_table_control(case: str) -> None:
|
||||
"""Контроль: расхождение таблицы называется именем."""
|
||||
leaves = dict(rotation.LEAVES)
|
||||
services = copy.deepcopy(_compose())
|
||||
if case == "owner":
|
||||
leaves["relay"] = leaves["relay"]._replace(owner="worker")
|
||||
want = "identity relay: owner worker"
|
||||
elif case == "checker":
|
||||
leaves["relay"] = leaves["relay"]._replace(checkers=("valkey",))
|
||||
want = "identity relay: valkey has no crl.pem"
|
||||
elif case == "identity":
|
||||
leaves["mallory"] = leaves["relay"]
|
||||
want = "identity mallory"
|
||||
else:
|
||||
services["valkey"]["secrets"].append("crl.pem")
|
||||
want = "service valkey: reads crl.pem and checks nobody"
|
||||
problems = _table_problems(leaves, services, _identities())
|
||||
assert any(text.startswith(want) for text in problems), problems
|
||||
|
||||
|
||||
def test_revoke_only_by_rotation() -> None:
|
||||
"""Design, решение 8: кого отзывают только заменой — и почему."""
|
||||
refused = {
|
||||
name for name in rotation.LEAVES if rotation.revoke_refusal(name)
|
||||
}
|
||||
assert refused == {
|
||||
"haproxy",
|
||||
"api",
|
||||
"openbao",
|
||||
"ingress",
|
||||
"postgres",
|
||||
"valkey",
|
||||
"s3",
|
||||
"loki",
|
||||
"tempo",
|
||||
"prometheus",
|
||||
"grafana",
|
||||
"bao-operator",
|
||||
}
|
||||
for name in refused:
|
||||
text = rotation.revoke_refusal(name)
|
||||
assert f"make rotate_leaf IDENTITY={name}" in text
|
||||
|
||||
|
||||
def test_secret_table_matches_seed() -> None:
|
||||
"""Пути и поля = `bao.SEED`; переменная `.env` — мост compose той же
|
||||
переменной bootstrap, строка шаблона — есть."""
|
||||
bao = rotation.load_bao()
|
||||
assert set(rotation.SECRETS) == set(bao.SEED)
|
||||
services = _compose()
|
||||
template = ENV_EXAMPLE.read_text(encoding="utf-8")
|
||||
for path, secret in rotation.SECRETS.items():
|
||||
assert set(secret.variables) == set(bao.SEED[path])
|
||||
assert secret.kind in rotation.REFUSALS
|
||||
assert secret.kind in rotation.CHECK_PY
|
||||
assert secret.name in services
|
||||
for field, variable in secret.variables.items():
|
||||
service, bridge = bao.SEED[path][field]
|
||||
value = services[service]["environment"][bridge]
|
||||
assert value.startswith("${" + variable + ":"), (path, value)
|
||||
assert f"\n{variable}=" in template, variable
|
||||
|
||||
|
||||
def test_secret_readers() -> None:
|
||||
bao = rotation.load_bao()
|
||||
assert rotation.readers_of(bao, "postgres/api") == ["api"]
|
||||
assert rotation.readers_of(bao, "s3/cleaner") == ["cleaner"]
|
||||
assert rotation.readers_of(bao, "postgres/migrate") == []
|
||||
|
||||
|
||||
# .env ---------------------------------------------------------------------
|
||||
|
||||
ENV_TEXT = (
|
||||
"# POSTGRES_API_PASSWORD=comment\n"
|
||||
"POSTGRES_PASSWORD=aaaaaaaaaaaaaaaa\r\n"
|
||||
"POSTGRES_API_PASSWORD=0123456789abcdef\n"
|
||||
"\n"
|
||||
"LAST=$POSTGRES_API_PASSWORD"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env_file(tmp_path: Path) -> Path:
|
||||
path = tmp_path / ".env"
|
||||
path.write_bytes(ENV_TEXT.encode())
|
||||
path.chmod(0o640)
|
||||
return path
|
||||
|
||||
|
||||
def test_env_line_replaced(env_file: Path) -> None:
|
||||
rotation.replace_env_values(
|
||||
env_file,
|
||||
{"POSTGRES_API_PASSWORD": "fedcba9876543210"},
|
||||
)
|
||||
assert env_file.read_bytes().decode() == ENV_TEXT.replace(
|
||||
"0123456789abcdef",
|
||||
"fedcba9876543210",
|
||||
)
|
||||
assert env_file.stat().st_mode & 0o777 == 0o640 # noqa: PLR2004
|
||||
assert [p.name for p in env_file.parent.iterdir()] == [".env"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["MISSING", "TWICE"])
|
||||
def test_env_line_not_single(env_file: Path, name: str) -> None:
|
||||
"""Переменной нет или она не одна — отказ, файл прежний."""
|
||||
text = env_file.read_bytes() + b"\nTWICE=a\nTWICE=b\n"
|
||||
env_file.write_bytes(text)
|
||||
for action in (
|
||||
lambda: rotation.env_value(env_file, name),
|
||||
lambda: rotation.replace_env_values(
|
||||
env_file,
|
||||
{"POSTGRES_API_PASSWORD": "x", name: "y"},
|
||||
),
|
||||
):
|
||||
with pytest.raises(rotation.NotReady) as error:
|
||||
action()
|
||||
assert name in str(error.value)
|
||||
assert "lines in .env" in str(error.value)
|
||||
assert env_file.read_bytes() == text
|
||||
|
||||
|
||||
def test_env_value_format(env_file: Path) -> None:
|
||||
"""Значение в кавычках или подстановка — не наша форма: отказ без него в
|
||||
тексте."""
|
||||
assert (
|
||||
rotation.env_value(env_file, "POSTGRES_API_PASSWORD")
|
||||
== "0123456789abcdef"
|
||||
)
|
||||
with pytest.raises(rotation.NotReady) as error:
|
||||
rotation.env_value(env_file, "LAST")
|
||||
assert "POSTGRES_API_PASSWORD" not in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("current", ["ab" * 16, "0" * 21, "Zz9" * 5])
|
||||
def test_new_value(current: str) -> None:
|
||||
value = rotation.new_value(current)
|
||||
assert len(value) == len(current)
|
||||
assert value != current
|
||||
assert value.isalnum()
|
||||
if current.isdigit() or current.islower():
|
||||
assert set(value) <= set("0123456789abcdef")
|
||||
|
||||
|
||||
# LB, брокер, журналы --------------------------------------------------------
|
||||
|
||||
|
||||
class LbStand(rotation.Stand): # type: ignore[misc]
|
||||
def __init__(self, answers: list[str]) -> None:
|
||||
super().__init__()
|
||||
self.answers = answers
|
||||
self.commands: list[str] = []
|
||||
|
||||
def lb(self, command: str) -> str:
|
||||
self.commands.append(command)
|
||||
return self.answers.pop(0) if self.answers else ""
|
||||
|
||||
|
||||
CREATED = "Transaction created for certificate x!\n"
|
||||
PEM = "-----BEGIN CERTIFICATE-----\nAAAA\n\n-----END CERTIFICATE-----\n\n"
|
||||
|
||||
|
||||
def test_lb_update() -> None:
|
||||
"""Тело `set` — PEM без пустых строк: первая пустая кончает его."""
|
||||
stand = LbStand([CREATED, "Committing x....\nSuccess!\n"])
|
||||
stand.lb_update("cert", "/run/secrets/haproxy.pem", PEM)
|
||||
payload, commit = stand.commands
|
||||
head, *body = payload.split("\n")
|
||||
assert head == "set ssl cert /run/secrets/haproxy.pem <<"
|
||||
assert body == [
|
||||
"-----BEGIN CERTIFICATE-----",
|
||||
"AAAA",
|
||||
"-----END CERTIFICATE-----",
|
||||
"",
|
||||
]
|
||||
assert commit == "commit ssl cert /run/secrets/haproxy.pem"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("answers", "sent"),
|
||||
[
|
||||
(["unable to load private key\n"], 2),
|
||||
([CREATED, "Committing x\nfailed\n"], 3),
|
||||
([""], 2),
|
||||
],
|
||||
)
|
||||
def test_lb_refusal_aborts(answers: list[str], sent: int) -> None:
|
||||
"""Отказ `set` или `commit` — `abort`, сбой; LB на прежнем."""
|
||||
stand = LbStand(list(answers))
|
||||
with pytest.raises(rotation.Failed) as error:
|
||||
stand.lb_update("crl-file", rotation.LB_CRL, PEM)
|
||||
assert "previous one is in use" in str(error.value)
|
||||
assert "BEGIN" not in str(error.value)
|
||||
assert len(stand.commands) == sent
|
||||
assert stand.commands[-1] == f"abort ssl crl-file {rotation.LB_CRL}"
|
||||
|
||||
|
||||
def test_old_connections() -> None:
|
||||
"""Ротация закрывает соединения прежних leaf, а не нового и не чужие."""
|
||||
keep = "2026-12-01T00:00:00Z - 2027-03-01T00:00:00Z"
|
||||
old = "2026-11-01T00:00:00Z - 2027-01-30T00:00:00Z"
|
||||
listing = (
|
||||
f"<rabbit@localhost.1.2.0>\trelay\t{keep}\n"
|
||||
f"<rabbit@localhost.1.3.0>\trelay\t{old}\n"
|
||||
f"<rabbit@localhost.1.4.0>\tworker\t{old}\n"
|
||||
"<rabbit@localhost.1.5.0>\trelay\n"
|
||||
)
|
||||
assert rotation.old_connections(listing, "relay", keep) == [
|
||||
"<rabbit@localhost.1.3.0>",
|
||||
"<rabbit@localhost.1.5.0>",
|
||||
]
|
||||
|
||||
|
||||
def test_loaded_version() -> None:
|
||||
record = (
|
||||
'{"event": "Loaded process secrets", "versions": '
|
||||
'{"postgres/api": 4}}\n'
|
||||
)
|
||||
assert rotation.loaded_version("text\n" + record, "postgres/api") == 4 # noqa: PLR2004
|
||||
assert rotation.loaded_version(record, "s3/api") is None
|
||||
assert rotation.loaded_version("", "s3/api") is None
|
||||
|
||||
|
||||
def test_one_off_containers_are_not_the_service() -> None:
|
||||
"""`docker compose ps` называет и контейнеры `run` (`make reconcile`): в
|
||||
состояние сервиса они не входят — иначе команда ждала бы их перезапуска."""
|
||||
stand = rotation.Stand()
|
||||
ids = ["a" * 64, "b" * 64]
|
||||
line = (
|
||||
'{{"id":"{0}","oneoff":"{1}","status":"running",'
|
||||
'"started":"2026-12-01T02:05:14Z","health":null}}\n'
|
||||
)
|
||||
|
||||
def run(args: list[str], **_kwargs: Any) -> Any:
|
||||
out = "\n".join(ids)
|
||||
if args[:2] == ["docker", "inspect"]:
|
||||
assert "com.docker.compose.oneoff" in args[3]
|
||||
out = line.format(ids[0], "False") + line.format(ids[1], "True")
|
||||
return subprocess.CompletedProcess(args, 0, out, "")
|
||||
|
||||
stand.run = run # type: ignore[method-assign]
|
||||
assert [item["id"] for item in stand.containers("cleaner")] == [ids[0]]
|
||||
|
||||
|
||||
def test_parse_time() -> None:
|
||||
moment = rotation.parse_time("2026-12-01T02:05:14.63340347Z")
|
||||
assert moment.isoformat() == "2026-12-01T02:05:14.633403+00:00"
|
||||
assert rotation.parse_time("2026-12-01T02:05:14Z").microsecond == 0
|
||||
|
||||
|
||||
# команды на подставном стенде -------------------------------------------------
|
||||
|
||||
|
||||
class FakeStand(rotation.Stand): # type: ignore[misc]
|
||||
"""Записывает шаги вместо действий; `fail` — шаг, который падает."""
|
||||
|
||||
def __init__(self, env_file: Path | None = None) -> None:
|
||||
super().__init__()
|
||||
self.steps: list[str] = []
|
||||
self.fail: str | None = None
|
||||
self.not_ready: str | None = None
|
||||
self.stale: set[str] = set()
|
||||
self.stuck: set[str] = set()
|
||||
self.olders: dict[str, int] = {}
|
||||
self.stand_output = "CRL: next update 2027-01-01\n"
|
||||
self.seeded: dict[str, int] | None = None
|
||||
if env_file is not None:
|
||||
self.env_file = env_file
|
||||
|
||||
def step(self, name: str) -> None:
|
||||
if self.fail is not None and name.startswith(self.fail):
|
||||
raise rotation.Failed(f"step {name}")
|
||||
self.steps.append(name)
|
||||
|
||||
def require(self, services: Any, **kwargs: Any) -> None:
|
||||
self.required = (set(services), kwargs)
|
||||
if self.not_ready:
|
||||
raise rotation.NotReady(self.not_ready)
|
||||
|
||||
def pki(self, *args: str) -> str:
|
||||
self.step("pki " + " ".join(args))
|
||||
return self.stand_output if args == ("stand",) else "revoked x: 1\n"
|
||||
|
||||
def older(self) -> dict[str, int]:
|
||||
return dict(self.olders)
|
||||
|
||||
def serial(self, identity: str) -> str:
|
||||
return f"serial-{identity}"
|
||||
|
||||
def validity(self, identity: str) -> str:
|
||||
return f"validity-{identity}"
|
||||
|
||||
def owner_current(self, identity: str) -> bool:
|
||||
return identity not in self.stale
|
||||
|
||||
def lb_install_leaf(self, identity: str) -> None:
|
||||
self.step(f"lb leaf {identity}")
|
||||
self._moved(identity)
|
||||
|
||||
def lb_install_crl(self) -> None:
|
||||
self.step("lb crl")
|
||||
|
||||
def broker_install_leaf(self) -> None:
|
||||
self.step("broker leaf")
|
||||
self._moved("rabbitmq")
|
||||
|
||||
def broker_install_crl(self) -> None:
|
||||
self.step("broker crl")
|
||||
|
||||
def broker_close(self, user: str, keep: str | None) -> None:
|
||||
self.step(f"broker close {user} keep {keep}")
|
||||
|
||||
def replace_replicas(self) -> None:
|
||||
self.step("replicas")
|
||||
self._moved("api", "api-client")
|
||||
|
||||
def restart(self, service: str) -> float:
|
||||
self.step(f"restart {service}")
|
||||
self._moved(
|
||||
*(
|
||||
name
|
||||
for name, leaf in rotation.LEAVES.items()
|
||||
if leaf.owner == service and leaf.apply == "restart"
|
||||
),
|
||||
)
|
||||
return 1.0
|
||||
|
||||
def _moved(self, *identities: str) -> None:
|
||||
self.stale -= set(identities) - self.stuck
|
||||
|
||||
def bao_cli(self, *args: str) -> str:
|
||||
self.step("bao " + " ".join(args))
|
||||
return "done"
|
||||
|
||||
def seed(self) -> dict[str, int]:
|
||||
self.step("seed")
|
||||
return dict(self.seeded or {})
|
||||
|
||||
def one_off(self, service: str) -> None:
|
||||
self.step(f"one-off {service}")
|
||||
|
||||
def s3_bootstrap_keep(self) -> None:
|
||||
self.step("s3 keep")
|
||||
|
||||
def recreate_valkey(self) -> None:
|
||||
self.step("recreate valkey")
|
||||
|
||||
def database_time(self) -> str:
|
||||
self.step("database time")
|
||||
return "T1"
|
||||
|
||||
def close_sessions(self, role: str, before: str) -> None:
|
||||
self.step(f"close sessions {role} {before}")
|
||||
|
||||
def check_values(
|
||||
self,
|
||||
path: str,
|
||||
old: dict[str, str],
|
||||
new: dict[str, str],
|
||||
) -> None:
|
||||
assert old.keys() == new.keys()
|
||||
assert all(old[key] != new[key] for key in old)
|
||||
self.step(f"check {path}")
|
||||
|
||||
def apply_secret(self, service: str, path: str, version: int) -> None:
|
||||
self.step(f"apply {service} {path} {version}")
|
||||
|
||||
|
||||
def _run(stand: FakeStand, command: Any, *args: str) -> int:
|
||||
return rotation.execute(stand, lambda: command(stand, *args))
|
||||
|
||||
|
||||
def test_leaf_order() -> None:
|
||||
"""Новый leaf → владелец → отзыв прежних → CRL, токены и соединения
|
||||
прежнего leaf (выданные новому остаются)."""
|
||||
stand = FakeStand()
|
||||
stand.stale = {"relay"}
|
||||
assert _run(stand, rotation.cmd_leaf, "relay") == 0
|
||||
assert stand.steps == [
|
||||
"pki rotate relay",
|
||||
"restart relay",
|
||||
"pki revoke relay --superseded",
|
||||
"bao configure",
|
||||
"bao revoke-tokens --role relay --keep-serial serial-relay",
|
||||
"broker crl",
|
||||
"broker close relay keep validity-relay",
|
||||
"restart otel-gateway",
|
||||
]
|
||||
services, flags = stand.required
|
||||
assert services == {"relay", "rabbitmq", "otel-gateway", "openbao"}
|
||||
assert flags == {"replicas": False, "openbao": True}
|
||||
|
||||
|
||||
def test_leaf_of_lb_and_replicas() -> None:
|
||||
stand = FakeStand()
|
||||
assert _run(stand, rotation.cmd_leaf, "haproxy") == 0
|
||||
assert stand.steps == [
|
||||
"pki rotate haproxy",
|
||||
"lb leaf haproxy",
|
||||
"pki revoke haproxy --superseded",
|
||||
"replicas",
|
||||
]
|
||||
assert stand.required[1] == {"replicas": True, "openbao": True}
|
||||
stand = FakeStand()
|
||||
assert _run(stand, rotation.cmd_leaf, "api") == 0
|
||||
assert stand.steps == [
|
||||
"pki rotate api",
|
||||
"replicas",
|
||||
"pki revoke api --superseded",
|
||||
"lb crl",
|
||||
]
|
||||
|
||||
|
||||
def test_leaf_owner_on_previous(capsys: pytest.CaptureFixture[str]) -> None:
|
||||
"""Владелец остался на прежнем leaf — прежний не отзывается, код 1 и имя
|
||||
сервиса."""
|
||||
stand = FakeStand()
|
||||
stand.stale = stand.stuck = {"relay"}
|
||||
assert _run(stand, rotation.cmd_leaf, "relay") == 1
|
||||
assert stand.steps == ["pki rotate relay", "restart relay"]
|
||||
out = capsys.readouterr().out
|
||||
assert "relay still works with the previous leaf" in out
|
||||
assert "FAILED in phase 'owner'" in out
|
||||
assert "make rotate_leaf IDENTITY=relay" in out
|
||||
|
||||
|
||||
def test_leaf_of_openbao(capsys: pytest.CaptureFixture[str]) -> None:
|
||||
"""Leaf OpenBao только выпускается: рестарт запечатал бы его."""
|
||||
stand = FakeStand()
|
||||
assert _run(stand, rotation.cmd_leaf, "openbao") == 0
|
||||
assert stand.steps == ["pki rotate openbao"]
|
||||
out = capsys.readouterr().out
|
||||
assert "make bao_unseal" in out
|
||||
assert "make pki_renew" in out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("identity", ["migrate", "bao-operator"])
|
||||
def test_leaf_without_running_owner(identity: str) -> None:
|
||||
stand = FakeStand()
|
||||
assert _run(stand, rotation.cmd_leaf, identity) == 0
|
||||
assert stand.steps[:2] == [
|
||||
f"pki rotate {identity}",
|
||||
f"pki revoke {identity} --superseded",
|
||||
]
|
||||
|
||||
|
||||
def test_revoke_order(capsys: pytest.CaptureFixture[str]) -> None:
|
||||
"""Отзыв: OpenBao и брокер раньше перезапусков; токены и соединения —
|
||||
все; окна названы, владелец не перезапускается."""
|
||||
stand = FakeStand()
|
||||
assert _run(stand, rotation.cmd_revoke, "relay") == 0
|
||||
assert stand.steps == [
|
||||
"pki revoke relay",
|
||||
"bao configure",
|
||||
"bao revoke-tokens --role relay",
|
||||
"broker crl",
|
||||
"broker close relay keep None",
|
||||
"restart otel-gateway",
|
||||
]
|
||||
out = capsys.readouterr().out
|
||||
for checker in ("openbao", "rabbitmq", "otel-gateway"):
|
||||
assert f"{checker}: new CRL applied" in out
|
||||
assert "seconds from the start to the new CRL: openbao" in out
|
||||
assert "make rotate_leaf IDENTITY=relay" in out
|
||||
|
||||
|
||||
def test_revoke_replicas_last() -> None:
|
||||
stand = FakeStand()
|
||||
assert _run(stand, rotation.cmd_revoke, "otel-collector") == 0
|
||||
assert stand.steps[1:] == ["restart relay", "restart worker", "replicas"]
|
||||
|
||||
|
||||
def test_revoke_already_revoked_in_files() -> None:
|
||||
"""После `make pki_revoke` действующих leaf нет: команда применяет CRL."""
|
||||
stand = FakeStand()
|
||||
|
||||
def pki(*args: str) -> str:
|
||||
stand.step("pki " + " ".join(args))
|
||||
if args == ("revoke", "relay"):
|
||||
raise rotation.Failed(
|
||||
"pki.sh revoke: exit 1: pki: no valid certificate of identity "
|
||||
"'relay'; nothing changed",
|
||||
)
|
||||
return ""
|
||||
|
||||
stand.pki = pki # type: ignore[method-assign]
|
||||
assert _run(stand, rotation.cmd_revoke, "relay") == 0
|
||||
assert stand.steps[:3] == ["pki revoke relay", "pki crl", "bao configure"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("identity", ["haproxy", "openbao", "postgres"])
|
||||
def test_revoke_refused(
|
||||
identity: str,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
stand = FakeStand()
|
||||
assert _run(stand, rotation.cmd_revoke, identity) == 2 # noqa: PLR2004
|
||||
assert stand.steps == []
|
||||
out = capsys.readouterr().out
|
||||
assert f"make rotate_leaf IDENTITY={identity}" in out
|
||||
assert "nothing changed" in out
|
||||
|
||||
|
||||
def test_renew_crl_only() -> None:
|
||||
"""Без перевыпуска каждый сервис перезапускается ровно один раз, реплики
|
||||
— последними."""
|
||||
stand = FakeStand()
|
||||
assert _run(stand, rotation.cmd_renew) == 0
|
||||
assert stand.steps == [
|
||||
"pki stand",
|
||||
"bao configure",
|
||||
"broker crl",
|
||||
"lb crl",
|
||||
"restart otel-gateway",
|
||||
"restart loki-gateway",
|
||||
"restart tempo-gateway",
|
||||
"restart prometheus-gateway",
|
||||
"restart relay",
|
||||
"restart worker",
|
||||
"restart cleaner",
|
||||
"replicas",
|
||||
]
|
||||
|
||||
|
||||
def test_renew_reissued() -> None:
|
||||
"""Перевыпущенные — владельцам (LB и брокер раньше перезапусков и замены
|
||||
реплик, реплики — один раз на оба leaf), затем отзыв прежних, затем CRL."""
|
||||
stand = FakeStand()
|
||||
names = {"api", "api-client", "haproxy", "rabbitmq", "postgres", "relay"}
|
||||
stand.stale = set(names)
|
||||
stand.olders = dict.fromkeys(names, 1)
|
||||
assert _run(stand, rotation.cmd_renew) == 0
|
||||
crl = stand.steps.index("bao configure")
|
||||
owners = stand.steps[1 : stand.steps.index("pki revoke api --superseded")]
|
||||
assert owners == [
|
||||
"lb leaf haproxy",
|
||||
"broker leaf",
|
||||
"restart postgres",
|
||||
"restart relay",
|
||||
"replicas",
|
||||
]
|
||||
revoked = {
|
||||
step.split()[2]
|
||||
for step in stand.steps[:crl]
|
||||
if step.startswith("pki revoke ")
|
||||
}
|
||||
assert revoked == names
|
||||
assert stand.steps[crl:].count("replicas") == 1
|
||||
|
||||
|
||||
def test_renew_openbao_waits_for_operator(
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""OpenBao на прежнем leaf: его leaf не отзывается, шаги названы."""
|
||||
stand = FakeStand()
|
||||
stand.stale = {"openbao"}
|
||||
stand.olders = {"openbao": 1}
|
||||
assert _run(stand, rotation.cmd_renew) == 0
|
||||
assert not any(step.startswith("pki revoke") for step in stand.steps)
|
||||
assert "make bao_unseal" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_renew_stops_before_crl_kills_openbao(
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""OpenBao работает на отозванном leaf: новый CRL остановил бы его
|
||||
клиентов — сбой до CRL."""
|
||||
stand = FakeStand()
|
||||
stand.stale = {"openbao"}
|
||||
assert _run(stand, rotation.cmd_renew) == 1
|
||||
assert stand.steps == ["pki stand"]
|
||||
assert "docker compose restart openbao" in capsys.readouterr().out
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def secret_env(tmp_path: Path) -> Path:
|
||||
path = tmp_path / ".env"
|
||||
lines = [
|
||||
f"{variable}={number:02d}" + "ab" * 12
|
||||
for secret in rotation.SECRETS.values()
|
||||
for number, variable in enumerate(secret.variables.values())
|
||||
]
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
SECRET_ORDER = {
|
||||
"s3/api": [
|
||||
"s3 keep",
|
||||
"seed",
|
||||
"apply api s3/api 2",
|
||||
"one-off s3-bootstrap",
|
||||
"check s3/api",
|
||||
],
|
||||
"postgres/api": [
|
||||
"seed",
|
||||
"one-off postgres-bootstrap",
|
||||
"database time",
|
||||
"apply api postgres/api 2",
|
||||
"close sessions api T1",
|
||||
"check postgres/api",
|
||||
],
|
||||
"postgres/migrate": [
|
||||
"seed",
|
||||
"one-off postgres-bootstrap",
|
||||
"database time",
|
||||
"close sessions migrate T1",
|
||||
"check postgres/migrate",
|
||||
],
|
||||
"valkey/api": [
|
||||
"seed",
|
||||
"recreate valkey",
|
||||
"apply api valkey/api 2",
|
||||
"check valkey/api",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", sorted(SECRET_ORDER))
|
||||
def test_secret_order(
|
||||
path: str,
|
||||
secret_env: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Порядок фаз по видам хранилищ (design, решение 9); в `.env` меняются
|
||||
только переменные пути; значений в выводе нет."""
|
||||
before = secret_env.read_text().splitlines()
|
||||
stand = FakeStand(secret_env)
|
||||
stand.seeded = {path: 2}
|
||||
assert _run(stand, rotation.cmd_secret, path) == 0
|
||||
assert stand.steps == SECRET_ORDER[path]
|
||||
after = secret_env.read_text().splitlines()
|
||||
changed = {
|
||||
line.split("=")[0]
|
||||
for line, old in zip(after, before, strict=True)
|
||||
if line != old
|
||||
}
|
||||
assert changed == set(rotation.SECRETS[path].variables.values())
|
||||
out = capsys.readouterr().out
|
||||
for line in (*before, *after):
|
||||
assert line.split("=")[1] not in out
|
||||
assert f"{path}: version 2" in out
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("fail", "phase"),
|
||||
[
|
||||
("seed", "seed"),
|
||||
("one-off", "storage"),
|
||||
("apply", "processes"),
|
||||
("close", "sessions"),
|
||||
("check", "verify"),
|
||||
],
|
||||
)
|
||||
def test_secret_failure_names_phase(
|
||||
secret_env: Path,
|
||||
fail: str,
|
||||
phase: str,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
stand = FakeStand(secret_env)
|
||||
stand.seeded = {"postgres/api": 2}
|
||||
stand.fail = fail
|
||||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 1
|
||||
out = capsys.readouterr().out
|
||||
assert f"FAILED in phase '{phase}'" in out
|
||||
assert "make rotate_secret SECRET=postgres/api" in out
|
||||
assert "make run_docker" in out
|
||||
|
||||
|
||||
def test_secret_not_ready(
|
||||
secret_env: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Предусловие (запечатанный OpenBao) — код 2, `.env` прежний."""
|
||||
before = secret_env.read_bytes()
|
||||
stand = FakeStand(secret_env)
|
||||
stand.not_ready = "OpenBao is sealed: run make bao_unseal"
|
||||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 2 # noqa: PLR2004
|
||||
assert secret_env.read_bytes() == before
|
||||
assert stand.steps == []
|
||||
assert "run make bao_unseal; nothing changed" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_secret_hidden_by_environment(
|
||||
secret_env: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
monkeypatch.setenv("POSTGRES_API_PASSWORD", "from-the-environment")
|
||||
stand = FakeStand(secret_env)
|
||||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 2 # noqa: PLR2004
|
||||
out = capsys.readouterr().out
|
||||
assert "POSTGRES_API_PASSWORD is set in the environment" in out
|
||||
assert "from-the-environment" not in out
|
||||
|
||||
|
||||
def test_secret_restarts_drifted_readers(secret_env: Path) -> None:
|
||||
"""`seed` записал и путь прерванной раньше ротации: его читатели тоже
|
||||
переходят на новую версию."""
|
||||
stand = FakeStand(secret_env)
|
||||
stand.seeded = {"postgres/api": 2, "s3/worker": 5}
|
||||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 0
|
||||
assert "restart worker" in stand.steps
|
||||
|
||||
|
||||
def test_unexpected_error_is_a_failure(
|
||||
secret_env: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Исключение процесса после первого изменения — код 1 без его текста: в
|
||||
нём могут быть данные."""
|
||||
stand = FakeStand(secret_env)
|
||||
|
||||
def seed() -> dict[str, int]:
|
||||
raise subprocess.TimeoutExpired(["secret-argv"], 1, output="secret")
|
||||
|
||||
stand.seed = seed # type: ignore[method-assign]
|
||||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 1
|
||||
out = capsys.readouterr().out
|
||||
assert "TimeoutExpired" in out
|
||||
assert "secret-argv" not in out
|
||||
|
||||
|
||||
def test_signal_before_change() -> None:
|
||||
stand = FakeStand()
|
||||
with pytest.raises(SystemExit) as error:
|
||||
stand.on_signal(signal.SIGINT, None)
|
||||
assert error.value.code == 130 # noqa: PLR2004
|
||||
|
||||
|
||||
def test_signal_after_change_is_deferred(
|
||||
secret_env: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Сценарий «Прерывание ротации секрета»: сигнал после записи нового
|
||||
значения — команда доводится до конца."""
|
||||
stand = FakeStand(secret_env)
|
||||
|
||||
def seed() -> dict[str, int]:
|
||||
stand.on_signal(signal.SIGTERM, None)
|
||||
stand.on_signal(signal.SIGINT, None)
|
||||
stand.step("seed")
|
||||
return {"postgres/api": 2}
|
||||
|
||||
stand.seed = seed # type: ignore[method-assign]
|
||||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 0
|
||||
assert stand.steps == SECRET_ORDER["postgres/api"]
|
||||
assert "the command will be finished first" in capsys.readouterr().out
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"argv",
|
||||
[
|
||||
["secret", "postgres/mallory"],
|
||||
["leaf", "mallory"],
|
||||
["revoke", "mallory"],
|
||||
],
|
||||
)
|
||||
def test_unknown_name(
|
||||
argv: list[str],
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Сценарий «Неизвестный путь»: код 2 и перечень."""
|
||||
with pytest.raises(SystemExit) as error:
|
||||
rotation.main(argv)
|
||||
assert error.value.code == 2 # noqa: PLR2004
|
||||
text = capsys.readouterr().err
|
||||
names = rotation.SECRETS if argv[0] == "secret" else rotation.LEAVES
|
||||
assert all(name in text for name in names)
|
||||
Reference in New Issue
Block a user