702 lines
26 KiB
Python
702 lines
26 KiB
Python
"""Лаба 7: секреты процесса из OpenBao (перенос openbao-secrets).
|
||
|
||
Без стенда. Подставной OpenBao — HTTPS-сервер в потоке с временной PKI
|
||
(`infra/pki/pki.sh stand`; без OpenSSL ≥ 3 — пропуск с причиной): обязательный
|
||
сертификат клиента CA стенда, вход по DNS SAN, KV v2, продление, срок и предел роли,
|
||
запечатанное состояние. Проверяются вход и чтение, отказы 400 / 403 / 404 / 503,
|
||
TLS (сервер другого CA, имя вне SAN, отозванный сервер, только TLS 1.2 — отказ до
|
||
запроса), ожидание и коды старта, продление и повторный вход, сверка версий, журнал
|
||
без значений и токенов. Настоящий OpenBao — `make bao-check`, `make bao-outage`.
|
||
"""
|
||
|
||
import contextlib
|
||
import http.server
|
||
import json
|
||
import logging
|
||
import os
|
||
import secrets
|
||
import shutil
|
||
import signal
|
||
import ssl
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
from collections.abc import Iterator
|
||
from dataclasses import dataclass, field
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
from src.client_tls import (
|
||
API_STORAGES,
|
||
BOOTSTRAP_STORAGES,
|
||
CLEANER_STORAGES,
|
||
MIGRATION_STORAGES,
|
||
RELAY_STORAGES,
|
||
REPLAY_STORAGES,
|
||
WORKER_STORAGES,
|
||
client_tls_problems,
|
||
)
|
||
from src.config import ConfigError, SecretStore, Settings
|
||
from src.secrets_renewal import SecretsRenewal
|
||
from src.secrets_store import (
|
||
EXIT_REFUSED,
|
||
EXIT_UNAVAILABLE,
|
||
ProcessSecrets,
|
||
SecretsStartupError,
|
||
load,
|
||
load_or_exit,
|
||
)
|
||
|
||
pytestmark = pytest.mark.unit
|
||
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
PKI = ROOT / "infra" / "pki" / "pki.sh"
|
||
BAO_FILES = ("BAO_CERT_FILE", "BAO_KEY_FILE", "BAO_CRL_FILE")
|
||
|
||
|
||
def _pki(env: dict[str, str], *args: str) -> None:
|
||
done = subprocess.run(
|
||
["sh", str(PKI), *args], env=env, capture_output=True, text=True, check=False
|
||
)
|
||
# пропуск — только без OpenSSL 3+ (первый вызов); дальше — ошибка
|
||
if done.returncode != 0 and args[0] == "stand":
|
||
pytest.skip(f"infra/pki/pki.sh stand failed (OpenSSL 3+?): {done.stderr}")
|
||
assert done.returncode == 0, done.stderr
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def pki(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
||
"""`stand` — файлы стенда с CRL, `revoked` — отозванная пара openbao (CRL её
|
||
называет), `other` — файлы другого оператора."""
|
||
base = tmp_path_factory.mktemp("bao-pki")
|
||
env = {
|
||
**os.environ,
|
||
"PKI_OPERATOR_DIR": str(base / "operator"),
|
||
"PKI_STAND_DIR": str(base / "stand"),
|
||
}
|
||
_pki(env, "stand")
|
||
(base / "revoked").mkdir()
|
||
for name in ("openbao.crt", "openbao.key"):
|
||
shutil.copy(base / "stand" / name, base / "revoked" / name)
|
||
_pki(env, "revoke", "openbao")
|
||
# перевыпуск: у стенда действующая пара, прежняя — в CRL
|
||
_pki(env, "stand")
|
||
other = {
|
||
**env,
|
||
"PKI_OPERATOR_DIR": str(base / "other-operator"),
|
||
"PKI_STAND_DIR": str(base / "other"),
|
||
}
|
||
_pki(other, "stand")
|
||
return base
|
||
|
||
|
||
@dataclass
|
||
class Bao:
|
||
"""Состояние подставного OpenBao; тест меняет его между запросами."""
|
||
|
||
port: int = 0
|
||
ttl: float = 600
|
||
max_ttl: float = 3600
|
||
sealed: bool = False
|
||
# статус входа вместо 200 (None — по сертификату)
|
||
login_status: int | None = None
|
||
kv: dict[str, tuple[dict[str, str], int]] = field(default_factory=dict)
|
||
policies: dict[str, set[str]] = field(default_factory=dict)
|
||
# токен → (роль, SAN, срок, предел)
|
||
tokens: dict[str, list] = field(default_factory=dict)
|
||
requests: list[tuple[str, str]] = field(default_factory=list)
|
||
|
||
|
||
def _handler(bao: Bao) -> type[http.server.BaseHTTPRequestHandler]:
|
||
class Handler(http.server.BaseHTTPRequestHandler):
|
||
protocol_version = "HTTP/1.1"
|
||
|
||
def _san(self) -> str:
|
||
names = dict(self.connection.getpeercert().get("subjectAltName", ()))
|
||
return names.get("DNS", "")
|
||
|
||
def _answer(self, status: int, payload: dict | None = None) -> None:
|
||
body = json.dumps(payload or {"errors": ["secret body"]}).encode()
|
||
self.send_response(status)
|
||
self.send_header("Content-Length", str(len(body)))
|
||
self.end_headers()
|
||
self.wfile.write(body)
|
||
|
||
def _auth(self, token: str, role: str, ttl: float) -> None:
|
||
auth = {
|
||
"client_token": token,
|
||
"lease_duration": int(ttl),
|
||
"renewable": True,
|
||
"token_policies": [role],
|
||
}
|
||
self._answer(200, {"auth": auth})
|
||
|
||
def _current(self) -> list | None:
|
||
token = bao.tokens.get(self.headers.get("X-Vault-Token", ""))
|
||
return token if token and time.monotonic() < token[2] else None
|
||
|
||
def do_POST(self) -> None: # noqa: N802 - имя задаёт http.server
|
||
size = int(self.headers.get("Content-Length") or 0)
|
||
body = json.loads(self.rfile.read(size) or b"{}")
|
||
bao.requests.append(("POST", self.path))
|
||
now = time.monotonic()
|
||
if bao.sealed:
|
||
self._answer(503)
|
||
elif self.path == "/v1/auth/cert/login":
|
||
role = body["name"]
|
||
if bao.login_status is not None:
|
||
self._answer(bao.login_status)
|
||
elif self._san() != role:
|
||
self._answer(400)
|
||
else:
|
||
token = "s." + secrets.token_hex(12)
|
||
bao.tokens[token] = [
|
||
role,
|
||
self._san(),
|
||
now + bao.ttl,
|
||
now + bao.max_ttl,
|
||
]
|
||
self._auth(token, role, bao.ttl)
|
||
elif self.path == "/v1/auth/token/renew-self":
|
||
token = self._current()
|
||
if token is None or token[1] != self._san():
|
||
self._answer(403)
|
||
else:
|
||
token[2] = min(now + bao.ttl, token[3])
|
||
self._auth(self.headers["X-Vault-Token"], token[0], token[2] - now)
|
||
else:
|
||
self._answer(404)
|
||
|
||
def do_GET(self) -> None: # noqa: N802 - имя задаёт http.server
|
||
bao.requests.append(("GET", self.path))
|
||
path = self.path.removeprefix("/v1/messenger/data/")
|
||
token = self._current()
|
||
if bao.sealed:
|
||
self._answer(503)
|
||
elif token is None or path not in bao.policies.get(token[0], set()):
|
||
self._answer(403)
|
||
elif path not in bao.kv:
|
||
self._answer(404)
|
||
else:
|
||
data, version = bao.kv[path]
|
||
self._answer(
|
||
200, {"data": {"data": data, "metadata": {"version": version}}}
|
||
)
|
||
|
||
def log_message(self, *_args: object) -> None:
|
||
return None
|
||
|
||
return Handler
|
||
|
||
|
||
SECRET_VALUES = {
|
||
"postgres/api": {"password": "pg-" + secrets.token_hex(8)},
|
||
"valkey/api": {"password": "vk-" + secrets.token_hex(8)},
|
||
"s3/api": {
|
||
"access_key_id": "id-" + secrets.token_hex(8),
|
||
"secret_access_key": "sk-" + secrets.token_hex(8),
|
||
},
|
||
}
|
||
|
||
|
||
@contextlib.contextmanager
|
||
def _openbao(
|
||
pki: Path, *, pair: str = "stand", tls12: bool = False, port: int = 0
|
||
) -> Iterator[Bao]:
|
||
bao = Bao()
|
||
bao.kv = {
|
||
path: (dict(data), number)
|
||
for number, (path, data) in enumerate(SECRET_VALUES.items(), start=1)
|
||
}
|
||
bao.policies = {"api": set(SECRET_VALUES)}
|
||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||
context.load_cert_chain(pki / pair / "openbao.crt", pki / pair / "openbao.key")
|
||
context.load_verify_locations(cafile=pki / "stand" / "ca.crt")
|
||
context.verify_mode = ssl.CERT_REQUIRED
|
||
if tls12:
|
||
context.maximum_version = ssl.TLSVersion.TLSv1_2
|
||
server = http.server.ThreadingHTTPServer(("127.0.0.1", port), _handler(bao))
|
||
server.daemon_threads = True
|
||
server.handle_error = lambda *_args: None # type: ignore[method-assign]
|
||
server.socket = context.wrap_socket(server.socket, server_side=True)
|
||
bao.port = server.server_address[1]
|
||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||
try:
|
||
yield bao
|
||
finally:
|
||
server.shutdown()
|
||
server.server_close()
|
||
|
||
|
||
def _env(
|
||
pki: Path, port: int, identity: str = "api-client", **extra: str
|
||
) -> dict[str, str]:
|
||
stand = pki / "stand"
|
||
return {
|
||
"CLIENT_TLS_CA_FILE": str(stand / "ca.crt"),
|
||
"BAO_ADDR": f"https://localhost:{port}",
|
||
"BAO_CERT_FILE": str(stand / f"{identity}.crt"),
|
||
"BAO_KEY_FILE": str(stand / f"{identity}.key"),
|
||
"BAO_CRL_FILE": str(stand / "crl.pem"),
|
||
"BAO_CONNECT_TIMEOUT": "2",
|
||
"BAO_STARTUP_TIMEOUT": "0",
|
||
"BAO_RETRY_SECONDS": "0.1",
|
||
**extra,
|
||
}
|
||
|
||
|
||
def _load(pki: Path, bao: Bao, **extra: str) -> ProcessSecrets:
|
||
return load("api", Settings.from_env(_env(pki, bao.port, **extra)))
|
||
|
||
|
||
def _refuse(pki: Path, bao: Bao, **extra: str) -> int:
|
||
with pytest.raises(SecretsStartupError) as error:
|
||
_load(pki, bao, **extra)
|
||
return error.value.exit_code
|
||
|
||
|
||
@pytest.fixture
|
||
def journal(caplog: pytest.LogCaptureFixture) -> pytest.LogCaptureFixture:
|
||
"""Журнал модулей секретов (их логгер `src` не пишет в корневой)."""
|
||
logger = logging.getLogger("src")
|
||
propagate, level = logger.propagate, logger.level
|
||
logger.propagate = True
|
||
logger.setLevel(logging.DEBUG)
|
||
caplog.set_level(logging.DEBUG)
|
||
yield caplog
|
||
logger.propagate = propagate
|
||
logger.setLevel(level)
|
||
|
||
|
||
def _no_secrets(text: str, bao: Bao) -> None:
|
||
values = [value for data in SECRET_VALUES.values() for value in data.values()]
|
||
for value in (*values, *bao.tokens, "secret body"):
|
||
assert value not in text
|
||
|
||
|
||
# --- настройки и проверка точки входа ---------------------------------------------
|
||
|
||
|
||
def test_settings_and_skeleton_names_not_read() -> None:
|
||
store = Settings.from_env({}).secret_store
|
||
assert store == SecretStore()
|
||
assert store.address == "https://localhost:8200"
|
||
assert (store.startup_timeout, store.retry) == (30.0, 2.0)
|
||
# токен и CA имён skeleton не читаются: постоянного секрета входа нет
|
||
other = Settings.from_env(
|
||
{"BAO_TOKEN": "s.x", "BAO_CACERT": "/x", "VAULT_TOKEN": "y"}
|
||
)
|
||
assert other.secret_store == SecretStore()
|
||
for value in ("http://openbao:8200", "openbao:8200", "https://openbao:8200/v1"):
|
||
with pytest.raises(ConfigError, match="BAO_ADDR"):
|
||
Settings.from_env({"BAO_ADDR": value})
|
||
|
||
|
||
def test_every_process_checks_files(pki: Path, tmp_path: Path) -> None:
|
||
for storages in (
|
||
API_STORAGES,
|
||
WORKER_STORAGES,
|
||
CLEANER_STORAGES,
|
||
RELAY_STORAGES,
|
||
REPLAY_STORAGES,
|
||
MIGRATION_STORAGES,
|
||
):
|
||
assert "secret_store" in storages
|
||
problems = client_tls_problems(Settings.from_env({}), storages)
|
||
assert problems[-3:] == list(BAO_FILES)
|
||
# bootstrap ролей OpenBao не использует
|
||
assert BOOTSTRAP_STORAGES == ("database",)
|
||
good = _env(pki, 8200)
|
||
assert client_tls_problems(Settings.from_env(good), MIGRATION_STORAGES) == []
|
||
stand = pki / "stand"
|
||
for variable, path in (
|
||
("BAO_CERT_FILE", stand / "crl.pem"),
|
||
("BAO_KEY_FILE", stand / "worker.key"),
|
||
("BAO_KEY_FILE", tmp_path / "missing"),
|
||
("BAO_CRL_FILE", stand / "ca.crt"),
|
||
("BAO_ADDR", "https://127.0.0.1:8200"),
|
||
):
|
||
settings = Settings.from_env({**good, variable: str(path)})
|
||
assert client_tls_problems(settings, MIGRATION_STORAGES) == [variable]
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"command",
|
||
[
|
||
["-m", "src"],
|
||
["-m", "src.worker"],
|
||
["-m", "src.relay"],
|
||
["-m", "src.relay", "replay"],
|
||
["-m", "src.cleaner", "--once"],
|
||
["-m", "alembic", "upgrade", "head"],
|
||
],
|
||
ids=["api", "worker", "relay", "replay", "cleaner", "migrate"],
|
||
)
|
||
def test_entry_points_without_crl_exit_2(
|
||
pki: Path, command: list[str], tmp_path: Path
|
||
) -> None:
|
||
"""Процесс целиком: без CRL — код 2 и имя переменной, OpenBao не спрошен."""
|
||
stand = pki / "stand"
|
||
env = {
|
||
"PATH": os.environ["PATH"],
|
||
**_env(pki, 1, identity="relay"),
|
||
"BAO_CRL_FILE": str(tmp_path / "no-such.pem"),
|
||
"DB_HOST": "postgres",
|
||
"CACHE_HOST": "valkey",
|
||
"S3_ENDPOINT": "https://s3:8333",
|
||
"BROKER_HOST": "rabbitmq",
|
||
"BROKER_CERT_FILE": str(stand / "relay.crt"),
|
||
"BROKER_KEY_FILE": str(stand / "relay.key"),
|
||
"BROKER_CRL_FILE": str(stand / "crl.pem"),
|
||
}
|
||
done = subprocess.run(
|
||
[sys.executable, *command],
|
||
cwd=ROOT,
|
||
env=env,
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
timeout=60,
|
||
)
|
||
assert done.returncode == 2, done.stderr
|
||
assert "invalid client TLS settings: BAO_CRL_FILE" in done.stderr
|
||
assert "no-such" not in done.stderr
|
||
|
||
|
||
# --- вход и чтение ------------------------------------------------------------------
|
||
|
||
|
||
def test_load_gives_a_copy_of_settings(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
settings = Settings.from_env(_env(pki, bao.port))
|
||
loaded = load("api", settings)
|
||
assert (
|
||
loaded.settings.database.password
|
||
== SECRET_VALUES["postgres/api"]["password"]
|
||
)
|
||
assert loaded.settings.cache.password == SECRET_VALUES["valkey/api"]["password"]
|
||
keys = SECRET_VALUES["s3/api"]
|
||
assert loaded.settings.s3.access_key_id == keys["access_key_id"]
|
||
assert loaded.settings.s3.secret_access_key == keys["secret_access_key"]
|
||
assert loaded.versions == {"postgres/api": 1, "valkey/api": 2, "s3/api": 3}
|
||
# исходные настройки и окружение прежние, остальные поля копии — те же
|
||
assert settings.database.password == settings.s3.access_key_id == ""
|
||
assert "DB_PASSWORD" not in os.environ
|
||
assert loaded.settings.database.host == settings.database.host
|
||
text = journal.text
|
||
assert "process secrets loaded process=api role=api" in text
|
||
assert "versions=postgres/api:1,valkey/api:2,s3/api:3 token_ttl=600s" in text
|
||
_no_secrets(text + repr(loaded), bao)
|
||
|
||
|
||
def test_environment_secret_is_ignored(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
loaded = _load(pki, bao, DB_PASSWORD="wrong-value", S3_ACCESS_KEY_ID="wrong-id")
|
||
assert (
|
||
loaded.settings.database.password
|
||
== SECRET_VALUES["postgres/api"]["password"]
|
||
)
|
||
assert (
|
||
"secret settings ignored process=api variables=DB_PASSWORD,S3_ACCESS_KEY_ID"
|
||
in journal.text
|
||
)
|
||
assert "wrong-" not in journal.text
|
||
_no_secrets(journal.text, bao)
|
||
|
||
|
||
@pytest.mark.parametrize("status", [400, 401, 403])
|
||
def test_login_refused_is_code_2_without_retries(
|
||
pki: Path, journal, status: int
|
||
) -> None:
|
||
with _openbao(pki) as bao:
|
||
bao.login_status = status
|
||
code = _refuse(pki, bao, BAO_STARTUP_TIMEOUT="5")
|
||
assert code == EXIT_REFUSED
|
||
assert bao.requests == [("POST", "/v1/auth/cert/login")]
|
||
assert f"reason=login status={status} path=auth/cert/login" in journal.text
|
||
_no_secrets(journal.text, bao)
|
||
|
||
|
||
def test_foreign_identity_is_refused(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
env = _env(pki, bao.port, identity="worker")
|
||
with pytest.raises(SecretsStartupError) as error:
|
||
load("api", Settings.from_env(env))
|
||
assert error.value.exit_code == EXIT_REFUSED
|
||
assert "reason=login status=400" in journal.text
|
||
|
||
|
||
def test_denied_and_missing_path_and_field(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
bao.policies["api"] = {"postgres/api"}
|
||
assert _refuse(pki, bao) == EXIT_REFUSED
|
||
assert (
|
||
"reason=permission status=403 path=messenger/data/valkey/api"
|
||
in journal.text
|
||
)
|
||
bao.policies["api"] = set(SECRET_VALUES)
|
||
data, version = bao.kv.pop("valkey/api")
|
||
assert _refuse(pki, bao) == EXIT_REFUSED
|
||
assert (
|
||
"reason=missing status=404 path=messenger/data/valkey/api" in journal.text
|
||
)
|
||
bao.kv["valkey/api"] = ({"other": "x", **dict.fromkeys(data, "")}, version)
|
||
assert _refuse(pki, bao) == EXIT_REFUSED
|
||
assert (
|
||
"secret field is missing process=api path=messenger/data/valkey/api "
|
||
"field=password" in journal.text
|
||
)
|
||
_no_secrets(journal.text, bao)
|
||
|
||
|
||
def test_server_error_and_bad_answer_are_unavailable(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
bao.login_status = 500
|
||
assert _refuse(pki, bao) == EXIT_UNAVAILABLE
|
||
assert "error=http_500" in journal.text
|
||
# 200 без токена — не вход
|
||
bao.login_status = 200
|
||
assert _refuse(pki, bao) == EXIT_UNAVAILABLE
|
||
assert "error=bad_response" in journal.text
|
||
|
||
|
||
# --- TLS ----------------------------------------------------------------------
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"case", ["other CA", "revoked server", "TLS 1.2", "name outside SAN", "no CRL"]
|
||
)
|
||
def test_bad_server_gets_no_request(pki: Path, case: str) -> None:
|
||
pair = {"other CA": "other", "revoked server": "revoked"}.get(case, "stand")
|
||
with _openbao(pki, pair=pair, tls12=case == "TLS 1.2") as bao:
|
||
extra = {}
|
||
if case == "name outside SAN":
|
||
# IP отвергла бы проверка точки входа; здесь — сам клиент
|
||
extra["BAO_ADDR"] = f"https://127.0.0.1:{bao.port}"
|
||
if case == "no CRL":
|
||
extra["BAO_CRL_FILE"] = ""
|
||
assert _refuse(pki, bao, **extra) == EXIT_UNAVAILABLE
|
||
assert bao.requests == []
|
||
|
||
|
||
def test_client_without_certificate_of_stand_ca_is_rejected(pki: Path) -> None:
|
||
with _openbao(pki) as bao:
|
||
other = pki / "other"
|
||
code = _refuse(
|
||
pki,
|
||
bao,
|
||
BAO_CERT_FILE=str(other / "api-client.crt"),
|
||
BAO_KEY_FILE=str(other / "api-client.key"),
|
||
)
|
||
assert code == EXIT_UNAVAILABLE
|
||
assert bao.requests == []
|
||
|
||
|
||
def test_proxy_of_environment_is_not_used(pki: Path, monkeypatch) -> None:
|
||
monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:1")
|
||
monkeypatch.setenv("https_proxy", "http://127.0.0.1:1")
|
||
with _openbao(pki) as bao:
|
||
assert _load(pki, bao).versions["postgres/api"] == 1
|
||
|
||
|
||
# --- ожидание на старте --------------------------------------------------------
|
||
|
||
|
||
def test_sealed_waits_then_code_1(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
bao.sealed = True
|
||
started = time.monotonic()
|
||
assert _refuse(pki, bao, BAO_STARTUP_TIMEOUT="0.6") == EXIT_UNAVAILABLE
|
||
assert 0.4 <= time.monotonic() - started < 3
|
||
assert len(bao.requests) >= 3
|
||
# одна строка на ожидание и одна на отказ
|
||
assert journal.text.count("waiting for secret store process=api") == 1
|
||
assert journal.text.count("secret store is unavailable process=api") == 1
|
||
assert "error=sealed" in journal.text
|
||
|
||
|
||
def test_unsealed_while_waiting(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
bao.sealed = True
|
||
threading.Timer(0.5, lambda: setattr(bao, "sealed", False)).start()
|
||
loaded = _load(pki, bao, BAO_STARTUP_TIMEOUT="10")
|
||
assert loaded.versions["postgres/api"] == 1
|
||
assert "waiting for secret store" in journal.text
|
||
|
||
|
||
def test_nobody_listens_is_code_1(pki: Path, capsys) -> None:
|
||
with _openbao(pki) as bao:
|
||
port = bao.port
|
||
settings = Settings.from_env(_env(pki, port))
|
||
with pytest.raises(SystemExit) as error:
|
||
load_or_exit("api", settings)
|
||
assert error.value.code == EXIT_UNAVAILABLE
|
||
|
||
|
||
def test_sigterm_while_waiting_is_code_0(pki: Path) -> None:
|
||
"""Процесс уборщика целиком: SIGTERM во время ожидания OpenBao — ранний
|
||
обработчик, код 0 сразу."""
|
||
with _openbao(pki) as bao:
|
||
bao.sealed = True
|
||
env = {
|
||
"PATH": os.environ["PATH"],
|
||
**_env(pki, bao.port, identity="cleaner", BAO_STARTUP_TIMEOUT="60"),
|
||
"DB_HOST": "postgres",
|
||
"S3_ENDPOINT": "https://s3:8333",
|
||
}
|
||
process = subprocess.Popen(
|
||
[sys.executable, "-m", "src.cleaner"],
|
||
cwd=ROOT,
|
||
env=env,
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.STDOUT,
|
||
text=True,
|
||
)
|
||
try:
|
||
deadline = time.monotonic() + 30
|
||
while not bao.requests and time.monotonic() < deadline:
|
||
time.sleep(0.05)
|
||
assert bao.requests, "the process did not reach OpenBao"
|
||
time.sleep(0.3)
|
||
stopped = time.monotonic()
|
||
process.send_signal(signal.SIGTERM)
|
||
out, _ = process.communicate(timeout=10)
|
||
assert time.monotonic() - stopped < 3
|
||
finally:
|
||
process.kill()
|
||
assert process.returncode == 0, out
|
||
assert "waiting for secret store process=cleaner" in out
|
||
assert "stopped before startup signal=SIGTERM" in out
|
||
|
||
|
||
# --- продление -----------------------------------------------------------------
|
||
|
||
|
||
def _logins(bao: Bao) -> int:
|
||
return bao.requests.count(("POST", "/v1/auth/cert/login"))
|
||
|
||
|
||
def test_renews_at_two_thirds(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
loaded = _load(pki, bao)
|
||
renewal = SecretsRenewal(loaded)
|
||
assert 390 < renewal._next_delay() <= 400
|
||
delay = renewal.step()
|
||
assert 390 < delay <= 400
|
||
assert _logins(bao) == 1
|
||
assert ("POST", "/v1/auth/token/renew-self") in bao.requests
|
||
assert (
|
||
"secret token renewed process=api token_ttl=600s capped=false"
|
||
in journal.text
|
||
)
|
||
_no_secrets(journal.text, bao)
|
||
|
||
|
||
def test_login_again_at_max_ttl(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
bao.ttl, bao.max_ttl = 10, 11
|
||
renewal = SecretsRenewal(_load(pki, bao))
|
||
# за 2 с от предела ответ короче запрошенного
|
||
next(iter(bao.tokens.values()))[3] = time.monotonic() + 2
|
||
renewal.step()
|
||
assert _logins(bao) == 1
|
||
assert "capped=true" in journal.text
|
||
renewal.step()
|
||
assert _logins(bao) == 2
|
||
assert "again process=api role=api reason=max_ttl token_ttl=10s" in journal.text
|
||
|
||
|
||
def test_login_again_after_expiry_and_revocation(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
bao.ttl = 1
|
||
renewal = SecretsRenewal(_load(pki, bao))
|
||
time.sleep(1.1)
|
||
renewal.step()
|
||
assert "reason=expired" in journal.text
|
||
bao.tokens.clear()
|
||
renewal.step()
|
||
assert "reason=renew_refused" in journal.text
|
||
assert _logins(bao) == 3
|
||
|
||
|
||
def test_outage_is_one_line_and_return_is_one_line(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
renewal = SecretsRenewal(_load(pki, bao))
|
||
bao.sealed = True
|
||
assert [renewal.step(), renewal.step(), renewal.step()] == [0.1, 0.1, 0.1]
|
||
assert journal.text.count("secret store is unavailable process=api") == 1
|
||
bao.sealed = False
|
||
assert renewal.step() > 300
|
||
renewal.step()
|
||
assert journal.text.count("secret store is available again") == 1
|
||
|
||
|
||
def test_refused_login_is_an_error_and_the_process_lives(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
renewal = SecretsRenewal(_load(pki, bao))
|
||
bao.tokens.clear()
|
||
bao.login_status = 400
|
||
assert renewal.step() == 0.1
|
||
assert "ERROR" in journal.text
|
||
assert (
|
||
"refused access process=api role=api reason=login status=400"
|
||
in journal.text
|
||
)
|
||
bao.login_status = None
|
||
assert renewal.step() > 300
|
||
|
||
|
||
def test_new_version_is_a_warning_once(pki: Path, journal) -> None:
|
||
with _openbao(pki) as bao:
|
||
loaded = _load(pki, bao)
|
||
renewal = SecretsRenewal(loaded)
|
||
bao.kv["valkey/api"] = ({"password": "new"}, 5)
|
||
renewal.step()
|
||
renewal.step()
|
||
line = (
|
||
"secret version changed process=api path=messenger/data/valkey/api "
|
||
"loaded=2 current=5"
|
||
)
|
||
assert journal.text.count(line) == 1
|
||
assert loaded.settings.cache.password == SECRET_VALUES["valkey/api"]["password"]
|
||
|
||
|
||
def test_thread_renews_and_stops_without_network(pki: Path) -> None:
|
||
with _openbao(pki) as bao:
|
||
bao.ttl, bao.max_ttl = 1, 3
|
||
renewal = SecretsRenewal(_load(pki, bao))
|
||
renewal.start()
|
||
deadline = time.monotonic() + 15
|
||
while _logins(bao) < 3 and time.monotonic() < deadline:
|
||
time.sleep(0.05)
|
||
started = time.monotonic()
|
||
renewal.stop()
|
||
assert time.monotonic() - started < 0.2
|
||
assert _logins(bao) >= 3
|
||
time.sleep(0.5)
|
||
quiet = len(bao.requests)
|
||
time.sleep(1.5)
|
||
assert len(bao.requests) == quiet
|
||
|
||
|
||
def test_thread_survives_unexpected_error(pki: Path, journal, monkeypatch) -> None:
|
||
with _openbao(pki) as bao:
|
||
bao.ttl = 1
|
||
renewal = SecretsRenewal(_load(pki, bao))
|
||
calls = []
|
||
|
||
def step() -> float:
|
||
calls.append(1)
|
||
raise RuntimeError("unexpected")
|
||
|
||
monkeypatch.setattr(renewal, "step", step)
|
||
renewal.start()
|
||
deadline = time.monotonic() + 10
|
||
while len(calls) < 3 and time.monotonic() < deadline:
|
||
time.sleep(0.05)
|
||
renewal.stop()
|
||
assert len(calls) >= 3
|
||
assert "secret renewal failed process=api error=RuntimeError" in journal.text
|