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:
2026-11-26 23:31:52 +03:00
co-authored by Claude Opus 5.5
parent 2bedcc5621
commit 8a09f51fbf
12 changed files with 784 additions and 49 deletions
+79 -15
View File
@@ -62,8 +62,10 @@ S3 и брокер со своими volumes, порты хранилищ не
продления, нет поля; журнал аудита OpenBao — входы и продления по ролям,
ответы с ошибкой, токены открытым текстом. Строка `secrets log: …` —
всегда; ненулевой код — у роли `api`, `worker`, `relay` или `cleaner`
нет продлений в аудите, жизнь процесса длиннее `max_ttl + ttl` без
повторного входа, отказ по правам, сбой продления, нет поля или токен
нет продлений в аудите, промежуток внутри жизни процесса между загрузкой
или повторным входом и следующим входом (или концом жизни) длиннее
`max_ttl + ttl` за вычетом окон недоступности OpenBao (правки verify
S1), отказ по правам, сбой продления, нет поля или токен
открытым текстом; при падении — ещё хвост журнала `openbao` (значения в
аудите — HMAC);
- удаляет стенд вместе с volume при любом исходе, в том числе по Ctrl+C,
@@ -493,16 +495,80 @@ def _container_end(container: str) -> datetime.datetime | None:
return _parse_time(finished)
def life_gaps(
life: list[dict],
finish: datetime.datetime,
) -> list[tuple[float, dict]]:
"""Промежутки одной жизни без повторного входа (правило 2 сводки, правки
verify S1): от загрузки секретов или повторного входа до следующего входа,
у последнего — до конца жизни `finish`; из промежутка вычитаются окна
недоступности OpenBao в журнале этого процесса (от `warning` «Secrets
store is unavailable» до «… available again» или до входа): после простоя
вход бывает и `max_ttl`, и промежуток иначе включал бы простой. Отдаёт
пары (секунды, запись-начало)."""
gaps: list[tuple[float, dict]] = []
anchor = life[0]
anchor_at = _parse_time(str(anchor.get("timestamp", "")))
if anchor_at is None:
return gaps
outage_from: datetime.datetime | None = None
outage_s = 0.0
for record in life[1:]:
at = _parse_time(str(record.get("timestamp", "")))
if at is None:
continue
event = record.get("event")
if (
event == "Secrets store is unavailable"
and record.get("level") == "warning"
):
outage_from = outage_from or at
elif outage_from is not None and event in (
"Secrets store is available again",
RELOGIN_EVENT,
):
outage_s += (at - outage_from).total_seconds()
outage_from = None
if event == RELOGIN_EVENT:
seconds = (at - anchor_at).total_seconds() - outage_s
gaps.append((seconds, anchor))
anchor, anchor_at, outage_s = record, at, 0.0
if outage_from is not None:
outage_s += max((finish - outage_from).total_seconds(), 0.0)
gaps.append(((finish - anchor_at).total_seconds() - outage_s, anchor))
return gaps
def process_secrets_summary(
name: str,
container: str,
limit_s: int,
) -> tuple[str, list[str], dict[str, int]]:
"""Журнал одного контейнера: жизни (от «Loaded process secrets» до
следующей или до конца), повторные входы по причинам, недоступность и
возврат, записи-проблемы. Отдаёт строку сводки, проблемы и счётчики."""
"""Журнал одного контейнера (`docker logs`, конец последней жизни —
`_container_end`) — разбор `summarize_process_log`."""
logs = run("docker", "logs", container, check=False, quiet=True)
text = logs.stdout + logs.stderr
return summarize_process_log(
name,
logs.stdout + logs.stderr,
end=_container_end(container),
limit_s=limit_s,
)
def summarize_process_log(
name: str,
text: str,
*,
end: datetime.datetime | None,
limit_s: int,
) -> tuple[str, list[str], dict[str, int]]:
"""Журнал одного процесса без docker: жизни (от «Loaded process secrets»
до следующей, до записи нового процесса без секретов или до конца),
повторные входы по причинам, недоступность и возврат, записи-проблемы,
наибольший промежуток без повторного входа (`life_gaps`; больше
`limit_s` — проблема). `end` — конец открытой последней жизни (у
работающего контейнера — сейчас, у остановленного — `FinishedAt`).
Отдаёт строку сводки, проблемы и счётчики."""
records = _records(text)
counts = {
"lives": 0,
@@ -554,29 +620,27 @@ def process_secrets_summary(
)
if counts["tokens"]:
problems.append(f"{name}: {counts['tokens']} s.-tokens in plaintext")
end = _container_end(container)
# последняя жизнь открыта, только если после неё не стартовал процесс
# без секретов
open_last = current is not None
longest = 0.0
for index, life in enumerate(lives):
start = _parse_time(str(life[0].get("timestamp", "")))
if index + 1 < len(lives) or end is None or not open_last:
# жизнь кончилась следующей загрузкой: её конец — последняя
# запись (момент kill неизвестен; оценка снизу)
finish = _parse_time(str(life[-1].get("timestamp", "")))
else:
finish = end
relogins = sum(r.get("event") == RELOGIN_EVENT for r in life)
if start is None or finish is None:
if finish is None:
continue
seconds = (finish - start).total_seconds()
if not relogins:
for seconds, anchor in life_gaps(life, finish):
longest = max(longest, seconds)
if seconds > limit_s:
problems.append(
f"{name}: lived {seconds:.0f} s without logging in "
f"again (limit {limit_s} s)",
f"{name}: {seconds:.0f} s without logging in again "
f"after {anchor.get('event')!r} at "
f"{anchor.get('timestamp')} (limit {limit_s} s, "
"OpenBao outages excluded)",
)
line = (
f"secrets log [{name}]: lives {counts['lives']}, relogins max_ttl "
@@ -584,7 +648,7 @@ def process_secrets_summary(
f"{counts['renew_refused']}, unavailable {counts['unavailable']} / "
f"available again {counts['available_again']}, startup unavailable "
f"{counts['startup_unavailable']}, versions changed "
f"{counts['versions_changed']}, longest life without relogin "
f"{counts['versions_changed']}, longest gap without relogin "
f"{longest:.0f} s"
)
return line, problems, counts