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
+215
View File
@@ -0,0 +1,215 @@
"""Конфигурация OpenBao в репозитории согласована (change `openbao-secrets`,
design, решения 2, 6, 7, 9; спек `secret-store`, «Политика на процесс», «Вход
процесса по сертификату», «OpenBao в стенде вне dev-mode»).
- Файлы политик `infra/openbao/policies/*.hcl`: без шаблонов `*` и `+`,
только `read` своих путей `messenger/data/…` и три пути своего токена.
- Таблица процессов кода (`src/infra/secrets/process.py`) = пути политик =
таблицы `infra/openbao/bao.py` (роли входа, пути наполнения, сервисы
перезапуска) = строки `infra/pki/identities.conf` (CN = имя строки, SAN,
профиль `client`).
- `infra/openbao/config.hcl`: слушатель сети — TLS 1.3 с обязательным
сертификатом клиента CA стенда; health и кластерные адреса — на
`127.0.0.1`; `ui = false`; хранилище raft; аудит в stdout.
Контроль: лишний путь в файле политики или роль с чужим SAN — тест красный с
именем политики, пути или роли.
"""
import importlib.util
import re
import sys
from types import ModuleType
import pytest
from src.config.settings import BASE_DIR
from src.infra.secrets import PROCESSES
OPENBAO_DIR = BASE_DIR / "infra" / "openbao"
POLICIES_DIR = OPENBAO_DIR / "policies"
CONFIG_HCL = OPENBAO_DIR / "config.hcl"
IDENTITIES = BASE_DIR / "infra" / "pki" / "identities.conf"
COMPOSE = BASE_DIR / "docker-compose.yml"
TOKEN_PATHS = {
"auth/token/lookup-self": "read",
"auth/token/renew-self": "update",
"auth/token/revoke-self": "update",
}
RULE_RE = re.compile(
r'path\s+"([^"]+)"\s*\{\s*capabilities\s*=\s*\[([^\]]*)\]\s*\}',
)
# спек secret-store, «Политика на процесс»: пути messenger/data/ по политикам
SPEC_POLICIES = {
"api": {"postgres/api", "valkey/api", "s3/api"},
"worker": {"postgres/worker", "s3/worker"},
"relay": {"postgres/relay"},
"cleaner": {"postgres/cleaner", "s3/cleaner"},
"migrate": {"postgres/migrate"},
}
def _bao() -> ModuleType:
spec = importlib.util.spec_from_file_location(
"bao",
OPENBAO_DIR / "bao.py",
)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules.setdefault("bao", module)
spec.loader.exec_module(module)
return module
def _identities() -> dict[str, tuple[str, list[str]]]:
rows: dict[str, tuple[str, list[str]]] = {}
for line in IDENTITIES.read_text(encoding="utf-8").splitlines():
line = line.split("#", 1)[0].strip()
if not line:
continue
name, profile, sans, _form = line.split()
rows[name] = (profile, sans.split(","))
return rows
def _rules(name: str) -> dict[str, list[str]]:
text = (POLICIES_DIR / f"{name}.hcl").read_text(encoding="utf-8")
code = "\n".join(line.split("#", 1)[0] for line in text.splitlines())
rules: dict[str, list[str]] = {}
for path, caps in RULE_RE.findall(code):
assert path not in rules, f"policy {name}: duplicate path {path}"
rules[path] = [
c.strip().strip('"') for c in caps.split(",") if c.strip()
]
# всё, что не правило path, — ошибка разбора (неожиданная конструкция)
rest = RULE_RE.sub("", code).strip()
assert rest == "", f"policy {name}: unexpected text {rest[:60]!r}"
return rules
def test_policy_files_match_roles() -> None:
assert {p.stem for p in POLICIES_DIR.glob("*.hcl")} == set(SPEC_POLICIES)
@pytest.mark.parametrize("name", sorted(SPEC_POLICIES))
def test_policy_without_wildcards(name: str) -> None:
"""«Без шаблонов и политики default»: ни `*`, ни `+` в путях."""
for path in _rules(name):
assert "*" not in path and "+" not in path, f"policy {name}: {path}"
@pytest.mark.parametrize("name", sorted(SPEC_POLICIES))
def test_policy_paths_exactly_spec(name: str) -> None:
"""Ровно пути таблицы спека с `read` и три пути своего токена; ни
`metadata/`, ни записи, ни системных путей."""
rules = _rules(name)
expected = {
f"messenger/data/{path}": ["read"] for path in SPEC_POLICIES[name]
}
expected.update({path: [cap] for path, cap in TOKEN_PATHS.items()})
extra = sorted(set(rules) - set(expected))
missing = sorted(set(expected) - set(rules))
assert not extra, f"policy {name}: extra paths {extra}"
assert not missing, f"policy {name}: missing paths {missing}"
for path, caps in rules.items():
assert caps == expected[path], f"policy {name}: {path} {caps}"
def test_process_table_matches_policies() -> None:
"""Таблица процессов кода = политики: роль процесса читает ровно пути
своей политики (replay — роль relay)."""
for process, spec in PROCESSES.items():
assert spec.role in SPEC_POLICIES, (
f"process {process}: role {spec.role}"
)
assert set(spec.paths) == SPEC_POLICIES[spec.role], process
assert {spec.role for spec in PROCESSES.values()} == set(SPEC_POLICIES)
def test_bao_tables_match_code_and_identities() -> None:
"""Таблицы `bao.py` = таблица кода = список identity: роль входа
принимает CN строки списка и её единственный DNS SAN, профиль строки —
`client`; пути наполнения = пути политик; сервис перезапуска — сервис
compose роли (у migrate — нет: одноразовый)."""
bao = _bao()
identities = _identities()
assert set(bao.ROLES) == set(SPEC_POLICIES)
for role, spec in bao.ROLES.items():
cn, san = spec["cn"], spec["san"]
assert cn in identities, f"role {role}: identity {cn} is not listed"
profile, sans = identities[cn]
assert profile == "client", f"role {role}: {cn} is {profile}"
assert sans == [san], f"role {role}: SAN {sans} != {san}"
assert set(bao.policy_paths(role)) == SPEC_POLICIES[role], role
all_paths = set().union(*SPEC_POLICIES.values())
assert set(bao.SEED) == all_paths
# наполнение берёт значения у bootstrap и хранилищ, а не у процессов
for path, fields in bao.SEED.items():
for _field, (service, variable) in fields.items():
assert service in {
"postgres-bootstrap",
"valkey",
"s3-bootstrap",
}, path
assert variable, path
# поля путей наполнения = поля, которые читает код
for spec in PROCESSES.values():
for item in spec.fields:
assert item.key in bao.SEED[item.path], (item.path, item.key)
readers = bao.readers()
for path in all_paths:
assert readers[path], path
services = {spec["service"] for spec in bao.ROLES.values()}
assert services == {"api", "worker", "relay", "cleaner", None}
def test_identity_rows_of_openbao() -> None:
"""Строки списка identity change: сервер `openbao` (SAN `openbao`,
`localhost`), клиенты `cleaner`, `migrate`, `bao-operator`."""
identities = _identities()
assert identities["openbao"] == ("server", ["openbao", "localhost"])
for name in ("cleaner", "migrate", "bao-operator"):
assert identities[name] == ("client", [name])
def _blocks(text: str, kind: str) -> list[str]:
"""Тела блоков `kind "…" {…}` (без вложенных фигурных скобок)."""
return re.findall(kind + r'\s+"[^"]*"\s*\{([^{}]*)\}', text)
def test_config_hcl() -> None:
text = "\n".join(
line.split("#", 1)[0]
for line in CONFIG_HCL.read_text(encoding="utf-8").splitlines()
)
listeners = _blocks(text, "listener")
assert len(listeners) == 2 # noqa: PLR2004
network = next(b for b in listeners if '"0.0.0.0:8200"' in b)
health = next(b for b in listeners if '"127.0.0.1:8210"' in b)
assert re.search(r'tls_min_version\s*=\s*"tls13"', network)
assert re.search(r"tls_require_and_verify_client_cert\s*=\s*true", network)
assert re.search(
r'tls_client_ca_file\s*=\s*"/run/secrets/ca.crt"',
network,
)
assert re.search(r'cluster_address\s*=\s*"127\.0\.0\.1:8201"', network)
assert "tls_disable " not in network
assert re.search(r'tls_min_version\s*=\s*"tls13"', health)
assert re.search(r'cluster_address\s*=\s*"127\.0\.0\.1:8211"', health)
assert re.search(r'cluster_addr\s*=\s*"https://127\.0\.0\.1:8201"', text)
assert re.search(r"^ui\s*=\s*false", text, re.M)
assert re.search(r'storage\s+"raft"', text)
assert re.search(r'audit\s+"file"', text)
assert 'file_path = "stdout"' in text
assert "dev" not in re.findall(r"\b\w+\b", text)
def test_compose_service_and_secrets() -> None:
"""Сервис `openbao`: тег и digest индекса, порт только на `127.0.0.1`,
пары `bao-operator` нет ни у одного сервиса (её нет и в верхнеуровневых
secrets compose)."""
text = COMPOSE.read_text(encoding="utf-8")
assert re.search(r"openbao/openbao:2\.7\.\d+@sha256:[0-9a-f]{64}", text)
assert '"127.0.0.1:${BAO_OUT_PORT:-8200}:8200"' in text
assert "bao-operator.crt" not in text
assert "bao-operator.key" not in text