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:
@@ -15,8 +15,20 @@ from fakes import (
|
||||
FakeUnitOfWork,
|
||||
)
|
||||
from src.config import settings
|
||||
from src.infra.secrets import substitute_for_tests
|
||||
from src.schemas.enums import MetricBucketsEnum
|
||||
|
||||
# глобалы клиентов процесса API (src/api/dependencies.py → db/session.py,
|
||||
# cache/instance.py, s3/instance.py) берут секции с секретами из OpenBao
|
||||
# (change openbao-secrets): быстрые тесты подставляют их кодом до импорта
|
||||
# клиентов, OpenBao и сети нет
|
||||
substitute_for_tests(
|
||||
"api",
|
||||
database=settings.database,
|
||||
cache=settings.cache,
|
||||
s3=settings.s3,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend() -> str:
|
||||
|
||||
@@ -37,7 +37,7 @@ import aiormq.exceptions
|
||||
import pytest
|
||||
|
||||
from src.config import settings
|
||||
from src.config.settings import BASE_DIR, Broker, Settings
|
||||
from src.config.settings import BASE_DIR, Broker, Secrets, Settings
|
||||
from src.core.exceptions import BrokerUnavailable
|
||||
from src.infra.broker import client as broker_client
|
||||
from src.infra.broker.client import JobConsumer, JobPublisher, broker_context
|
||||
@@ -340,6 +340,12 @@ def _settings(broker: Broker, pki: Path) -> Settings:
|
||||
database=settings.database.model_copy(update={"host": "postgres"}),
|
||||
s3=settings.s3.model_copy(update={"host": "s3"}),
|
||||
broker=broker,
|
||||
# OpenBao (change openbao-secrets): действующие файлы identity
|
||||
secrets=Secrets(
|
||||
cert_file=str(pki / "stand" / "relay.crt"),
|
||||
key_file=str(pki / "stand" / "relay.key"),
|
||||
crl_file=str(pki / "stand" / "crl.pem"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -402,6 +408,10 @@ def _run(
|
||||
"BROKER__KEY_FILE": str(stand / "relay.key"),
|
||||
"BROKER__CRL_FILE": str(stand / "crl.pem"),
|
||||
"TELEMETRY__ENABLED": "false",
|
||||
"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,
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,785 @@
|
||||
"""Секреты процесса из OpenBao (change `openbao-secrets`, design, решения 7–11;
|
||||
спеки `secret-store`, «Секреты процесса при старте», «Токены с ограниченным
|
||||
сроком, продление и повторный вход», «Работа при недоступном OpenBao»,
|
||||
`transport-security`, «mTLS к OpenBao», `service-logging`, «Журнал секретов
|
||||
процесса»).
|
||||
|
||||
Подставной OpenBao — HTTPS-сервер в процессе теста с временной PKI
|
||||
(`infra/pki/pki.sh stand`: CA, leaf `openbao`, клиентские пары; посторонний
|
||||
CA; отозванный leaf `openbao` и CRL): обязательный сертификат клиента CA
|
||||
стенда, cert auth по DNS SAN, KV v2, продление своего токена, срок и предел
|
||||
роли, запечатанное состояние. Проверяются классы исходов и коды загрузки,
|
||||
рукопожатие (сервер другого CA, имя вне SAN, отозванный сертификат сервера,
|
||||
только TLS 1.2 — отказ до запроса), поток продления со сроком роли 1–3 с и
|
||||
журнал без значений и токенов. Без OpenSSL 3+ тесты пропускаются с причиной.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from pydantic import SecretStr
|
||||
|
||||
from src.config import settings
|
||||
from src.config.settings import (
|
||||
BASE_DIR,
|
||||
S3,
|
||||
Cache,
|
||||
ClientTls,
|
||||
Database,
|
||||
Secrets,
|
||||
Settings,
|
||||
)
|
||||
from src.infra.secrets import (
|
||||
EXIT_REFUSED,
|
||||
EXIT_UNAVAILABLE,
|
||||
PROCESSES,
|
||||
SecretsRenewal,
|
||||
SecretsStartupError,
|
||||
forget_for_tests,
|
||||
ignored_fields,
|
||||
load,
|
||||
)
|
||||
from src.infra.secrets import process as secrets_process
|
||||
|
||||
PKI_SCRIPT = BASE_DIR / "infra" / "pki" / "pki.sh"
|
||||
SERVER_NAME = "openbao"
|
||||
TOKEN_PREFIX = "s."
|
||||
# DNS SAN клиента → роль, в которую он входит (подставной cert auth)
|
||||
ROLE_SANS = {"api": "api", "worker": "worker", "relay": "relay"}
|
||||
|
||||
|
||||
def _openssl() -> str | None:
|
||||
binary = os.environ.get("OPENSSL") or shutil.which("openssl")
|
||||
if not binary:
|
||||
return None
|
||||
version = subprocess.run( # noqa: S603
|
||||
[binary, "version"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
).stdout
|
||||
if not version.startswith("OpenSSL ") or int(version[8]) < 3: # noqa: PLR2004
|
||||
return None
|
||||
return binary
|
||||
|
||||
|
||||
def _pki(env: dict[str, str], *args: str) -> None:
|
||||
subprocess.run( # noqa: S603
|
||||
["/bin/sh", str(PKI_SCRIPT), *args],
|
||||
env={**os.environ, **env},
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def pki(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
||||
"""CA стенда с leaf по списку identity, отозванный leaf `openbao` (копия
|
||||
пары до `revoke`, CRL стенда его называет) и посторонний CA."""
|
||||
binary = _openssl()
|
||||
if binary is None:
|
||||
pytest.skip("OpenSSL 3+ is required for TLS handshake tests")
|
||||
root = tmp_path_factory.mktemp("secrets-pki")
|
||||
env = {
|
||||
"OPENSSL": binary,
|
||||
"PKI_OPERATOR_DIR": str(root / "op"),
|
||||
"PKI_STAND_DIR": str(root / "stand"),
|
||||
}
|
||||
_pki(env, "stand")
|
||||
revoked = root / "revoked"
|
||||
revoked.mkdir()
|
||||
for name in ("openbao.crt", "openbao.key"):
|
||||
shutil.copy(root / "stand" / name, revoked / name)
|
||||
_pki(env, "revoke", "openbao")
|
||||
_pki(env, "stand")
|
||||
_pki(
|
||||
{
|
||||
"OPENSSL": binary,
|
||||
"PKI_OPERATOR_DIR": str(root / "other-op"),
|
||||
"PKI_STAND_DIR": str(root / "other"),
|
||||
},
|
||||
"stand",
|
||||
)
|
||||
return root
|
||||
|
||||
|
||||
# --- подставной OpenBao --------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Token:
|
||||
value: str
|
||||
role: str
|
||||
san: str
|
||||
expires: float
|
||||
max_expires: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Bao:
|
||||
"""Состояние подставного OpenBao; тест меняет его между запросами."""
|
||||
|
||||
port: int = 0
|
||||
ttl: float = 600
|
||||
max_ttl: float = 3600
|
||||
sealed: bool = False
|
||||
login_status: int = 200
|
||||
kv: dict[str, tuple[dict[str, str], int]] = field(default_factory=dict)
|
||||
# роль → пути, которые разрешает её политика
|
||||
policies: dict[str, set[str]] = field(default_factory=dict)
|
||||
tokens: dict[str, _Token] = field(default_factory=dict)
|
||||
requests: list[tuple[str, str, str]] = field(default_factory=list)
|
||||
lock: threading.Lock = field(default_factory=threading.Lock)
|
||||
|
||||
def issue(self, role: str, san: str) -> _Token:
|
||||
now = time.monotonic()
|
||||
token = _Token(
|
||||
value=TOKEN_PREFIX + secrets.token_urlsafe(18),
|
||||
role=role,
|
||||
san=san,
|
||||
expires=now + self.ttl,
|
||||
max_expires=now + self.max_ttl,
|
||||
)
|
||||
self.tokens[token.value] = token
|
||||
return token
|
||||
|
||||
|
||||
def _auth(token: _Token, ttl: float) -> dict[str, Any]:
|
||||
return {
|
||||
"auth": {
|
||||
"client_token": token.value,
|
||||
"lease_duration": int(ttl),
|
||||
"renewable": True,
|
||||
"token_policies": [token.role],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _handler(state: _Bao) -> type[http.server.BaseHTTPRequestHandler]:
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def _peer(self) -> str:
|
||||
peer = self.connection.getpeercert() or {}
|
||||
names = [
|
||||
v for k, v in peer.get("subjectAltName", ()) if k == "DNS"
|
||||
]
|
||||
return names[0] if names else ""
|
||||
|
||||
def _send(self, status: int, payload: dict[str, Any]) -> None:
|
||||
body = json.dumps(payload).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _body(self) -> dict[str, Any]:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
return json.loads(self.rfile.read(length) or b"{}")
|
||||
|
||||
def _token(self) -> _Token | None:
|
||||
token = state.tokens.get(self.headers.get("X-Vault-Token", ""))
|
||||
if token is None or time.monotonic() >= token.expires:
|
||||
return None
|
||||
return token
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
body = self._body()
|
||||
with state.lock:
|
||||
state.requests.append(("POST", self.path, self._peer()))
|
||||
if state.sealed:
|
||||
self._send(503, {"errors": ["Vault is sealed"]})
|
||||
return
|
||||
if self.path == "/v1/auth/cert/login":
|
||||
role = body.get("name", "")
|
||||
san = self._peer()
|
||||
if state.login_status != 200: # noqa: PLR2004
|
||||
self._send(state.login_status, {"errors": ["refused"]})
|
||||
return
|
||||
if ROLE_SANS.get(role) != san:
|
||||
self._send(400, {"errors": ["invalid certificate"]})
|
||||
return
|
||||
token = state.issue(role, san)
|
||||
self._send(200, _auth(token, state.ttl))
|
||||
return
|
||||
if self.path == "/v1/auth/token/renew-self":
|
||||
token = self._token()
|
||||
if token is None or token.san != self._peer():
|
||||
self._send(403, {"errors": ["permission denied"]})
|
||||
return
|
||||
now = time.monotonic()
|
||||
token.expires = min(now + state.ttl, token.max_expires)
|
||||
self._send(200, _auth(token, token.expires - now))
|
||||
return
|
||||
self._send(404, {"errors": []})
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
with state.lock:
|
||||
state.requests.append(("GET", self.path, self._peer()))
|
||||
if state.sealed:
|
||||
self._send(503, {"errors": ["Vault is sealed"]})
|
||||
return
|
||||
prefix = "/v1/messenger/data/"
|
||||
token = self._token()
|
||||
path = self.path.removeprefix(prefix)
|
||||
if token is None or path not in state.policies.get(
|
||||
token.role,
|
||||
set(),
|
||||
):
|
||||
self._send(403, {"errors": ["permission denied"]})
|
||||
return
|
||||
if path not in state.kv:
|
||||
self._send(404, {"errors": []})
|
||||
return
|
||||
data, version = state.kv[path]
|
||||
self._send(
|
||||
200,
|
||||
{"data": {"data": data, "metadata": {"version": version}}},
|
||||
)
|
||||
|
||||
def log_message(self, *_args: Any) -> None:
|
||||
return None
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _openbao(
|
||||
pki: Path,
|
||||
*,
|
||||
cert: str = "stand",
|
||||
max_version: ssl.TLSVersion | None = None,
|
||||
state: _Bao | None = None,
|
||||
) -> Iterator[_Bao]:
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(
|
||||
pki / cert / "openbao.crt",
|
||||
pki / cert / "openbao.key",
|
||||
)
|
||||
context.load_verify_locations(cafile=pki / "stand" / "ca.crt")
|
||||
context.verify_mode = ssl.CERT_REQUIRED
|
||||
if max_version is not None:
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.maximum_version = max_version
|
||||
state = state or _Bao()
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _handler(state))
|
||||
server.daemon_threads = True
|
||||
server.socket = context.wrap_socket(server.socket, server_side=True)
|
||||
state.port = server.server_address[1]
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield state
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def _seed(state: _Bao) -> dict[str, str]:
|
||||
"""Секреты роли api в подставном KV; значения — для проверок журнала."""
|
||||
values = {
|
||||
"database": secrets.token_hex(16),
|
||||
"cache": secrets.token_hex(16),
|
||||
"s3_id": secrets.token_hex(10),
|
||||
"s3_secret": secrets.token_hex(20),
|
||||
"worker": secrets.token_hex(16),
|
||||
}
|
||||
state.kv.update(
|
||||
{
|
||||
"postgres/api": ({"password": values["database"]}, 3),
|
||||
"valkey/api": ({"password": values["cache"]}, 1),
|
||||
"s3/api": (
|
||||
{
|
||||
"access_key_id": values["s3_id"],
|
||||
"secret_access_key": values["s3_secret"],
|
||||
},
|
||||
2,
|
||||
),
|
||||
"postgres/worker": ({"password": values["worker"]}, 1),
|
||||
"s3/worker": (
|
||||
{"access_key_id": "w", "secret_access_key": "ws"},
|
||||
1,
|
||||
),
|
||||
},
|
||||
)
|
||||
state.policies.update(
|
||||
{
|
||||
"api": {"postgres/api", "valkey/api", "s3/api"},
|
||||
"worker": {"postgres/worker", "s3/worker"},
|
||||
},
|
||||
)
|
||||
return values
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def resolve(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Имена `openbao` и `wrong-name` — на loopback (как DNS стенда)."""
|
||||
original = socket.getaddrinfo
|
||||
|
||||
def getaddrinfo(host: Any, *args: Any, **kwargs: Any) -> Any:
|
||||
if host in {SERVER_NAME, "wrong-name"}:
|
||||
host = "127.0.0.1"
|
||||
return original(host, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(socket, "getaddrinfo", getaddrinfo)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _restore_loaded() -> Iterator[None]:
|
||||
"""Кэш процесса не переносится между тестами: после теста — снова
|
||||
подстановка `unit/conftest.py` (её берут глобалы клиентов API)."""
|
||||
saved = dict(secrets_process._loaded)
|
||||
yield
|
||||
forget_for_tests()
|
||||
secrets_process._loaded.update(saved)
|
||||
|
||||
|
||||
def _config(
|
||||
pki: Path,
|
||||
port: int,
|
||||
*,
|
||||
identity: str = "api-client",
|
||||
host: str = SERVER_NAME,
|
||||
crl: str | None = None,
|
||||
**database: Any,
|
||||
) -> Settings:
|
||||
stand = pki / "stand"
|
||||
return Settings.model_construct(
|
||||
client_tls=ClientTls(ca_file=str(stand / "ca.crt")),
|
||||
secrets=Secrets(
|
||||
address=f"https://{host}:{port}",
|
||||
cert_file=str(stand / f"{identity}.crt"),
|
||||
key_file=str(stand / f"{identity}.key"),
|
||||
crl_file=crl or str(stand / "crl.pem"),
|
||||
connect_timeout_seconds=0.5,
|
||||
request_timeout_seconds=0.5,
|
||||
startup_timeout_seconds=1.5,
|
||||
retry_seconds=0.2,
|
||||
),
|
||||
database=Database(**database),
|
||||
cache=Cache(),
|
||||
s3=S3(),
|
||||
)
|
||||
|
||||
|
||||
class Recorder:
|
||||
"""Журнал теста: записи (уровень, событие, поля) вместо structlog."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
records: list[dict[str, Any]] | None = None,
|
||||
**context: Any,
|
||||
) -> None:
|
||||
self.records = [] if records is None else records
|
||||
self.context = context
|
||||
|
||||
def bind(self, **context: Any) -> "Recorder":
|
||||
return Recorder(self.records, **{**self.context, **context})
|
||||
|
||||
def _write(self, level: str, event: str, **fields: Any) -> None:
|
||||
self.records.append(
|
||||
{"level": level, "event": event, **self.context, **fields},
|
||||
)
|
||||
|
||||
def debug(self, event: str, **fields: Any) -> None:
|
||||
self._write("debug", event, **fields)
|
||||
|
||||
def info(self, event: str, **fields: Any) -> None:
|
||||
self._write("info", event, **fields)
|
||||
|
||||
def warning(self, event: str, **fields: Any) -> None:
|
||||
self._write("warning", event, **fields)
|
||||
|
||||
def error(self, event: str, **fields: Any) -> None:
|
||||
self._write("error", event, **fields)
|
||||
|
||||
def events(self, level: str | None = None) -> list[str]:
|
||||
return [
|
||||
r["event"]
|
||||
for r in self.records
|
||||
if level is None or r["level"] == level
|
||||
]
|
||||
|
||||
|
||||
def _assert_clean(
|
||||
recorder: Recorder,
|
||||
state: _Bao,
|
||||
values: dict[str, str],
|
||||
) -> None:
|
||||
"""В журнале ни значений секретов, ни токенов, ни PEM."""
|
||||
text = json.dumps(recorder.records)
|
||||
for value in values.values():
|
||||
assert value not in text
|
||||
for token in state.tokens:
|
||||
assert token not in text
|
||||
assert "BEGIN" not in text
|
||||
|
||||
|
||||
# --- загрузка при старте -------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("resolve")
|
||||
def test_load_secrets(pki: Path) -> None:
|
||||
"""«Старт с секретами из OpenBao» и «Загрузка секретов в журнале»: роль
|
||||
api, три пути с версиями, секции — копии, `settings` не изменён."""
|
||||
recorder = Recorder()
|
||||
with _openbao(pki) as state:
|
||||
values = _seed(state)
|
||||
config = _config(pki, state.port)
|
||||
loaded = load("api", config=config, log=recorder)
|
||||
assert loaded.role == "api"
|
||||
assert loaded.versions == {"postgres/api": 3, "valkey/api": 1, "s3/api": 2}
|
||||
assert loaded.database.password.get_secret_value() == values["database"]
|
||||
assert loaded.cache.password.get_secret_value() == values["cache"]
|
||||
assert loaded.s3.access_key_id.get_secret_value() == values["s3_id"]
|
||||
assert (
|
||||
loaded.s3.secret_access_key.get_secret_value() == values["s3_secret"]
|
||||
)
|
||||
# копии: исходные секции и общий settings без секретов
|
||||
assert config.database.password.get_secret_value() == ""
|
||||
assert loaded.database is not config.database
|
||||
assert settings.database.password.get_secret_value() != values["database"]
|
||||
assert loaded.token is not None
|
||||
assert loaded.token.policies == ("api",)
|
||||
assert "value" not in repr(loaded.token)
|
||||
assert values["database"] not in repr(loaded)
|
||||
# вход одной ролью сертификатом api-client (SAN api), затем три чтения
|
||||
assert [r[:2] for r in state.requests][0] == (
|
||||
"POST",
|
||||
"/v1/auth/cert/login",
|
||||
)
|
||||
assert {r[2] for r in state.requests} == {"api"}
|
||||
record = next(
|
||||
r for r in recorder.records if r["event"] == "Loaded process secrets"
|
||||
)
|
||||
assert record["role"] == "api"
|
||||
assert record["paths"] == [
|
||||
"messenger/data/postgres/api",
|
||||
"messenger/data/valkey/api",
|
||||
"messenger/data/s3/api",
|
||||
]
|
||||
assert record["versions"] == loaded.versions
|
||||
assert record["token_ttl_seconds"] == 600 # noqa: PLR2004
|
||||
assert record["token_renewable"] is True
|
||||
_assert_clean(recorder, state, values)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("resolve")
|
||||
def test_ignored_secret_settings(pki: Path) -> None:
|
||||
"""«Секрет из окружения не действует»: пароль из настроек игнорируется,
|
||||
`warning` называет поле без значения."""
|
||||
recorder = Recorder()
|
||||
wrong = secrets.token_hex(8)
|
||||
with _openbao(pki) as state:
|
||||
values = _seed(state)
|
||||
config = _config(pki, state.port, password=SecretStr(wrong))
|
||||
assert ignored_fields("api", config) == ["database.password"]
|
||||
loaded = load("api", config=config, log=recorder)
|
||||
assert loaded.database.password.get_secret_value() == values["database"]
|
||||
warning = next(
|
||||
r for r in recorder.records if r["event"] == "Ignored secret settings"
|
||||
)
|
||||
assert warning["level"] == "warning"
|
||||
assert warning["fields"] == ["database.password"]
|
||||
assert wrong not in json.dumps(recorder.records)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("resolve")
|
||||
@pytest.mark.parametrize(
|
||||
("case", "expected_reason"),
|
||||
[
|
||||
("login_refused", "login"),
|
||||
("foreign_identity", "login"),
|
||||
("forbidden_path", "permission"),
|
||||
("missing_path", "missing"),
|
||||
("missing_field", "missing_field"),
|
||||
],
|
||||
)
|
||||
def test_refusals_exit_2(pki: Path, case: str, expected_reason: str) -> None:
|
||||
"""«Чужая роль», «Отказ входа на старте»: отказ по правам — `error` с
|
||||
ролью, путём и полем, код 2, без повторов."""
|
||||
recorder = Recorder()
|
||||
identity = "api-client"
|
||||
with _openbao(pki) as state:
|
||||
values = _seed(state)
|
||||
if case == "login_refused":
|
||||
state.login_status = 400
|
||||
elif case == "foreign_identity":
|
||||
identity = "worker"
|
||||
elif case == "forbidden_path":
|
||||
state.policies["api"].discard("s3/api")
|
||||
elif case == "missing_path":
|
||||
del state.kv["valkey/api"]
|
||||
elif case == "missing_field":
|
||||
state.kv["s3/api"] = ({"access_key_id": "x"}, 4)
|
||||
config = _config(pki, state.port, identity=identity)
|
||||
with pytest.raises(SecretsStartupError) as caught:
|
||||
load("api", config=config, log=recorder)
|
||||
logins = sum(1 for r in state.requests if r[1].endswith("/login"))
|
||||
assert caught.value.exit_code == EXIT_REFUSED
|
||||
assert logins == 1, "no retries on refusal"
|
||||
last = recorder.records[-1]
|
||||
assert last["level"] == "error"
|
||||
assert last["role"] == "api"
|
||||
assert last["reason"] == expected_reason
|
||||
if case == "missing_field":
|
||||
assert last["path"] == "messenger/data/s3/api"
|
||||
assert last["field"] == "secret_access_key"
|
||||
_assert_clean(recorder, state, values)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("resolve")
|
||||
def test_sealed_waits_then_exit_1(pki: Path) -> None:
|
||||
"""«OpenBao недоступен на старте»: запечатанный — одна запись `warning`,
|
||||
повторы до срока ожидания, затем `error` и код 1."""
|
||||
recorder = Recorder()
|
||||
with _openbao(pki) as state:
|
||||
_seed(state)
|
||||
state.sealed = True
|
||||
started = time.monotonic()
|
||||
with pytest.raises(SecretsStartupError) as caught:
|
||||
load("api", config=_config(pki, state.port), log=recorder)
|
||||
elapsed = time.monotonic() - started
|
||||
attempts = len(state.requests)
|
||||
assert caught.value.exit_code == EXIT_UNAVAILABLE
|
||||
assert 1.0 <= elapsed < 2.5 # noqa: PLR2004
|
||||
assert attempts >= 3 # noqa: PLR2004
|
||||
assert recorder.events("warning") == ["Waiting for secrets store"]
|
||||
assert recorder.records[0]["error_type"] == "sealed"
|
||||
assert recorder.events("error") == ["Secrets store is unavailable"]
|
||||
assert recorder.records[-1]["waited_seconds"] >= 1.0 # noqa: PLR2004
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("resolve")
|
||||
def test_unseal_during_wait(pki: Path) -> None:
|
||||
"""Распечатан во время ожидания — загрузка проходит, ожидание в записи."""
|
||||
recorder = Recorder()
|
||||
with _openbao(pki) as state:
|
||||
_seed(state)
|
||||
state.sealed = True
|
||||
timer = threading.Timer(0.5, lambda: setattr(state, "sealed", False))
|
||||
timer.start()
|
||||
loaded = load("api", config=_config(pki, state.port), log=recorder)
|
||||
timer.join()
|
||||
assert loaded.versions["postgres/api"] == 3 # noqa: PLR2004
|
||||
assert recorder.events("warning") == ["Waiting for secrets store"]
|
||||
record = recorder.records[-1]
|
||||
assert record["event"] == "Loaded process secrets"
|
||||
assert record["waited_seconds"] > 0
|
||||
|
||||
|
||||
def test_unreachable_exit_1(pki: Path) -> None:
|
||||
"""Порт закрыт — недоступность (класс ошибки соединения), код 1."""
|
||||
recorder = Recorder()
|
||||
with socket.socket() as probe:
|
||||
probe.bind(("127.0.0.1", 0))
|
||||
port = probe.getsockname()[1]
|
||||
config = _config(pki, port, host="localhost")
|
||||
with pytest.raises(SecretsStartupError) as caught:
|
||||
load("api", config=config, log=recorder)
|
||||
assert caught.value.exit_code == EXIT_UNAVAILABLE
|
||||
assert recorder.records[0]["error_type"] == "ConnectionRefusedError"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("resolve")
|
||||
@pytest.mark.parametrize(
|
||||
"case",
|
||||
["other_ca", "wrong_name", "revoked_server", "tls12_only"],
|
||||
)
|
||||
def test_foreign_server_refused_before_request(pki: Path, case: str) -> None:
|
||||
"""«Чужой сервер под именем OpenBao»: сервер другого CA, имя вне SAN,
|
||||
отозванный по CRL сертификат сервера, только TLS 1.2 — рукопожатие
|
||||
обрывается до запроса входа, процесс считает OpenBao недоступным."""
|
||||
recorder = Recorder()
|
||||
server = {"cert": "stand"}
|
||||
host = SERVER_NAME
|
||||
if case == "other_ca":
|
||||
server["cert"] = "other"
|
||||
elif case == "revoked_server":
|
||||
server["cert"] = "revoked"
|
||||
elif case == "wrong_name":
|
||||
host = "wrong-name"
|
||||
max_version = ssl.TLSVersion.TLSv1_2 if case == "tls12_only" else None
|
||||
with _openbao(pki, cert=server["cert"], max_version=max_version) as state:
|
||||
_seed(state)
|
||||
with pytest.raises(SecretsStartupError) as caught:
|
||||
load(
|
||||
"api",
|
||||
config=_config(pki, state.port, host=host),
|
||||
log=recorder,
|
||||
)
|
||||
seen = list(state.requests)
|
||||
assert caught.value.exit_code == EXIT_UNAVAILABLE
|
||||
assert seen == [], "request must not reach a foreign server"
|
||||
assert recorder.events("warning") == ["Waiting for secrets store"]
|
||||
|
||||
|
||||
def test_process_table_paths() -> None:
|
||||
"""Таблица процессов: роль и пути (полная сверка с политиками и bao.py —
|
||||
`test_openbao_config.py`)."""
|
||||
assert PROCESSES["api"].paths == ("postgres/api", "valkey/api", "s3/api")
|
||||
assert PROCESSES["replay"].role == "relay"
|
||||
assert PROCESSES["migrate"].sections == ("database",)
|
||||
|
||||
|
||||
# --- продление в работе ---------------------------------------------------------
|
||||
|
||||
|
||||
def _renewal(
|
||||
pki: Path,
|
||||
state: _Bao,
|
||||
recorder: Recorder,
|
||||
) -> tuple[SecretsRenewal, dict[str, str]]:
|
||||
values = _seed(state)
|
||||
loaded = load(
|
||||
"worker",
|
||||
config=_config(pki, state.port, identity="worker"),
|
||||
log=recorder,
|
||||
)
|
||||
renewal = SecretsRenewal(loaded, retry_seconds=0.2, log=recorder)
|
||||
return renewal, values
|
||||
|
||||
|
||||
def _wait(predicate: Any, timeout: float) -> bool:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return True
|
||||
time.sleep(0.05)
|
||||
return False
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("resolve")
|
||||
def test_renewal_extends_then_relogins(pki: Path) -> None:
|
||||
"""«Продление и повторный вход в работе»: срок роли 1,5 с, предел 4 с —
|
||||
продления (`debug`), упёрлись в предел — новый вход (`info`, причина
|
||||
`max_ttl`); токен в записях не появляется."""
|
||||
recorder = Recorder()
|
||||
with _openbao(pki, state=_Bao(ttl=1.5, max_ttl=4)) as state:
|
||||
renewal, values = _renewal(pki, state, recorder)
|
||||
renewal.start()
|
||||
try:
|
||||
assert _wait(
|
||||
lambda: (
|
||||
"Logged in to secrets store again" in recorder.events()
|
||||
),
|
||||
10,
|
||||
), recorder.records
|
||||
finally:
|
||||
renewal.stop()
|
||||
renews = sum(1 for r in state.requests if r[1].endswith("/renew-self"))
|
||||
logins = sum(1 for r in state.requests if r[1].endswith("/login"))
|
||||
assert renews >= 2 # noqa: PLR2004
|
||||
assert logins >= 2 # noqa: PLR2004
|
||||
assert "Renewed secrets token" in recorder.events("debug")
|
||||
relogin = next(
|
||||
r
|
||||
for r in recorder.records
|
||||
if r["event"] == "Logged in to secrets store again"
|
||||
)
|
||||
assert relogin["level"] == "info"
|
||||
assert relogin["reason"] == "max_ttl"
|
||||
assert recorder.events("warning") == []
|
||||
_assert_clean(recorder, state, values)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("resolve")
|
||||
def test_renewal_outage_and_return(pki: Path) -> None:
|
||||
"""«Отказ OpenBao в работе»: запечатан дольше срока — одна запись
|
||||
`warning` за отказ, повторы; возврат — `info`, токен истёк — новый вход
|
||||
(причина `expired`)."""
|
||||
recorder = Recorder()
|
||||
with _openbao(pki, state=_Bao(ttl=1.5, max_ttl=60)) as state:
|
||||
renewal, values = _renewal(pki, state, recorder)
|
||||
state.sealed = True
|
||||
renewal.start()
|
||||
try:
|
||||
time.sleep(2.5)
|
||||
assert recorder.events("warning") == [
|
||||
"Secrets store is unavailable",
|
||||
]
|
||||
state.sealed = False
|
||||
assert _wait(
|
||||
lambda: (
|
||||
"Secrets store is available again" in recorder.events()
|
||||
),
|
||||
5,
|
||||
), recorder.records
|
||||
assert _wait(
|
||||
lambda: (
|
||||
"Logged in to secrets store again" in recorder.events()
|
||||
),
|
||||
5,
|
||||
)
|
||||
finally:
|
||||
renewal.stop()
|
||||
assert recorder.events("warning") == ["Secrets store is unavailable"]
|
||||
relogin = next(
|
||||
r
|
||||
for r in recorder.records
|
||||
if r["event"] == "Logged in to secrets store again"
|
||||
)
|
||||
assert relogin["reason"] == "expired"
|
||||
_assert_clean(recorder, state, values)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("resolve")
|
||||
def test_renewal_reports_new_version(pki: Path) -> None:
|
||||
"""«Новая версия секрета»: при продлении — `warning` с путём и версиями,
|
||||
значения в загруженных секциях прежние."""
|
||||
recorder = Recorder()
|
||||
with _openbao(pki, state=_Bao(ttl=1.2, max_ttl=60)) as state:
|
||||
renewal, values = _renewal(pki, state, recorder)
|
||||
loaded_password = renewal._loaded.database.password.get_secret_value()
|
||||
new_value = secrets.token_hex(16)
|
||||
state.kv["postgres/worker"] = ({"password": new_value}, 2)
|
||||
renewal.start()
|
||||
try:
|
||||
assert _wait(
|
||||
lambda: "Secret version changed" in recorder.events(),
|
||||
5,
|
||||
), recorder.records
|
||||
time.sleep(1.2)
|
||||
finally:
|
||||
renewal.stop()
|
||||
changed = [
|
||||
r for r in recorder.records if r["event"] == "Secret version changed"
|
||||
]
|
||||
assert len(changed) == 1, "one record per new version"
|
||||
assert changed[0]["path"] == "messenger/data/postgres/worker"
|
||||
assert changed[0]["loaded_version"] == 1
|
||||
assert changed[0]["current_version"] == 2 # noqa: PLR2004
|
||||
assert (
|
||||
renewal._loaded.database.password.get_secret_value() == loaded_password
|
||||
)
|
||||
assert new_value not in json.dumps(recorder.records)
|
||||
_assert_clean(recorder, state, values)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("resolve")
|
||||
def test_renewal_stop_does_not_wait(pki: Path) -> None:
|
||||
"""Остановка без ожидания сети: поток daemon, `stop()` возвращается сразу."""
|
||||
recorder = Recorder()
|
||||
with _openbao(pki) as state:
|
||||
renewal, _ = _renewal(pki, state, recorder)
|
||||
renewal.start()
|
||||
started = time.monotonic()
|
||||
renewal.stop()
|
||||
assert time.monotonic() - started < 0.1 # noqa: PLR2004
|
||||
assert renewal._thread is not None
|
||||
assert renewal._thread.daemon
|
||||
@@ -444,3 +444,78 @@ def test_auth_from_environment_over_file(
|
||||
assert _EnvAndToml().auth.login_max_failures_per_account == 7
|
||||
monkeypatch.setenv("AUTH__LOGIN_MAX_FAILURES_PER_ACCOUNT", "3")
|
||||
assert _EnvAndToml().auth.login_max_failures_per_account == 3
|
||||
|
||||
|
||||
# --- [secrets] (change openbao-secrets, design, решения 7, 10; спек
|
||||
# service-configuration, «Параметры хранилища секретов»)
|
||||
|
||||
|
||||
def test_secrets_defaults() -> None:
|
||||
"""«Значения по умолчанию»: OpenBao в сети стенда, ожидание при старте
|
||||
30 с, повтор 2 с; файлов identity по умолчанию нет."""
|
||||
loaded = _ArgumentsOnly().secrets
|
||||
assert loaded.address == "https://openbao:8200"
|
||||
assert loaded.startup_timeout_seconds == 30
|
||||
assert loaded.retry_seconds == 2
|
||||
assert loaded.request_timeout_seconds < loaded.startup_timeout_seconds
|
||||
assert (loaded.cert_file, loaded.key_file, loaded.crl_file) == ("", "", "")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value"),
|
||||
[
|
||||
("address", "http://openbao:8200"),
|
||||
("address", "https://openbao:8200/v1"),
|
||||
("address", "https://openbao:8200?x=1"),
|
||||
("address", "https://user:pw@openbao:8200"),
|
||||
("address", "https://openbao"),
|
||||
("connect_timeout_seconds", 0),
|
||||
("request_timeout_seconds", float("inf")),
|
||||
("startup_timeout_seconds", 0),
|
||||
("startup_timeout_seconds", float("nan")),
|
||||
("retry_seconds", -1),
|
||||
],
|
||||
)
|
||||
def test_wrong_secrets_value_names_field(field: str, value: object) -> None:
|
||||
"""«Адрес только https», «Неверный срок»: ошибка называет поле."""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_ArgumentsOnly(secrets={field: value})
|
||||
assert ("secrets", field) in {e["loc"] for e in caught.value.errors()}
|
||||
|
||||
|
||||
def test_secrets_request_shorter_than_startup() -> None:
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_ArgumentsOnly(
|
||||
secrets={
|
||||
"request_timeout_seconds": 10,
|
||||
"startup_timeout_seconds": 10,
|
||||
},
|
||||
)
|
||||
assert ("secrets", "startup_timeout_seconds") in {
|
||||
e["loc"] for e in caught.value.errors()
|
||||
}
|
||||
|
||||
|
||||
def test_wrong_secrets_from_environment_names_field(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setenv("SECRETS__STARTUP_TIMEOUT_SECONDS", "0")
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_EnvironmentOnly()
|
||||
assert ("secrets", "startup_timeout_seconds") in {
|
||||
e["loc"] for e in caught.value.errors()
|
||||
}
|
||||
|
||||
|
||||
def test_example_toml_has_no_secrets_paths() -> None:
|
||||
"""Адрес и пути identity задают compose и цели make: в шаблоне только
|
||||
закомментированные сроки, и он загружается с умолчаниями."""
|
||||
text = EXAMPLE_TOML_PATH.read_text()
|
||||
section = text.split("[secrets]", 1)[1]
|
||||
active = [
|
||||
line
|
||||
for line in section.splitlines()
|
||||
if line.strip() and not line.lstrip().startswith("#")
|
||||
]
|
||||
assert active == []
|
||||
assert _ExampleToml().secrets == _ArgumentsOnly().secrets
|
||||
|
||||
@@ -1458,6 +1458,10 @@ def _loaded_modules(imports: str) -> set[str]:
|
||||
|
||||
code = (
|
||||
"import json, sys\n"
|
||||
# глобалы клиентов API берут секреты из OpenBao (change
|
||||
# openbao-secrets): подстановка кодом теста, без сети
|
||||
"from src.infra.secrets import substitute_for_tests\n"
|
||||
"substitute_for_tests('api')\n"
|
||||
f"import {imports}\n"
|
||||
"prefixes = ('opentelemetry.sdk', 'opentelemetry.exporter',\n"
|
||||
" 'google.protobuf', 'requests')\n"
|
||||
|
||||
@@ -42,7 +42,7 @@ import requests
|
||||
from pydantic import ValidationError
|
||||
|
||||
from src.config import settings
|
||||
from src.config.settings import BASE_DIR, Settings
|
||||
from src.config.settings import BASE_DIR, Secrets, Settings
|
||||
from src.config.settings import Telemetry as TelemetrySettings
|
||||
from src.infra.tls import (
|
||||
API_STORAGES,
|
||||
@@ -64,6 +64,17 @@ TRACES_PATH = "/v1/traces"
|
||||
ALLOWED_ROWS = ("api-client", "worker", "relay")
|
||||
|
||||
|
||||
def _secrets_env(stand: Path) -> dict[str, str]:
|
||||
"""OpenBao процесса (change `openbao-secrets`): действующие файлы identity,
|
||||
чтобы дойти до проверяемого поля; адрес — имя, а не IP."""
|
||||
return {
|
||||
"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"),
|
||||
}
|
||||
|
||||
|
||||
def _openssl() -> str | None:
|
||||
binary = os.environ.get("OPENSSL") or shutil.which("openssl")
|
||||
if not binary:
|
||||
@@ -420,6 +431,12 @@ def _settings(pki: Path, telemetry: TelemetrySettings) -> Settings:
|
||||
},
|
||||
),
|
||||
telemetry=telemetry,
|
||||
# OpenBao (change openbao-secrets): действующие файлы identity
|
||||
secrets=Secrets(
|
||||
cert_file=str(pki / "stand" / "relay.crt"),
|
||||
key_file=str(pki / "stand" / "relay.key"),
|
||||
crl_file=str(pki / "stand" / "crl.pem"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -509,6 +526,7 @@ def _run(
|
||||
"TELEMETRY__CERT_FILE": str(stand / "relay.crt"),
|
||||
"TELEMETRY__KEY_FILE": str(stand / "relay.key"),
|
||||
"TELEMETRY__CRL_FILE": str(stand / "crl.pem"),
|
||||
**_secrets_env(stand),
|
||||
**env,
|
||||
},
|
||||
capture_output=True,
|
||||
@@ -582,6 +600,14 @@ def _run_replay(pki: Path, **env: str) -> tuple[int, list[dict[str, Any]]]:
|
||||
"TELEMETRY__CERT_FILE": "",
|
||||
"TELEMETRY__KEY_FILE": "",
|
||||
"TELEMETRY__CRL_FILE": "",
|
||||
**_secrets_env(stand),
|
||||
# с change openbao-secrets после проверки replay первым делом
|
||||
# входит в OpenBao: закрытый порт и короткий срок ожидания — код 1
|
||||
# за секунду, без стенда
|
||||
"SECRETS__ADDRESS": "https://localhost:1",
|
||||
"SECRETS__REQUEST_TIMEOUT_SECONDS": "0.5",
|
||||
"SECRETS__STARTUP_TIMEOUT_SECONDS": "1",
|
||||
"SECRETS__RETRY_SECONDS": "0.2",
|
||||
**env,
|
||||
},
|
||||
capture_output=True,
|
||||
@@ -599,7 +625,8 @@ def _run_replay(pki: Path, **env: str) -> tuple[int, list[dict[str, Any]]]:
|
||||
def test_replay_does_not_check_telemetry(pki: Path) -> None:
|
||||
"""Команда replay SDK не запускает (verify S2): при включённой телеметрии
|
||||
без файлов `[telemetry]` проверка при старте их не называет, команда
|
||||
доходит до PostgreSQL (закрытый порт — код 1, а не 2)."""
|
||||
доходит до следующего шага (с change `openbao-secrets` — вход в OpenBao:
|
||||
закрытый порт — код 1, а не 2)."""
|
||||
code, records = _run_replay(pki)
|
||||
refusal = [
|
||||
r for r in records if r["event"] == "Invalid client TLS settings"
|
||||
|
||||
Reference in New Issue
Block a user