"""Local operator-only OpenBao initialization and manual unseal on Windows.""" import argparse import json import ssl import subprocess import time import urllib.error import urllib.request from pathlib import Path PRIVATE = Path("secrets") RECOVERY = PRIVATE / "operator" / "openbao.dpapi" ADDRESS = "https://localhost:8200" DPAPI = """ $ErrorActionPreference = 'Stop' Add-Type -AssemblyName System.Security $bytes = [Convert]::FromBase64String([Console]::In.ReadToEnd()) $result = [Security.Cryptography.ProtectedData]::ACTION( $bytes, $null, [Security.Cryptography.DataProtectionScope]::CurrentUser) [Console]::Write([Convert]::ToBase64String($result)) """ def protect(data, action): import base64 proc = subprocess.run( ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", DPAPI.replace("ACTION", action)], input=base64.b64encode(data), capture_output=True, check=True, ) return base64.b64decode(proc.stdout, validate=True) def request(path, method="GET", payload=None, token=None): context = ssl.create_default_context(cafile=PRIVATE / "ca/server.crt") headers = {"Content-Type": "application/json"} if token: headers["X-Vault-Token"] = token opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=context)) req = urllib.request.Request(ADDRESS + "/v1/" + path, data=None if payload is None else json.dumps(payload).encode(), headers=headers, method=method) try: with opener.open(req, timeout=5) as response: body = response.read() except urllib.error.HTTPError as exc: raise RuntimeError(f"OpenBao {method} {path} returned HTTP {exc.code}") from None return json.loads(body) if body else {} def seal_status(): for attempt in range(20): try: return request("sys/seal-status") except (urllib.error.URLError, OSError): if attempt == 19: raise RuntimeError("OpenBao TLS listener is unavailable") from None time.sleep(1) def configure(token): if "lab7/" not in request("sys/mounts", token=token): request("sys/mounts/lab7", "POST", {"type": "kv", "options": {"version": "2"}}, token) if "cert/" not in request("sys/auth", token=token): request("sys/auth/cert", "POST", {"type": "cert"}, token) cert_ca = (PRIVATE / "ca/bao.crt").read_text(encoding="ascii") for role in ("api", "worker"): policy = f"lab7-{role}" request(f"sys/policies/acl/{policy}", "PUT", {"policy": Path(f"infra/openbao/{role}.hcl").read_text(encoding="ascii")}, token) request(f"auth/cert/certs/{role}", "POST", { "certificate": cert_ca, "allowed_dns_sans": [f"bao-{role}"], "token_policies": [policy], "token_no_default_policy": True, "token_ttl": 300, "token_max_ttl": 300, }, token) data = json.loads((PRIVATE / f"bao-seed/{role}.json").read_bytes()) request(f"lab7/data/{role}", "POST", {"data": data}, token) print("PASS: persistent KV v2, independent certificate auth, scoped policies, 300s max TTL") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("bootstrap", "unseal", "status")) args = parser.parse_args() status = seal_status() print(f"OpenBao {status['version']}: initialized={status['initialized']} sealed={status['sealed']}") if args.action == "status": return if not status["initialized"]: if args.action != "bootstrap" or RECOVERY.exists(): raise SystemExit("Use explicit bootstrap with matching local operator state") RECOVERY.parent.mkdir(parents=True, exist_ok=True) # Verify local DPAPI before creating operator material. probe = b"lab7" if protect(protect(probe, "Protect"), "Unprotect") != probe: raise RuntimeError("DPAPI self-check failed") recovery = request("sys/init", "PUT", {"secret_shares": 3, "secret_threshold": 2}) RECOVERY.write_bytes(protect(json.dumps(recovery).encode(), "Protect")) print("PASS: initialized file storage, 2-of-3 shares encrypted for local Windows operator") recovery = json.loads(protect(RECOVERY.read_bytes(), "Unprotect")) if status["sealed"]: for share in recovery["keys_base64"][:2]: result = request("sys/unseal", "PUT", {"key": share}) if result["sealed"]: raise RuntimeError("Unseal did not finish") print("PASS: operator unseal completed") if args.action == "bootstrap": configure(recovery["root_token"]) if __name__ == "__main__": main()