#!/usr/bin/env python3 """Operator-only OpenBao bootstrap, unseal and KV operations over verified HTTPS.""" import argparse import base64 import fcntl import json import os import ssl import stat from urllib.error import HTTPError from urllib.request import HTTPSHandler, Request, build_opener from pki import STATE BASE = os.environ.get("LAB7_OPENBAO_URL", "https://localhost:18200").rstrip("/") + "/v1/" OPERATOR = STATE / "operator/openbao-v2.json" INIT_ATTEMPT = OPERATOR.with_suffix(".init-attempted") STAGED_OPERATOR = OPERATOR.with_suffix(".pending") OPERATOR_LOCK = OPERATOR.with_suffix(".lock") def request(path, body=None, token=None, method=None, accepted=(), timeout=4): if not BASE.startswith("https://"): raise ValueError("OpenBao operator endpoint requires HTTPS") context = ssl.create_default_context(cafile=str(STATE / "trust/ca.crt")) # Existing lab roots omit Key Usage. Keep certificate and hostname # verification against the explicit lab CA on Python 3.13 and newer. context.verify_flags &= ~ssl.VERIFY_X509_STRICT headers = {"Content-Type": "application/json"} if token: headers["X-Vault-Token"] = token payload = None if body is None else json.dumps(body).encode() req = Request(BASE + path, data=payload, headers=headers, method=method) try: response = build_opener(HTTPSHandler(context=context)).open(req, timeout=timeout) except HTTPError as exc: if exc.code not in accepted: raise RuntimeError(f"OpenBao operation {path} returned {exc.code}") from None response = exc with response: data = response.read() return json.loads(data) if data else {} def status(): return request("sys/health", accepted=(429, 501, 503)) def private_operator_directory(): directory = OPERATOR.parent directory.mkdir(mode=0o700, exist_ok=True) metadata = directory.lstat() if (not stat.S_ISDIR(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) != 0o700 or metadata.st_uid != os.getuid()): raise RuntimeError("OpenBao operator directory must be owned by this user with mode 0700") return directory def validate_operator(material): try: encoded_shares = material["keys_base64"] token = material["root_token"] if isinstance(encoded_shares, list) and len(encoded_shares) == 3: shares = [base64.b64decode(share, validate=True) for share in encoded_shares] if len(set(shares)) == 3 and all(shares) and isinstance(token, str) and token: return material except (KeyError, TypeError, ValueError): pass raise RuntimeError("Invalid OpenBao operator material") def operator(): private_operator_directory() try: with os.fdopen(os.open(OPERATOR, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)) as file: metadata = os.fstat(file.fileno()) if (not stat.S_ISREG(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) != 0o600 or metadata.st_uid != os.getuid()): raise RuntimeError("OpenBao operator file must be owned by this user with mode 0600") return validate_operator(json.load(file)) except (OSError, ValueError): raise RuntimeError("OpenBao operator file is unavailable or unreadable; reconcile it before continuing") from None def initialize(): directory = private_operator_directory() if any(os.path.lexists(path) for path in (OPERATOR, INIT_ATTEMPT, STAGED_OPERATOR)): raise RuntimeError("Existing OpenBao v2 operator files or init attempt require manual reconciliation") directory_fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) try: parent_fd = os.open(directory.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) try: os.fsync(parent_fd) finally: os.close(parent_fd) # Reserve one attempt even if the server responds after a client timeout. with os.fdopen(os.open(INIT_ATTEMPT, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as marker: marker.write("OpenBao v2 initialization attempted\n") marker.flush() os.fsync(marker.fileno()) fd = os.open(STAGED_OPERATOR, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w+") as staged: os.fchmod(staged.fileno(), 0o600) os.fsync(directory_fd) material = validate_operator(request("sys/init", {"secret_shares": 3, "secret_threshold": 2}, timeout=180)) json.dump(material, staged) staged.flush() os.fsync(staged.fileno()) staged.seek(0) if json.load(staged) != material: raise RuntimeError("OpenBao operator file verification failed") # Hard-link publication is atomic and refuses to replace an existing file. os.link(STAGED_OPERATOR, OPERATOR) os.fsync(directory_fd) if operator() != material: raise RuntimeError("Published OpenBao operator file verification failed") STAGED_OPERATOR.unlink() os.fsync(directory_fd) except (OSError, RuntimeError, ValueError): raise RuntimeError( "OpenBao initialization did not complete locally. Preserve the operator files and " "check status before manual reconciliation. Initialization will not be retried." ) from None finally: os.close(directory_fd) def unseal(): if status().get("sealed"): for share in operator()["keys_base64"]: result = request("sys/unseal", {"key": share}) if not result["sealed"]: break else: raise RuntimeError("Unseal did not reach the configured threshold") def conninfo(role, password=None): value = password or (STATE / "postgres" / role).read_text().strip() return (f"host=postgres dbname=messenger user={role} password={value} " "sslmode=verify-full sslrootcert=/run/trust/ca.crt gssencmode=disable") def configure(): api_role = os.environ.get("LAB7_API_DB_ROLE", "api_blue") if api_role not in ("api_blue", "api_green"): raise RuntimeError("LAB7_API_DB_ROLE must be api_blue or api_green") token = operator()["root_token"] if "cert/" not in request("sys/auth", token=token): request("sys/auth/cert", {"type": "cert"}, token) if "kv/" not in request("sys/mounts", token=token): request("sys/mounts/kv", {"type": "kv", "options": {"version": "2"}}, token) ca = (STATE / "trust/ca.crt").read_text() for role in ("api-a", "api-b", "publisher", "worker", "recovery"): scope = "api" if role.startswith("api-") else role policy = (f'path "kv/data/messenger/{scope}" {{ capabilities = ["read"] }}\n' 'path "auth/token/renew-self" { capabilities = ["update"] }') policy_path = f"sys/policies/acl/{scope}" if not request(policy_path, token=token, accepted=(404,)).get("data"): request(policy_path, {"policy": policy}, token) cert_path = f"auth/cert/certs/{role}" if not request(cert_path, token=token, accepted=(404,)).get("data"): request(cert_path, {"certificate": ca, "allowed_dns_sans": [f"{role}.bao.lab"], "token_policies": [scope], "token_no_default_policy": True, "token_type": "service", "token_ttl": "20s", "token_explicit_max_ttl": "60s"}, token) for scope in ("api", "publisher", "worker", "recovery"): path = f"kv/data/messenger/{scope}" if request(path, token=token, accepted=(404,)).get("data"): continue data = {"database_url": conninfo(api_role if scope == "api" else scope)} if scope != "publisher": data.update(s3_user="lab-" + scope, s3_password=(STATE / "s3" / scope).read_text().strip()) request(path, {"options": {"cas": 0}, "data": data}, token) def prepare_local_dsn(): for role in ("migrator", "ops"): directory = STATE / role directory.mkdir(exist_ok=True) path = directory / "dsn" if not path.exists(): path.write_text(conninfo(role)) path.chmod(0o444) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("bootstrap", "unseal", "status", "local-dsn")) action = parser.parse_args().action if action == "local-dsn": prepare_local_dsn() return if action in ("bootstrap", "unseal"): private_operator_directory() fd = os.open(OPERATOR_LOCK, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, "w") as lock: fcntl.flock(lock, fcntl.LOCK_EX) if action == "bootstrap" and not status()["initialized"]: initialize() unseal() if action == "bootstrap": configure() state = status() print(f"OpenBao initialized={state['initialized']} sealed={state['sealed']}") if __name__ == "__main__": main()