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:
@@ -21,6 +21,24 @@ S3 и брокер со своими volumes, порты хранилищ не
|
||||
окружении процесса, а значит, каждого вызова compose, pytest и hook:
|
||||
`secrets` проекта отказов ни разу не разрешаются в каталог рабочего
|
||||
стенда, каталог оператора не читается;
|
||||
- поднимает свой OpenBao прогона (change `openbao-tooling`, design, решения
|
||||
1, 2) до bootstrap ролей и процессов приложения: сервис `openbao`
|
||||
основного файла под проектом отказов (volume проекта, `restart: "no"`),
|
||||
порт — свободный `127.0.0.1:<BAO_OUT_PORT>` в окружении процесса;
|
||||
оператор — сам прогон: `infra/openbao/bao.py ready` интерпретатором
|
||||
прогона с явными `--address`, `--operator-dir`, `--pki-dir`, `--project`
|
||||
и короткими сроками ролей (`FAULT_BAO_TOKEN_TTL` /
|
||||
`FAULT_BAO_TOKEN_MAX_TTL` окружения команды, по умолчанию 20s / 60s:
|
||||
продление и повторный вход идут под всеми проверками); модель compose
|
||||
для `seed` — `COMPOSE_PROJECT_NAME` / `COMPOSE_FILE` только в окружении
|
||||
подпроцесса (hook узнаёт проект рабочего стенда вызовом compose без
|
||||
них). Материалы — `<каталог PKI прогона>/operator/openbao/<проект>`:
|
||||
`BAO_OPERATOR_DIR` окружения (Makefile экспортирует рабочий) заменяется
|
||||
им, до первого вызова — сверка «внутри каталога PKI прогона и не в
|
||||
каталоге оператора рабочего стенда» (иначе код 2); удаляются вместе с
|
||||
каталогом PKI. Тестам — `FAULT_BAO_ADDRESS`, `FAULT_BAO_OPERATOR_DIR`,
|
||||
`FAULT_BAO_TOKEN_TTL_S`, `FAULT_BAO_TOKEN_MAX_TTL_S`,
|
||||
`FAULT_SECRETS_STARTUP_TIMEOUT_S` (из конфигурации compose `api`);
|
||||
- запускает пять контейнеров API с TLS-настройками рабочего стенда (только
|
||||
mTLS, CA и CRL этой PKI, allowlist `haproxy`), порт —
|
||||
`127.0.0.1:<свободный>`, готовность — `healthy`: обычный (с
|
||||
@@ -38,6 +56,16 @@ S3 и брокер со своими volumes, порты хранилищ не
|
||||
- после тестов читает журнал PostgreSQL стенда: печатает сводку и падает
|
||||
на признаках аварийного перезапуска (решение 12 design change
|
||||
`fix-known-issues`);
|
||||
- затем сводку секретов (change `openbao-tooling`, design, решение 2):
|
||||
журналы пяти API, уборщика, worker и relay — повторные входы по
|
||||
причинам, недоступность и возврат OpenBao, отказы по правам, сбои
|
||||
продления, нет поля; журнал аудита OpenBao — входы и продления по ролям,
|
||||
ответы с ошибкой, токены открытым текстом. Строка `secrets log: …` —
|
||||
всегда; ненулевой код — у роли `api`, `worker`, `relay` или `cleaner`
|
||||
нет продлений в аудите, жизнь процесса длиннее `max_ttl + ttl` без
|
||||
повторного входа, отказ по правам, сбой продления, нет поля или токен
|
||||
открытым текстом; при падении — ещё хвост журнала `openbao` (значения в
|
||||
аудите — HMAC);
|
||||
- удаляет стенд вместе с volume при любом исходе, в том числе по Ctrl+C,
|
||||
затем каталог PKI; не удалился — строка с путём и код 1.
|
||||
|
||||
@@ -48,8 +76,10 @@ S3 и брокер со своими volumes, порты хранилищ не
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
@@ -75,6 +105,39 @@ PKI_CLIENT_IDENTITY = "haproxy"
|
||||
API_SERVER_NAME = "api"
|
||||
READY_TIMEOUT_S = 60
|
||||
LOG_TAIL_LINES = 50
|
||||
# OpenBao прогона (change openbao-tooling, design, решения 1, 2): оператор —
|
||||
# этот скрипт, материалы — внутри каталога PKI прогона
|
||||
BAO_SCRIPT = ROOT / "infra" / "openbao" / "bao.py"
|
||||
BAO_IN_CONTAINER_PORT = 8200
|
||||
# сроки ролей входа прогона: продление раз в ~13 с, повторный вход раз в
|
||||
# минуту у каждого процесса; окружение команды меняет их только для контроля
|
||||
# сводки и отладки
|
||||
BAO_TOKEN_TTL_DEFAULT = "20s"
|
||||
BAO_TOKEN_MAX_TTL_DEFAULT = "60s"
|
||||
WORKING_OPERATOR_DIR = Path.home() / ".config" / "mtusi-lab7" / "operator"
|
||||
DURATION_RE = re.compile(r"(\d+)([smh]?)")
|
||||
# сводка секретов: роли долгоживущих процессов, у которых в аудите должны
|
||||
# быть продления, и записи журнала процессов
|
||||
RENEWING_ROLES = ("api", "worker", "relay", "cleaner")
|
||||
AUDIT_LOGIN_PATH = "auth/cert/login"
|
||||
AUDIT_RENEW_PATH = "auth/token/renew-self"
|
||||
TOKEN_RE = re.compile(r"\bs\.[A-Za-z0-9]{24,}\b")
|
||||
LOADED_EVENT = "Loaded process secrets"
|
||||
RELOGIN_EVENT = "Logged in to secrets store again"
|
||||
# записи нового процесса до загрузки секретов: прежняя жизнь контейнера уже
|
||||
# кончилась
|
||||
STARTUP_EVENTS = (
|
||||
"Waiting for secrets store",
|
||||
"Stopped API before startup",
|
||||
"Stopped worker before startup",
|
||||
"Stopped relay before startup",
|
||||
"Stopped cleaner before startup",
|
||||
)
|
||||
SECRETS_PROBLEM_EVENTS = (
|
||||
"Secrets store refused access",
|
||||
"Secrets renewal failed",
|
||||
"Secret field is missing",
|
||||
)
|
||||
# признаки аварийного перезапуска PostgreSQL: postmaster счёл аварией выход
|
||||
# неизвестного потомка, завершил все процессы и восстанавливается. Штатные
|
||||
# stop / start дают «database system was shut down», обрыв backend — FATAL
|
||||
@@ -285,6 +348,347 @@ def relay_timings(project: str) -> dict[str, str]:
|
||||
}
|
||||
|
||||
|
||||
def secrets_startup_timeout(project: str) -> str:
|
||||
"""Срок ожидания OpenBao при старте API стенда — из конфигурации compose
|
||||
(`failures.compose.yml`): проверка «новый API без OpenBao» ждёт по нему."""
|
||||
config = dc(project, "config", "--format", "json", quiet=True)
|
||||
environment = json.loads(config.stdout)["services"]["api"]["environment"]
|
||||
return environment["SECRETS__STARTUP_TIMEOUT_SECONDS"]
|
||||
|
||||
|
||||
def duration_seconds(value: str) -> int:
|
||||
"""`20s`, `10m`, `1h`, `600` → секунды (как `bao.py parse_duration`)."""
|
||||
match = DURATION_RE.fullmatch(value.strip())
|
||||
if not match or int(match.group(1)) <= 0:
|
||||
raise ValueError(f"bad duration: {value!r}")
|
||||
return (
|
||||
int(match.group(1))
|
||||
* {"": 1, "s": 1, "m": 60, "h": 3600}[match.group(2)]
|
||||
)
|
||||
|
||||
|
||||
def _inside(path: Path, parent: Path) -> bool:
|
||||
path, parent = path.resolve(), parent.resolve()
|
||||
return path == parent or parent in path.parents
|
||||
|
||||
|
||||
def operator_dir_problem(
|
||||
operator_dir: Path,
|
||||
run_dir: Path,
|
||||
working_dirs: tuple[Path, ...] = (WORKING_OPERATOR_DIR,),
|
||||
) -> str | None:
|
||||
"""Сверка каталога материалов OpenBao прогона до первого вызова
|
||||
(спек `secret-store`, «Каталог материалов вне прогона»): только внутри
|
||||
временного каталога прогона и не внутри каталога оператора рабочего
|
||||
стенда. `init` переносит материалы неинициализированного OpenBao в
|
||||
`stale-<UTC>/`: прогон, указавший на рабочий каталог, оставил бы рабочий
|
||||
OpenBao без долей. Отдаёт текст отказа или None."""
|
||||
if not _inside(operator_dir, run_dir):
|
||||
return (
|
||||
f"OpenBao operator dir {operator_dir} is outside the run "
|
||||
f"directory {run_dir}"
|
||||
)
|
||||
for working in working_dirs:
|
||||
if _inside(operator_dir, working):
|
||||
return (
|
||||
f"OpenBao operator dir {operator_dir} is inside the working "
|
||||
f"operator directory {working}"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def start_openbao(
|
||||
project: str,
|
||||
*,
|
||||
address: str,
|
||||
operator_dir: Path,
|
||||
token_ttl: str,
|
||||
token_max_ttl: str,
|
||||
) -> None:
|
||||
"""OpenBao прогона: `up -d openbao`, затем `bao.py ready` (init, unseal,
|
||||
сведение, наполнение) с явными аргументами. Модель compose для `seed` —
|
||||
те же файлы и проект через `COMPOSE_*` только в окружении подпроцесса.
|
||||
Код ≠ 0 — `RuntimeError` (отказ прогона до миграций)."""
|
||||
dc(project, "up", "-d", "--no-deps", "openbao")
|
||||
env = os.environ | {
|
||||
"COMPOSE_PROJECT_NAME": project,
|
||||
"COMPOSE_FILE": os.pathsep.join(str(path) for path in COMPOSE_FILES),
|
||||
}
|
||||
env.pop("COMPOSE_ENV_FILES", None)
|
||||
started = time.monotonic()
|
||||
result = run(
|
||||
sys.executable,
|
||||
str(BAO_SCRIPT),
|
||||
"--address",
|
||||
address,
|
||||
"--project",
|
||||
project,
|
||||
"--operator-dir",
|
||||
str(operator_dir),
|
||||
"--pki-dir",
|
||||
os.environ["PKI_STAND_DIR"],
|
||||
"ready",
|
||||
"--token-ttl",
|
||||
token_ttl,
|
||||
"--token-max-ttl",
|
||||
token_max_ttl,
|
||||
check=False,
|
||||
env=env,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(
|
||||
f"OpenBao of the run is not ready: bao.py ready exited "
|
||||
f"{result.returncode}",
|
||||
)
|
||||
say(f"openbao ready in {time.monotonic() - started:.1f} s")
|
||||
|
||||
|
||||
def _parse_time(value: str) -> datetime.datetime | None:
|
||||
"""ISO 8601 структурного журнала или `docker inspect` (наносекунды)."""
|
||||
if not value or value.startswith("0001-"):
|
||||
return None
|
||||
text = value.strip().replace("Z", "+00:00")
|
||||
match = re.match(r"(.*T\d\d:\d\d:\d\d)(\.\d+)?(.*)", text)
|
||||
if not match:
|
||||
return None
|
||||
fraction = (match.group(2) or "")[:7]
|
||||
try:
|
||||
return datetime.datetime.fromisoformat(
|
||||
match.group(1) + fraction + (match.group(3) or "+00:00"),
|
||||
)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _records(text: str) -> list[dict]:
|
||||
records = []
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if not line.startswith("{"):
|
||||
continue
|
||||
try:
|
||||
record = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(record, dict):
|
||||
records.append(record)
|
||||
return records
|
||||
|
||||
|
||||
def _container_end(container: str) -> datetime.datetime | None:
|
||||
"""Конец последней жизни контейнера: сейчас — у работающего, иначе
|
||||
`FinishedAt`."""
|
||||
state = run(
|
||||
"docker",
|
||||
"inspect",
|
||||
"-f",
|
||||
"{{.State.Running}} {{.State.FinishedAt}}",
|
||||
container,
|
||||
check=False,
|
||||
quiet=True,
|
||||
)
|
||||
running, _, finished = state.stdout.strip().partition(" ")
|
||||
if running == "true":
|
||||
return datetime.datetime.now(datetime.timezone.utc) # noqa: UP017
|
||||
return _parse_time(finished)
|
||||
|
||||
|
||||
def process_secrets_summary(
|
||||
name: str,
|
||||
container: str,
|
||||
limit_s: int,
|
||||
) -> tuple[str, list[str], dict[str, int]]:
|
||||
"""Журнал одного контейнера: жизни (от «Loaded process secrets» до
|
||||
следующей или до конца), повторные входы по причинам, недоступность и
|
||||
возврат, записи-проблемы. Отдаёт строку сводки, проблемы и счётчики."""
|
||||
logs = run("docker", "logs", container, check=False, quiet=True)
|
||||
text = logs.stdout + logs.stderr
|
||||
records = _records(text)
|
||||
counts = {
|
||||
"lives": 0,
|
||||
"max_ttl": 0,
|
||||
"expired": 0,
|
||||
"renew_refused": 0,
|
||||
"unavailable": 0,
|
||||
"available_again": 0,
|
||||
"startup_unavailable": 0,
|
||||
"versions_changed": 0,
|
||||
"issues": 0,
|
||||
"tokens": len(TOKEN_RE.findall(text)),
|
||||
}
|
||||
problems: list[str] = []
|
||||
lives: list[list[dict]] = []
|
||||
current: list[dict] | None = None
|
||||
for record in records:
|
||||
event = record.get("event")
|
||||
if event == LOADED_EVENT:
|
||||
current = [record]
|
||||
lives.append(current)
|
||||
counts["lives"] += 1
|
||||
continue
|
||||
if event in STARTUP_EVENTS:
|
||||
# новый процесс в том же контейнере ещё без секретов: прежняя
|
||||
# жизнь кончилась раньше (kill), её записи сюда не идут
|
||||
current = None
|
||||
if current is not None:
|
||||
current.append(record)
|
||||
if event == RELOGIN_EVENT:
|
||||
reason = str(record.get("reason"))
|
||||
counts[reason] = counts.get(reason, 0) + 1
|
||||
elif event == "Secrets store is unavailable":
|
||||
key = (
|
||||
"unavailable"
|
||||
if record.get("level") == "warning"
|
||||
else "startup_unavailable"
|
||||
)
|
||||
counts[key] += 1
|
||||
elif event == "Secrets store is available again":
|
||||
counts["available_again"] += 1
|
||||
elif event == "Secret version changed":
|
||||
counts["versions_changed"] += 1
|
||||
elif event in SECRETS_PROBLEM_EVENTS:
|
||||
counts["issues"] += 1
|
||||
problems.append(
|
||||
f"{name}: {event} ({record.get('reason')}, "
|
||||
f"{record.get('path')}, {record.get('error_type')})",
|
||||
)
|
||||
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:
|
||||
continue
|
||||
seconds = (finish - start).total_seconds()
|
||||
if not relogins:
|
||||
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)",
|
||||
)
|
||||
line = (
|
||||
f"secrets log [{name}]: lives {counts['lives']}, relogins max_ttl "
|
||||
f"{counts['max_ttl']} expired {counts['expired']} renew_refused "
|
||||
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"{longest:.0f} s"
|
||||
)
|
||||
return line, problems, counts
|
||||
|
||||
|
||||
def audit_summary(project: str) -> tuple[str, list[str]]:
|
||||
"""Журнал аудита OpenBao стенда: входы и продления по ролям
|
||||
(`display_name` `cert-<роль>`), ответы с ошибкой, токены открытым
|
||||
текстом. Берутся только путь запроса, роль и признак ошибки."""
|
||||
logs = dc(
|
||||
project,
|
||||
"logs",
|
||||
"--no-log-prefix",
|
||||
"openbao",
|
||||
check=False,
|
||||
quiet=True,
|
||||
)
|
||||
text = logs.stdout + logs.stderr
|
||||
logins: dict[str, int] = {}
|
||||
renewals: dict[str, int] = {}
|
||||
errors: dict[str, int] = {}
|
||||
for record in _records(text):
|
||||
if record.get("type") != "response":
|
||||
continue
|
||||
path = str((record.get("request") or {}).get("path", ""))
|
||||
name = str((record.get("auth") or {}).get("display_name") or "")
|
||||
role = name.removeprefix("cert-") if name.startswith("cert-") else ""
|
||||
if record.get("error"):
|
||||
errors[path] = errors.get(path, 0) + 1
|
||||
continue
|
||||
if path == AUDIT_LOGIN_PATH and role:
|
||||
logins[role] = logins.get(role, 0) + 1
|
||||
elif path == AUDIT_RENEW_PATH and role:
|
||||
renewals[role] = renewals.get(role, 0) + 1
|
||||
tokens = len(TOKEN_RE.findall(text))
|
||||
problems: list[str] = []
|
||||
if not renewals:
|
||||
problems.append(
|
||||
"audit parsed nothing: no renewals of any role (parser or "
|
||||
"audit format, not the stand)",
|
||||
)
|
||||
missing = [role for role in RENEWING_ROLES if not renewals.get(role)]
|
||||
if missing:
|
||||
problems.append(
|
||||
"roles without renewals in the audit: " + " ".join(missing),
|
||||
)
|
||||
if tokens:
|
||||
problems.append(f"audit: {tokens} s.-tokens in plaintext")
|
||||
|
||||
def fmt(counts: dict[str, int]) -> str:
|
||||
return (
|
||||
" ".join(f"{key}={value}" for key, value in sorted(counts.items()))
|
||||
or "none"
|
||||
)
|
||||
|
||||
line = (
|
||||
f"logins {fmt(logins)}; renewals {fmt(renewals)}; error responses "
|
||||
f"{fmt(errors)}; s.-tokens in plaintext {tokens}"
|
||||
)
|
||||
return line, problems
|
||||
|
||||
|
||||
def secrets_log_check(
|
||||
project: str,
|
||||
containers: dict[str, str],
|
||||
*,
|
||||
token_ttl_s: int,
|
||||
token_max_ttl_s: int,
|
||||
) -> int:
|
||||
"""Сводка секретов (design, решение 2): журналы процессов и аудит
|
||||
OpenBao; строка `secrets log: …` всегда, 1 — нарушено правило."""
|
||||
limit_s = token_max_ttl_s + token_ttl_s
|
||||
problems: list[str] = []
|
||||
totals: dict[str, int] = {}
|
||||
details: list[str] = []
|
||||
for name, container in containers.items():
|
||||
line, found, counts = process_secrets_summary(
|
||||
name,
|
||||
container,
|
||||
limit_s,
|
||||
)
|
||||
details.append(line)
|
||||
problems += found
|
||||
for key, value in counts.items():
|
||||
totals[key] = totals.get(key, 0) + value
|
||||
audit, audit_problems = audit_summary(project)
|
||||
problems += audit_problems
|
||||
say(
|
||||
f"secrets log: {len(containers)} containers, roles ttl "
|
||||
f"{token_ttl_s} s / max {token_max_ttl_s} s; relogins max_ttl "
|
||||
f"{totals.get('max_ttl', 0)} expired {totals.get('expired', 0)} "
|
||||
f"renew_refused {totals.get('renew_refused', 0)}; unavailable "
|
||||
f"{totals.get('unavailable', 0)} / available again "
|
||||
f"{totals.get('available_again', 0)}; refused access, renewal "
|
||||
f"failures, missing fields {totals.get('issues', 0)}; "
|
||||
f"audit: {audit}",
|
||||
)
|
||||
for line in details:
|
||||
say(line)
|
||||
for problem in problems:
|
||||
say(f"secrets log problem: {problem}")
|
||||
return 1 if problems else 0
|
||||
|
||||
|
||||
def env_pairs(env: dict[str, str]) -> str:
|
||||
"""`KEY=value` через пробел: так окружение API получают тесты."""
|
||||
return " ".join(f"{key}={value}" for key, value in env.items())
|
||||
@@ -445,6 +849,21 @@ def start_api(
|
||||
return f"https://127.0.0.1:{port}"
|
||||
|
||||
|
||||
def bao_settings() -> dict:
|
||||
"""Сроки ролей прогона из окружения команды (по умолчанию 20s / 60s);
|
||||
неверное значение — `ValueError`."""
|
||||
ttl = os.environ.get("FAULT_BAO_TOKEN_TTL") or BAO_TOKEN_TTL_DEFAULT
|
||||
max_ttl = (
|
||||
os.environ.get("FAULT_BAO_TOKEN_MAX_TTL") or BAO_TOKEN_MAX_TTL_DEFAULT
|
||||
)
|
||||
return {
|
||||
"token_ttl": ttl,
|
||||
"token_max_ttl": max_ttl,
|
||||
"token_ttl_s": duration_seconds(ttl),
|
||||
"token_max_ttl_s": duration_seconds(max_ttl),
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
pytest_args = sys.argv[1:]
|
||||
working = working_project()
|
||||
@@ -452,17 +871,45 @@ def main() -> int:
|
||||
if project == working or not project.endswith(PROJECT_SUFFIX):
|
||||
say(f"refusing to use project {project!r}")
|
||||
return 2
|
||||
try:
|
||||
bao = bao_settings()
|
||||
except ValueError as e:
|
||||
say(f"OpenBao token TTL: {e}")
|
||||
return 2
|
||||
# каталог оператора рабочего стенда — до того, как make_pki заменит
|
||||
# PKI_OPERATOR_DIR окружения каталогом прогона
|
||||
working_dirs = tuple(
|
||||
Path(value)
|
||||
for value in (
|
||||
os.environ.get("PKI_OPERATOR_DIR"),
|
||||
os.environ.get("BAO_OPERATOR_DIR"),
|
||||
str(WORKING_OPERATOR_DIR),
|
||||
)
|
||||
if value
|
||||
)
|
||||
pki_dir = Path(tempfile.mkdtemp(prefix=PKI_DIR_PREFIX))
|
||||
pki_dir.chmod(0o700)
|
||||
code = 1
|
||||
try:
|
||||
say(f"pki: temporary CA and leaf certificates in {pki_dir}")
|
||||
operator_dir = pki_dir / "operator" / "openbao" / project
|
||||
problem = operator_dir_problem(operator_dir, pki_dir, working_dirs)
|
||||
if problem:
|
||||
say(problem)
|
||||
return 2
|
||||
# вызов bao.py без аргумента (hook, драйвер) взял бы экспорт
|
||||
# Makefile — каталог рабочего стенда
|
||||
os.environ["BAO_OPERATOR_DIR"] = str(operator_dir)
|
||||
# свободный порт OpenBao прогона: окружение compose сильнее .env
|
||||
os.environ["BAO_OUT_PORT"] = str(free_port())
|
||||
bao["operator_dir"] = operator_dir
|
||||
bao["address"] = f"https://localhost:{os.environ['BAO_OUT_PORT']}"
|
||||
try:
|
||||
client_env = make_pki(pki_dir)
|
||||
except subprocess.CalledProcessError as e:
|
||||
say(f"pki failed: {e}")
|
||||
return 1
|
||||
code = run_stand(project, working, pytest_args, client_env)
|
||||
code = run_stand(project, working, pytest_args, client_env, bao)
|
||||
except KeyboardInterrupt:
|
||||
say("interrupted")
|
||||
code = 130
|
||||
@@ -481,8 +928,9 @@ def run_stand(
|
||||
working: str,
|
||||
pytest_args: list[str],
|
||||
client_env: dict[str, str],
|
||||
bao: dict,
|
||||
) -> int:
|
||||
"""Стенд отказов на PKI прогона: подготовка, тесты, уборка."""
|
||||
"""Стенд отказов на PKI и OpenBao прогона: подготовка, тесты, уборка."""
|
||||
default_name = f"{project}-api"
|
||||
tight_name = f"{project}-api-tight"
|
||||
uploads_name = f"{project}-api-uploads"
|
||||
@@ -526,6 +974,23 @@ def run_stand(
|
||||
"s3",
|
||||
"rabbitmq",
|
||||
)
|
||||
# секреты процессов — из своего OpenBao прогона до bootstrap ролей,
|
||||
# миграций и процессов (change openbao-tooling, design, решение 2)
|
||||
startup_timeout = secrets_startup_timeout(project)
|
||||
say(
|
||||
f"start openbao: {bao['address']} (port in container "
|
||||
f"{BAO_IN_CONTAINER_PORT}), roles token ttl {bao['token_ttl']} "
|
||||
f"max {bao['token_max_ttl']}, api startup timeout "
|
||||
f"{startup_timeout} s, operator materials in "
|
||||
f"{bao['operator_dir']}",
|
||||
)
|
||||
start_openbao(
|
||||
project,
|
||||
address=bao["address"],
|
||||
operator_dir=bao["operator_dir"],
|
||||
token_ttl=bao["token_ttl"],
|
||||
token_max_ttl=bao["token_max_ttl"],
|
||||
)
|
||||
# роли процессов и владелец схемы — до миграций (change storage-roles,
|
||||
# design, решение 10): код bootstrap — отдельным up, как s3-bootstrap
|
||||
say("database roles bootstrap")
|
||||
@@ -626,6 +1091,11 @@ def run_stand(
|
||||
"FAULT_UPLOADS_ENV": env_pairs(UPLOADS_ENV),
|
||||
"FAULT_S3_ENV": env_pairs(S3_ENV),
|
||||
"FAULT_BACKLOG_ENV": env_pairs(BACKLOG_ENV),
|
||||
"FAULT_BAO_ADDRESS": bao["address"],
|
||||
"FAULT_BAO_OPERATOR_DIR": str(bao["operator_dir"]),
|
||||
"FAULT_BAO_TOKEN_TTL_S": str(bao["token_ttl_s"]),
|
||||
"FAULT_BAO_TOKEN_MAX_TTL_S": str(bao["token_max_ttl_s"]),
|
||||
"FAULT_SECRETS_STARTUP_TIMEOUT_S": startup_timeout,
|
||||
}
|
||||
| client_env
|
||||
| storage_names(project)
|
||||
@@ -647,6 +1117,32 @@ def run_stand(
|
||||
failed = bool(results["fault"])
|
||||
# стенд ещё жив: журнал PostgreSQL до уборки
|
||||
results["postgres"] = postgres_log_check(project)
|
||||
# и сводка секретов: журналы процессов и аудит OpenBao прогона
|
||||
processes = {
|
||||
"api": default_name,
|
||||
"api-tight": tight_name,
|
||||
"api-uploads": uploads_name,
|
||||
"api-s3": s3_name,
|
||||
"api-backlog": backlog_name,
|
||||
}
|
||||
for service in ("cleaner", "worker", "relay"):
|
||||
ids = dc(
|
||||
project,
|
||||
"ps",
|
||||
"-a",
|
||||
"-q",
|
||||
service,
|
||||
check=False,
|
||||
quiet=True,
|
||||
).stdout.split()
|
||||
if ids:
|
||||
processes[service] = ids[0]
|
||||
results["secrets"] = secrets_log_check(
|
||||
project,
|
||||
processes,
|
||||
token_ttl_s=bao["token_ttl_s"],
|
||||
token_max_ttl_s=bao["token_max_ttl_s"],
|
||||
)
|
||||
except KeyboardInterrupt:
|
||||
say("interrupted")
|
||||
results["interrupted"] = 130
|
||||
@@ -678,6 +1174,17 @@ def run_stand(
|
||||
service,
|
||||
check=False,
|
||||
)
|
||||
# журнал OpenBao прогона: значения и токены в аудите — HMAC
|
||||
say(f"last {LOG_TAIL_LINES} lines of openbao")
|
||||
dc(
|
||||
project,
|
||||
"logs",
|
||||
"--no-log-prefix",
|
||||
"--tail",
|
||||
str(LOG_TAIL_LINES),
|
||||
"openbao",
|
||||
check=False,
|
||||
)
|
||||
say("cleanup")
|
||||
if not cleanup(project, containers):
|
||||
say("cleanup failed")
|
||||
|
||||
Reference in New Issue
Block a user