fix: address rotation-revocation control verify findings
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>
This commit is contained in:
@@ -55,7 +55,11 @@ def base(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
||||
return root
|
||||
|
||||
|
||||
def _run_in(root: Path, *args: str) -> subprocess.CompletedProcess[str]:
|
||||
def _run_in(
|
||||
root: Path,
|
||||
*args: str,
|
||||
env: dict[str, str] | None = None,
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
result = subprocess.run( # noqa: S603
|
||||
["/bin/sh", str(PKI_SCRIPT), *args],
|
||||
env={
|
||||
@@ -63,6 +67,7 @@ def _run_in(root: Path, *args: str) -> subprocess.CompletedProcess[str]:
|
||||
"OPENSSL": _openssl() or "openssl",
|
||||
"PKI_OPERATOR_DIR": str(root / "op"),
|
||||
"PKI_STAND_DIR": str(root / "stand"),
|
||||
**(env or {}),
|
||||
},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
@@ -340,6 +345,169 @@ def test_hold_survives_a_failed_crl(root: Path, pki: Run) -> None:
|
||||
assert _held(root) == ["relay"]
|
||||
|
||||
|
||||
def _fake_openssl(root: Path, part: str, body: str) -> dict[str, str]:
|
||||
"""Подставной openssl: на вызове с аргументом `part` исполняет `body`
|
||||
(`real` — настоящий с теми же аргументами, $PPID — pki.sh)."""
|
||||
binary = root / "fake-openssl"
|
||||
binary.write_text(
|
||||
"#!/bin/sh\n"
|
||||
f'real() {{ "{_openssl()}" "$@"; }}\n'
|
||||
f'case " $* " in *" {part} "*)\n{body}\n;; esac\nreal "$@"\n',
|
||||
)
|
||||
binary.chmod(0o755)
|
||||
return {"OPENSSL": str(binary)}
|
||||
|
||||
|
||||
def _revoked(root: Path) -> bool:
|
||||
rows = (root / "op" / "index.txt").read_text().splitlines()
|
||||
(row,) = [line for line in rows if line.endswith("/CN=relay")]
|
||||
return row.startswith("R")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("when", ["before", "after"])
|
||||
@pytest.mark.parametrize("number", ["HUP", "INT", "TERM"])
|
||||
def test_hold_survives_a_signal(number: str, when: str, root: Path) -> None:
|
||||
"""Сигнал самой команде или всей группе во время отзыва (до записи в базу
|
||||
и после неё): отзыв доведён до CRL, отметка стоит — `stand` отозванной
|
||||
identity ключа не выдаст."""
|
||||
body = (
|
||||
f"kill -{number} $PPID $$"
|
||||
if when == "before"
|
||||
else f'real "$@"; kill -{number} $PPID $$; exit 0'
|
||||
)
|
||||
crl = (root / "stand" / "crl.pem").read_bytes()
|
||||
env = _fake_openssl(root, "-revoke", body)
|
||||
result = _run_in(root, "revoke", "relay", "--hold", env=env)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert _revoked(root)
|
||||
assert _held(root) == ["relay"]
|
||||
assert (root / "stand" / "crl.pem").read_bytes() != crl
|
||||
assert "held relay: revoked" in _run_in(root, "stand").stdout
|
||||
|
||||
|
||||
def test_signal_of_a_repeated_revocation(root: Path, pki: Run) -> None:
|
||||
"""Отметка поставлена раньше, и отзыв без удержания: сигнал посреди
|
||||
отзыва — тоже до CRL."""
|
||||
for flags in (["--hold"], []):
|
||||
assert pki("revoke", "relay", "--hold").returncode in (0, 1)
|
||||
out = root / "stand"
|
||||
args = ("issue", "relay", "--profile", "client", "--san", "relay")
|
||||
assert pki(*args, "--days", "90", "--out", str(out)).returncode == 0
|
||||
env = _fake_openssl(root, "-revoke", "kill -TERM $PPID $$")
|
||||
result = _run_in(root, "revoke", "relay", *flags, env=env)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert _verify(root, out / "relay.crt") == "certificate revoked"
|
||||
assert _held(root) == ["relay"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
'real "$@"; kill -USR1 $PPID; sleep 0.2; exit 0',
|
||||
# команда кончилась раньше, чем openssl записал базу
|
||||
"kill -USR1 $PPID; sleep 0.5",
|
||||
],
|
||||
)
|
||||
def test_hold_survives_an_exit_by_another_signal(
|
||||
body: str,
|
||||
root: Path,
|
||||
) -> None:
|
||||
"""Сигнал, который команда не перехватывает, её обрывает, и оболочка зовёт
|
||||
cleanup: отметку начатого отзыва он не снимает."""
|
||||
env = _fake_openssl(root, "-revoke", body)
|
||||
result = _run_in(root, "revoke", "relay", "--hold", env=env)
|
||||
assert result.returncode != 0
|
||||
deadline = time.time() + 10
|
||||
while not _revoked(root) and time.time() < deadline:
|
||||
time.sleep(0.1)
|
||||
assert _revoked(root)
|
||||
assert _held(root) == ["relay"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("body", "revoked", "held"),
|
||||
[
|
||||
# openssl убит после записи: leaf отозван, хотя openssl и «не смог»
|
||||
('real "$@"; kill -KILL $$', True, ["relay"]),
|
||||
("kill -KILL $$", False, []),
|
||||
("exit 1", False, []),
|
||||
],
|
||||
)
|
||||
def test_hold_after_openssl_failed(
|
||||
body: str,
|
||||
revoked: bool,
|
||||
held: list[str],
|
||||
root: Path,
|
||||
) -> None:
|
||||
"""Отметку решает база, а не код openssl."""
|
||||
env = _fake_openssl(root, "-revoke", body)
|
||||
result = _run_in(root, "revoke", "relay", "--hold", env=env)
|
||||
assert result.returncode == 1
|
||||
assert _revoked(root) is revoked
|
||||
assert _held(root) == held
|
||||
|
||||
|
||||
def test_hold_of_a_half_done_revocation(root: Path, pki: Run) -> None:
|
||||
"""Первый leaf отозван, отзыв второго не удался — отметка, поставленная
|
||||
этой же командой, остаётся."""
|
||||
out = root / "probe"
|
||||
args = ("issue", "relay", "--profile", "client", "--san", "relay")
|
||||
assert pki(*args, "--days", "1", "--out", str(out)).returncode == 0
|
||||
(root / "op" / "certs" / f"{_serial(out / 'relay.crt')}.pem").unlink()
|
||||
assert pki("revoke", "relay", "--hold").returncode == 1
|
||||
rows = (root / "op" / "index.txt").read_text().splitlines()
|
||||
marks = sorted(r[0] for r in rows if r.endswith("/CN=relay"))
|
||||
assert marks == ["R", "V"]
|
||||
assert _held(root) == ["relay"]
|
||||
|
||||
|
||||
def test_hold_without_a_temporary_directory(root: Path) -> None:
|
||||
"""Отзыв не начат (журналу openssl негде быть) — отметки нет."""
|
||||
result = _run_in(
|
||||
root,
|
||||
*("revoke", "relay", "--hold"),
|
||||
env={"TMPDIR": str(root / "missing")},
|
||||
)
|
||||
assert result.returncode != 0
|
||||
assert not _revoked(root)
|
||||
assert _held(root) == []
|
||||
|
||||
|
||||
def test_killed_init_leaves_no_ca_key(tmp_path: Path) -> None:
|
||||
"""`init`, убитый SIGKILL между ключом CA и сертификатом: временный каталог
|
||||
остаётся, но ключа CA в нём нет; повтор создаёт CA."""
|
||||
if _openssl() is None:
|
||||
pytest.skip("OpenSSL 3+ is required for PKI tests")
|
||||
temporary = tmp_path / "tmp"
|
||||
temporary.mkdir()
|
||||
env = _fake_openssl(tmp_path, "req", "kill -KILL $PPID; exit 1")
|
||||
result = _run_in(tmp_path, "init", env={**env, "TMPDIR": str(temporary)})
|
||||
assert result.returncode == -9 # noqa: PLR2004
|
||||
left = [p for p in temporary.rglob("*") if p.is_file()]
|
||||
assert not [p for p in left if "PRIVATE" in p.read_text()]
|
||||
assert not (tmp_path / "op" / "ca.key").exists()
|
||||
assert _run_in(tmp_path, "init").returncode == 0
|
||||
key = tmp_path / "op" / "ca.key"
|
||||
assert key.stat().st_mode & 0o777 == 0o600 # noqa: PLR2004
|
||||
assert not (tmp_path / "op" / ".ca.key.tmp").exists()
|
||||
|
||||
|
||||
def test_two_held_in_a_recreated_stand_directory(root: Path, pki: Run) -> None:
|
||||
"""Файлы нужны всем удержанным разом: цепочка называет каждую, кроме той,
|
||||
чьи файлы на месте."""
|
||||
for name in ("cleaner", "otel-collector", "worker"):
|
||||
assert pki("revoke", name, "--hold").returncode == 0
|
||||
for name in ("cleaner.key", "otel-collector.pem"):
|
||||
(root / "stand" / name).unlink()
|
||||
out = pki("stand").stdout
|
||||
chain = (
|
||||
"to return it: infra/pki/pki.sh rotate otel-collector; "
|
||||
"infra/pki/pki.sh rotate cleaner; make stop; "
|
||||
)
|
||||
assert out.count(chain) == 2 # noqa: PLR2004
|
||||
assert "rotate worker;" not in out
|
||||
|
||||
|
||||
def test_hold_in_a_recreated_stand_directory(root: Path, pki: Run) -> None:
|
||||
"""Сценарий «Каталог стенда создан заново»: leaf удержанной identity не
|
||||
выдан, её файлов нет — вывод и статус называют, чем она возвращается;
|
||||
@@ -350,7 +518,8 @@ def test_hold_in_a_recreated_stand_directory(root: Path, pki: Run) -> None:
|
||||
assert "held relay: missing" in out
|
||||
assert (
|
||||
"held relay: compose cannot start without its files; to return it: "
|
||||
"infra/pki/pki.sh rotate relay; make run_docker; make pki_renew"
|
||||
"infra/pki/pki.sh rotate relay; make stop; make bao_unseal; "
|
||||
"make run_docker; make pki_renew"
|
||||
) in out
|
||||
assert not list((root / "stand").glob("relay*"))
|
||||
line = _leaf_line(pki("status").stdout, "relay")
|
||||
|
||||
Reference in New Issue
Block a user