forked from mtusi2026/mtusi2026lab7
Keep the hold mark of an identity whose revocation has started whatever signal ends pki.sh, refuse every rotation command while the files of a held identity are missing, bound the handshake of the LB metrics port, name sessions of another password until verify ends, and run Makefile prerequisites in order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1455 lines
54 KiB
Python
1455 lines
54 KiB
Python
"""Команды оператора ротации, отзыва и продления (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 os
|
||
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"
|
||
"ok\n"
|
||
)
|
||
assert rotation.old_connections(listing, "relay", None) == [
|
||
"<rabbit@localhost.1.2.0>",
|
||
"<rabbit@localhost.1.3.0>",
|
||
"<rabbit@localhost.1.5.0>",
|
||
]
|
||
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'
|
||
)
|
||
later = record.replace("4", "5")
|
||
assert rotation.loaded_versions("text\n" + record) == {"postgres/api": 4}
|
||
assert rotation.loaded_versions(record + later) == {"postgres/api": 5}
|
||
assert rotation.loaded_versions("") == {}
|
||
|
||
|
||
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
|
||
# путь → версия KV; отличается от .env; сервис → путь → версия процесса
|
||
self.kv = dict.fromkeys(
|
||
rotation.SECRETS,
|
||
rotation.KvVersion(1, "T1"),
|
||
)
|
||
self.differs: set[str] = set()
|
||
self.lag: dict[str, set[str]] = {}
|
||
# отозванные identity по чтению статуса: первое, второе, …
|
||
self.statuses: list[set[str]] = []
|
||
if env_file is not None:
|
||
self.env_file = env_file
|
||
|
||
def read_status(self) -> None:
|
||
if self.statuses:
|
||
self.revoked = self.statuses.pop(0)
|
||
|
||
def kv_state(self) -> tuple[dict[str, Any], set[str]]:
|
||
return dict(self.kv), set(self.differs)
|
||
|
||
def lagging(self, versions: dict[str, Any]) -> dict[str, set[str]]:
|
||
assert versions == self.kv
|
||
return {name: set(paths) for name, paths in self.lag.items()}
|
||
|
||
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) -> list[str]:
|
||
self.step(f"broker close {user} keep {keep}")
|
||
return ["pid"]
|
||
|
||
def broker_late(
|
||
self,
|
||
users: dict[str, str | None],
|
||
installed: float,
|
||
) -> None:
|
||
assert installed > 0
|
||
for user, keep in sorted(users.items()):
|
||
self.step(f"broker late {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:
|
||
# новое — то, что уже в .env; прежнего там нет
|
||
written = {
|
||
field: rotation.env_value(self.env_file, name)
|
||
for field, name in rotation.SECRETS[path].variables.items()
|
||
}
|
||
assert new == written
|
||
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",
|
||
"broker late relay keep validity-relay",
|
||
]
|
||
services, flags = stand.required
|
||
assert services == {"relay", "rabbitmq", "otel-gateway", "openbao"}
|
||
assert flags == {
|
||
"replaced": {"relay", "otel-gateway", "openbao"},
|
||
"owner": None,
|
||
"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 == (
|
||
{"haproxy", "api"},
|
||
{
|
||
"replaced": {"api"},
|
||
"owner": None,
|
||
"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",
|
||
]
|
||
# владелец не запущен и не нужен готовым, нужен только проверяющий
|
||
want = set(rotation.LEAVES[identity].checkers)
|
||
assert stand.required[0] == stand.required[1]["replaced"] == want
|
||
|
||
|
||
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 --hold",
|
||
"bao configure",
|
||
"bao revoke-tokens --role relay",
|
||
"broker crl",
|
||
"broker close relay keep None",
|
||
"restart otel-gateway",
|
||
"broker late relay keep None",
|
||
]
|
||
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
|
||
assert "make rotate_secret SECRET=postgres/relay" in out
|
||
assert "postgres/worker" not 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", "--hold"):
|
||
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 --hold",
|
||
"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
|
||
|
||
|
||
RENEW_TOKENS = [
|
||
f"bao revoke-tokens --role {role} --keep-serial serial-{identity}"
|
||
for identity, role in (
|
||
("api-client", "api"),
|
||
("cleaner", "cleaner"),
|
||
("migrate", "migrate"),
|
||
("relay", "relay"),
|
||
("worker", "worker"),
|
||
)
|
||
]
|
||
|
||
|
||
def test_renew_crl_only() -> None:
|
||
"""Без перевыпуска каждый сервис перезапускается ровно один раз, реплики
|
||
— последними."""
|
||
stand = FakeStand()
|
||
assert _run(stand, rotation.cmd_renew) == 0
|
||
assert stand.steps == [
|
||
"pki stand",
|
||
"bao configure",
|
||
*RENEW_TOKENS,
|
||
"broker crl",
|
||
"broker close relay keep validity-relay",
|
||
"broker close worker keep validity-worker",
|
||
"lb crl",
|
||
"restart otel-gateway",
|
||
"restart loki-gateway",
|
||
"restart tempo-gateway",
|
||
"restart prometheus-gateway",
|
||
"restart relay",
|
||
"restart worker",
|
||
"restart cleaner",
|
||
"replicas",
|
||
"broker late relay keep validity-relay",
|
||
"broker late worker keep validity-worker",
|
||
]
|
||
|
||
|
||
def test_renew_closes_what_a_revoked_leaf_opened() -> None:
|
||
"""Сценарий «Продление после отзыва в файлах»: соединения и токены не
|
||
текущего leaf закрываются у всех identity; у отозванной
|
||
`revoke_identity` — все, а её процесс не перезапускается."""
|
||
stand = FakeStand()
|
||
stand.revoked = {"relay"}
|
||
assert _run(stand, rotation.cmd_renew) == 0
|
||
assert "bao revoke-tokens --role relay" in stand.steps
|
||
assert "broker close relay keep None" in stand.steps
|
||
assert "broker late relay keep None" in stand.steps
|
||
assert "broker close worker keep validity-worker" in stand.steps
|
||
assert "restart relay" not in stand.steps
|
||
assert "restart worker" in stand.steps
|
||
assert "relay" not in stand.required[0]
|
||
|
||
|
||
def test_renew_does_not_apply_a_revoked_leaf() -> None:
|
||
"""Leaf отозванной identity владельцу не применяется (вместе с ним — и
|
||
перезапуск процесса, который не войдёт в OpenBao)."""
|
||
stand = FakeStand()
|
||
stand.revoked = {"cleaner", "prometheus-client"}
|
||
stand.stale = {"cleaner", "prometheus-client", "grafana-client"}
|
||
assert _run(stand, rotation.cmd_renew) == 0
|
||
assert "restart cleaner" not in stand.steps
|
||
assert "restart prometheus" not in stand.steps
|
||
assert "restart grafana" in stand.steps
|
||
|
||
|
||
def test_revoke_leaves_other_revoked_processes() -> None:
|
||
"""Проверяющий с отозванной identity готовым не требуется и не
|
||
перезапускается: в OpenBao он не войдёт."""
|
||
stand = FakeStand()
|
||
stand.revoked = {"relay"}
|
||
assert _run(stand, rotation.cmd_revoke, "otel-collector") == 0
|
||
assert stand.required[0] == {"worker", "api"}
|
||
assert stand.steps[1:] == ["restart worker", "replicas"]
|
||
|
||
|
||
def test_renew_of_a_stopped_owner() -> None:
|
||
"""Реплики с отозванной `api-client` не заменяются и ради leaf `api`:
|
||
новые не вошли бы в OpenBao."""
|
||
stand = FakeStand()
|
||
stand.revoked = {"api-client"}
|
||
stand.stale = {"api", "api-client"}
|
||
assert _run(stand, rotation.cmd_renew) == 0
|
||
assert "replicas" not in stand.steps
|
||
assert "api" not in stand.required[0]
|
||
|
||
|
||
def test_renew_reads_the_status_after_the_issue() -> None:
|
||
"""Отозванный только в файлах leaf `pki.sh stand` перевыпустил: владелец
|
||
получает его, а соединения закрываются не все, а прежнего leaf."""
|
||
stand = FakeStand()
|
||
stand.statuses = [{"relay"}, set()]
|
||
stand.stale = {"relay"}
|
||
assert _run(stand, rotation.cmd_renew) == 0
|
||
assert "restart relay" in stand.steps
|
||
assert "broker close relay keep validity-relay" in stand.steps
|
||
|
||
|
||
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",
|
||
"close sessions migrate T1",
|
||
"check postgres/migrate",
|
||
],
|
||
# сессии прежнего пароля — сразу после смены и ещё раз в конце: сбой
|
||
# между ними их уже не оставит; реплики на прежнем пароле держат пул до
|
||
# замены (строка postgres/api)
|
||
"postgres/cleaner": [
|
||
"seed",
|
||
"one-off postgres-bootstrap",
|
||
"database time",
|
||
"close sessions cleaner T1",
|
||
"apply cleaner postgres/cleaner 2",
|
||
"close sessions cleaner T1",
|
||
"check postgres/cleaner",
|
||
],
|
||
"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
|
||
# от новой строки .env до конца verify: сессия могла сменить пароль роли
|
||
# раньше закрытия и открыть другую, а run_docker её не закроет
|
||
assert "sessions of role api opened with another password may" in out
|
||
assert "only restores the service" in out
|
||
assert "or run `make run_docker`" not in out
|
||
|
||
|
||
@pytest.mark.parametrize("fail", ["apply", "check"])
|
||
def test_failure_after_the_sessions_are_closed(
|
||
fail: str,
|
||
secret_env: Path,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Сессии роли без реплик закрыты сразу после смены пароля, но что
|
||
открытых не осталось, подтверждает только verify: до его конца вывод их
|
||
называет."""
|
||
stand = FakeStand(secret_env)
|
||
stand.seeded = {"postgres/cleaner": 2}
|
||
stand.fail = fail
|
||
assert _run(stand, rotation.cmd_secret, "postgres/cleaner") == 1
|
||
out = capsys.readouterr().out.split("FAILED", 1)[1]
|
||
assert "sessions of role cleaner opened with another password" in out
|
||
assert "or run `make run_docker`" not in out
|
||
|
||
|
||
@pytest.mark.parametrize("path", ["postgres/worker", "s3/api", "valkey/api"])
|
||
@pytest.mark.parametrize("phase", [".env", "seed"])
|
||
def test_failure_before_the_storage(
|
||
path: str,
|
||
phase: str,
|
||
secret_env: Path,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Сценарий «Сессии прежнего пароля после сбоя до смены пароля»: сбой в
|
||
`.env` и `seed` — `run_docker` сменил бы пароль и оставил сессии, поэтому у
|
||
`postgres/*` сводит только повтор; у остальных — и `run_docker`."""
|
||
stand = FakeStand(secret_env)
|
||
if phase == ".env":
|
||
|
||
def refuse(*_args: Any) -> None:
|
||
raise OSError("disk is full")
|
||
|
||
monkeypatch.setattr(rotation, "replace_env_values", refuse)
|
||
else:
|
||
stand.fail = "seed"
|
||
assert _run(stand, rotation.cmd_secret, path) == 1
|
||
out = capsys.readouterr().out.split("FAILED", 1)[1]
|
||
assert f"in phase '{phase}'" in out
|
||
assert f"Repeat `make rotate_secret SECRET={path}`" in out
|
||
postgres = path.startswith("postgres/")
|
||
assert ("sessions of role worker opened with" in out) is postgres
|
||
assert ("or run `make run_docker`" in out) is not postgres
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("command", "args", "fail", "phase"),
|
||
[
|
||
("cmd_leaf", ("relay",), "pki rotate", "issue"),
|
||
("cmd_leaf", ("relay",), "restart relay", "owner"),
|
||
("cmd_leaf", ("relay",), "pki revoke", "revoke previous"),
|
||
("cmd_leaf", ("relay",), "bao configure", "CRL"),
|
||
("cmd_leaf", ("relay",), "broker late", "late connections"),
|
||
("cmd_revoke", ("relay",), "pki revoke", "revoke"),
|
||
("cmd_revoke", ("relay",), "restart otel", "CRL"),
|
||
("cmd_renew", (), "pki stand", "issue"),
|
||
("cmd_renew", (), "lb crl", "CRL"),
|
||
],
|
||
)
|
||
def test_failure_of_pki_commands_is_repeated(
|
||
command: str,
|
||
args: tuple[str, ...],
|
||
fail: str,
|
||
phase: str,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Сбой leaf, отзыва и продления сводит только повтор: `make run_docker`
|
||
файлов CRL у проверяющих не меняет."""
|
||
stand = FakeStand()
|
||
stand.fail = fail
|
||
assert _run(stand, getattr(rotation, command), *args) == 1
|
||
out = capsys.readouterr().out
|
||
assert f"FAILED in phase '{phase}'" in out
|
||
assert "Repeat `make " in out
|
||
assert "run_docker" not in out.split("FAILED", 1)[1]
|
||
|
||
|
||
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
|
||
|
||
|
||
REPEAT = "make rotate_secret SECRET="
|
||
|
||
|
||
@pytest.mark.parametrize("how", ["differs", "lag"])
|
||
@pytest.mark.parametrize(
|
||
("half", "path", "hint"),
|
||
[
|
||
# сессии прежнего пароля закрывает только повтор этого пути
|
||
({"postgres/worker"}, "s3/cleaner", f"{REPEAT}postgres/worker"),
|
||
({"s3/worker"}, "s3/cleaner", "make run_docker"),
|
||
# двое отказали бы друг из-за друга: сначала run_docker
|
||
(
|
||
{"postgres/worker", "postgres/cleaner"},
|
||
"s3/cleaner",
|
||
f"make run_docker; {REPEAT}postgres/cleaner; "
|
||
f"{REPEAT}postgres/worker",
|
||
),
|
||
(
|
||
{"postgres/worker", "postgres/cleaner"},
|
||
"postgres/cleaner",
|
||
f"make run_docker; {REPEAT}postgres/cleaner; "
|
||
f"{REPEAT}postgres/worker",
|
||
),
|
||
(
|
||
{"s3/worker", "postgres/cleaner"},
|
||
"s3/worker",
|
||
f"make run_docker; {REPEAT}postgres/cleaner",
|
||
),
|
||
],
|
||
)
|
||
def test_secret_refuses_half_rotated_path(
|
||
how: str,
|
||
half: set[str],
|
||
path: str,
|
||
hint: str,
|
||
secret_env: Path,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Сценарий «Прерванная ротация другого пути»: KV не из `.env` или процесс
|
||
не на версии KV — код 2 с именем пути и тем, что сводит, ничего не
|
||
изменено."""
|
||
before = secret_env.read_bytes()
|
||
stand = FakeStand(secret_env)
|
||
stand.seeded = {path: 2}
|
||
if how == "differs":
|
||
stand.differs = set(half)
|
||
else:
|
||
for name in half:
|
||
stand.lag.setdefault(name.split("/")[1], set()).add(name)
|
||
assert _run(stand, rotation.cmd_secret, path) == 2 # noqa: PLR2004
|
||
out = capsys.readouterr().out
|
||
assert all(name in out for name in half - {path})
|
||
reason = out.split(" (an interrupted rotation)")[0]
|
||
assert path not in reason
|
||
assert f"rotation): run {hint} first; nothing changed" in out
|
||
assert secret_env.read_bytes() == before
|
||
assert stand.steps == []
|
||
|
||
|
||
def test_secret_repeats_its_own_path(secret_env: Path) -> None:
|
||
"""Расхождение самого пути — повтор прерванной ротации, а отставание
|
||
процесса с отозванной identity сводит `rotate_leaf`."""
|
||
stand = FakeStand(secret_env)
|
||
stand.seeded = {"postgres/api": 2}
|
||
stand.differs = {"postgres/api"}
|
||
stand.lag = {"api": {"postgres/api"}, "cleaner": {"postgres/cleaner"}}
|
||
stand.revoked = {"cleaner"}
|
||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 0
|
||
|
||
|
||
def test_secret_of_revoked_identity(
|
||
secret_env: Path,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Сценарий «Ротация секрета отозванной identity»: процесс, который не
|
||
войдёт в OpenBao, не нужен готовым, не перезапускается и назван; прежние
|
||
сессии закрыты, прежнее значение отвергнуто."""
|
||
stand = FakeStand(secret_env)
|
||
stand.seeded = {"postgres/cleaner": 2}
|
||
stand.revoked = {"cleaner"}
|
||
assert _run(stand, rotation.cmd_secret, "postgres/cleaner") == 0
|
||
assert stand.required[0] == {"postgres"}
|
||
assert stand.steps == [
|
||
"seed",
|
||
"one-off postgres-bootstrap",
|
||
"database time",
|
||
"close sessions cleaner T1",
|
||
"close sessions cleaner T1",
|
||
"check postgres/cleaner",
|
||
]
|
||
out = capsys.readouterr().out
|
||
assert "cleaner: identity cleaner is revoked, not restarted" in out
|
||
assert "make rotate_leaf IDENTITY=cleaner" in out
|
||
|
||
|
||
def test_secret_of_revoked_replicas(secret_env: Path) -> None:
|
||
"""Реплики с отозванной `api-client` не заменяются, и их сессии закрываются
|
||
сразу: ждать замены нечего."""
|
||
stand = FakeStand(secret_env)
|
||
stand.seeded = {"postgres/api": 2}
|
||
stand.revoked = {"api-client"}
|
||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 0
|
||
assert "apply api postgres/api 2" not in stand.steps
|
||
assert stand.steps.count("close sessions api T1") == 2 # noqa: PLR2004
|
||
assert stand.required[1]["replicas"] is False
|
||
|
||
|
||
def test_leaf_of_revoked_identity() -> None:
|
||
"""Владельца отозванной identity отзыв мог остановить: предусловие — только
|
||
его контейнер, остановленный возвращает перезапуск, а не применение на
|
||
месте."""
|
||
stand = FakeStand()
|
||
stand.revoked = {"cleaner"}
|
||
stand.stale = {"cleaner"}
|
||
assert _run(stand, rotation.cmd_leaf, "cleaner") == 0
|
||
assert stand.required[1]["owner"] == "cleaner"
|
||
# владелец — среди сервисов команды: его контейнер проверяют и заменяют
|
||
assert stand.required[0] == {"cleaner", "openbao"}
|
||
assert "restart cleaner" in stand.steps
|
||
stand = FakeStand()
|
||
stand.revoked = {"rabbitmq"}
|
||
stand.stale = {"rabbitmq"}
|
||
stand.down = {"rabbitmq"}
|
||
stand.restart = lambda service: ( # type: ignore[method-assign]
|
||
stand.step(f"restart {service}"),
|
||
stand._moved("rabbitmq"),
|
||
1.0,
|
||
)[2]
|
||
assert _run(stand, rotation.cmd_leaf, "rabbitmq") == 0
|
||
assert stand.required[1]["owner"] == "rabbitmq"
|
||
assert stand.steps[1] == "restart rabbitmq"
|
||
assert "broker leaf" not in stand.steps
|
||
|
||
|
||
def test_leaf_leaves_other_revoked_processes() -> None:
|
||
"""Проверяющий с отозванной identity не перезапускается: он не вошёл бы в
|
||
OpenBao, и команда ждала бы его до срока."""
|
||
stand = FakeStand()
|
||
stand.revoked = {"relay"}
|
||
assert _run(stand, rotation.cmd_leaf, "otel-collector") == 0
|
||
assert "restart relay" not in stand.steps
|
||
assert "restart worker" in stand.steps
|
||
assert "relay" not in stand.required[0]
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"error",
|
||
[IndexError("secret-argv"), KeyError("secret-argv"), AttributeError("x")],
|
||
)
|
||
def test_any_error_has_code_and_phase(
|
||
error: Exception,
|
||
secret_env: Path,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Любая ошибка кода — код и фаза, без traceback и без её текста."""
|
||
stand = FakeStand(secret_env)
|
||
|
||
def seed() -> dict[str, int]:
|
||
raise error
|
||
|
||
stand.seed = seed # type: ignore[method-assign]
|
||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 1
|
||
out = capsys.readouterr().out
|
||
assert f"FAILED in phase 'seed': {type(error).__name__}." in out
|
||
assert "secret-argv" not in out
|
||
stand = FakeStand(secret_env)
|
||
stand.kv_state = seed # type: ignore[assignment, method-assign]
|
||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 2 # noqa: PLR2004
|
||
out = capsys.readouterr().out
|
||
assert f"rotation: {type(error).__name__}; nothing changed" in out
|
||
|
||
|
||
@pytest.mark.parametrize("how", ["closed pipe", "closed file"])
|
||
def test_closed_output_does_not_stop(how: str, tmp_path: Path) -> None:
|
||
"""Сценарий «Терминал закрыт»: вывод в закрытую трубу или закрытый
|
||
дескриптор не обрывает команду (настоящий процесс)."""
|
||
done = tmp_path / "done"
|
||
code = (
|
||
"import importlib.util, os, sys\n"
|
||
f"spec = importlib.util.spec_from_file_location('r', {str(SCRIPT)!r})\n"
|
||
"r = importlib.util.module_from_spec(spec)\n"
|
||
"sys.modules['r'] = r\n"
|
||
"spec.loader.exec_module(r)\n"
|
||
"stand = r.Stand()\n"
|
||
"def command():\n"
|
||
" stand.begin_change('issue')\n"
|
||
+ (" os.close(1)\n" if how == "closed file" else "")
|
||
+ " for n in range(3):\n"
|
||
" stand.enter('next')\n"
|
||
f" open({str(done)!r}, 'w').close()\n"
|
||
"sys.exit(r.execute(stand, command))\n"
|
||
)
|
||
read, write = os.pipe()
|
||
proc = subprocess.Popen( # noqa: S603
|
||
[sys.executable, "-c", code],
|
||
stdout=write,
|
||
stderr=subprocess.PIPE,
|
||
)
|
||
os.close(write)
|
||
if how == "closed pipe":
|
||
os.close(read)
|
||
_, err = proc.communicate(timeout=30)
|
||
assert proc.returncode == 0, err
|
||
assert err == b""
|
||
assert done.exists()
|
||
|
||
|
||
def test_signal_inside_a_print(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Сигнал застал печать другой строки: print буфера вложенно не пишет
|
||
(RuntimeError), и обработчик из-за этого команду не обрывает, а вывод
|
||
остаётся на месте."""
|
||
|
||
def reentrant(*_args: Any, **_kwargs: Any) -> None:
|
||
raise RuntimeError("reentrant call inside <_io.BufferedWriter>")
|
||
|
||
stand = FakeStand()
|
||
stand.begin_change("issue")
|
||
monkeypatch.setattr(rotation, "print", reentrant, raising=False)
|
||
moved: list[int] = []
|
||
monkeypatch.setattr(rotation.os, "dup2", lambda *a: moved.append(a[1]))
|
||
stand.on_signal(signal.SIGTERM, None)
|
||
assert stand.pending == signal.SIGTERM
|
||
assert moved == []
|
||
monkeypatch.undo()
|
||
stand.say("next line")
|
||
assert "next line" in capsys.readouterr().out
|
||
|
||
|
||
def test_one_command_at_a_time(tmp_path: Path) -> None:
|
||
"""Вторая команда на том же стенде — код 2; блокировка убитого процесса не
|
||
мешает: её снимает ядро."""
|
||
code = (
|
||
"import importlib.util, sys, time\n"
|
||
f"spec = importlib.util.spec_from_file_location('r', {str(SCRIPT)!r})\n"
|
||
"r = importlib.util.module_from_spec(spec)\n"
|
||
"sys.modules['r'] = r\n"
|
||
"spec.loader.exec_module(r)\n"
|
||
"r.Stand().lock()\n"
|
||
"print('locked', flush=True)\n"
|
||
"time.sleep(60)\n"
|
||
)
|
||
proc = subprocess.Popen( # noqa: S603
|
||
[sys.executable, "-c", code],
|
||
env={**os.environ, "PKI_STAND_DIR": str(tmp_path)},
|
||
stdout=subprocess.PIPE,
|
||
text=True,
|
||
)
|
||
assert proc.stdout is not None
|
||
assert proc.stdout.readline() == "locked\n"
|
||
stand = rotation.Stand()
|
||
stand.pki_dir = tmp_path
|
||
with pytest.raises(rotation.NotReady, match="another rotation command"):
|
||
stand.lock()
|
||
# run_docker и rolling_update спрашивают то же самое, не держа блокировки
|
||
assert _idle(tmp_path) == 2 # noqa: PLR2004
|
||
proc.kill()
|
||
proc.wait()
|
||
assert _idle(tmp_path) == 0
|
||
stand.lock()
|
||
assert (tmp_path / ".rotation.lock").stat().st_mode & 0o777 == 0o600 # noqa: PLR2004
|
||
# первый запуск: каталога стенда ещё нет
|
||
assert _idle(tmp_path / "missing") == 0
|
||
assert not (tmp_path / "missing").exists()
|
||
|
||
|
||
def _idle(pki_dir: Path) -> int:
|
||
"""`rotation.py idle` настоящим процессом."""
|
||
return subprocess.run( # noqa: S603
|
||
[sys.executable, str(SCRIPT), "idle"],
|
||
env={**os.environ, "PKI_STAND_DIR": str(pki_dir)},
|
||
capture_output=True,
|
||
check=False,
|
||
).returncode
|
||
|
||
|
||
@pytest.mark.skipif(os.getuid() == 0, reason="root ignores file modes")
|
||
@pytest.mark.parametrize("how", ["file", "directory", "parent"])
|
||
def test_lock_file_is_named(
|
||
how: str,
|
||
tmp_path: Path,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
"""Чужой файл блокировки, каталог только на чтение и недоступный — код 2 с
|
||
путём; каталога нет — `make pki_stand`."""
|
||
stand = FakeStand()
|
||
stand.pki_dir = tmp_path / "parent" / "stand"
|
||
stand.pki_dir.mkdir(parents=True)
|
||
lock = stand.pki_dir / ".rotation.lock"
|
||
path = {
|
||
"file": lock,
|
||
"directory": stand.pki_dir,
|
||
"parent": stand.pki_dir.parent,
|
||
}[how]
|
||
lock.touch() if how == "file" else None
|
||
mode = path.stat().st_mode
|
||
path.chmod(0o500 if how == "directory" else 0)
|
||
try:
|
||
code = rotation.execute(stand, lambda: rotation.cmd_idle(stand))
|
||
out = capsys.readouterr().out
|
||
finally:
|
||
path.chmod(mode)
|
||
assert code == 2 # noqa: PLR2004
|
||
assert out == (
|
||
f"rotation: cannot lock {lock}: Permission denied; nothing changed\n"
|
||
)
|
||
stand.pki_dir = tmp_path / "missing"
|
||
assert rotation.execute(stand, stand.lock) == 2 # noqa: PLR2004
|
||
out = capsys.readouterr().out
|
||
assert f"no {tmp_path / 'missing'}: run make pki_stand" in out
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"argv",
|
||
[["leaf", "relay"], ["secret", "s3/api"], ["renew"], ["revoke", "relay"]],
|
||
)
|
||
def test_busy_command_changes_nothing(
|
||
argv: list[str],
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
def busy(_self: Any) -> None:
|
||
raise rotation.NotReady("another rotation command is running")
|
||
|
||
monkeypatch.setattr(rotation.Stand, "lock", busy)
|
||
monkeypatch.setattr(rotation.signal, "signal", lambda *_args: None)
|
||
for name in ("cmd_leaf", "cmd_secret", "cmd_renew", "cmd_revoke"):
|
||
monkeypatch.setattr(
|
||
rotation,
|
||
name,
|
||
lambda *_args: pytest.fail("command started"),
|
||
)
|
||
assert rotation.main(argv) == 2 # noqa: PLR2004
|
||
assert "another rotation command" in capsys.readouterr().out
|
||
|
||
|
||
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)
|