forked from mtusi2026/mtusi2026lab7
feat: run a per-run OpenBao for failure checks, bench, CI and driver stands
Every stand with its own storages now brings up its own OpenBao and acts
as its operator: materials live in the run's temporary directory and are
removed on any outcome; the working stand's OpenBao is never touched.
- make failure_checks: own OpenBao, 20 s / 60 s token roles, six new
OpenBao fault checks, hook actions and the secrets log summary
- bao.py rewrite and waiting for the active node after unseal
- bench/: OpenBao in every fresh stand, "before" variants get secrets
via ${...} references, passport stand.secrets and limits.openbao
- CI job: BAO_ADDRESS, run OpenBao operator, override with openbao,
cleaner and migrate pairs, test_ci_override.py
- driver: shared temporary stand for freeze-lb and reconcile-signal
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -6938,3 +6938,344 @@ def test_failed_login_keeps_old_hash(api: Api, stand: Stand) -> None:
|
||||
BASIC_CHALLENGE,
|
||||
)
|
||||
assert stand("password-params", actor.username) == OLD_HASH_PARAMS
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OpenBao стенда отказов (change openbao-tooling, design, решения 2–4): свой
|
||||
# OpenBao прогона с короткими сроками ролей (FAULT_BAO_TOKEN_TTL_S /
|
||||
# _MAX_TTL_S, 20 / 60 с), срок ожидания OpenBao при старте обычного API —
|
||||
# FAULT_SECRETS_STARTUP_TIMEOUT_S (15 с). Сценарии спека secret-store — в
|
||||
# докстрингах: capability вне сверки покрытия. Каждая проверка возвращает
|
||||
# OpenBao (start, unseal) и обычный API в finally
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
BAO_TOKEN_TTL_S = int(os.environ.get("FAULT_BAO_TOKEN_TTL_S") or 0)
|
||||
BAO_TOKEN_MAX_TTL_S = int(os.environ.get("FAULT_BAO_TOKEN_MAX_TTL_S") or 0)
|
||||
SECRETS_STARTUP_TIMEOUT_S = float(
|
||||
os.environ.get("FAULT_SECRETS_STARTUP_TIMEOUT_S") or 0,
|
||||
)
|
||||
# [secrets] retry_seconds и request_timeout_seconds по умолчанию
|
||||
SECRETS_RETRY_S = 2
|
||||
SECRETS_REQUEST_TIMEOUT_S = 5
|
||||
# продление — на 2/3 срока токена (renewal.py RENEW_FRACTION)
|
||||
RENEW_FRACTION = 2 / 3
|
||||
# остановка процесса — меньше срока Docker по умолчанию
|
||||
STOP_BUDGET_S = 10
|
||||
|
||||
|
||||
def renewal_bound_s() -> float:
|
||||
"""Не позже какого срока процесс замечает отказ или новую версию при
|
||||
продлении: 2/3 срока токена, пауза повтора, срок операции и запас."""
|
||||
return (
|
||||
BAO_TOKEN_TTL_S * RENEW_FRACTION
|
||||
+ SECRETS_RETRY_S
|
||||
+ SECRETS_REQUEST_TIMEOUT_S
|
||||
+ 3
|
||||
)
|
||||
|
||||
|
||||
def assert_bao_stand(stand: Stand) -> None:
|
||||
"""Стенд запущен со сроками, которые назвал run_failures.py: последняя
|
||||
загрузка секретов обычного API — с токеном FAULT_BAO_TOKEN_TTL_S из
|
||||
OpenBao стенда (адрес — сеть стенда, :8200)."""
|
||||
assert BAO_TOKEN_TTL_S > 0, "FAULT_BAO_TOKEN_TTL_S is not set"
|
||||
assert BAO_TOKEN_MAX_TTL_S >= BAO_TOKEN_TTL_S
|
||||
assert SECRETS_STARTUP_TIMEOUT_S > 0
|
||||
loaded = [
|
||||
record
|
||||
for record in api_records(stand, "default")
|
||||
if record.get("event") == "Loaded process secrets"
|
||||
]
|
||||
assert loaded, "the default API has no Loaded process secrets record"
|
||||
record = loaded[-1]
|
||||
assert record["token_ttl_seconds"] == BAO_TOKEN_TTL_S, record
|
||||
assert str(record["address"]).endswith(":8200"), record["address"]
|
||||
|
||||
|
||||
def new_api_records(stand: Stand, after: int) -> list[dict[str, Any]]:
|
||||
"""Записи обычного API после первых `after` (порядок журнала Docker)."""
|
||||
return api_records(stand, "default")[after:]
|
||||
|
||||
|
||||
def wait_api_event(
|
||||
stand: Stand,
|
||||
after: int,
|
||||
event: str,
|
||||
*,
|
||||
timeout: float,
|
||||
match: Callable[[dict[str, Any]], bool] = lambda _record: True,
|
||||
) -> dict[str, Any]:
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
for record in new_api_records(stand, after):
|
||||
if record.get("event") == event and match(record):
|
||||
return record
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError(
|
||||
f"no {event!r} in the API log in {timeout:.0f}s",
|
||||
)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def api_state(stand: Stand) -> dict[str, Any]:
|
||||
return json.loads(stand("api-state"))
|
||||
|
||||
|
||||
def restore_openbao(stand: Stand) -> None:
|
||||
"""OpenBao стенда снова работает и распечатан (после stop — запечатан)."""
|
||||
state = json.loads(stand("openbao-state"))
|
||||
if not state["running"]:
|
||||
stand("start", "openbao")
|
||||
stand("unseal", "openbao")
|
||||
|
||||
|
||||
def restore_api(stand: Stand) -> None:
|
||||
"""Обычный API снова отвечает: тот же контейнер, ожидание healthy."""
|
||||
stand("start-api")
|
||||
|
||||
|
||||
def serve_under_openbao_outage(api: Api) -> None:
|
||||
"""Запросы и задания с загруженными секретами: регистрация, вход, чат,
|
||||
сообщение, загрузка до ready, /health/ready."""
|
||||
alice = api.register()
|
||||
bob = api.register()
|
||||
assert_ok(
|
||||
api.login_response(alice.username, alice.password),
|
||||
201,
|
||||
"Session",
|
||||
)
|
||||
chat = api.create_chat(alice, bob, title="OpenBao outage")
|
||||
api.send_message(alice, chat["id"], "secrets are cached")
|
||||
ready = api.upload_ready(alice, chat["id"], images.sample_png())
|
||||
assert ready["status"] == "ready", ready
|
||||
assert api.request("GET", "/health/ready").status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["stop", "pause"])
|
||||
def test_openbao_down_under_running_stand(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
mode: str,
|
||||
) -> None:
|
||||
"""Спек `secret-store`, «OpenBao остановлен под работающим стендом» (и
|
||||
замороженный OpenBao — тот же исход требования «Работа при недоступном
|
||||
OpenBao», «недоступен по сети»): запросы, загрузка до `ready` и
|
||||
`/health/ready` проходят, в журнале API — запись о недоступности при
|
||||
продлении; после возврата (и распечатывания остановленного) — запись о
|
||||
возврате и повторный вход: простой длиннее срока токена."""
|
||||
assert_bao_stand(stand)
|
||||
before = len(api_records(stand, "default"))
|
||||
started = time.monotonic()
|
||||
stand(mode, "openbao")
|
||||
try:
|
||||
record = wait_api_event(
|
||||
stand,
|
||||
before,
|
||||
"Secrets store is unavailable",
|
||||
timeout=renewal_bound_s(),
|
||||
match=lambda r: r.get("level") == "warning",
|
||||
)
|
||||
assert "token_expires_in_seconds" in record, record
|
||||
serve_under_openbao_outage(api)
|
||||
# простой длиннее срока токена: после возврата — повторный вход
|
||||
sleep_until(started + BAO_TOKEN_TTL_S + 1)
|
||||
finally:
|
||||
stand("start" if mode == "stop" else "unpause", "openbao")
|
||||
if mode == "stop":
|
||||
# рестарт запечатывает OpenBao: явный unseal оператора прогона
|
||||
stand("unseal", "openbao")
|
||||
records = new_api_records(stand, before)
|
||||
marker = next(
|
||||
index
|
||||
for index, record in enumerate(records)
|
||||
if record.get("event") == "Secrets store is unavailable"
|
||||
)
|
||||
after = before + marker + 1
|
||||
wait_api_event(
|
||||
stand,
|
||||
after,
|
||||
"Secrets store is available again",
|
||||
timeout=SECRETS_RETRY_S + SECRETS_REQUEST_TIMEOUT_S + 5,
|
||||
)
|
||||
relogin = wait_api_event(
|
||||
stand,
|
||||
after,
|
||||
"Logged in to secrets store again",
|
||||
timeout=SECRETS_RETRY_S + SECRETS_REQUEST_TIMEOUT_S + 5,
|
||||
)
|
||||
assert relogin["reason"] in ("expired", "max_ttl"), relogin
|
||||
assert relogin["token_ttl_seconds"] == BAO_TOKEN_TTL_S, relogin
|
||||
# стенд снова принимает работу
|
||||
serve_under_openbao_outage(api)
|
||||
|
||||
|
||||
def test_openbao_sealed_by_operator(api: Api, stand: Stand) -> None:
|
||||
"""Спек `secret-store`, «OpenBao запечатан оператором»: работающий стенд
|
||||
обслуживает запросы; новый процесс API ждёт OpenBao («Waiting for secrets
|
||||
store») и не становится `healthy`; после `unseal` тот же процесс без
|
||||
перезапуска загружает секреты и становится `healthy` в срок ожидания."""
|
||||
assert_bao_stand(stand)
|
||||
stand("seal", "openbao")
|
||||
try:
|
||||
alice = api.register()
|
||||
chat = api.create_chat(alice, api.register(), title="Sealed")
|
||||
api.send_message(alice, chat["id"], "sealed store")
|
||||
assert api.request("GET", "/health/ready").status_code == 200
|
||||
before = len(api_records(stand, "default"))
|
||||
stand("kill-api")
|
||||
stand("start-api", "nowait")
|
||||
started = time.monotonic()
|
||||
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"]
|
||||
stand("unseal", "openbao")
|
||||
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}"
|
||||
time.sleep(0.2)
|
||||
assert state["restart_count"] == restarts, state
|
||||
records = new_api_records(stand, before)
|
||||
loaded = [
|
||||
r for r in records if r.get("event") == "Loaded process secrets"
|
||||
]
|
||||
assert len(loaded) == 1, loaded
|
||||
assert loaded[0]["waited_seconds"] > 0, loaded[0]
|
||||
assert (
|
||||
sum(r.get("event") == "Waiting for secrets store" for r in records)
|
||||
== 1
|
||||
)
|
||||
api.send_message(alice, chat["id"], "unsealed store")
|
||||
finally:
|
||||
stand("unseal", "openbao")
|
||||
restore_api(stand)
|
||||
|
||||
|
||||
def test_api_start_without_openbao(api: Api, stand: Stand) -> None:
|
||||
"""Спек `secret-store`, «OpenBao недоступен на старте»: обычный API убит,
|
||||
OpenBao остановлен, API запущен снова — ждёт OpenBao, через срок ожидания
|
||||
выходит с кодом 1 и записью о недоступности (`waited_seconds`), `healthy`
|
||||
не становится; после запуска и распечатывания OpenBao стартует и
|
||||
отвечает."""
|
||||
assert_bao_stand(stand)
|
||||
before = len(api_records(stand, "default"))
|
||||
stand("kill-api")
|
||||
stand("stop", "openbao")
|
||||
try:
|
||||
started = time.monotonic()
|
||||
stand("start-api", "nowait")
|
||||
healthy_seen = False
|
||||
deadline = started + SECRETS_STARTUP_TIMEOUT_S + 5
|
||||
while (state := api_state(stand))["running"]:
|
||||
healthy_seen = healthy_seen or state["health"] == "healthy"
|
||||
assert time.monotonic() < deadline, f"API still waits: {state}"
|
||||
time.sleep(0.2)
|
||||
took = time.monotonic() - started
|
||||
assert state["exit_code"] == 1, state
|
||||
assert not healthy_seen and state["health"] != "healthy", state
|
||||
assert took <= SECRETS_STARTUP_TIMEOUT_S + 5, took
|
||||
records = new_api_records(stand, before)
|
||||
waiting = [
|
||||
r for r in records if r.get("event") == "Waiting for secrets store"
|
||||
]
|
||||
assert len(waiting) == 1, waiting
|
||||
assert waiting[0]["timeout_seconds"] == SECRETS_STARTUP_TIMEOUT_S
|
||||
failed = [
|
||||
r
|
||||
for r in records
|
||||
if r.get("event") == "Secrets store is unavailable"
|
||||
and r.get("level") == "error"
|
||||
]
|
||||
assert len(failed) == 1, failed
|
||||
waited = failed[0]["waited_seconds"]
|
||||
assert (
|
||||
SECRETS_STARTUP_TIMEOUT_S - SECRETS_RETRY_S - 1
|
||||
<= waited
|
||||
<= SECRETS_STARTUP_TIMEOUT_S
|
||||
), waited
|
||||
assert not any(
|
||||
r.get("event") == "Loaded process secrets" for r in records
|
||||
)
|
||||
finally:
|
||||
restore_openbao(stand)
|
||||
restore_api(stand)
|
||||
assert api.register().token
|
||||
|
||||
|
||||
def test_api_stop_while_waiting_for_openbao(api: Api, stand: Stand) -> None:
|
||||
"""Спек `secret-store`, «Остановка во время ожидания»: API ждёт
|
||||
остановленный OpenBao, `docker stop` — код 0 быстрее 10 с и запись
|
||||
«Stopped API before startup»."""
|
||||
assert_bao_stand(stand)
|
||||
before = len(api_records(stand, "default"))
|
||||
stand("kill-api")
|
||||
stand("stop", "openbao")
|
||||
try:
|
||||
stand("start-api", "nowait")
|
||||
wait_api_event(
|
||||
stand,
|
||||
before,
|
||||
"Waiting for secrets store",
|
||||
timeout=SECRETS_STARTUP_TIMEOUT_S / 2,
|
||||
)
|
||||
stopped = json.loads(stand("stop-api"))
|
||||
assert stopped["exit_code"] == 0, stopped
|
||||
assert stopped["seconds"] < STOP_BUDGET_S, stopped
|
||||
records = new_api_records(stand, before)
|
||||
assert any(
|
||||
r.get("event") == "Stopped API before startup" for r in records
|
||||
), [r.get("event") for r in records]
|
||||
assert not any(
|
||||
r.get("event") == "Loaded process secrets" for r in records
|
||||
)
|
||||
finally:
|
||||
restore_openbao(stand)
|
||||
restore_api(stand)
|
||||
assert api.register().token
|
||||
|
||||
|
||||
def test_secret_new_version(api: Api, stand: Stand) -> None:
|
||||
"""Спек `secret-store`, «Новая версия секрета»: оператор записал новую
|
||||
версию `postgres/api` с прежним значением (`bao.py rewrite`) — не позже
|
||||
следующего продления API пишет «Secret version changed» с путём и
|
||||
версиями N → N+1, запросы проходят; после перезапуска API — «Loaded
|
||||
process secrets» с версией N+1. Значение прежнее, поэтому ни один
|
||||
процесс стенда не ломается."""
|
||||
assert_bao_stand(stand)
|
||||
alice = api.register()
|
||||
chat = api.create_chat(alice, api.register(), title="New version")
|
||||
before = len(api_records(stand, "default"))
|
||||
output = stand("bao-rewrite", "postgres/api")
|
||||
parts = output.split("version ", 1)[1].split(",", 1)[0].split(" -> ")
|
||||
old, new = int(parts[0]), int(parts[1])
|
||||
assert new == old + 1, output
|
||||
changed = wait_api_event(
|
||||
stand,
|
||||
before,
|
||||
"Secret version changed",
|
||||
timeout=renewal_bound_s(),
|
||||
match=lambda r: r.get("path") == "messenger/data/postgres/api",
|
||||
)
|
||||
assert changed["current_version"] == new, changed
|
||||
assert "password" not in json.dumps(changed), changed
|
||||
api.send_message(alice, chat["id"], "same password, new version")
|
||||
restart_from = len(api_records(stand, "default"))
|
||||
try:
|
||||
stand("kill-api")
|
||||
finally:
|
||||
restore_api(stand)
|
||||
loaded = [
|
||||
r
|
||||
for r in new_api_records(stand, restart_from)
|
||||
if r.get("event") == "Loaded process secrets"
|
||||
]
|
||||
assert len(loaded) == 1, loaded
|
||||
assert loaded[0]["versions"]["postgres/api"] == new, loaded[0]
|
||||
api.send_message(alice, chat["id"], "after restart")
|
||||
|
||||
Reference in New Issue
Block a user