"""Лаба 7, перенос rotation-revocation: команды оператора без стенда. Таблицы `infra/rotation/rotation.py` против файлов стенда (identities.conf, secrets compose, SEED и политики OpenBao, .env.example); порядок шагов команд на подставном стенде (`FakeStand`): leaf — выпуск → владелец → отзыв прежних → CRL проверяющим; отзыв — с удержанием; секрет — .env → хранилище и OpenBao → процессы → прежнее отвергнуто; предусловие — код 2 без изменений, сбой — код 1 с фазой и командой, которая сводит; сигнал после начала — отложен. Чистые функции (.env, версии в журнале, брокер). `pki.sh` с OpenSSL ≥ 3 на временном CA: ротация без отзыва, отзыв прежних, удержание, отказ без базы CA. Мелкие правки соседей: 28P01 — недоступность, ROLLOUT_CHECK, --install-*, S3_KEEP_STALE_KEYS, `:8404` LB, цели make и правила Codex. """ import importlib.util import os import re import shutil import signal import subprocess import sys from pathlib import Path from types import ModuleType import pytest pytestmark = pytest.mark.unit ROOT = Path(__file__).resolve().parents[2] PKI = ROOT / "infra" / "pki" / "pki.sh" def _load(name: str, path: Path) -> ModuleType: spec = importlib.util.spec_from_file_location(name, path) assert spec is not None assert spec.loader is not None module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) return module rotation = _load("unit_rotation", ROOT / "infra" / "rotation" / "rotation.py") bao = _load("unit_rotation_bao", ROOT / "infra" / "openbao" / "bao.py") def _text(rel: str) -> str: lines = (ROOT / rel).read_text(encoding="utf-8").splitlines() return "\n".join(line for line in lines if not line.lstrip().startswith("#")) + "\n" def _identities() -> dict[str, tuple[str, str]]: """Имя строки identities.conf → (профиль, форма).""" out = {} for line in _text("infra/pki/identities.conf").splitlines(): fields = line.split() if fields: out[fields[0]] = (fields[1], fields[3]) return out def _service_secrets() -> dict[str, list[str]]: """Сервис compose.yaml → его `secrets` (короткая запись списком).""" text = _text("compose.yaml") section = re.search(r"^services:\n((?:(?: .*)?\n)*)", text, re.M) assert section is not None out = {} for match in re.finditer( r"^ ([a-z0-9-]+):\n((?:(?: .*)?\n)*)", section.group(1), re.M ): listed = re.search(r"^ secrets:\n((?: - .*\n)*)", match.group(2), re.M) out[match.group(1)] = re.findall(r"- (\S+)", listed.group(1)) if listed else [] return out # --- таблицы против файлов стенда -------------------------------------------- def test_leaves_are_the_identity_list() -> None: assert set(rotation.LEAVES) == set(_identities()) def test_owner_holds_the_leaf_file() -> None: secrets = _service_secrets() for identity, leaf in rotation.LEAVES.items(): if leaf.owner is None: continue files = secrets.get(leaf.owner, []) assert f"{identity}.crt" in files or f"{identity}.pem" in files, identity def test_every_crl_reader_is_a_checker() -> None: """Сервис с crl.pem (кроме одноразового migrate) — чей-то проверяющий; проверяющий без crl.pem — только OpenBao (CRL ему грузит bao-configure).""" secrets = _service_secrets() readers = {s for s, files in secrets.items() if "crl.pem" in files} - {"migrate"} checkers = {c for leaf in rotation.LEAVES.values() for c in leaf.checkers} assert readers <= checkers, sorted(readers - checkers) assert {c for c in checkers if "crl.pem" not in secrets.get(c, [])} == {"openbao"} def test_secrets_are_the_seed_and_the_env_template() -> None: assert set(rotation.SECRETS) == set(bao.SEED) template = (ROOT / ".env.example").read_text(encoding="utf-8") for path, secret in rotation.SECRETS.items(): assert set(secret.variables) == set(bao.SEED[path]), path for name in secret.variables.values(): assert re.search(rf"^{name}=", template, re.M), name def test_broker_users_and_processes_are_roles() -> None: cns = {str(spec["cn"]) for spec in bao.ROLES.values()} assert set(rotation.BROKER_USERS) <= cns services = {spec["service"] for spec in bao.ROLES.values() if spec["service"]} assert set(rotation.PROCESSES) == services def test_revoke_only_by_rotation() -> None: for identity in ("haproxy", "api", "openbao", "ingress", "postgres", "grafana"): assert "make rotate-leaf" in (rotation.revoke_refusal(identity) or ""), identity for identity in ("relay", "worker", "api-client", "cleaner", "rabbitmq"): assert rotation.revoke_refusal(identity) is None, identity def test_recreated_steps_match_pki_sh() -> None: text = PKI.read_text(encoding="utf-8") assert "; ".join(rotation.RECREATED_STEPS) in text def test_broker_late_covers_its_login_timeouts() -> None: """Сроки входа брокера — умолчания (5 с TLS + 10 с AMQP): конфигурация их не меняет, иначе BROKER_LATE_SECONDS меняется вместе с ними.""" conf = _text("infra/rabbitmq/rabbitmq.conf") + _text( "infra/rabbitmq/advanced.config" ) assert "handshake_timeout" not in conf assert rotation.BROKER_LATE_SECONDS >= 5 + 10 # --- подставной стенд: порядок шагов --------------------------------------- class FakeStand(rotation.Stand): """Стенд без docker: шаги — в журнал `calls`.""" def __init__(self, *, revoked: set[str] | None = None) -> None: # noqa: D107 self.started = 0.0 self.changed = False self.pending = None self.phase = "preconditions" self.repeat = "" self.converge = "" self.exposed = "" self.revoked = set(revoked or ()) self.missing: set[str] = set() self.down: set[str] = set() self.lock_file = None self.pki_dir = Path("/nonexistent") self.env_file = Path("/nonexistent/.env") self.bao = bao self.openssl = "openssl" self.window = [] self.calls: list[str] = [] self.fail_at: str | None = None self.not_ready = False def elapsed(self) -> float: return 0.0 def say(self, text: str) -> None: self.calls.append("say " + text) def _step(self, name: str) -> None: self.calls.append(name) if self.fail_at and name.startswith(self.fail_at): raise rotation.Failed(f"{name} failed") def read_status(self) -> None: self.calls.append("status") def require(self, services, **kwargs) -> None: self.calls.append("require " + " ".join(sorted(services))) if self.not_ready: raise rotation.NotReady("a service is unhealthy") def pki(self, *args: str) -> str: self._step("pki " + " ".join(args)) return "revoked x: serial 01" def serial(self, identity: str) -> str: return "0A" def validity(self, identity: str) -> str: return "v" def apply_owner(self, identity: str) -> None: self._step(f"owner {identity}") def owner_current(self, identity: str) -> bool: return True def apply_crl(self, services, identities) -> None: self._step("crl " + " ".join(sorted(services)) + " " + repr(identities)) def seed(self): self._step("seed") return {"postgres/api": 2, "s3/api": 2} def require_consistent(self, path: str) -> None: self.calls.append("consistent") 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("valkey") def database_time(self) -> str: return "t" def close_sessions(self, role: str, before: str) -> None: self._step(f"sessions {role}") def apply_secret(self, service: str, path: str, version: int) -> None: self._step(f"processes {service}") def check_values(self, path, old, new) -> None: self._step("verify") def _steps(stand: FakeStand) -> list[str]: return [ c for c in stand.calls if not c.startswith(("say ", "status", "require ", "consistent")) ] def test_leaf_order_issue_owner_revoke_crl() -> None: stand = FakeStand() assert rotation.execute(stand, lambda: rotation.cmd_leaf(stand, "relay")) == 0 steps = _steps(stand) assert steps[0] == "pki rotate relay" assert steps[1] == "owner relay" assert steps[2] == "pki revoke relay --superseded" assert steps[3].startswith("crl openbao otel-gateway rabbitmq ") # ротация: закрываются соединения и токены только прежнего leaf assert "{'relay': '0A'}" in steps[3] def test_revoke_holds_and_closes_everything() -> None: stand = FakeStand() assert rotation.execute(stand, lambda: rotation.cmd_revoke(stand, "worker")) == 0 steps = _steps(stand) assert steps[0] == "pki revoke worker --hold" assert steps[1] == "crl openbao otel-gateway rabbitmq {'worker': None}" assert any("make rotate-secret SECRET=s3/worker" in c for c in stand.calls) def test_revoke_refused_before_any_change() -> None: stand = FakeStand() code = rotation.execute(stand, lambda: rotation.cmd_revoke(stand, "haproxy")) assert code == 2 assert not _steps(stand) def test_precondition_is_exit_2_and_nothing_changed() -> None: stand = FakeStand() stand.not_ready = True assert rotation.execute(stand, lambda: rotation.cmd_leaf(stand, "relay")) == 2 assert not stand.changed assert not _steps(stand) def test_failure_names_phase_and_repeat() -> None: stand = FakeStand() stand.fail_at = "owner" assert rotation.execute(stand, lambda: rotation.cmd_leaf(stand, "worker")) == 1 last = stand.calls[-1] assert "FAILED in phase 'owner'" in last assert "make rotate-leaf IDENTITY=worker" in last # прежний leaf не отозван: владелец мог не перейти assert not any(c.startswith("pki revoke") for c in stand.calls) def test_revoked_owner_process_is_left_alone() -> None: stand = FakeStand(revoked={"worker"}) assert rotation.execute(stand, lambda: rotation.cmd_revoke(stand, "rabbitmq")) == 0 assert any("crl relay {'rabbitmq': None}" in c for c in stand.calls) def test_signal_after_the_first_change_is_deferred() -> None: stand = FakeStand() stand.begin_change("issue") stand.on_signal(signal.SIGINT, None) assert stand.pending == signal.SIGINT fresh = FakeStand() with pytest.raises(SystemExit) as exit_info: fresh.on_signal(signal.SIGTERM, None) assert exit_info.value.code == 130 def _env_file(tmp_path: Path) -> Path: path = tmp_path / ".env" path.write_text( "POSTGRES_API_PASSWORD=0123456789abcdef0123456789abcdef\n" "S3_API_ACCESS_KEY=" + "a" * 64 + "\nS3_API_SECRET_KEY=" + "b" * 64 + "\n", encoding="utf-8", ) path.chmod(0o600) return path def test_postgres_secret_order(tmp_path: Path) -> None: stand = FakeStand() stand.env_file = _env_file(tmp_path) code = rotation.execute(stand, lambda: rotation.cmd_secret(stand, "postgres/api")) assert code == 0 assert _steps(stand) == [ "seed", "one-off postgres-bootstrap", "processes api", "sessions api", "verify", ] assert "0123456789abcdef" not in stand.env_file.read_text(encoding="utf-8") assert stand.env_file.stat().st_mode & 0o777 == 0o600 def test_s3_secret_keeps_both_keys_until_processes_move(tmp_path: Path) -> None: stand = FakeStand() stand.env_file = _env_file(tmp_path) assert rotation.execute(stand, lambda: rotation.cmd_secret(stand, "s3/api")) == 0 assert _steps(stand) == [ "s3 keep", "seed", "processes api", "one-off s3-bootstrap", "verify", ] def test_postgres_secret_failure_names_open_sessions(tmp_path: Path) -> None: stand = FakeStand() stand.env_file = _env_file(tmp_path) stand.fail_at = "processes" code = rotation.execute(stand, lambda: rotation.cmd_secret(stand, "postgres/api")) assert code == 1 assert "may stay open" in stand.calls[-1] assert "make rotate-secret SECRET=postgres/api" in stand.calls[-1] # --- чистые функции ------------------------------------------------------------ def test_env_replace_keeps_other_lines(tmp_path: Path) -> None: path = _env_file(tmp_path) old = rotation.env_value(path, "POSTGRES_API_PASSWORD") new = rotation.new_value(old) assert len(new) == len(old) assert re.fullmatch("[0-9a-f]+", new) assert new != old rotation.replace_env_values(path, {"POSTGRES_API_PASSWORD": new}) text = path.read_text(encoding="utf-8") assert f"POSTGRES_API_PASSWORD={new}\n" in text assert "S3_API_ACCESS_KEY=" + "a" * 64 in text with pytest.raises(rotation.NotReady): rotation.env_value(path, "MISSING_VARIABLE") def test_loaded_versions_from_her_log_line() -> None: log = ( "2026-12-02T05:00:00.000Z INFO src.secrets_store [rid=-] process secrets " "loaded process=api role=api address=https://openbao:8200 " "versions=postgres/api:1,valkey/api:1,s3/api:1 token_ttl=600s policies=api " "waited=0.1s\n" "2026-12-02T05:01:00.000Z INFO src.secrets_store [rid=-] process secrets " "loaded process=api role=api address=https://openbao:8200 " "versions=postgres/api:2,valkey/api:1,s3/api:3 token_ttl=600s policies=api " "waited=0.1s\n" ) assert rotation.loaded_versions(log) == { "postgres/api": 2, "valkey/api": 1, "s3/api": 3, } def test_broker_connections_of_previous_leaf() -> None: listing = "<0.1.0>\trelay\told\n<0.2.0>\trelay\tnew\n<0.3.0>\tworker\told\n" assert rotation.old_connections(listing, "relay", "new") == ["<0.1.0>"] assert rotation.old_connections(listing, "relay", None) == ["<0.1.0>", "<0.2.0>"] def test_converging_hint() -> None: assert ( rotation.converging(["postgres/api"]) == "make rotate-secret SECRET=postgres/api" ) assert rotation.converging(["s3/api", "postgres/worker"]).startswith("make up; ") def test_lb_payload_has_no_empty_lines() -> None: payload = rotation.Stand.lb_payload("cert", "/run/secrets/x.pem", "A\n\nB\n") assert "\n\n" not in payload.rstrip("\n") # --- pki.sh на временном CA ------------------------------------------------- def _openssl() -> str | None: for candidate in ( os.environ.get("OPENSSL") or "", "openssl", "/opt/homebrew/opt/openssl@3/bin/openssl", "/usr/local/opt/openssl@3/bin/openssl", ): path = shutil.which(candidate) if candidate else None if path: out = subprocess.run([path, "version"], capture_output=True, text=True) if re.match(r"OpenSSL [3-9]", out.stdout): return path return None @pytest.fixture def pki(tmp_path: Path): binary = _openssl() if binary is None: pytest.skip("no OpenSSL 3+ (macOS: brew install openssl@3)") identities = tmp_path / "identities.conf" identities.write_text("worker client worker split\n", encoding="utf-8") env = { **os.environ, "OPENSSL": binary, "PKI_OPERATOR_DIR": str(tmp_path / "operator"), "PKI_STAND_DIR": str(tmp_path / "stand"), "PKI_IDENTITIES": str(identities), } def run(*args: str) -> subprocess.CompletedProcess: return subprocess.run( ["sh", str(PKI), *args], env=env, capture_output=True, text=True ) assert run("stand").returncode == 0 run.dir = tmp_path # type: ignore[attr-defined] return run def test_rotate_keeps_the_previous_leaf_valid(pki) -> None: first = pki("status").stdout assert "older leaf" not in first out = pki("rotate", "worker") assert out.returncode == 0 assert "not revoked yet" in out.stdout assert "older leaf worker: 1 still valid" in pki("status").stdout revoked = pki("revoke", "worker", "--superseded") assert revoked.returncode == 0 assert revoked.stdout.count("revoked worker") == 1 status = pki("status").stdout assert "older leaf" not in status assert "REVOKED" not in status again = pki("revoke", "worker", "--superseded") assert again.returncode == 0 assert "nothing to revoke" in again.stdout def test_hold_blocks_stand_until_rotate(pki) -> None: out = pki("revoke", "worker", "--hold") assert out.returncode == 0 assert "make revoke-identity" in out.stdout stand = pki("stand").stdout assert "held worker: revoked" in stand assert "reissue worker" not in stand assert ( "REVOKED, held until make rotate-leaf IDENTITY=worker" in pki("status").stdout ) assert pki("rotate", "worker").returncode == 0 status = pki("status").stdout assert "held" not in status assert "REVOKED" not in status def test_hold_refuses_a_name_not_in_the_list(pki) -> None: out = pki("revoke", "stranger", "--hold") assert out.returncode == 1 assert "not in" in out.stderr assert not (pki.dir / "operator" / "revoked" / "stranger").exists() def test_lost_ca_database_is_refused(pki) -> None: index = pki.dir / "operator" / "index.txt" shutil.copyfile(index, str(index) + ".old") index.unlink() for command in (("status",), ("crl",), ("stand",), ("revoke", "worker")): out = pki(*command) assert out.returncode == 1, command assert "index.txt is missing" in out.stderr, command assert "cp -n" in out.stderr, command assert not index.exists() # --- соседние правки --------------------------------------------------------- def test_role_password_refusal_is_unavailable() -> None: from sqlalchemy import exc as sa_exc from src.db import is_unavailable class Refused(Exception): sqlstate = "28P01" error = sa_exc.DBAPIError("connect", None, Refused()) assert is_unavailable(error) def test_neighbour_files() -> None: rollout = (ROOT / "scripts" / "rolling-update.sh").read_text(encoding="utf-8") assert 'check_only="${ROLLOUT_CHECK:-0}"' in rollout assert "com.docker.compose.image" in rollout start = (ROOT / "infra" / "rabbitmq" / "start.sh").read_text(encoding="utf-8") assert '"--install-crl"' in start assert '"--install-leaf"' in start boot = (ROOT / "infra" / "s3" / "bootstrap.sh").read_text(encoding="utf-8") assert 'if [ "$KEEP_STALE_KEYS" = 1 ]; then' in boot monitor = _text("infra/haproxy/haproxy.cfg").split("frontend monitor", 1)[1] monitor = monitor.split("\nfrontend ", 1)[0] assert "option httpclose" in monitor assert "timeout client-hs 5s" in monitor def test_make_targets_and_codex_rules() -> None: makefile = (ROOT / "Makefile").read_text(encoding="utf-8") rules = (ROOT / ".codex" / "rules" / "messenger.rules").read_text(encoding="utf-8") for target in ( "rotate-leaf", "revoke-identity", "pki-renew", "rotate-secret", "rotation-check", ): assert re.search(rf"^{target}:", makefile, re.M), target assert f'"{target}"' in rules, target assert re.search(r"^up: rotation-idle ", makefile, re.M) assert "@$(ROTATION) idle\n\tAPI_REPLICAS" in makefile