Files
mtusi2026lab7-safronov/service-tests/unit/test_secrets_summary.py
ricoromaandClaude Opus 5.5 8a09f51fbf 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>
2026-11-26 23:31:52 +03:00

163 lines
6.6 KiB
Python

"""Сводка секретов `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