import json import os import secrets import ssl import time from pathlib import Path from urllib.request import Request,urlopen from urllib.error import HTTPError,URLError root = Path(__file__).resolve().parents[1] local = root/".local" ctx = ssl.create_default_context(cafile=str(local/"ca.crt")) base = "https://127.0.0.1:"+os.getenv("BAO_PORT","18200")+"/v1/" def call(path,body=None,token=None,method=None): headers = {"Content-Type":"application/json"} if token: headers["X-Vault-Token"]=token req = Request(base+path,data=None if body is None else json.dumps(body).encode(),headers=headers,method=method) with urlopen(req,context=ctx,timeout=30) as r: return json.loads(r.read() or b"{}") for _ in range(60): try: initialized = call("sys/init")["initialized"] break except URLError: time.sleep(1) else: raise SystemExit("OpenBao unavailable") admin = local/"operator.json" if not initialized: init = call("sys/init",dict(secret_shares=1,secret_threshold=1)) admin.write_text(json.dumps(init)) init = json.loads(admin.read_text()) if call("sys/seal-status")["sealed"]: call("sys/unseal",{"key":init["keys"][0]}) token = init["root_token"] config = json.loads((local/"services.json").read_text()) for path,kind in [("sys/auth/approle","approle"),("sys/mounts/messenger","kv")]: try: call(path,{"type":kind},token) except HTTPError as exc: if exc.code!=400: raise for role,values in config.items(): call("messenger/"+role,values,token) policy = 'path "messenger/'+role+'" { capabilities = ["read"] }' call("sys/policies/acl/"+role,{"policy":policy},token,method="PUT") call("auth/approle/role/"+role,dict(token_policies=[role],token_ttl="10m",token_max_ttl="10m"),token) role_id = call("auth/approle/role/"+role+"/role-id",token=token)["data"]["role_id"] secret_id = call("auth/approle/role/"+role+"/secret-id",{},token)["data"]["secret_id"] (local/(role+"-role.json")).write_text(json.dumps(dict(role_id=role_id,secret_id=secret_id))) print("OpenBao unsealed; scoped AppRole credentials installed")