fix: address openbao-secrets verify findings

bao_check now compares cert auth roles and policies in OpenBao with
the repository and tries every foreign identity against every role
and without a role name; API and migrations exit with code 2 on
invalid settings; stop-at-start runs its attempts next to the stand's
OpenBao again; openbao-outage checks the exit code, the record and
the restart; run_docker restarts only services started before seed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 15:17:57 +03:00
co-authored by Claude Opus 5.5
parent 3875db4007
commit 4dd73299cf
16 changed files with 699 additions and 83 deletions
+261 -39
View File
@@ -72,7 +72,8 @@
уборщика по префиксам staging и базы; код 1 при расхождении
stop-at-start [--image ТЕГ] [--delays 0.2,0.3,0.4,1.5,5]
[--server-start 3] docker stop контейнеров образа (лимиты
реплики, без сети) во время старта: через паузу после
реплики, сеть default рабочего стенда без алиаса — секреты из
его OpenBao, не healthy — код 2) во время старта: через паузу после
docker run и по строке «Started server process»; время
сигнала и выхода, код выхода, этап старта, кто остановил
(ранний обработчик или uvicorn); код 1, если стартующий
@@ -5652,9 +5653,23 @@ SAS_TLS_ENV = (
"API_TLS__CLIENT_CA_FILE=/run/secrets/ca.crt",
"-e",
"API_TLS__CRL_FILE=/run/secrets/crl.pem",
# OpenBao (change openbao-secrets): пара api-client — как у реплик; в
# --network none OpenBao нет, старт ждёт его до срока, и сигнал в это
# время — окно A (ранний обработчик), а не B / C
# CA стенда клиентам хранилищ и OpenBao (change storage-tls): без него
# каждая попытка — код 2 «Invalid client TLS settings» за доли секунды
# (правки verify W3 change openbao-secrets)
"-e",
"CLIENT_TLS__CA_FILE=/run/secrets/ca.crt",
# имена хранилищ, а не IP по умолчанию (проверка при старте, change
# storage-tls); localhost в контейнере — никуда: соединения ленивые, а
# запросов и healthcheck у попытки нет
"-e",
"DATABASE__HOST=localhost",
"-e",
"CACHE__HOST=localhost",
"-e",
"S3__HOST=localhost",
# OpenBao (change openbao-secrets): пара api-client — как у реплик;
# попытка — в сети default стенда, где OpenBao отвечает по имени
# openbao, иначе старт ждал бы его до срока и окна B / C не наступали бы
"-e",
"SECRETS__CERT_FILE=/run/secrets/api-client.crt",
"-e",
@@ -5695,8 +5710,11 @@ def cmd_stop_at_start(image: str, delays: list[float], server: int) -> int:
(решение 8 design change `fix-known-issues`).
Каждая попытка — свой контейнер образа с лимитами реплики `api`
(1 CPU / 512 МиБ без swap), без сети и без `config.toml`: приложение
стартует на дефолтах, соединения с хранилищами ленивые. `docker stop`
(1 CPU / 512 МиБ без swap), без `config.toml`: приложение стартует на
дефолтах, соединения с хранилищами ленивые. С change `openbao-secrets`
(правки verify W3) — в сети `default` рабочего стенда без алиаса (LB её
не видит): старт входит в OpenBao стенда сертификатом `api-client` и
читает секреты, как реплика; OpenBao не `healthy` — код 2. `docker stop`
(срок 10 с, как `stop_grace_period`) — через паузу после `docker run`
или, у попыток `--server-start`, сразу по строке «Started server
process» (`docker logs -f`). Время — часы ВМ Docker: поток `docker
@@ -5719,7 +5737,18 @@ def cmd_stop_at_start(image: str, delays: list[float], server: int) -> int:
if not image_id:
print(f"image {image} not found")
return 1
print(f"image {image} ({image_id[:19]}), label {label}")
bao = service_ids("openbao")
health = mc_inspect(bao[0], "{{.State.Health.Status}}") if bao else ""
if health != "healthy":
print(
f"stop-at-start: openbao of the stand is {health or 'not running'}: "
"run make run_docker (sealed — make bao_unseal)",
)
return 2
network = (
f"{json.loads(compose('config', '--format', 'json'))['name']}_default"
)
print(f"image {image} ({image_id[:19]}), label {label}, network {network}")
with events_path.open("w") as out:
stream = subprocess.Popen(
[
@@ -5761,6 +5790,7 @@ def cmd_stop_at_start(image: str, delays: list[float], server: int) -> int:
label,
f"mtusi-stop-at-start-{tag}-{number}",
events_path,
network=network,
delay=delay if how == "delay" else None,
),
)
@@ -5792,6 +5822,7 @@ def stop_attempt(
name: str,
events_path: Path,
*,
network: str,
delay: float | None,
) -> dict[str, object]:
"""Одна попытка: контейнер, `docker stop`, события и журнал."""
@@ -5801,7 +5832,8 @@ def stop_attempt(
"run",
"-d",
"--network",
"none",
network,
"--no-healthcheck",
"--cpus",
"1",
"--memory",
@@ -13550,6 +13582,20 @@ def scratch_run(
"0",
len(TOKEN_RE.findall(proc.stdout + proc.stderr)),
)
# пустой стенд: seed пишет все пути, а контейнеры, созданные up -d,
# уже читают новые версии — перезапуска нет (правки verify S3)
seeded = re.search(r"seed: (\d+) of (\d+) paths written", proc.stdout)
restarted = re.search(
r"restart services with new secret versions:(.*)",
proc.stdout,
)
add(
"make run_docker output: seed paths written, services restarted",
"9 of 9, none",
f"{seeded.group(1) if seeded else '-'} of "
f"{seeded.group(2) if seeded else '-'}, "
f"{restarted.group(1).strip() if restarted else 'none'}",
)
time.sleep(SCRATCH_SETTLE_S)
_, out = scratch("ps", "-a", "--format", "json")
containers = [
@@ -20904,6 +20950,10 @@ OB_LABEL = "mtusi.openbao-check"
OB_PROBE_IDENTITY = "bao-probe"
# разовый сертификат с SAN api и чужим CN (CN = имя строки pki.sh issue)
OB_PROBE_CN_IDENTITY = "bao-probe-cn"
# разовый сертификат с двумя SAN: своим и api (правки verify W1)
OB_PROBE_2SAN_IDENTITY = "bao-probe-2san"
# политики OpenBao, которых нет файлами (встроенные)
OB_BUILTIN_POLICIES = ("default", "root")
# роль входа → identity (CN) процесса; сервис compose — роль
OB_ROLES = {
"api": "api-client",
@@ -21136,8 +21186,9 @@ def ob_materials(material: Path) -> str | None:
"""Каталог пробы (0700): CA стенда, пары bao-operator, api (серверный
leaf), haproxy, worker и процессов — копии; разовые leaf CA оператора
(bao-probe — client SAN bao-probe; bao-probe-cn — client SAN api, чужой
CN; 1 день); CA и клиентский leaf постороннего CA (ключ CA удаляется
сразу). Ошибка — строка."""
CN; bao-probe-2san — client SAN bao-probe-2san и api; 1 день); CA и
клиентский leaf постороннего CA (ключ CA удаляется сразу). Ошибка —
строка."""
stand = pki_stand_dir()
copies = [("ca.crt", "stand-ca.crt")]
for identity in ("bao-operator", "api", "haproxy", *OB_ROLES.values()):
@@ -21150,9 +21201,10 @@ def ob_materials(material: Path) -> str | None:
shutil.copyfile(stand / source, material / target)
env = dict(os.environ)
try:
for identity, san in (
(OB_PROBE_IDENTITY, OB_PROBE_IDENTITY),
(OB_PROBE_CN_IDENTITY, "api"),
for identity, sans in (
(OB_PROBE_IDENTITY, (OB_PROBE_IDENTITY,)),
(OB_PROBE_CN_IDENTITY, ("api",)),
(OB_PROBE_2SAN_IDENTITY, (OB_PROBE_2SAN_IDENTITY, "api")),
):
mc_pki(
[
@@ -21160,8 +21212,7 @@ def ob_materials(material: Path) -> str | None:
identity,
"--profile",
"client",
"--san",
san,
*(arg for san in sans for arg in ("--san", san)),
"--days",
"1",
"--out",
@@ -21373,27 +21424,90 @@ def ob_process_rows(
return rows
def ob_foreign_rows(material: Path) -> list[tuple[str, str, str]]:
"""«Чужая identity того же CA»: haproxy, bao-operator, разовая проба,
worker с ролью api и сертификат с SAN api и чужим CN — отказ входа."""
def ob_login_outcome(http, role: str | None) -> tuple[str, str]:
"""Вход с ролью или без имени роли: «статус token / no token» и политики
выданного токена (пусто без токена)."""
status, payload = bao_try(
http,
"POST",
"auth/cert/login",
body={"name": role} if role else {},
)
auth = payload.get("auth") or {}
token = str(auth.get("client_token") or "")
policies = " ".join(sorted(auth.get("token_policies") or []))
return f"{status} {'token' if token else 'no token'}", policies
def ob_foreign_rows(material: Path, root: str) -> list[tuple[str, str, str]]:
"""«Чужая identity того же CA»: роли cert auth в OpenBao = таблица ролей;
haproxy, bao-operator, разовая проба, сертификат с SAN api и чужим CN и
сертификат с двумя SAN (свой и api) — отказ входа в каждую роль таблицы и
OpenBao и без имени роли; identity процесса — отказ во всех чужих ролях, а
без имени роли — токен ровно своей политики (правки verify W1)."""
rows = []
for name, identity, role in (
("haproxy", "haproxy", "api"),
("bao-operator", "bao-operator", "api"),
("one-off bao-probe", OB_PROBE_IDENTITY, "api"),
("worker with role api", "worker", "api"),
("SAN api, CN bao-probe-cn", OB_PROBE_CN_IDENTITY, "api"),
_, listed = bao_try(
bao_identity("bao-operator"),
"LIST",
"auth/cert/certs",
token=root,
)
roles = sorted((listed.get("data") or {}).get("keys") or [])
rows.append(
(
"login roles in OpenBao (LIST auth/cert/certs) = role table",
" ".join(sorted(OB_ROLES)),
" ".join(roles) or "none",
),
)
every = [*sorted(set(OB_ROLES) | set(roles)), None]
refused = "400 no token"
def tried(http, targets: list[str | None]) -> str:
bad = []
for role in targets:
outcome, _ = ob_login_outcome(http, role)
if outcome != refused:
bad.append(f"{role or '(no role)'}: {outcome}")
return " ".join(bad) or f"{refused} × {len(targets)}"
for name, identity in (
("haproxy", "haproxy"),
("bao-operator", "bao-operator"),
("one-off bao-probe", OB_PROBE_IDENTITY),
("SAN api, CN bao-probe-cn", OB_PROBE_CN_IDENTITY),
("two SAN bao-probe-2san and api", OB_PROBE_2SAN_IDENTITY),
):
http = bao_http(
material / f"{identity}.crt",
material / f"{identity}.key",
)
status, token, _ = bao_login(http, role)
rows.append(
(
f"login refused: {name}",
"400 no token",
f"{status} {'token' if token else 'no token'}",
f"login refused: {name} in every role and without role",
f"{refused} × {len(every)}",
tried(http, every),
),
)
for own, identity in OB_ROLES.items():
http = bao_http(
material / f"{identity}.crt",
material / f"{identity}.key",
)
others = [role for role in every if role is not None and role != own]
rows.append(
(
f"login refused: {identity} in other roles",
f"{refused} × {len(others)}",
tried(http, others),
),
)
outcome, policies = ob_login_outcome(http, None)
rows.append(
(
f"{identity} without role: token policies",
f"200 token {own}",
f"{outcome} {policies}".strip(),
),
)
return rows
@@ -21495,7 +21609,14 @@ def ob_short_ttl_rows(
role(OB_CRL_TTL_S, OB_CRL_TTL_S)
status, token, _ = bao_login(probe, OB_PROBE_IDENTITY)
rows.append(("before revocation: login", "200", str(status)))
mc_pki(["revoke", OB_PROBE_IDENTITY], dict(os.environ))
# разовые leaf с SAN api (чужой CN, два SAN) уже не нужны — отзываются
# вместе с пробой и попадают в тот же CRL
for identity in (
OB_PROBE_IDENTITY,
OB_PROBE_CN_IDENTITY,
OB_PROBE_2SAN_IDENTITY,
):
mc_pki(["revoke", identity], dict(os.environ))
operator.request(
"POST",
"auth/cert/crls/stand",
@@ -21670,12 +21791,24 @@ def ob_inspect_rows(
def ob_policy_rows(root: str) -> list[tuple[str, str, str]]:
"""Файлы политик без шаблонов и политики OpenBao = файлы."""
"""Файлы политик без шаблонов, список политик OpenBao (кроме встроенных)
= файлы (правки verify W1) и каждая политика OpenBao = файл."""
rows = []
operator = bao_identity("bao-operator")
for path in sorted(
(ROOT / "infra" / "openbao" / "policies").glob("*.hcl"),
):
files = sorted((ROOT / "infra" / "openbao" / "policies").glob("*.hcl"))
_, listed = bao_try(operator, "LIST", "sys/policies/acl", token=root)
names = sorted(
set((listed.get("data") or {}).get("keys") or [])
- set(OB_BUILTIN_POLICIES),
)
rows.append(
(
"policies in OpenBao except root and default = policy files",
" ".join(path.stem for path in files),
" ".join(names) or "none",
),
)
for path in files:
text = path.read_text()
code = "\n".join(line.split("#", 1)[0] for line in text.splitlines())
rows.append(
@@ -21934,7 +22067,7 @@ def cmd_openbao_check(*, report: bool, compose_dir: str | None) -> int:
rows.append(
(f"{where}: {case}", want, got.get(case, "no result")),
)
rows += ob_foreign_rows(material)
rows += ob_foreign_rows(material, root)
paths_by_role = {
role: module.policy_paths(role) for role in OB_ROLES
}
@@ -21995,6 +22128,8 @@ OO_TOKEN_MAX_TTL = "300s"
OO_RENEW_WAIT_S = 60
OO_REPLICA_WAIT_S = 90
OO_ONE_OFF_TIMEOUT_S = "6"
# выход новой реплики по сроку ожидания OpenBao (30 с) и перезапуск политикой
OO_STARTUP_FAIL_WAIT_S = 60
OO_STOP_LIMIT_S = 10
OO_APP_LONG = ("worker", "relay", "cleaner")
@@ -22062,6 +22197,55 @@ def oo_restart_processes() -> None:
detached("make", "replicas", timeout=240)
def oo_die_stream(container: str, path: Path) -> subprocess.Popen:
"""Поток событий `die` контейнера в файл: коды выхода по порядку. Поток,
а не `docker events --since`: буфер событий демона перекрывают события
exec healthcheck всех контейнеров (как у `stop-at-start`)."""
with path.open("w") as out:
return subprocess.Popen(
[
"docker",
"events",
"--filter",
f"container={container}",
"--filter",
"event=die",
"--format",
'{{index .Actor.Attributes "exitCode"}}',
],
stdout=out,
stderr=subprocess.DEVNULL,
)
def oo_startup_failure(
container: str,
since: float,
codes: list[str],
) -> tuple[str, float | None]:
"""Код выхода по сроку ожидания (второй `die` потока: первый — остановка
`docker restart`) и `waited_seconds` записи `error` «Secrets store is
unavailable» журнала контейнера с `since` (`None` — записи нет)."""
code = codes[1] if len(codes) > 1 else "-"
logs = subprocess.run(
["docker", "logs", "--since", str(int(since)), container],
capture_output=True,
text=True,
check=False,
).stdout
waited = None
for line in logs.splitlines():
with contextlib.suppress(ValueError, TypeError):
record = json.loads(line)
if (
record.get("event") == "Secrets store is unavailable"
and record.get("level") == "error"
):
waited = float(record.get("waited_seconds"))
break
return code, waited
def oo_one_off() -> tuple[int, str, float]:
"""Новый процесс (разовая команда replay в контейнере relay) с коротким
сроком ожидания: код, последнее событие, секунды."""
@@ -22204,14 +22388,52 @@ def openbao_outage(port: int, project: str) -> int:
"yes",
yes(bool(seen)),
)
# 2. новая реплика без OpenBao не стартует, LB обслуживает другую
# 2. новая реплика без OpenBao не стартует, LB обслуживает другую: ждёт
# срок ожидания, выходит с кодом 1 записью «Secrets store is
# unavailable», политика перезапуска стартует её снова (правки verify S2)
replica = service_ids("api")[0]
detached("docker", "restart", replica, timeout=60)
time.sleep(15)
restarts_before = int(mc_inspect(replica, "{{.RestartCount}}") or 0)
dies = Path(tempfile.mkstemp(prefix="mtusi-openbao-outage-")[1])
stream = oo_die_stream(replica, dies)
try:
# поток подключается к демону до действия
time.sleep(1)
restarted_at = time.time()
detached("docker", "restart", replica, timeout=60)
time.sleep(15)
add(
"stopped: restarted replica not healthy",
"yes",
yes(mc_inspect(replica, "{{.State.Health.Status}}") != "healthy"),
)
poll(
lambda: (
int(mc_inspect(replica, "{{.RestartCount}}") or 0)
> restarts_before
),
timeout=OO_STARTUP_FAIL_WAIT_S,
interval=2,
)
finally:
stream.terminate()
stream.wait()
codes = dies.read_text().split()
dies.unlink(missing_ok=True)
exit_code, waited = oo_startup_failure(replica, restarted_at, codes)
add(
"stopped: restarted replica not healthy",
"stopped: restarted replica exits after the startup wait "
"(exit code, error record, waited ≥ 25 s)",
"1 yes yes",
f"{exit_code} {yes(waited is not None)} "
f"{yes(waited is not None and waited >= 25)}",
)
add(
"stopped: restart policy starts it again (RestartCount grew)",
"yes",
yes(mc_inspect(replica, "{{.State.Health.Status}}") != "healthy"),
yes(
int(mc_inspect(replica, "{{.RestartCount}}") or 0)
> restarts_before,
),
)
status, _, _ = call(port, "GET", f"{USERS}/me", token=token)
add("stopped: LB serves through the other replica", "200", status)