fix: address openbao-tooling verify findings
- secrets summary: per-life gap between logins (OpenBao outages excluded) catches a renewal thread that died after the first login; delta and rule updated, fast tests on synthetic logs - record the apply deviation (operator materials read by the leak scan) and switch the leak scan to patterns - test_secret_new_version checks N -> N+1, sealed-by-operator test unseals right after the waiting record - driver: operator dir refusal exits with code 2 - fast test for Operator.wait_active, check counts 158 -> 164 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,236 @@
|
||||
"""Оператор OpenBao ждёт активный узел после unseal (change `openbao-tooling`,
|
||||
design, «Уточнения apply», п. 1; правки verify S7): `Operator.wait_active`
|
||||
(`infra/openbao/bao.py`) опрашивает `sys/health` — 200 активный, 429 standby
|
||||
только для чтения (raft сразу после распечатывания).
|
||||
|
||||
Подставной OpenBao — HTTPS-сервер в процессе теста с временной PKI
|
||||
(`infra/pki/pki.sh stand`: CA, leaf `openbao` с SAN `localhost`, пара
|
||||
`bao-operator`), обязательный сертификат клиента CA стенда. Проверки: 429,
|
||||
затем 200 — успех; 429 дольше срока — `BaoError` со статусом, а команда
|
||||
оператора (`main … rewrite`) — код 1 до чтения root token. Без OpenSSL 3+
|
||||
тесты пропускаются с причиной.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import http.server
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from src.config.settings import BASE_DIR
|
||||
|
||||
PKI_SCRIPT = BASE_DIR / "infra" / "pki" / "pki.sh"
|
||||
BAO_SCRIPT = BASE_DIR / "infra" / "openbao" / "bao.py"
|
||||
STANDBY = 429
|
||||
ACTIVE = 200
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def bao() -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location("bao", BAO_SCRIPT)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules.setdefault("bao", module)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
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 pki(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
||||
"""Файлы стенда временной PKI (CA, `openbao`, `bao-operator`)."""
|
||||
binary = _openssl()
|
||||
if binary is None:
|
||||
pytest.skip("OpenSSL 3+ is required for TLS handshake tests")
|
||||
root = tmp_path_factory.mktemp("bao-operator-pki")
|
||||
subprocess.run( # noqa: S603
|
||||
["/bin/sh", str(PKI_SCRIPT), "stand"],
|
||||
env={
|
||||
**os.environ,
|
||||
"OPENSSL": binary,
|
||||
"PKI_OPERATOR_DIR": str(root / "op"),
|
||||
"PKI_STAND_DIR": str(root / "stand"),
|
||||
},
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
return root / "stand"
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Health:
|
||||
"""Ответы `sys/health` по порядку; последний повторяется."""
|
||||
|
||||
statuses: list[int]
|
||||
asked: int = 0
|
||||
paths: list[str] = field(default_factory=list)
|
||||
lock: threading.Lock = field(default_factory=threading.Lock)
|
||||
|
||||
def next_status(self) -> int:
|
||||
with self.lock:
|
||||
index = min(self.asked, len(self.statuses) - 1)
|
||||
self.asked += 1
|
||||
return self.statuses[index]
|
||||
|
||||
|
||||
def _handler(state: _Health) -> 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": False})
|
||||
elif self.path == "/v1/sys/health":
|
||||
status = state.next_status()
|
||||
self._send(status, {"standby": status == STANDBY})
|
||||
else:
|
||||
self._send(404, {"errors": []})
|
||||
|
||||
def log_message(self, *_args: Any) -> None:
|
||||
return None
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _openbao(
|
||||
stand: Path,
|
||||
statuses: list[int],
|
||||
) -> Iterator[tuple[str, _Health]]:
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(stand / "openbao.crt", stand / "openbao.key")
|
||||
context.load_verify_locations(cafile=stand / "ca.crt")
|
||||
context.verify_mode = ssl.CERT_REQUIRED
|
||||
state = _Health(statuses=statuses)
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _handler(state))
|
||||
server.daemon_threads = True
|
||||
server.socket = context.wrap_socket(server.socket, server_side=True)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield f"https://localhost:{server.server_address[1]}", state
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def _argv(address: str, stand: Path, operator_dir: Path) -> list[str]:
|
||||
return [
|
||||
"--address",
|
||||
address,
|
||||
"--pki-dir",
|
||||
str(stand),
|
||||
"--operator-dir",
|
||||
str(operator_dir),
|
||||
"--project",
|
||||
"bao-operator-test",
|
||||
"--wait",
|
||||
"2",
|
||||
]
|
||||
|
||||
|
||||
def _operator(
|
||||
bao: ModuleType,
|
||||
address: str,
|
||||
stand: Path,
|
||||
operator_dir: Path,
|
||||
) -> Any:
|
||||
args = bao.build_parser().parse_args(
|
||||
[*_argv(address, stand, operator_dir), "status"],
|
||||
)
|
||||
return bao.Operator(args)
|
||||
|
||||
|
||||
def test_standby_then_active(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Два ответа standby (429), затем активный (200) — успех без ошибки,
|
||||
три опроса `sys/health`."""
|
||||
with _openbao(pki, [STANDBY, STANDBY, ACTIVE]) as (address, state):
|
||||
operator = _operator(bao, address, pki, tmp_path / "op")
|
||||
started = time.monotonic()
|
||||
operator.wait_active(timeout=10)
|
||||
took = time.monotonic() - started
|
||||
assert state.asked == 3, state.paths # noqa: PLR2004
|
||||
assert took < 5, took # noqa: PLR2004
|
||||
|
||||
|
||||
def test_standby_too_long(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Узел остаётся standby дольше срока — `BaoError` со статусом 429 и
|
||||
текстом без тела ответа."""
|
||||
with _openbao(pki, [STANDBY]) as (address, state):
|
||||
operator = _operator(bao, address, pki, tmp_path / "op")
|
||||
started = time.monotonic()
|
||||
with pytest.raises(bao.BaoError) as error:
|
||||
operator.wait_active(timeout=1.0)
|
||||
took = time.monotonic() - started
|
||||
assert error.value.status == STANDBY
|
||||
assert "is not active in 1 s (sys/health 429)" in str(error.value)
|
||||
assert not isinstance(error.value, bao.Sealed)
|
||||
assert 1.0 <= took < 4, took # noqa: PLR2004
|
||||
assert state.asked >= 2, state.paths # noqa: PLR2004
|
||||
|
||||
|
||||
def test_command_exits_1_when_not_active(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Команда оператора, которой нужен распечатанный OpenBao (`rewrite`), на
|
||||
затянувшемся standby — код 1 и строка `bao: …`; root token не читается
|
||||
(каталога материалов нет)."""
|
||||
monkeypatch.setattr(bao.Operator.wait_active, "__defaults__", (1.0,))
|
||||
operator_dir = tmp_path / "op"
|
||||
with _openbao(pki, [STANDBY]) as (address, state):
|
||||
code = bao.main(
|
||||
[*_argv(address, pki, operator_dir), "rewrite", "postgres/api"],
|
||||
)
|
||||
out = capsys.readouterr().out
|
||||
assert code == 1, out
|
||||
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()
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Сводка секретов `make failure_checks` (change `openbao-tooling`, design,
|
||||
решение 2, правило 2; правки verify S1; спек `student-tests`, «Стенд отказов
|
||||
на своём OpenBao»): разбор журнала процесса без docker на синтетических
|
||||
записях — `summarize_process_log` из `student-tests/run_failures.py`.
|
||||
|
||||
Нарушение — промежуток внутри жизни между загрузкой секретов или повторным
|
||||
входом и следующим входом (у последнего — до конца жизни) длиннее `max_ttl +
|
||||
ttl` за вычетом окон недоступности OpenBao в журнале процесса. Контроль:
|
||||
«поток продления умер после первого повторного входа» — нарушение (прежнее
|
||||
правило искало только жизнь совсем без повторных входов и его пропускало);
|
||||
штатная жизнь, жизнь с простоем OpenBao и жизнь, оборванная `kill`, — нет.
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from types import ModuleType
|
||||
|
||||
import pytest
|
||||
|
||||
from src.config.settings import BASE_DIR
|
||||
|
||||
RUN_FAILURES = BASE_DIR / "student-tests" / "run_failures.py"
|
||||
TTL_S = 20
|
||||
MAX_TTL_S = 60
|
||||
LIMIT_S = MAX_TTL_S + TTL_S
|
||||
T0 = datetime.datetime(2026, 11, 26, 10, 0, tzinfo=datetime.UTC)
|
||||
NAME = "worker"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_failures() -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"run_failures",
|
||||
RUN_FAILURES,
|
||||
)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules.setdefault("run_failures", module)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _at(seconds: float) -> datetime.datetime:
|
||||
return T0 + datetime.timedelta(seconds=seconds)
|
||||
|
||||
|
||||
def _line(seconds: float, event: str, **fields: object) -> str:
|
||||
stamp = _at(seconds).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
return json.dumps(
|
||||
{"event": event, "level": "info", "timestamp": stamp, **fields},
|
||||
)
|
||||
|
||||
|
||||
def _loaded(seconds: float) -> str:
|
||||
return _line(seconds, "Loaded process secrets", token_ttl_seconds=TTL_S)
|
||||
|
||||
|
||||
def _relogin(seconds: float, reason: str = "max_ttl") -> str:
|
||||
return _line(
|
||||
seconds,
|
||||
"Logged in to secrets store again",
|
||||
reason=reason,
|
||||
token_ttl_seconds=TTL_S,
|
||||
)
|
||||
|
||||
|
||||
def _summary(
|
||||
module: ModuleType,
|
||||
lines: list[str],
|
||||
end_s: float,
|
||||
) -> tuple[str, list[str], dict[str, int]]:
|
||||
return module.summarize_process_log(
|
||||
NAME,
|
||||
"\n".join(lines) + "\n",
|
||||
end=_at(end_s),
|
||||
limit_s=LIMIT_S,
|
||||
)
|
||||
|
||||
|
||||
def test_renewal_thread_died_after_relogin(run_failures: ModuleType) -> None:
|
||||
"""Повторный вход был один, дальше процесс живёт 240 с без входа:
|
||||
поток продления умер — нарушение с началом промежутка."""
|
||||
lines = [
|
||||
_loaded(0),
|
||||
_relogin(58),
|
||||
*(_line(60 + 20 * n, "Handled request") for n in range(12)),
|
||||
]
|
||||
line, problems, counts = _summary(run_failures, lines, end_s=300)
|
||||
assert counts["max_ttl"] == 1
|
||||
assert len(problems) == 1, problems
|
||||
assert "242 s without logging in again" in problems[0], problems
|
||||
assert "Logged in to secrets store again" in problems[0], problems
|
||||
assert "longest gap without relogin 242 s" in line, line
|
||||
|
||||
|
||||
def test_life_without_relogin(run_failures: ModuleType) -> None:
|
||||
"""Ни одного повторного входа за 120 с — нарушение (прежний случай)."""
|
||||
lines = [_loaded(0), _line(90, "Handled request")]
|
||||
_, problems, _ = _summary(run_failures, lines, end_s=120)
|
||||
assert len(problems) == 1, problems
|
||||
assert "after 'Loaded process secrets'" in problems[0], problems
|
||||
|
||||
|
||||
def test_regular_life(run_failures: ModuleType) -> None:
|
||||
"""Вход раз в ~58 с пять минут — нарушения нет."""
|
||||
lines = [_loaded(0), *(_relogin(58 * n) for n in range(1, 6))]
|
||||
line, problems, counts = _summary(run_failures, lines, end_s=310)
|
||||
assert problems == [], problems
|
||||
assert counts["max_ttl"] == 5
|
||||
assert "longest gap without relogin 58 s" in line, line
|
||||
|
||||
|
||||
def test_openbao_outage_is_excluded(run_failures: ModuleType) -> None:
|
||||
"""Простой OpenBao 60 с: вход после возврата — `max_ttl` (токен упёрся
|
||||
в предел до простоя), промежуток 102 с минус окно 60 с — не нарушение;
|
||||
открытый простой в конце жизни тоже вычитается."""
|
||||
lines = [
|
||||
_loaded(0),
|
||||
_relogin(58),
|
||||
_line(100, "Secrets store is unavailable", level="warning"),
|
||||
_line(160, "Secrets store is available again"),
|
||||
_relogin(160),
|
||||
_relogin(218),
|
||||
_line(250, "Secrets store is unavailable", level="warning"),
|
||||
]
|
||||
line, problems, counts = _summary(run_failures, lines, end_s=400)
|
||||
assert problems == [], problems
|
||||
assert counts["unavailable"] == 2
|
||||
assert counts["available_again"] == 1
|
||||
assert "longest gap without relogin 58 s" in line, line
|
||||
|
||||
|
||||
def test_outage_does_not_hide_dead_thread(run_failures: ModuleType) -> None:
|
||||
"""После возврата OpenBao процесс не входил 200 с — нарушение: вычитается
|
||||
только окно недоступности."""
|
||||
lines = [
|
||||
_loaded(0),
|
||||
_line(30, "Secrets store is unavailable", level="warning"),
|
||||
_line(50, "Secrets store is available again"),
|
||||
]
|
||||
_, problems, _ = _summary(run_failures, lines, end_s=250)
|
||||
assert len(problems) == 1, problems
|
||||
assert "230 s without logging in again" in problems[0], problems
|
||||
|
||||
|
||||
def test_killed_life_ends_with_last_record(run_failures: ModuleType) -> None:
|
||||
"""Жизнь, оборванная `kill` (заморозка проверки, затем новый процесс без
|
||||
секретов), кончается своей последней записью; новая жизнь — с новой
|
||||
загрузки: нарушения нет."""
|
||||
lines = [
|
||||
_loaded(0),
|
||||
_relogin(58),
|
||||
_line(70, "Handled request"),
|
||||
_line(300, "Waiting for secrets store", timeout_seconds=15),
|
||||
_loaded(302),
|
||||
_relogin(360),
|
||||
]
|
||||
_, problems, counts = _summary(run_failures, lines, end_s=380)
|
||||
assert problems == [], problems
|
||||
assert counts["lives"] == 2
|
||||
Reference in New Issue
Block a user