"""Explicit operator init/unseal/configure; no unseal material enters containers.""" import argparse import json import os import ssl import time import httpx from cryptography import x509 from scripts.bootstrap_security import ( OPERATOR, ROLES, ROOT, TRUST, ca, public, sign_intermediate, write_private, ) class Operator: def __init__(self): context = ssl.create_default_context(cafile=TRUST / "ca.pem") context.minimum_version = ssl.TLSVersion.TLSv1_3 context.load_cert_chain( OPERATOR / "client/cert.pem", OPERATOR / "client/key.pem" ) self.http = httpx.Client( base_url="https://localhost:" + os.getenv("BAO_PORT", "8207") + "/v1/", verify=context, trust_env=False, timeout=10, ) self.token = None def close(self): self.http.close() def call(self, method, path, payload=None, *, token=None): response = self.http.request( method, path, json=payload, headers={"X-Vault-Token": token} if token else {}, ) if response.status_code >= 300: raise RuntimeError( "Operator request denied/unavailable: " + path + " status " + str(response.status_code) ) return response.json() if response.content else {} def init(self): if self.call("GET", "sys/init")["initialized"]: return result = self.call( "POST", "sys/init", {"secret_shares": 3, "secret_threshold": 2} ) for index, key in enumerate(result["keys_base64"]): write_private( OPERATOR / ("unseal-" + str(index + 1) + ".json"), json.dumps({"key": key}) + "\n", ) write_private(OPERATOR / "bootstrap-root-token", result["root_token"]) def unseal(self): state = self.call("GET", "sys/seal-status") if not state["sealed"]: return for index in [1, 2]: share = json.loads( (OPERATOR / ("unseal-" + str(index) + ".json")).read_text() ) state = self.call("POST", "sys/unseal", {"key": share["key"]}) if not state["sealed"]: return raise RuntimeError("Unseal threshold not reached") def authenticate(self): cached = OPERATOR / "operator-token.json" if cached.exists(): data = json.loads(cached.read_text()) if data["expires_at"] > time.time() + 30: self.token = data["token"] return self.token result = self.call("POST", "auth/cert/login", {})["auth"] self.token = result["client_token"] write_private( cached, json.dumps( { "token": self.token, "expires_at": time.time() + result["lease_duration"], } ) + "\n", ) return self.token def authorized(self, method, path, payload=None): return self.call( method, path, payload, token=self.token or self.authenticate() ) def configure(self): marker = OPERATOR / "configured.json" if marker.exists(): self.authenticate() self.authorized("GET", "auth/token/lookup-self") return token = (OPERATOR / "bootstrap-root-token").read_text().strip() def root(method, path, payload=None): return self.call(method, path, payload, token=token) mounts = root("GET", "sys/mounts") mounts = mounts.get("data", mounts) if "secret/" not in mounts: root( "POST", "sys/mounts/secret", {"type": "kv", "options": {"version": "2"}}, ) if "pki/" not in mounts: root( "POST", "sys/mounts/pki", {"type": "pki", "config": {"max_lease_ttl": "720h"}}, ) auth = root("GET", "sys/auth") auth = auth.get("data", auth) if "cert/" not in auth: root("POST", "sys/auth/cert", {"type": "cert"}) issuer_marker = OPERATOR / "initial-issuer.json" if not issuer_marker.exists(): csr = root( "POST", "pki/intermediate/generate/internal", { "common_name": "Messenger service intermediate", "key_type": "ec", "key_bits": 256, }, )["data"]["csr"] key, cert = ca() intermediate = sign_intermediate( key, cert, x509.load_pem_x509_csr(csr.encode()) ) imported = root( "POST", "pki/intermediate/set-signed", { "certificate": ( public(intermediate) + public(cert) ).decode() }, ) issuers = imported["data"]["imported_issuers"] selected = None for issuer in issuers: details = root("GET", "pki/issuer/" + issuer)["data"] loaded = x509.load_pem_x509_certificate( details["certificate"].encode() ) if loaded.serial_number == intermediate.serial_number: selected = issuer assert selected, "Imported signing intermediate not found" root( "POST", "pki/config/issuers", {"default": selected, "default_follows_latest_issuer": False}, ) write_private( issuer_marker, json.dumps( { "configured": True, "imported_issuers": imported.get("data", {}).get( "imported_issuers", [] ), } ) + "\n", ) _, cert = ca() material = json.loads((OPERATOR / "service-secrets.json").read_text()) for role, cfg in ROLES.items(): policy = ( ROOT / "infra/openbao/policies" / (role + ".hcl") ).read_text() if cfg["kv"]: root( "POST", "secret/data/" + role, {"data": material["services"][role]["values"]}, ) root( "PUT", "sys/policies/acl/messenger-" + role, {"policy": policy} ) root( "POST", "pki/roles/" + role, { "allowed_domains": cfg["dns"], "allow_bare_domains": True, "allow_subdomains": False, "allow_wildcard_certificates": False, "allow_any_name": False, "allow_localhost": "localhost" in cfg["dns"], "allow_ip_sans": bool(cfg.get("ip")), "allowed_uri_sans": ["spiffe://messenger/" + role], "enforce_hostnames": True, "key_type": "ec", "key_bits": 256, "server_flag": True, "client_flag": True, "ttl": "120s", "max_ttl": "120s", "issuer_ref": "default", }, ) root( "POST", "auth/cert/certs/" + role + "-v1", { "display_name": role, "certificate": public(cert).decode(), "allowed_common_names": [role], "allowed_uri_sans": ["spiffe://messenger/" + role], "token_policies": ["messenger-" + role], "token_ttl": "120s", "token_max_ttl": "600s", "token_no_default_policy": True, }, ) operator_policy = ( ROOT / "infra/openbao/policies/operator.hcl" ).read_text() root( "PUT", "sys/policies/acl/messenger-operator", {"policy": operator_policy}, ) root( "POST", "auth/cert/certs/operator-v1", { "display_name": "operator", "certificate": public(cert).decode(), "allowed_common_names": ["operator"], "allowed_uri_sans": ["spiffe://messenger/operator"], "token_policies": ["messenger-operator"], "token_ttl": "900s", "token_max_ttl": "3600s", "token_no_default_policy": True, }, ) audit = root("GET", "sys/audit") audit = audit.get("data", audit) if "file/" not in audit: root( "PUT", "sys/audit/file", { "type": "file", "options": { "file_path": "/data/audit/audit.log", "mode": "0600", }, }, ) created = root( "POST", "auth/token/create-orphan", { "policies": ["messenger-operator"], "ttl": "900s", "renewable": True, "no_default_policy": True, }, )["auth"] write_private( OPERATOR / "operator-token.json", json.dumps( { "token": created["client_token"], "expires_at": time.time() + created["lease_duration"], } ) + "\n", ) root("POST", "auth/token/revoke-self", {}) write_private( marker, json.dumps({"configured": True, "root_token_revoked": True}) + "\n", ) (OPERATOR / "bootstrap-root-token").unlink() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "action", choices=["init", "unseal", "configure", "status", "seal"] ) args = parser.parse_args() operator = Operator() try: if args.action == "init": operator.init() operator.unseal() operator.configure() elif args.action == "unseal": operator.unseal() elif args.action == "configure": operator.configure() elif args.action == "seal": operator.authorized("POST", "sys/seal", {}) else: state = operator.call("GET", "sys/seal-status") print( json.dumps( { k: state[k] for k in [ "initialized", "sealed", "version", "storage_type", ] if k in state } ) ) if args.action != "status": print( "Operator action completed; no tokens or unseal shares printed" ) finally: operator.close() if __name__ == "__main__": main()