forked from mtusi2026/mtusi2026lab7
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:
@@ -17,10 +17,11 @@ API) — роль `api`. Права временной базы сверяет `
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -88,9 +89,10 @@ if _missing:
|
||||
os.environ.update(
|
||||
{
|
||||
"APP__RUN_MODE": "console",
|
||||
# глобальный engine приложения — роль api (путь запроса)
|
||||
# глобальный engine приложения — роль api (путь запроса); её пароль —
|
||||
# подстановкой ниже (change openbao-secrets: окружением процесс
|
||||
# секретов не берёт, OpenBao тесты не трогают)
|
||||
"DATABASE__USER": "api",
|
||||
"DATABASE__PASSWORD": ROLE_PASSWORDS["api"],
|
||||
"DATABASE__NAME": TEST_DB,
|
||||
"DATABASE__POOL_SIZE": "1",
|
||||
"DATABASE__MAX_OVERFLOW": "0",
|
||||
@@ -119,8 +121,29 @@ from src.infra.db import ( # noqa: E402
|
||||
)
|
||||
from src.infra.db.models.base import Base # noqa: E402
|
||||
from src.infra.db.uow import SqlAlchemyUnitOfWork # noqa: E402
|
||||
from src.infra.secrets import substitute_for_tests # noqa: E402
|
||||
from src.infra.tls import build_client_context # noqa: E402
|
||||
|
||||
# секреты процессов — подстановкой кодом теста до импорта клиентов (design
|
||||
# change openbao-secrets, решение 9): глобальный engine API (test_request_flow)
|
||||
# — роль api, alembic в процессе теста (run_alembic) — роль migrate. Пароли —
|
||||
# из .env, как раньше; к OpenBao тесты не обращаются
|
||||
substitute_for_tests(
|
||||
"api",
|
||||
database=settings.database.model_copy(
|
||||
update={"password": SecretStr(ROLE_PASSWORDS["api"])},
|
||||
),
|
||||
)
|
||||
substitute_for_tests(
|
||||
"migrate",
|
||||
database=settings.database.model_copy(
|
||||
update={
|
||||
"user": "migrate",
|
||||
"password": SecretStr(ROLE_PASSWORDS["migrate"]),
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
_created = False
|
||||
|
||||
|
||||
@@ -184,13 +207,36 @@ async def _bootstrap_roles() -> None:
|
||||
)
|
||||
|
||||
|
||||
def migrate_env() -> dict[str, str]:
|
||||
"""Окружение alembic: роль migrate (владелец схемы)."""
|
||||
return {
|
||||
**os.environ,
|
||||
"DATABASE__USER": "migrate",
|
||||
"DATABASE__PASSWORD": ROLE_PASSWORDS["migrate"],
|
||||
}
|
||||
def run_alembic(*args: str) -> str:
|
||||
"""Команда alembic в процессе теста, ролью migrate (владелец схемы):
|
||||
`migrations/env.py` берёт секцию роли из подстановки, а не из OpenBao
|
||||
(change openbao-secrets; прежде — подпроцесс с паролем окружением).
|
||||
Отдельный поток: `env.py` зовёт `asyncio.run`, а тест может идти внутри
|
||||
цикла событий. Вывод `--sql` — текстом; ошибка — исключение команды."""
|
||||
from alembic.config import CommandLine, Config
|
||||
|
||||
output = io.StringIO()
|
||||
errors: list[BaseException] = []
|
||||
|
||||
def target() -> None:
|
||||
try:
|
||||
options = CommandLine().parser.parse_args(list(args))
|
||||
config = Config(
|
||||
str(ROOT / "alembic.ini"),
|
||||
cmd_opts=options,
|
||||
output_buffer=output,
|
||||
stdout=output,
|
||||
)
|
||||
CommandLine().run_cmd(config, options)
|
||||
except BaseException as e: # noqa: BLE001 — исключение — в тест
|
||||
errors.append(e)
|
||||
|
||||
thread = threading.Thread(target=target)
|
||||
thread.start()
|
||||
thread.join()
|
||||
if errors:
|
||||
raise errors[0]
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def pytest_sessionstart(session: pytest.Session) -> None:
|
||||
@@ -198,13 +244,7 @@ def pytest_sessionstart(session: pytest.Session) -> None:
|
||||
_created = True
|
||||
asyncio.run(_recreate(create=True))
|
||||
asyncio.run(_bootstrap_roles())
|
||||
subprocess.run(
|
||||
[sys.executable, "-m", "alembic", "upgrade", "head"],
|
||||
cwd=ROOT,
|
||||
env=migrate_env(),
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
run_alembic("upgrade", "head")
|
||||
|
||||
|
||||
def pytest_unconfigure(config: pytest.Config) -> None:
|
||||
|
||||
Reference in New Issue
Block a user