"""Операторская настройка OpenBao по TLS с локальным хранением unseal-материала.""" import json import os from pathlib import Path import ssl import time from urllib.error import HTTPError from urllib.request import HTTPSHandler, Request, build_opener from app.core.bao import NoRedirect ROOT = Path(__file__).resolve().parents[1] TLS = ROOT / "secrets/tls" ROLES = ("api", "worker", "publisher", "cleanup") class Bao: def __init__(self, port: int, certificate: Path | None = None, key: Path | None = None): self.address = f"https://localhost:{port}/v1/" context = ssl.create_default_context(cafile=str(TLS / "ca.crt")) if certificate: context.load_cert_chain(certificate, key) self.opener = build_opener(NoRedirect(), HTTPSHandler(context=context)) def call(self, path, payload=None, *, token=None, method=None): headers = {"Content-Type": "application/json"} if token: headers["X-Vault-Token"] = token request = Request(self.address + path, headers=headers, method=method, data=None if payload is None else json.dumps(payload).encode()) with self.opener.open(request, timeout=5) as response: body = response.read() return json.loads(body) if body else None def operator_token(port: int) -> str: config = ROOT / f"secrets/bao-operator/operator-{port}.json" return json.loads(config.read_text())["root_token"] def bootstrap(port: int, *, unseal_only: bool = False) -> None: call = Bao(port).call deadline = time.monotonic() + 30 while True: try: status = call("sys/seal-status") break except OSError: if time.monotonic() >= deadline: raise RuntimeError("OpenBao недоступен") from None time.sleep(0.5) directory = ROOT / "secrets/bao-operator" directory.mkdir(mode=0o700, exist_ok=True) # После удаления тома прежние ключи сохраняются отдельным operator-файлом. material = directory / f"operator-{port}.json" if not status["initialized"]: if unseal_only: raise RuntimeError("OpenBao ещё не инициализирован") if material.exists(): material.rename(directory / f"operator-{port}-{time.time_ns()}.json") descriptor = os.open(material, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) try: result = call("sys/init", {"secret_shares": 1, "secret_threshold": 1}) with os.fdopen(descriptor, "w") as target: descriptor = -1 json.dump(result, target) finally: if descriptor != -1: os.close(descriptor) credentials = json.loads(material.read_text()) if status["sealed"] or not status["initialized"]: call("sys/unseal", {"key": credentials["keys_base64"][0]}) if unseal_only: print("OpenBao распечатан") return token = credentials["root_token"] if "cert/" not in call("sys/auth", token=token): call("sys/auth/cert", {"type": "cert"}, token=token) if "messenger/" not in call("sys/mounts", token=token): call("sys/mounts/messenger", {"type": "kv", "options": {"version": "2"}}, token=token) for role in ROLES: path = f"messenger/data/{role}" policy = (ROOT / "infra/openbao/read-secret.hcl").read_text().replace("SERVICE_ROLE", role) call(f"sys/policies/acl/{role}", {"policy": policy}, token=token) call(f"auth/cert/certs/{role}", { "certificate": (TLS / f"{role}-bao.crt").read_text(), "token_policies": [role], "token_no_default_policy": True, "token_ttl": "10m", "token_max_ttl": "10m", }, token=token) value = (ROOT / "secrets" / f"{role}_db_password").read_text().strip() call(path, {"data": {"db_password": value}}, token=token) print("OpenBao готов: роли и KV настроены") if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--port", type=int, default=18200) parser.add_argument("--unseal-only", action="store_true") args = parser.parse_args() try: bootstrap(args.port, unseal_only=args.unseal_only) except HTTPError as error: raise SystemExit(f"Ошибка OpenBao HTTP {error.code}") from None