"""Лаба 7: согласованность OpenBao (перенос openbao-secrets), без стенда. Политика процесса = пути его кода (`src/secrets_store.py`), роли входа = строки `infra/pki/identities.conf`, пути наполнения — ровно их объединение, значения — те переменные, которые compose отдаёт хранилищам; в `compose.yaml` у процессов нет секретов в окружении, файлы — только свои, OpenBao закреплён, не dev-mode и ждёт его каждый процесс. Команды оператора (`infra/openbao/bao.py`): материалы временного стенда только в его каталоге, вывод без токенов, запечатанный — код 2. Контроли: лишний путь и чужой SAN краснят сверку. """ import argparse import importlib.util import os import re import stat import subprocess import sys from pathlib import Path from types import ModuleType import pytest from src.secrets_store import KV_MOUNT, PROCESSES pytestmark = pytest.mark.unit ROOT = Path(__file__).resolve().parents[2] BAO_DIR = ROOT / "infra" / "openbao" OWN_TOKEN = { "auth/token/lookup-self": "read", "auth/token/renew-self": "update", "auth/token/revoke-self": "update", } # пара identity процесса в OpenBao: сервис compose → имя строки identities.conf PAIRS = { "api": "api-client", "worker": "worker", "relay": "relay", "cleaner": "cleaner", "migrate": "migrate", } def _module() -> ModuleType: spec = importlib.util.spec_from_file_location("test_bao", BAO_DIR / "bao.py") module = importlib.util.module_from_spec(spec) sys.modules["test_bao"] = module spec.loader.exec_module(module) return module bao = _module() def _code_paths() -> dict[str, set[str]]: """Роль входа → пути, которые читает код её процессов.""" paths: dict[str, set[str]] = {} for spec in PROCESSES.values(): paths.setdefault(spec.role, set()).update(spec.paths) return paths def _policy(text: str) -> dict[str, str]: """Путь → права файла политики (комментарии убраны).""" code = "\n".join(line.split("#", 1)[0] for line in text.splitlines()) rules = re.findall( r'path\s+"([^"]+)"\s*\{\s*capabilities\s*=\s*\[([^\]]*)\]\s*\}', code ) assert len(rules) == code.count("path "), "unparsed policy rule" return {path: rights.replace('"', "").strip() for path, rights in rules} def _policy_problems(role: str, text: str, paths: set[str]) -> list[str]: want = {f"{KV_MOUNT}/data/{path}": "read" for path in paths} | OWN_TOKEN got = _policy(text) problems = [f"extra {p}" for p in sorted(set(got) - set(want))] problems += [f"missing {p}" for p in sorted(set(want) - set(got))] problems += [f"rights {p}" for p in got if p in want and got[p] != want[p]] problems += [f"wildcard {p}" for p in got if set("*+") & set(p)] return problems def _identities() -> dict[str, tuple[str, str]]: rows = {} text = (ROOT / "infra" / "pki" / "identities.conf").read_text(encoding="utf-8") for line in text.splitlines(): if line.strip() and not line.startswith("#"): name, profile, sans, _ = line.split() rows[name] = (profile, sans) return rows def _role_problems(rows: dict[str, tuple[str, str]]) -> list[str]: problems = [] for role, spec in bao.ROLES.items(): if rows.get(spec["cn"]) != ("client", spec["san"]): problems.append(f"{role}: {spec['cn']} {rows.get(spec['cn'])}") return problems def _services() -> dict[str, str]: """Блоки сервисов compose.yaml текстом (отступ в два пробела).""" text = (ROOT / "compose.yaml").read_text(encoding="utf-8") body = text.split("\nservices:\n", 1)[1].split("\nnetworks:\n", 1)[0] blocks: dict[str, str] = {} name = "" for line in body.splitlines(): found = re.match(r"^ ([a-z0-9-]+):$", line) if found: name = found.group(1) blocks[name] = "" elif name and not line.lstrip().startswith("#"): blocks[name] += line + "\n" return blocks # --- политики, роли, пути --------------------------------------------------------- def test_policies_equal_code_needs() -> None: needs = _code_paths() files = {path.stem for path in (BAO_DIR / "policies").glob("*.hcl")} assert files == set(needs) == set(bao.ROLES) for role, paths in needs.items(): text = (BAO_DIR / "policies" / f"{role}.hcl").read_text(encoding="utf-8") assert _policy_problems(role, text, paths) == [], role assert set(bao.policy_paths(role)) == paths @pytest.mark.parametrize( "extra", [ 'path "messenger/data/postgres/api" {\n capabilities = ["read"]\n}\n', 'path "messenger/data/*" {\n capabilities = ["read"]\n}\n', 'path "sys/mounts" {\n capabilities = ["read"]\n}\n', ], ) def test_control_extra_policy_rule_is_red(extra: str) -> None: text = (BAO_DIR / "policies" / "worker.hcl").read_text(encoding="utf-8") assert _policy_problems("worker", text + extra, _code_paths()["worker"]) def test_control_wider_rights_are_red() -> None: text = (BAO_DIR / "policies" / "relay.hcl").read_text(encoding="utf-8") wide = text.replace('["read"]', '["read", "update"]', 1) assert _policy_problems("relay", wide, _code_paths()["relay"]) def test_roles_equal_identity_rows() -> None: rows = _identities() assert _role_problems(rows) == [] assert rows["openbao"] == ("server", "openbao,localhost") assert rows["bao-operator"] == ("client", "bao-operator") # CN разных ролей различны: одного leaf на две роли нет assert len({spec["cn"] for spec in bao.ROLES.values()}) == len(bao.ROLES) def test_control_changed_san_is_red() -> None: rows = {**_identities(), "cleaner": ("client", "cleaner,api")} assert _role_problems(rows) == ["cleaner: cleaner ('client', 'cleaner,api')"] def test_role_needs_both_cn_and_san_and_no_default_policy(tmp_path: Path) -> None: (tmp_path / "ca.crt").write_text("ca", encoding="ascii") operator = object.__new__(bao.Operator) operator.pki_dir = tmp_path operator.args = argparse.Namespace(token_ttl=600, token_max_ttl=3600) role = operator._desired_role("api") assert role["allowed_common_names"] == ["api-client"] assert role["allowed_dns_sans"] == ["api"] assert role["token_policies"] == ["api"] assert role["token_no_default_policy"] is True assert role["token_type"] == "service" assert (role["token_ttl"], role["token_max_ttl"]) == (600, 3600) assert (bao.TOKEN_TTL, bao.TOKEN_MAX_TTL) == (600, 3600) def test_seed_covers_code_paths_and_fields() -> None: fields: dict[str, set[str]] = {} for spec in PROCESSES.values(): for item in spec.fields: fields.setdefault(item.path, set()).add(item.key) assert {path: set(keys) for path, keys in bao.SEED.items()} == fields def test_seed_takes_what_compose_gives_to_storages() -> None: blocks = _services() for path, keys in bao.SEED.items(): for service, variable in keys.values(): assert f" {variable}: ${{" in blocks[service], (path, variable) def test_seed_has_no_administrative_secrets() -> None: text = repr(bao.SEED) for name in ("S3_ROOT", "JWT", "OPERATOR", "GRAFANA", "POSTGRES_PASSWORD"): assert name not in text # --- compose ---------------------------------------------------------------------- def test_processes_have_no_secrets_in_environment() -> None: blocks = _services() for service, pair in PAIRS.items(): block = blocks[service] for name in ( "PASSWORD", "ACCESS_KEY", "SECRET_KEY", "SIGNING_KEY", "BAO_TOKEN", "VAULT_TOKEN", ): assert name not in block, (service, name) assert "*bao-env" in block, service assert f"BAO_CERT_FILE: /run/secrets/{pair}.crt\n" in block, service assert f"BAO_KEY_FILE: /run/secrets/{pair}.key\n" in block, service files = set(re.findall(r"^ - ([a-z-]+\.(?:crt|key|pem))$", block, re.M)) own = {"ca.crt", "crl.pem", f"{pair}.crt", f"{pair}.key"} if service == "api": own |= {"api.crt", "api.key"} assert files == own, service assert "openbao:\n condition: service_healthy" in block, service anchors = ( (ROOT / "compose.yaml").read_text(encoding="utf-8").split("\nservices:")[0] ) assert "BAO_ADDR: https://openbao:8200\n" in anchors assert "PASSWORD:" not in anchors def test_storages_and_bootstraps_do_not_wait_for_openbao() -> None: blocks = _services() for service in ("postgres", "valkey", "s3", "rabbitmq", "postgres-bootstrap", "s3-bootstrap", "haproxy"): # fmt: skip assert "openbao:" not in blocks[service], service def test_openbao_service() -> None: blocks = _services() block = blocks["openbao"] assert re.search( r"image: openbao/openbao:\d+\.\d+\.\d+@sha256:[0-9a-f]{64}\n", block ) assert '"-dev' not in block assert "DEV_ROOT" not in block assert '- "127.0.0.1:${BAO_HOST_PORT:-8200}:8200"' in block assert "- openbao_data:/openbao/file" in block assert "<<: *hardened" in block files = set(re.findall(r"^ - ([a-z-]+\.(?:crt|key|pem))$", block, re.M)) assert files == {"ca.crt", "openbao.crt", "openbao.key"} # пара оператора и его каталог — ни у одного сервиса text = (ROOT / "compose.yaml").read_text(encoding="utf-8") code = "\n".join(line.split("#", 1)[0] for line in text.splitlines()) for word in ("bao-operator", "vladimirceva-lab7/operator", "unseal", "root-token"): assert word not in code, word def test_openbao_config_is_not_dev_and_requires_client_certificates() -> None: text = (BAO_DIR / "config.hcl").read_text(encoding="utf-8") code = "\n".join(line.split("#", 1)[0] for line in text.splitlines()) listeners = re.findall(r'listener "tcp" \{(.*?)\n\}', code, re.S) assert len(listeners) == 2 main = next(item for item in listeners if '"0.0.0.0:8200"' in item) health = next(item for item in listeners if '"127.0.0.1:8210"' in item) assert re.search(r"tls_require_and_verify_client_cert\s*=\s*true", main) assert "tls_client_ca_file" in main for item in listeners: assert re.search(r'tls_min_version\s*=\s*"tls13"', item) assert "tls_disable " not in item assert re.search(r'cluster_address\s*=\s*"127\.0\.0\.1:', item) assert "tls_disable_client_certs" in health assert 'storage "raft"' in code assert re.search(r"ui\s*=\s*false", code) assert 'audit "file" "stdout"' in code # --- команды оператора --------------------------------------------------------------- def _args(tmp_path: Path, **extra: object) -> argparse.Namespace: pki = tmp_path / "pki" pki.mkdir(exist_ok=True) for name in ("ca.crt", "bao-operator.crt", "bao-operator.key"): (pki / name).write_text("x", encoding="ascii") values = { "command": "bao-status", "address": "https://localhost:1", "project": "test", "operator_dir": str(tmp_path / "operator" / "openbao" / "test"), "pki_dir": str(pki), "inside": None, "wait": 0.0, } return argparse.Namespace(**{**values, **extra}) class _Http: """Подмена API: ответы по пути, журнал запросов без тел.""" address = "https://localhost:1" def __init__(self, state: dict) -> None: self.state = state self.calls: list[str] = [] def request(self, method, path, body=None, *, token=None, ok=(), timeout=None): self.calls.append(f"{method} {path}") if path == "sys/seal-status": return 200, dict(self.state) if path == "sys/health": return 200, {} if path == "sys/init": self.state |= {"initialized": True, "sealed": True, "t": 3, "n": 5} return 200, {"keys": [f"share-value-{n}" for n in range(5)], "root_token": "root-value"} # fmt: skip if path == "sys/unseal": if "key" in (body or {}): self.state["progress"] = self.state.get("progress", 0) + 1 self.state["sealed"] = self.state["progress"] < 3 return 200, {"sealed": self.state["sealed"]} raise AssertionError(path) @pytest.fixture def operator(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): def build(state: dict, **extra: object): http = _Http(state) monkeypatch.setattr(bao, "BaoHttp", lambda *_a, **_k: http) return bao.Operator(_args(tmp_path, **extra)), http return build def test_init_writes_0600_files_and_prints_no_secrets( operator, tmp_path, capsys ) -> None: target, http = operator({"initialized": False, "sealed": True}) assert target.init() == 0 directory = target.operator_dir assert stat.S_IMODE(directory.stat().st_mode) == 0o700 names = sorted(path.name for path in directory.iterdir()) assert names == [ "init-info", "root-token", *(f"unseal-share-{n}" for n in range(1, 6)), ] for path in directory.iterdir(): assert stat.S_IMODE(path.stat().st_mode) == 0o600, path.name out = capsys.readouterr().out assert "5 unseal shares, threshold 3" in out assert "unsealed OpenBao with 3 shares" in out assert "share-value" not in out assert "root-value" not in out # повтор ничего не меняет before = [path.read_bytes() for path in sorted(directory.iterdir())] assert target.init() == 0 assert [path.read_bytes() for path in sorted(directory.iterdir())] == before assert http.calls.count("PUT sys/init") == 1 def test_init_moves_stale_materials(operator, capsys) -> None: target, _ = operator({"initialized": False, "sealed": True}) target.operator_dir.mkdir(parents=True) (target.operator_dir / "root-token").write_text("old", encoding="ascii") assert target.init() == 0 stale = next(target.operator_dir.glob("stale-*")) assert (stale / "root-token").read_text(encoding="ascii") == "old" assert "moved materials of a previous initialization" in capsys.readouterr().out def test_ready_does_not_unseal(operator) -> None: target, http = operator({"initialized": True, "sealed": True, "t": 3}) with pytest.raises(bao.Sealed, match="run make bao-unseal"): target.ready() assert http.calls == ["GET sys/seal-status"] def test_unseal_needs_materials(operator) -> None: target, http = operator({"initialized": True, "sealed": True, "t": 3}) with pytest.raises(bao.BaoError, match="not enough unseal shares"): target.unseal() assert "PUT sys/unseal" not in http.calls target, _ = operator({"initialized": True, "sealed": False}) assert target.unseal() == 0 def test_materials_outside_the_run_are_refused(operator, tmp_path: Path) -> None: run = tmp_path / "run" inside = run / "operator" / "openbao" / "test" operator({}, operator_dir=str(inside), inside=str(run)) outside = ( tmp_path / "operator", run, run / ".." / "operator", Path.home() / ".config" / "vladimirceva-lab7" / "operator" / "openbao" / "x", ) for directory in outside: with pytest.raises(bao.Usage, match="is not inside"): operator({}, operator_dir=str(directory), inside=str(run)) # даже если «каталог прогона» — сам каталог оператора рабочего стенда home = Path.home() / ".config" / "vladimirceva-lab7" / "operator" with pytest.raises(bao.Usage, match="is not inside"): operator({}, operator_dir=str(home / "openbao" / "x"), inside=str(home)) def test_command_codes(monkeypatch: pytest.MonkeyPatch, tmp_path, capsys) -> None: def run(error: Exception | None) -> int: class Operator: def __init__(self, _args: argparse.Namespace) -> None: if error is not None: raise error def status(self) -> int: return 0 monkeypatch.setattr(bao, "Operator", Operator) return bao.run(_args(tmp_path)) assert run(None) == 0 assert run(bao.Sealed("OpenBao is sealed: run make bao-unseal")) == 2 assert run(bao.Usage("no file")) == 2 assert run(bao.BaoError("HTTP 500")) == 1 assert "bao: OpenBao is sealed: run make bao-unseal" in capsys.readouterr().out def test_lab7_has_operator_commands_and_missing_files_are_code_2( tmp_path: Path, ) -> None: for name in bao.COMMANDS: done = subprocess.run( [sys.executable, "scripts/lab7.py", f"bao-{name}", "--pki-dir", str(tmp_path)], cwd=ROOT, env={"PATH": os.environ["PATH"], "HOME": str(tmp_path)}, capture_output=True, text=True, check=False, timeout=60, ) # fmt: skip assert done.returncode == 2, (name, done.stderr) assert "run make pki-stand" in done.stdout, name def test_make_up_is_explicit_about_unseal() -> None: text = (ROOT / "Makefile").read_text(encoding="utf-8") up = text.split("\nup: ", 1)[1].split("\n\n", 1)[0] # перенос rotation-revocation: первой — проверка, что команда ротации не идёт assert up.splitlines()[0] == "rotation-idle env pki-stand bao-ready" assert "bao-unseal" not in up ready = text.split("\nbao-ready: ", 1)[1].split("\n\n", 1)[0] assert "bao-unseal" not in ready def test_instant_parses_docker_and_openbao_timestamps() -> None: first = bao._instant("2026-12-02T00:00:01.123456789Z") assert first < bao._instant("2026-12-02T00:00:01.2Z") assert first > bao._instant("2026-12-02T00:00:01Z") with pytest.raises(bao.BaoError): bao._instant("now") def test_temporary_stands_use_the_operator_command_of_their_run() -> None: for rel in ("student-tests/stand.py", "bench/common.py"): text = (ROOT / rel).read_text(encoding="utf-8") call = text.split('"bao-ready",', 1)[1].split("env=", 1)[0] for option in ( "--address", "--operator-dir", "--pki-dir", "--project", "--inside", ): assert option in call, (rel, option)