forked from mtusi2026/mtusi2026lab7
fix: address rotation-revocation re-verify findings
Name only the repeat of rotate_secret while sessions of the previous PostgreSQL password may stay open, compare KV version time with the container start when the load record is gone, refuse run_docker and rolling_update next to a running rotation, defer SIGQUIT, and name the remaining windows and cases in the trust matrix and threat model. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -385,19 +385,26 @@ class FakeStand(rotation.Stand): # type: ignore[misc]
|
||||
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, 1)
|
||||
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:
|
||||
pass
|
||||
if self.statuses:
|
||||
self.revoked = self.statuses.pop(0)
|
||||
|
||||
def kv_state(self) -> tuple[dict[str, int], set[str]]:
|
||||
def kv_state(self) -> tuple[dict[str, Any], set[str]]:
|
||||
return dict(self.kv), set(self.differs)
|
||||
|
||||
def lagging(self, _versions: dict[str, int]) -> dict[str, set[str]]:
|
||||
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:
|
||||
@@ -501,6 +508,12 @@ class FakeStand(rotation.Stand): # type: ignore[misc]
|
||||
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}")
|
||||
@@ -599,6 +612,9 @@ def test_leaf_without_running_owner(identity: str) -> None:
|
||||
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:
|
||||
@@ -731,6 +747,38 @@ def test_renew_does_not_apply_a_revoked_leaf() -> None:
|
||||
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."""
|
||||
@@ -888,9 +936,57 @@ def test_secret_failure_names_phase(
|
||||
assert f"FAILED in phase '{phase}'" in out
|
||||
assert "make rotate_secret SECRET=postgres/api" in out
|
||||
assert "make run_docker" in out
|
||||
# от смены пароля до закрытия сессии прежнего пароля открыты: названо
|
||||
open_sessions = phase in ("storage", "processes", "sessions")
|
||||
# от новой строки .env до закрытия сессии прежнего пароля открыты, и
|
||||
# run_docker их не закроет: названо
|
||||
open_sessions = phase != "verify"
|
||||
assert ("opened with the previous password" in out) is open_sessions
|
||||
assert ("only restores the service" in out) is open_sessions
|
||||
|
||||
|
||||
def test_failure_after_the_sessions_are_closed(
|
||||
secret_env: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Сессии роли без реплик закрыты сразу после смены пароля: дальше сбой
|
||||
сводит и `run_docker`, открытых сессий вывод не называет."""
|
||||
stand = FakeStand(secret_env)
|
||||
stand.seeded = {"postgres/cleaner": 2}
|
||||
stand.fail = "apply"
|
||||
assert _run(stand, rotation.cmd_secret, "postgres/cleaner") == 1
|
||||
out = capsys.readouterr().out.split("FAILED", 1)[1]
|
||||
assert "in phase 'processes'" in out
|
||||
assert "opened with the previous password" not in out
|
||||
assert "or run `make run_docker` to converge" 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(
|
||||
@@ -952,25 +1048,61 @@ def test_secret_hidden_by_environment(
|
||||
assert "from-the-environment" not in out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", ["differs", "lag"])
|
||||
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(
|
||||
case: str,
|
||||
how: str,
|
||||
half: set[str],
|
||||
path: str,
|
||||
hint: str,
|
||||
secret_env: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Сценарий «Прерванная ротация другого пути»: KV не из `.env` или процесс
|
||||
не на версии KV — код 2 с именем пути, ничего не изменено."""
|
||||
не на версии KV — код 2 с именем пути и тем, что сводит, ничего не
|
||||
изменено."""
|
||||
before = secret_env.read_bytes()
|
||||
stand = FakeStand(secret_env)
|
||||
stand.seeded = {"s3/cleaner": 2}
|
||||
if case == "differs":
|
||||
stand.differs = {"postgres/worker"}
|
||||
stand.seeded = {path: 2}
|
||||
if how == "differs":
|
||||
stand.differs = set(half)
|
||||
else:
|
||||
stand.lag = {"worker": {"postgres/worker"}}
|
||||
assert _run(stand, rotation.cmd_secret, "s3/cleaner") == 2 # noqa: PLR2004
|
||||
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 "postgres/worker" in out
|
||||
assert "run make run_docker first; nothing changed" in 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 == []
|
||||
|
||||
@@ -1032,6 +1164,8 @@ def test_leaf_of_revoked_identity() -> None:
|
||||
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"}
|
||||
@@ -1121,6 +1255,30 @@ def test_closed_output_does_not_stop(how: str, tmp_path: Path) -> None:
|
||||
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; блокировка убитого процесса не
|
||||
мешает: её снимает ядро."""
|
||||
@@ -1146,10 +1304,26 @@ def test_one_command_at_a_time(tmp_path: Path) -> None:
|
||||
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.parametrize("argv", [["leaf", "relay"], ["secret", "s3/api"]])
|
||||
|
||||
Reference in New Issue
Block a user