forked from mtusi2026/mtusi2026lab7
feat: rotate and revoke credentials on the running stand
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>
This commit is contained in:
@@ -326,6 +326,73 @@ async def test_handshake_outcomes(
|
||||
]
|
||||
|
||||
|
||||
def _server_reason(root: Path, cert: tuple[Path, Path]) -> str:
|
||||
"""Причина отказа клиенту контекстом сервера API (рукопожатие через
|
||||
буферы в памяти, без uvicorn)."""
|
||||
to_server, to_client = ssl.MemoryBIO(), ssl.MemoryBIO()
|
||||
context = ssl.create_default_context(cafile=root / "stand" / "ca.crt")
|
||||
context.load_cert_chain(certfile=cert[0], keyfile=cert[1])
|
||||
client = context.wrap_bio(to_client, to_server, server_hostname="api")
|
||||
server = build_server_context(_stand_tls(root)).wrap_bio(
|
||||
to_server,
|
||||
to_client,
|
||||
server_side=True,
|
||||
)
|
||||
for _ in range(4):
|
||||
with contextlib.suppress(ssl.SSLWantReadError):
|
||||
client.do_handshake()
|
||||
try:
|
||||
server.do_handshake()
|
||||
except ssl.SSLWantReadError:
|
||||
continue
|
||||
except ssl.SSLCertVerificationError as e:
|
||||
return e.verify_message
|
||||
return "accepted"
|
||||
return "no outcome"
|
||||
|
||||
|
||||
async def test_expired_client_leaf(
|
||||
pki: Path,
|
||||
mtls_server: tuple[int, _Recorder],
|
||||
) -> None:
|
||||
"""Сценарий «Истёкший leaf» (change `rotation-revocation`, design, решение
|
||||
12): leaf разрешённой identity с концом срока через секунды принят до него
|
||||
и отвергнут после."""
|
||||
port, recorder = mtls_server
|
||||
end = time.time() + 4
|
||||
_pki(
|
||||
{
|
||||
"OPENSSL": _openssl() or "openssl",
|
||||
"PKI_OPERATOR_DIR": str(pki / "op"),
|
||||
"PKI_STAND_DIR": str(pki / "stand"),
|
||||
},
|
||||
"issue",
|
||||
"haproxy",
|
||||
"--profile",
|
||||
"client",
|
||||
"--san",
|
||||
"haproxy",
|
||||
"--not-after",
|
||||
time.strftime("%Y%m%d%H%M%SZ", time.gmtime(end)),
|
||||
"--out",
|
||||
str(pki / "short"),
|
||||
)
|
||||
cert = (pki / "short" / "haproxy.crt", pki / "short" / "haproxy.key")
|
||||
before = await asyncio.to_thread(_client_exchange, port, pki, cert)
|
||||
assert before.startswith("HTTP/1.1 200"), before
|
||||
await asyncio.sleep(max(0.0, end - time.time()) + 1.5)
|
||||
after = await asyncio.to_thread(_client_exchange, port, pki, cert)
|
||||
assert not after.startswith("HTTP/"), after
|
||||
# alert asyncio не отправляет: причину называет контекст сервера
|
||||
reason = await asyncio.to_thread(_server_reason, pki, cert)
|
||||
assert reason == "certificate has expired"
|
||||
stand = pki / "stand"
|
||||
fresh = (stand / "haproxy.crt", stand / "haproxy.key")
|
||||
alive = await asyncio.to_thread(_client_exchange, port, pki, fresh)
|
||||
assert alive.startswith("HTTP/1.1 200"), alive
|
||||
assert recorder.records == []
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def revocation(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
||||
"""Свой PKI (общий `pki` не трогаем): отозванный `haproxy` (копия пары до
|
||||
|
||||
@@ -234,3 +234,208 @@ def test_command_exits_1_when_not_active(
|
||||
assert "bao: OpenBao is not active in 1 s (sys/health 429)" in out, out
|
||||
assert "/v1/sys/seal-status" in state.paths
|
||||
assert not operator_dir.exists()
|
||||
|
||||
|
||||
# отзыв токенов роли (change rotation-revocation, design, решение 8; спек
|
||||
# secret-store, «Отзыв токенов identity оператором»): accessor → (роль входа,
|
||||
# серийный номер leaf) и токен без роли (root); «исчезнувший» accessor есть в
|
||||
# списке, но его поиск отвечает 403, а отзыв другого — 400
|
||||
ROOT_TOKEN = "s.root-of-the-test" # noqa: S105
|
||||
OLD_SERIAL = 0x01AC0000000000000000000000000001
|
||||
NEW_SERIAL = 0x01AC0000000000000000000000000002
|
||||
ACCESSORS: dict[str, tuple[str, int] | None] = {
|
||||
"acc-relay-old": ("relay", OLD_SERIAL),
|
||||
"acc-relay-new": ("relay", NEW_SERIAL),
|
||||
"acc-relay-vanishing": ("relay", OLD_SERIAL),
|
||||
"acc-worker": ("worker", OLD_SERIAL),
|
||||
"acc-root": None,
|
||||
"acc-gone": None,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Tokens:
|
||||
sealed: bool = False
|
||||
revoked: list[str] = field(default_factory=list)
|
||||
paths: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _tokens_handler(
|
||||
state: _Tokens,
|
||||
) -> type[http.server.BaseHTTPRequestHandler]:
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def _send(self, status: int, payload: dict[str, Any]) -> None:
|
||||
body = json.dumps(payload).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
state.paths.append(self.path)
|
||||
if self.path == "/v1/sys/seal-status":
|
||||
self._send(
|
||||
200,
|
||||
{"initialized": True, "sealed": state.sealed},
|
||||
)
|
||||
else:
|
||||
self._send(200, {})
|
||||
|
||||
def do_LIST(self) -> None: # noqa: N802
|
||||
assert self.headers["X-Vault-Token"] == ROOT_TOKEN
|
||||
assert self.path == "/v1/auth/token/accessors"
|
||||
self._send(200, {"data": {"keys": list(ACCESSORS)}})
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
assert self.headers["X-Vault-Token"] == ROOT_TOKEN
|
||||
size = int(self.headers.get("Content-Length") or 0)
|
||||
accessor = json.loads(self.rfile.read(size))["accessor"]
|
||||
if self.path == "/v1/auth/token/lookup-accessor":
|
||||
if accessor == "acc-gone":
|
||||
self._send(403, {"errors": ["invalid accessor"]})
|
||||
return
|
||||
info = ACCESSORS[accessor]
|
||||
if info is None:
|
||||
data: dict[str, Any] = {
|
||||
"path": "auth/token/root",
|
||||
"display_name": "root",
|
||||
"meta": None,
|
||||
}
|
||||
else:
|
||||
data = {
|
||||
"path": "auth/cert/login",
|
||||
"display_name": f"cert-{info[0]}",
|
||||
"meta": {"serial_number": str(info[1])},
|
||||
}
|
||||
self._send(200, {"data": data})
|
||||
elif accessor == "acc-relay-vanishing":
|
||||
self._send(400, {"errors": ["invalid accessor"]})
|
||||
else:
|
||||
assert self.path == "/v1/auth/token/revoke-accessor"
|
||||
state.revoked.append(accessor)
|
||||
self._send(204, {})
|
||||
|
||||
def log_message(self, *_args: Any) -> None:
|
||||
return None
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _token_store(stand: Path, state: _Tokens) -> Iterator[str]:
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(stand / "openbao.crt", stand / "openbao.key")
|
||||
server = http.server.ThreadingHTTPServer(
|
||||
("127.0.0.1", 0),
|
||||
_tokens_handler(state),
|
||||
)
|
||||
server.daemon_threads = True
|
||||
server.socket = context.wrap_socket(server.socket, server_side=True)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield f"https://localhost:{server.server_address[1]}"
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def _revoke_tokens(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
state: _Tokens,
|
||||
*args: str,
|
||||
) -> int:
|
||||
operator_dir = tmp_path / "op"
|
||||
operator_dir.mkdir()
|
||||
(operator_dir / "root-token").write_text(ROOT_TOKEN)
|
||||
with _token_store(pki, state) as address:
|
||||
return bao.main(
|
||||
[*_argv(address, pki, operator_dir), "revoke-tokens", *args],
|
||||
)
|
||||
|
||||
|
||||
def _assert_no_secrets(out: str) -> None:
|
||||
assert ROOT_TOKEN not in out
|
||||
for accessor in ACCESSORS:
|
||||
assert accessor not in out, out
|
||||
|
||||
|
||||
def test_revoke_tokens_of_role(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Все токены роли: чужая роль, root и исчезнувшие accessors не тронуты;
|
||||
вывод — роль и число, без токенов и accessors."""
|
||||
state = _Tokens()
|
||||
code = _revoke_tokens(bao, pki, tmp_path, state, "--role", "relay")
|
||||
out = capsys.readouterr().out
|
||||
assert code == 0, out
|
||||
assert state.revoked == ["acc-relay-old", "acc-relay-new"]
|
||||
assert "role relay: revoked 2 tokens" in out, out
|
||||
_assert_no_secrets(out)
|
||||
|
||||
|
||||
def test_revoke_tokens_keep_serial(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Токен, выданный указанному leaf, остаётся; номер — шестнадцатеричный,
|
||||
как у `openssl x509 -serial`."""
|
||||
state = _Tokens()
|
||||
code = _revoke_tokens(
|
||||
bao,
|
||||
pki,
|
||||
tmp_path,
|
||||
state,
|
||||
"--role",
|
||||
"relay",
|
||||
"--keep-serial",
|
||||
f"{NEW_SERIAL:032X}",
|
||||
)
|
||||
out = capsys.readouterr().out
|
||||
assert code == 0, out
|
||||
assert state.revoked == ["acc-relay-old"]
|
||||
assert "role relay: revoked 1 tokens, kept 1" in out, out
|
||||
_assert_no_secrets(out)
|
||||
|
||||
|
||||
def test_revoke_tokens_sealed(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Запечатан — код 2 с подсказкой, ничего не отозвано."""
|
||||
state = _Tokens(sealed=True)
|
||||
code = _revoke_tokens(bao, pki, tmp_path, state, "--role", "relay")
|
||||
out = capsys.readouterr().out
|
||||
assert code == 2, out # noqa: PLR2004
|
||||
assert "make bao_unseal" in out
|
||||
assert state.revoked == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"args",
|
||||
[("--role", "mallory"), (), ("--role", "relay", "--keep-serial", "zz")],
|
||||
)
|
||||
def test_revoke_tokens_bad_arguments(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
args: tuple[str, ...],
|
||||
) -> None:
|
||||
"""Роль — только из таблицы ROLES, серийный номер — hex: код 2 до
|
||||
обращения к OpenBao."""
|
||||
state = _Tokens()
|
||||
with pytest.raises(SystemExit) as error:
|
||||
_revoke_tokens(bao, pki, tmp_path, state, *args)
|
||||
assert error.value.code == 2 # noqa: PLR2004
|
||||
assert state.paths == []
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Какие ошибки драйвера — недоступность PostgreSQL (change
|
||||
`rotation-revocation`, design, решение 10; спек `data-storage`, «Пароль роли
|
||||
отвергнут»): `src/infra/db/errors.py`.
|
||||
|
||||
Отказ входа роли (28P01) — недоступность зависимости (503), а отказ прав
|
||||
(42501) и нарушение ограничения (23505) — дефект запроса (500).
|
||||
"""
|
||||
|
||||
import asyncpg
|
||||
import pytest
|
||||
from sqlalchemy import exc as sa_exc
|
||||
|
||||
from src.infra.db.errors import is_db_unavailable
|
||||
|
||||
|
||||
def _dbapi_error(sqlstate: str) -> sa_exc.DBAPIError:
|
||||
"""Ошибка, как её отдаёт SQLAlchemy: `orig` несёт SQLSTATE asyncpg."""
|
||||
original = asyncpg.PostgresError.new({"C": sqlstate, "M": "text"})
|
||||
return sa_exc.DBAPIError("SELECT 1", {}, original)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"sqlstate",
|
||||
["08006", "53300", "57014", "57P01", "28P01"],
|
||||
)
|
||||
def test_unavailable(sqlstate: str) -> None:
|
||||
assert is_db_unavailable(_dbapi_error(sqlstate))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sqlstate", ["42501", "23505", "42601", "28000"])
|
||||
def test_not_unavailable(sqlstate: str) -> None:
|
||||
assert not is_db_unavailable(_dbapi_error(sqlstate))
|
||||
@@ -0,0 +1,277 @@
|
||||
"""Ротация 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
|
||||
@@ -0,0 +1,882 @@
|
||||
"""Команды оператора ротации, отзыва и продления (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 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"
|
||||
)
|
||||
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'
|
||||
)
|
||||
assert rotation.loaded_version("text\n" + record, "postgres/api") == 4 # noqa: PLR2004
|
||||
assert rotation.loaded_version(record, "s3/api") is None
|
||||
assert rotation.loaded_version("", "s3/api") is None
|
||||
|
||||
|
||||
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
|
||||
if env_file is not None:
|
||||
self.env_file = env_file
|
||||
|
||||
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) -> None:
|
||||
self.step(f"broker close {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:
|
||||
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",
|
||||
]
|
||||
services, flags = stand.required
|
||||
assert services == {"relay", "rabbitmq", "otel-gateway", "openbao"}
|
||||
assert flags == {"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[1] == {"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",
|
||||
]
|
||||
|
||||
|
||||
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",
|
||||
"bao configure",
|
||||
"bao revoke-tokens --role relay",
|
||||
"broker crl",
|
||||
"broker close relay keep None",
|
||||
"restart otel-gateway",
|
||||
]
|
||||
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
|
||||
|
||||
|
||||
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"):
|
||||
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", "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
|
||||
|
||||
|
||||
def test_renew_crl_only() -> None:
|
||||
"""Без перевыпуска каждый сервис перезапускается ровно один раз, реплики
|
||||
— последними."""
|
||||
stand = FakeStand()
|
||||
assert _run(stand, rotation.cmd_renew) == 0
|
||||
assert stand.steps == [
|
||||
"pki stand",
|
||||
"bao configure",
|
||||
"broker crl",
|
||||
"lb crl",
|
||||
"restart otel-gateway",
|
||||
"restart loki-gateway",
|
||||
"restart tempo-gateway",
|
||||
"restart prometheus-gateway",
|
||||
"restart relay",
|
||||
"restart worker",
|
||||
"restart cleaner",
|
||||
"replicas",
|
||||
]
|
||||
|
||||
|
||||
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",
|
||||
"check postgres/migrate",
|
||||
],
|
||||
"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
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_secret_restarts_drifted_readers(secret_env: Path) -> None:
|
||||
"""`seed` записал и путь прерванной раньше ротации: его читатели тоже
|
||||
переходят на новую версию."""
|
||||
stand = FakeStand(secret_env)
|
||||
stand.seeded = {"postgres/api": 2, "s3/worker": 5}
|
||||
assert _run(stand, rotation.cmd_secret, "postgres/api") == 0
|
||||
assert "restart worker" in stand.steps
|
||||
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user