feat: import lab 7 security implementation

This commit is contained in:
2026-12-02 23:44:32 +03:00
parent 20afc2c790
commit ee28cd7dbd
259 changed files with 84919 additions and 35 deletions
+361
View File
@@ -0,0 +1,361 @@
"""Проверки отказов OpenBao (лаба 7, перенос openbao-tooling): только `make
failure-checks`.
У стенда отказов свой OpenBao прогона (`stand.py`, оператор — сам прогон) с
короткими сроками ролей входа: токен 20 с, предел 60 с (`FAULT_BAO_TOKEN_TTL_S`,
`FAULT_BAO_TOKEN_MAX_TTL_S`); обычный API ждёт OpenBao на старте 15 с
(`FAULT_BAO_STARTUP_TIMEOUT_S`). Тесты сверяют стенд с этими сроками по строке
«process secrets loaded» обычного API. OpenBao тесты ломают только hook
(`stop`/`start`/`pause`/`unpause`/`seal`/`unseal openbao`, `bao-rewrite`), каждый
в `finally` возвращает OpenBao (запуск и распечатывание) и обычный API.
Что проверяется (правила — `infra/openbao/AGENTS.md`): OpenBao остановлен и
заморожен под работающим стендом — запросы, загрузка до `ready` и готовность
идут, при продлении — одна строка о недоступности, после возврата — строка о
возврате и повторный вход; запечатан оператором — работающий стенд обслуживает,
новый API ждёт и после `unseal` тем же процессом загружает секреты и становится
healthy; недоступен на старте — код 1 по сроку ожидания; остановка во время
ожидания — код 0 быстрее 10 с; новая версия секрета — строка о смене версии N →
N+1 не позже следующего продления, после перезапуска — загружена N+1. Продление и
повторный вход под всеми проверками — сводка секретов `stand.py` после pytest.
"""
import json
import os
import time
from collections.abc import Callable
from typing import Any
import httpx
import pytest
import secrets_log
from conftest import ClientFactory
from helpers import create_chat, ready, ready_upload, register, send
pytestmark = pytest.mark.fault
type Stand = Callable[..., str]
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)
STARTUP_TIMEOUT_S = float(os.environ.get("FAULT_BAO_STARTUP_TIMEOUT_S") or 0)
# BAO_RETRY_SECONDS и BAO_REQUEST_TIMEOUT по умолчанию (src/config.py)
RETRY_S = 2.0
REQUEST_TIMEOUT_S = 5.0
# продление — на 2/3 срока токена (src/secrets_renewal.py, RENEW_FRACTION)
RENEW_FRACTION = 2 / 3
# остановка процесса — меньше срока Docker по умолчанию
STOP_BUDGET_S = 10.0
# от docker start до начала загрузки секретов (интерпретатор, импорт)
PROCESS_START_SLACK_S = 2.0
API_HEALTHY_TIMEOUT_S = 60.0
def renewal_bound_s() -> float:
"""Не позже какого срока процесс замечает отказ или новую версию при
продлении: 2/3 срока токена, пауза повтора, срок запроса и запас."""
return BAO_TOKEN_TTL_S * RENEW_FRACTION + RETRY_S + REQUEST_TIMEOUT_S + 3
def api_records(stand: Stand) -> list[dict[str, Any]]:
"""Записи журнала обычного API (все жизни контейнера, порядок Docker)."""
return secrets_log.parse(stand("api-log", "default"))
def assert_bao_stand(stand: Stand) -> None:
"""Стенд запущен со сроками, которые назвал stand.py: без них тесты ничего не
доказывают."""
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 STARTUP_TIMEOUT_S > 0
loaded = [r for r in api_records(stand) if r["message"] == secrets_log.LOADED]
assert loaded, "the default API has no 'process secrets loaded' line"
fields = loaded[-1]["fields"]
assert fields["token_ttl"] == f"{BAO_TOKEN_TTL_S}s", fields
assert fields["address"].endswith(":8200"), fields
def wait_api_line(
stand: Stand,
after: int,
message: str,
*,
timeout: float,
level: str | None = None,
match: Callable[[dict[str, str]], bool] = lambda _fields: True,
) -> dict[str, Any]:
"""Первая запись `message` после первых `after` записей журнала API."""
deadline = time.monotonic() + timeout
while True:
for record in api_records(stand)[after:]:
if (
record["message"] == message
and (level is None or record["level"] == level)
and match(record["fields"])
):
return record
if time.monotonic() > deadline:
raise AssertionError(f"no {message!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, base_url: str) -> None:
"""Обычный API снова отвечает: тот же контейнер, ожидание healthy."""
if not api_state(stand)["running"]:
stand("start-api")
deadline = time.monotonic() + API_HEALTHY_TIMEOUT_S
while api_state(stand)["health"] != "healthy":
assert time.monotonic() < deadline, f"API not healthy: {api_state(stand)}"
time.sleep(0.5)
assert ready(base_url)
def serve(client: httpx.Client) -> None:
"""Работа на загруженных секретах: регистрация и вход, чат, сообщение,
загрузка до `ready` (worker и relay), готовность."""
alice = register(client, "bao")
bob = register(client, "bao")
chat = create_chat(client, alice, bob, title="OpenBao outage")
assert send(client, alice, chat, "secrets are cached").status_code == 201
ready_upload(client, alice, chat)
assert client.get("/health/ready").status_code == 200
@pytest.mark.parametrize("mode", ["stop", "pause"])
def test_openbao_down_under_running_stand(
new_client: ClientFactory, stand: Stand, mode: str
) -> None:
"""Остановленный или замороженный OpenBao не мешает работающему стенду; при
продлении — строка о недоступности; простой длиннее срока токена, поэтому
после возврата (и распечатывания остановленного) — строка о возврате и
повторный вход `expired` или `max_ttl`."""
assert_bao_stand(stand)
before = len(api_records(stand))
started = time.monotonic()
stand(mode, "openbao")
try:
lost = wait_api_line(
stand,
before,
secrets_log.UNAVAILABLE,
level="WARNING",
timeout=renewal_bound_s(),
)
print(f"openbao {mode}: API noticed in {time.monotonic() - started:.1f}s")
assert "token_expires_in" in lost["fields"], lost
serve(new_client())
# простой длиннее срока токена: после возврата — повторный вход
time.sleep(max(started + BAO_TOKEN_TTL_S + 1 - time.monotonic(), 0))
finally:
stand("start" if mode == "stop" else "unpause", "openbao")
if mode == "stop":
# рестарт запечатывает OpenBao: явный unseal оператора прогона
stand("unseal", "openbao")
records = api_records(stand)
marker = next(
index
for index in range(before, len(records))
if records[index]["message"] == secrets_log.UNAVAILABLE
)
back = wait_api_line(
stand,
marker + 1,
secrets_log.AVAILABLE,
timeout=RETRY_S + REQUEST_TIMEOUT_S + 5,
)
relogin = wait_api_line(
stand, marker + 1, secrets_log.RELOGIN, timeout=RETRY_S + REQUEST_TIMEOUT_S + 5
)
print(f"openbao {mode}: back at {back['at']}, relogin {relogin['fields']}")
assert relogin["fields"]["reason"] in ("expired", "max_ttl"), relogin
assert relogin["fields"]["token_ttl"] == f"{BAO_TOKEN_TTL_S}s", relogin
lost_lines = [
r
for r in api_records(stand)[before:]
if r["message"] == secrets_log.UNAVAILABLE and r["level"] == "WARNING"
]
assert len(lost_lines) == 1, "one line per outage, not one per retry"
serve(new_client())
def test_openbao_sealed_by_operator(new_client: ClientFactory, stand: Stand) -> None:
"""Запечатанный оператором OpenBao: работающий стенд обслуживает; новый
процесс API ждёт («waiting for secret store») и не healthy; после `unseal` тот
же процесс без перезапуска загружает секреты и становится healthy в срок
ожидания. Распечатывание — сразу после строки ожидания: срок идёт со старта
процесса, время unseal входит в него."""
assert_bao_stand(stand)
client = new_client()
base_url = str(client.base_url)
stand("seal", "openbao")
try:
alice = register(client, "sealed")
chat = create_chat(client, alice, title="Sealed")
assert send(client, alice, chat, "sealed store").status_code == 201
assert client.get("/health/ready").status_code == 200
before = len(api_records(stand))
stand("kill-api")
stand("start-api")
started = time.monotonic()
restarts = api_state(stand)["restart_count"]
waiting = wait_api_line(
stand, before, "waiting for secret store", timeout=STARTUP_TIMEOUT_S / 2
)
assert waiting["fields"]["timeout"] == f"{STARTUP_TIMEOUT_S:g}s", waiting
assert api_state(stand)["health"] != "healthy"
unseal_started = time.monotonic()
stand("unseal", "openbao")
unseal_s = time.monotonic() - unseal_started
deadline = started + STARTUP_TIMEOUT_S
while (state := api_state(stand))["health"] != "healthy":
assert state["running"], f"API exited (unseal {unseal_s:.1f}s): {state}"
assert time.monotonic() < deadline, (
f"API not healthy in {STARTUP_TIMEOUT_S:g}s (unseal {unseal_s:.1f}s, "
f"started {unseal_started - started:.1f}s after the API): {state}"
)
time.sleep(0.2)
print(
f"sealed: unseal {unseal_s:.1f}s, healthy {time.monotonic() - started:.1f}s"
)
assert state["restart_count"] == restarts, state
records = api_records(stand)[before:]
loaded = [r for r in records if r["message"] == secrets_log.LOADED]
assert len(loaded) == 1, loaded
waited = float(loaded[0]["fields"]["waited"].removesuffix("s"))
assert waited >= unseal_started - started - PROCESS_START_SLACK_S, waited
assert waited > 0
waits = [r for r in records if r["message"] == "waiting for secret store"]
assert len(waits) == 1
after = new_client()
assert send(after, alice, chat, "unsealed store").status_code == 201
finally:
stand("unseal", "openbao")
restore_api(stand, base_url)
def test_api_start_without_openbao(new_client: ClientFactory, stand: Stand) -> None:
"""OpenBao остановлен, API запущен заново: ждёт, через срок ожидания выходит
с кодом 1 и строкой «secret store is unavailable … waited=…», healthy не
становится; после запуска и распечатывания OpenBao стартует и отвечает."""
assert_bao_stand(stand)
base_url = str(new_client().base_url)
before = len(api_records(stand))
stand("kill-api")
stand("stop", "openbao")
try:
started = time.monotonic()
stand("start-api")
healthy_seen = False
deadline = started + 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
print(f"no openbao at start: exit {state['exit_code']} in {took:.1f}s")
assert state["exit_code"] == 1, state
assert not healthy_seen
assert took <= STARTUP_TIMEOUT_S + 5, took
records = api_records(stand)[before:]
waits = [r for r in records if r["message"] == "waiting for secret store"]
assert len(waits) == 1, waits
failed = [
r
for r in records
if r["message"] == secrets_log.UNAVAILABLE and r["level"] == "ERROR"
]
assert len(failed) == 1, failed
waited = float(failed[0]["fields"]["waited"].removesuffix("s"))
assert STARTUP_TIMEOUT_S - RETRY_S - 1 <= waited <= STARTUP_TIMEOUT_S, waited
assert not any(r["message"] == secrets_log.LOADED for r in records)
finally:
restore_openbao(stand)
restore_api(stand, base_url)
assert register(new_client(), "after")["token"]
def test_api_stop_while_waiting_for_openbao(
new_client: ClientFactory, stand: Stand
) -> None:
"""API ждёт остановленный OpenBao, `docker stop` — код 0 быстрее 10 с и
строка «stopped before startup signal=SIGTERM»."""
assert_bao_stand(stand)
base_url = str(new_client().base_url)
before = len(api_records(stand))
stand("kill-api")
stand("stop", "openbao")
try:
stand("start-api")
wait_api_line(
stand, before, "waiting for secret store", timeout=STARTUP_TIMEOUT_S / 2
)
stopped = json.loads(stand("stop-api"))
print(f"stop while waiting: {stopped}")
assert stopped["exit_code"] == 0, stopped
assert stopped["seconds"] < STOP_BUDGET_S, stopped
records = api_records(stand)[before:]
early = [r for r in records if r["message"] == "stopped before startup"]
assert early, [r["message"] for r in records]
assert early[0]["fields"]["signal"] == "SIGTERM"
assert not any(r["message"] == secrets_log.LOADED for r in records)
finally:
restore_openbao(stand)
restore_api(stand, base_url)
assert register(new_client(), "after")["token"]
def test_secret_new_version(new_client: ClientFactory, stand: Stand) -> None:
"""Оператор записал новую версию `postgres/api` с прежним значением
(`bao-rewrite`): не позже следующего продления API пишет «secret version
changed» с путём и версиями N → N+1, запросы проходят; после перезапуска —
«process secrets loaded» с версией N+1. Значение прежнее — ни один процесс
стенда не ломается."""
assert_bao_stand(stand)
client = new_client()
base_url = str(client.base_url)
alice = register(client, "version")
chat = create_chat(client, alice, title="New version")
before = len(api_records(stand))
output = stand("bao-rewrite", "postgres/api")
old, new = (
int(part)
for part in output.split("version ", 1)[1].split(",", 1)[0].split(" -> ")
)
assert new == old + 1, output
changed = wait_api_line(
stand,
before,
secrets_log.VERSION_CHANGED,
timeout=renewal_bound_s(),
match=lambda f: f.get("path") == "messenger/data/postgres/api",
)
assert changed["fields"]["loaded"] == str(old), changed
assert changed["fields"]["current"] == str(new), changed
assert send(client, alice, chat, "same password, new version").status_code == 201
restart_from = len(api_records(stand))
try:
stand("kill-api")
finally:
restore_api(stand, base_url)
loaded = [
r
for r in api_records(stand)[restart_from:]
if r["message"] == secrets_log.LOADED
]
assert len(loaded) == 1, loaded
assert f"postgres/api:{new}" in loaded[0]["fields"]["versions"].split(","), loaded
after = new_client()
assert send(after, alice, chat, "after restart").status_code == 201