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:
@@ -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
|
||||
|
||||
@@ -6961,6 +6961,9 @@ SECRETS_REQUEST_TIMEOUT_S = 5
|
||||
RENEW_FRACTION = 2 / 3
|
||||
# остановка процесса — меньше срока Docker по умолчанию
|
||||
STOP_BUDGET_S = 10
|
||||
# от docker start до начала загрузки секретов (старт интерпретатора, импорт
|
||||
# настроек) — с запасом
|
||||
PROCESS_START_SLACK_S = 2
|
||||
|
||||
|
||||
def renewal_bound_s() -> float:
|
||||
@@ -7113,7 +7116,13 @@ def test_openbao_sealed_by_operator(api: Api, stand: Stand) -> None:
|
||||
"""Спек `secret-store`, «OpenBao запечатан оператором»: работающий стенд
|
||||
обслуживает запросы; новый процесс API ждёт OpenBao («Waiting for secrets
|
||||
store») и не становится `healthy`; после `unseal` тот же процесс без
|
||||
перезапуска загружает секреты и становится `healthy` в срок ожидания."""
|
||||
перезапуска загружает секреты и становится `healthy` в срок ожидания.
|
||||
|
||||
Распечатывание — сразу после записи «Waiting» (правки verify S5): срок
|
||||
ожидания API идёт с его старта, и время unseal (`bao.py` и ожидание
|
||||
активного узла) входит в него; сообщения падения называют длительность
|
||||
unseal. До unseal процесс не `healthy`: «Loaded process secrets» пишется
|
||||
раньше «Started API», и её `waited_seconds` покрывает время до unseal."""
|
||||
assert_bao_stand(stand)
|
||||
stand("seal", "openbao")
|
||||
try:
|
||||
@@ -7125,21 +7134,29 @@ def test_openbao_sealed_by_operator(api: Api, stand: Stand) -> None:
|
||||
stand("kill-api")
|
||||
stand("start-api", "nowait")
|
||||
started = time.monotonic()
|
||||
restarts = api_state(stand)["restart_count"]
|
||||
waiting = wait_api_event(
|
||||
stand,
|
||||
before,
|
||||
"Waiting for secrets store",
|
||||
timeout=SECRETS_STARTUP_TIMEOUT_S / 2,
|
||||
)
|
||||
assert waiting["timeout_seconds"] == SECRETS_STARTUP_TIMEOUT_S
|
||||
state = api_state(stand)
|
||||
assert state["running"] and state["health"] != "healthy", state
|
||||
restarts = state["restart_count"]
|
||||
unseal_started = time.monotonic()
|
||||
stand("unseal", "openbao")
|
||||
unseal_s = time.monotonic() - unseal_started
|
||||
assert waiting["timeout_seconds"] == SECRETS_STARTUP_TIMEOUT_S
|
||||
deadline = started + SECRETS_STARTUP_TIMEOUT_S
|
||||
while (state := api_state(stand))["health"] != "healthy":
|
||||
assert state["running"], f"API exited while waiting: {state}"
|
||||
assert time.monotonic() < deadline, f"API not healthy: {state}"
|
||||
assert state["running"], (
|
||||
f"API exited while waiting (unseal took {unseal_s:.1f} s, "
|
||||
f"started {unseal_started - started:.1f} s after the API): "
|
||||
f"{state}"
|
||||
)
|
||||
assert time.monotonic() < deadline, (
|
||||
f"API not healthy in {SECRETS_STARTUP_TIMEOUT_S:.0f} s "
|
||||
f"(unseal took {unseal_s:.1f} s, started "
|
||||
f"{unseal_started - started:.1f} s after the API): {state}"
|
||||
)
|
||||
time.sleep(0.2)
|
||||
assert state["restart_count"] == restarts, state
|
||||
records = new_api_records(stand, before)
|
||||
@@ -7147,6 +7164,12 @@ def test_openbao_sealed_by_operator(api: Api, stand: Stand) -> None:
|
||||
r for r in records if r.get("event") == "Loaded process secrets"
|
||||
]
|
||||
assert len(loaded) == 1, loaded
|
||||
# процесс ждал не меньше, чем до начала unseal (запас — старт
|
||||
# интерпретатора до начала загрузки)
|
||||
assert (
|
||||
loaded[0]["waited_seconds"]
|
||||
>= unseal_started - started - PROCESS_START_SLACK_S
|
||||
), (loaded[0], unseal_started - started)
|
||||
assert loaded[0]["waited_seconds"] > 0, loaded[0]
|
||||
assert (
|
||||
sum(r.get("event") == "Waiting for secrets store" for r in records)
|
||||
@@ -7263,6 +7286,8 @@ def test_secret_new_version(api: Api, stand: Stand) -> None:
|
||||
timeout=renewal_bound_s(),
|
||||
match=lambda r: r.get("path") == "messenger/data/postgres/api",
|
||||
)
|
||||
# N → N+1: процесс загрузил версию N, в OpenBao теперь N+1
|
||||
assert changed["loaded_version"] == old, changed
|
||||
assert changed["current_version"] == new, changed
|
||||
assert "password" not in json.dumps(changed), changed
|
||||
api.send_message(alice, chat["id"], "same password, new version")
|
||||
|
||||
Reference in New Issue
Block a user