feat: load process secrets from OpenBao via cert auth

OpenBao 2.7.3 (raft, TLS 1.3 with client certificates) holds the
PostgreSQL role passwords, the Valkey password and the S3 keys; each
process logs in with its own mTLS identity, reads only its paths and
renews its token in the background. Operator init, unseal, configure
and seed go through infra/openbao/bao.py and make bao_*; checks are
make bao_check and driver.py openbao-outage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 13:55:09 +03:00
co-authored by Claude Opus 5.5
parent 4dd4a957be
commit 64210dace0
64 changed files with 6709 additions and 321 deletions
+144 -1
View File
@@ -32,6 +32,7 @@ from src.config.settings import (
Broker,
Cache,
Database,
Secrets,
Settings,
)
from src.infra.cache import client as cache_client
@@ -41,9 +42,11 @@ from src.infra.s3 import client as s3_client
from src.infra.s3.client import create_object_storage
from src.infra.tls import (
API_STORAGES,
BOOTSTRAP_STORAGES,
CLEANER_STORAGES,
MIGRATION_STORAGES,
RELAY_STORAGES,
REPLAY_STORAGES,
WORKER_STORAGES,
build_client_context,
client_tls_problems,
@@ -120,6 +123,18 @@ def _settings(**sections: Any) -> Settings:
cache=Cache(host=sections.pop("cache_host", "valkey")),
s3=S3(host=sections.pop("s3_host", "s3")),
broker=sections.pop("broker", Broker()),
secrets=sections.pop("secrets", Secrets()),
)
def _secrets(pki: Path, identity: str = "api-client") -> Secrets:
"""OpenBao с действующими файлами identity стенда (change
`openbao-secrets`): проверка файлов пройдена, остаются проверяемые поля."""
stand = pki / "stand"
return Secrets(
cert_file=str(stand / f"{identity}.crt"),
key_file=str(stand / f"{identity}.key"),
crl_file=str(stand / "crl.pem"),
)
@@ -153,7 +168,7 @@ def test_problems_ca_file(tmp_path: Path, pki: Path) -> None:
str(pki / "stand" / "ca.crt"): [],
}
for path, expected in cases.items():
loaded = _settings(client_tls={"ca_file": path})
loaded = _settings(client_tls={"ca_file": path}, secrets=_secrets(pki))
problems = client_tls_problems(loaded, API_STORAGES)
assert problems == expected, path
# сообщения — имена полей, без путей
@@ -183,6 +198,7 @@ def test_problems_ip_host_per_process(
cache_host="::1",
s3_host="10.0.0.5",
broker=_broker(pki, host="127.0.0.1"),
secrets=_secrets(pki),
)
assert client_tls_problems(loaded, storages) == expected
@@ -194,6 +210,7 @@ def test_names_pass(pki: Path) -> None:
database_host=host,
cache_host=host,
s3_host=host,
secrets=_secrets(pki),
)
assert client_tls_problems(loaded, API_STORAGES) == []
@@ -308,6 +325,12 @@ def _run_entrypoint(
"BROKER__KEY_FILE": str(stand / "relay.key"),
"BROKER__CRL_FILE": str(stand / "crl.pem"),
"TELEMETRY__ENABLED": "false",
# OpenBao (change openbao-secrets): действующие файлы identity,
# чтобы дойти до проверяемого поля; до OpenBao процесс не доходит
"SECRETS__ADDRESS": "https://openbao:8200",
"SECRETS__CERT_FILE": str(stand / "relay.crt"),
"SECRETS__KEY_FILE": str(stand / "relay.key"),
"SECRETS__CRL_FILE": str(stand / "crl.pem"),
**env,
},
capture_output=True,
@@ -370,6 +393,126 @@ def test_entrypoint_refuses_before_connecting(
assert str(tmp_path) not in json.dumps(records)
# --- OpenBao (change openbao-secrets, design, решения 7, 9; спеки
# secret-store, «Без файлов identity», transport-security, «Адрес OpenBao не
# https») ---
@pytest.mark.parametrize(
"storages",
[
API_STORAGES,
WORKER_STORAGES,
CLEANER_STORAGES,
RELAY_STORAGES,
MIGRATION_STORAGES,
REPLAY_STORAGES,
],
)
def test_problems_secrets_files(pki: Path, storages: tuple[str, ...]) -> None:
"""Секция `secrets` — у каждого процесса приложения: пустые файлы, чужой
ключ, CRL не CRL, IP-адрес — имена полей без путей; у bootstrap ролей
секции нет."""
stand = pki / "stand"
base = _secrets(pki)
cases: list[tuple[dict[str, str], list[str]]] = [
({}, []),
({"cert_file": ""}, ["secrets.cert_file"]),
({"key_file": ""}, ["secrets.key_file"]),
({"key_file": str(stand / "worker.key")}, ["secrets.key_file"]),
({"crl_file": ""}, ["secrets.crl_file"]),
({"crl_file": str(stand / "ca.crt")}, ["secrets.crl_file"]),
({"address": "https://127.0.0.1:8200"}, ["secrets.address"]),
({"address": "https://[::1]:8200"}, ["secrets.address"]),
]
for update, expected in cases:
loaded = _settings(
client_tls={"ca_file": str(stand / "ca.crt")},
broker=_broker(pki),
secrets=base.model_copy(update=update),
)
problems = client_tls_problems(loaded, storages)
assert problems == expected, update
assert str(pki) not in json.dumps(problems)
loaded = _settings(client_tls={"ca_file": str(stand / "ca.crt")})
assert client_tls_problems(loaded, BOOTSTRAP_STORAGES) == []
@pytest.mark.parametrize(
"name",
["api", "worker", "relay", "cleaner", "migrations"],
)
@pytest.mark.parametrize(
("env", "field"),
[
({"SECRETS__CERT_FILE": ""}, "secrets.cert_file"),
({"SECRETS__CRL_FILE": ""}, "secrets.crl_file"),
({"SECRETS__ADDRESS": "https://127.0.0.1:8200"}, "secrets.address"),
],
)
def test_entrypoint_without_secrets_files(
pki: Path,
name: str,
env: dict[str, str],
field: str,
) -> None:
"""«Без файлов identity»: процесс завершается с кодом 2 до обращения к
OpenBao и хранилищам, запись называет поле."""
code, records = _run_entrypoint(
name,
pki,
CLIENT_TLS__CA_FILE=str(pki / "stand" / "ca.crt"),
**env,
)
assert code == 2, records
refusal = [
r for r in records if r["event"] == "Invalid client TLS settings"
]
assert len(refusal) == 1, records
assert refusal[0]["fields"] == [field]
assert not [
r for r in records if r["event"] == "Waiting for secrets store"
]
def test_entrypoint_bad_secrets_address_value(pki: Path) -> None:
"""«Адрес только https»: `http://` — ошибка настроек с полем адреса."""
code, records = _run_entrypoint(
"worker",
pki,
CLIENT_TLS__CA_FILE=str(pki / "stand" / "ca.crt"),
SECRETS__ADDRESS="http://openbao:8200",
)
assert code == 2, records
errors = [r for r in records if r["event"] == "Invalid worker settings"]
assert errors, records
assert errors[0]["errors"][0]["loc"] == "secrets.address"
def test_entrypoint_ignores_secret_from_environment(pki: Path) -> None:
"""«Секрет из окружения не действует»: поле секрета окружением —
`warning` с именем поля без значения (дальше процесс ждёт OpenBao — здесь
закрытый порт и короткий срок, код 1)."""
secret = "env-secret-value-123"
code, records = _run_entrypoint(
"relay",
pki,
CLIENT_TLS__CA_FILE=str(pki / "stand" / "ca.crt"),
DATABASE__PASSWORD=secret,
SECRETS__ADDRESS="https://localhost:1",
SECRETS__REQUEST_TIMEOUT_SECONDS="0.3",
SECRETS__STARTUP_TIMEOUT_SECONDS="0.6",
SECRETS__RETRY_SECONDS="0.2",
)
assert code == 1, records
ignored = [r for r in records if r["event"] == "Ignored secret settings"]
assert len(ignored) == 1, records
assert ignored[0]["fields"] == ["database.password"]
assert ignored[0]["level"] == "warning"
assert secret not in json.dumps(records)
assert records[-1]["event"] == "Secrets store is unavailable"
_ROLE_PASSWORDS = {
f"DB_ROLES__{role.upper()}_PASSWORD": f"{role}-secret-value"
for role in ("migrate", "api", "worker", "relay", "cleaner")