forked from mtusi2026/mtusi2026lab7
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>
278 lines
9.9 KiB
Python
278 lines
9.9 KiB
Python
"""Ротация leaf скриптом PKI (change `rotation-revocation`, design, решение 4;
|
||
спек `pki`, «Новый leaf без отзыва прежнего и отзыв прежних», «Отзыв и CRL»).
|
||
|
||
Настоящий `infra/pki/pki.sh` во временных каталогах оператора и стенда:
|
||
`rotate` — новый leaf рядом с действующим, CRL и база отзыва прежние; `revoke
|
||
--superseded` — только прежние; отзывать нечего — база CA и CRL те же байты;
|
||
`issue --not-after` — точный конец срока; `status` называет identity с
|
||
действующими прежними leaf (истёкшие не считаются); `revoke` называет команду,
|
||
которая применяет отзыв. В выводе нет ключей. Без OpenSSL 3+ тесты
|
||
пропускаются с причиной.
|
||
"""
|
||
|
||
import os
|
||
import shutil
|
||
import subprocess
|
||
import time
|
||
from collections.abc import Callable
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
from src.config.settings import BASE_DIR
|
||
|
||
PKI_SCRIPT = BASE_DIR / "infra" / "pki" / "pki.sh"
|
||
Run = Callable[..., subprocess.CompletedProcess[str]]
|
||
|
||
|
||
def _openssl() -> str | None:
|
||
binary = os.environ.get("OPENSSL") or shutil.which("openssl")
|
||
if not binary:
|
||
return None
|
||
version = subprocess.run( # noqa: S603
|
||
[binary, "version"],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout
|
||
if not version.startswith("OpenSSL ") or int(version[8]) < 3: # noqa: PLR2004
|
||
return None
|
||
return binary
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def base(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
||
"""Готовая PKI (CA, CRL, leaf списка): тесты работают на её копии."""
|
||
if _openssl() is None:
|
||
pytest.skip("OpenSSL 3+ is required for PKI tests")
|
||
root = tmp_path_factory.mktemp("pki-rotation")
|
||
result = _run_in(root, "stand")
|
||
assert result.returncode == 0, result.stderr
|
||
return root
|
||
|
||
|
||
def _run_in(root: Path, *args: str) -> subprocess.CompletedProcess[str]:
|
||
result = subprocess.run( # noqa: S603
|
||
["/bin/sh", str(PKI_SCRIPT), *args],
|
||
env={
|
||
**os.environ,
|
||
"OPENSSL": _openssl() or "openssl",
|
||
"PKI_OPERATOR_DIR": str(root / "op"),
|
||
"PKI_STAND_DIR": str(root / "stand"),
|
||
},
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
assert "PRIVATE KEY" not in result.stdout + result.stderr
|
||
return result
|
||
|
||
|
||
@pytest.fixture
|
||
def root(base: Path, tmp_path: Path) -> Path:
|
||
target = tmp_path / "pki"
|
||
shutil.copytree(base, target)
|
||
return target
|
||
|
||
|
||
@pytest.fixture
|
||
def pki(root: Path) -> Run:
|
||
def run(*args: str) -> subprocess.CompletedProcess[str]:
|
||
return _run_in(root, *args)
|
||
|
||
return run
|
||
|
||
|
||
def _x509(path: Path, *args: str) -> str:
|
||
return subprocess.run( # noqa: S603
|
||
[_openssl() or "openssl", "x509", "-in", str(path), "-noout", *args],
|
||
capture_output=True,
|
||
text=True,
|
||
check=True,
|
||
).stdout.strip()
|
||
|
||
|
||
def _serial(path: Path) -> str:
|
||
return _x509(path, "-serial").split("=")[1]
|
||
|
||
|
||
def _verify(root: Path, path: Path) -> str:
|
||
"""`ok` или причина отказа `openssl verify -crl_check`."""
|
||
result = subprocess.run( # noqa: S603
|
||
[
|
||
_openssl() or "openssl",
|
||
"verify",
|
||
"-crl_check",
|
||
"-CAfile",
|
||
str(root / "stand" / "ca.crt"),
|
||
"-CRLfile",
|
||
str(root / "stand" / "crl.pem"),
|
||
str(path),
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
if result.returncode == 0:
|
||
return "ok"
|
||
out = result.stdout + result.stderr
|
||
for reason in ("certificate revoked", "certificate has expired"):
|
||
if reason in out:
|
||
return reason
|
||
return out
|
||
|
||
|
||
def _older(output: str) -> list[str]:
|
||
return [
|
||
line for line in output.splitlines() if line.startswith("older leaf ")
|
||
]
|
||
|
||
|
||
def _state(root: Path) -> tuple[bytes, bytes, bytes]:
|
||
return (
|
||
(root / "op" / "index.txt").read_bytes(),
|
||
(root / "op" / "crlnumber").read_bytes(),
|
||
(root / "stand" / "crl.pem").read_bytes(),
|
||
)
|
||
|
||
|
||
def test_rotate_keeps_previous_leaf(root: Path, pki: Run) -> None:
|
||
"""Сценарий «Новый leaf рядом с действующим»."""
|
||
stand = root / "stand"
|
||
old = root / "old.crt"
|
||
shutil.copyfile(stand / "relay.crt", old)
|
||
crl = (stand / "crl.pem").read_bytes()
|
||
before, old_key = _serial(old), (stand / "relay.key").read_bytes()
|
||
result = pki("rotate", "relay")
|
||
assert result.returncode == 0, result.stderr
|
||
after = _serial(stand / "relay.crt")
|
||
assert after != before
|
||
assert f"{before} -> {after}" in result.stdout
|
||
assert (stand / "relay.key").read_bytes() != old_key
|
||
assert (stand / "relay.key").stat().st_mode & 0o777 == 0o600 # noqa: PLR2004
|
||
for ext in ("subjectAltName", "extendedKeyUsage", "keyUsage"):
|
||
assert _x509(stand / "relay.crt", "-ext", ext) == _x509(
|
||
old,
|
||
"-ext",
|
||
ext,
|
||
)
|
||
assert (stand / "crl.pem").read_bytes() == crl
|
||
assert _verify(root, old) == "ok"
|
||
assert _verify(root, stand / "relay.crt") == "ok"
|
||
assert _older(pki("status").stdout) == [
|
||
"older leaf relay: 1 still valid and not revoked besides the stand "
|
||
"leaf",
|
||
]
|
||
|
||
|
||
def test_rotate_bundle_form(root: Path, pki: Run) -> None:
|
||
"""Форма `bundle`: `.pem` — новый сертификат и ключ."""
|
||
stand = root / "stand"
|
||
assert pki("rotate", "haproxy").returncode == 0
|
||
pem = (stand / "haproxy.pem").read_bytes()
|
||
assert (
|
||
pem
|
||
== (stand / "haproxy.crt").read_bytes()
|
||
+ (stand / "haproxy.key").read_bytes()
|
||
)
|
||
|
||
|
||
def test_rotate_unknown_identity(root: Path, pki: Run) -> None:
|
||
"""Имя не из списка — ненулевой код, ничего не выпущено."""
|
||
before = _state(root)
|
||
result = pki("rotate", "mallory")
|
||
assert result.returncode != 0
|
||
assert "mallory" in result.stderr
|
||
assert _state(root) == before
|
||
|
||
|
||
def test_revoke_superseded_only(root: Path, pki: Run) -> None:
|
||
"""Сценарий «Отзыв только прежних»: два прежних leaf отозваны, leaf стенда
|
||
и чужие identity действуют."""
|
||
stand = root / "stand"
|
||
previous = []
|
||
for number in range(2):
|
||
copy = root / f"old{number}.crt"
|
||
shutil.copyfile(stand / "relay.crt", copy)
|
||
previous.append(copy)
|
||
assert pki("rotate", "relay").returncode == 0
|
||
result = pki("revoke", "relay", "--superseded")
|
||
assert result.returncode == 0, result.stderr
|
||
for copy in previous:
|
||
assert _verify(root, copy) == "certificate revoked"
|
||
assert _serial(copy) in result.stdout
|
||
assert _verify(root, stand / "relay.crt") == "ok"
|
||
assert _serial(stand / "relay.crt") not in result.stdout
|
||
assert _verify(root, stand / "worker.crt") == "ok"
|
||
assert _older(pki("status").stdout) == []
|
||
|
||
|
||
def test_revoke_superseded_nothing(root: Path, pki: Run) -> None:
|
||
"""Сценарий «Отзывать нечего»: код 0, база CA и CRL — те же байты."""
|
||
before = _state(root)
|
||
result = pki("revoke", "relay", "--superseded")
|
||
assert result.returncode == 0, result.stderr
|
||
assert "nothing to revoke" in result.stdout
|
||
assert _state(root) == before
|
||
|
||
|
||
def test_revoke_superseded_requires_stand_leaf(root: Path, pki: Run) -> None:
|
||
"""Leaf стенда нет (не сверить, что оставлять) — отказ без изменений."""
|
||
before = _state(root)
|
||
(root / "stand" / "relay.crt").unlink()
|
||
assert pki("revoke", "relay", "--superseded").returncode != 0
|
||
assert _state(root) == before
|
||
|
||
|
||
def test_revoke_names_next_command(root: Path, pki: Run) -> None:
|
||
"""Сценарий «Подсказка применения отзыва»; с `--superseded` её нет."""
|
||
serial = _serial(root / "stand" / "relay.crt")
|
||
result = pki("revoke", "relay")
|
||
assert result.returncode == 0, result.stderr
|
||
assert serial in result.stdout
|
||
assert "make revoke_identity IDENTITY=relay" in result.stdout
|
||
assert pki("rotate", "relay").returncode == 0
|
||
assert pki("rotate", "relay").returncode == 0
|
||
result = pki("revoke", "relay", "--superseded")
|
||
assert "revoke_identity" not in result.stdout
|
||
|
||
|
||
def test_issue_not_after(root: Path, pki: Run) -> None:
|
||
"""Сценарий «Leaf с концом срока через секунды»; истёкшие прежние leaf
|
||
статус не считает, действующие — считает."""
|
||
end = time.time() + 4
|
||
stamp = time.strftime("%Y%m%d%H%M%SZ", time.gmtime(end))
|
||
out = root / "probe"
|
||
args = ("issue", "relay", "--profile", "client", "--san", "relay")
|
||
result = pki(*args, "--not-after", stamp, "--out", str(out))
|
||
assert result.returncode == 0, result.stderr
|
||
assert _verify(root, out / "relay.crt") == "ok"
|
||
assert len(_older(pki("status").stdout)) == 1
|
||
time.sleep(max(0.0, end - time.time()) + 1.5)
|
||
assert _verify(root, out / "relay.crt") == "certificate has expired"
|
||
assert _older(pki("status").stdout) == []
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"period",
|
||
[
|
||
(),
|
||
("--not-after", "20300101"),
|
||
("--not-after", "20300101000000Z", "--days", "1"),
|
||
],
|
||
)
|
||
def test_issue_period_is_required(
|
||
root: Path,
|
||
pki: Run,
|
||
period: tuple[str, ...],
|
||
) -> None:
|
||
"""Срок разового leaf — ровно один из `--days` и `--not-after`."""
|
||
before = _state(root)
|
||
result = pki(
|
||
*("issue", "probe", "--profile", "client", "--san", "probe"),
|
||
*period,
|
||
*("--out", str(root / "probe")),
|
||
)
|
||
assert result.returncode != 0
|
||
assert _state(root) == before
|