#!/usr/bin/env python3 """Explicit operator init/unseal and scoped cert-auth configuration (no dev-mode).""" import json import os from pathlib import Path import ssl import urllib.request import urllib.error os.chdir(Path(__file__).resolve().parents[1]) os.umask(0o077) ctx=ssl.create_default_context(cafile='secrets/ca.crt') addr='https://localhost:18200/v1/' def request(path,data=None,method=None,token=None): headers={'Content-Type':'application/json'} if token: headers['X-Vault-Token']=token req=urllib.request.Request(addr+path,data=json.dumps(data).encode() if data is not None else None,headers=headers,method=method) with urllib.request.urlopen(req,context=ctx,timeout=10) as response: raw=response.read() return json.loads(raw) if raw else {} p=Path('operator/bao-init.json') if not request('sys/init')['initialized']: if p.exists(): raise SystemExit('Existing operator keys with new storage: inspect manually') result=request('sys/init',{'secret_shares':3,'secret_threshold':2}) p.write_text(json.dumps(result)); p.chmod(0o600) if not p.exists(): raise SystemExit('Operator unseal keys required in operator/bao-init.json') state=json.loads(p.read_text()) if request('sys/seal-status')['sealed']: for key in state['keys'][:2]: request('sys/unseal',{'key':key}) if '--unseal-only' in __import__('sys').argv: print('OpenBao unsealed with persistent storage.'); raise SystemExit(0) token=state['root_token'] mounts=request('sys/mounts',token=token) if 'secret/' not in mounts: request('sys/mounts/secret',{'type':'kv','options':{'version':'2'}},token=token) auth=request('sys/auth',token=token) if 'cert/' not in auth: request('sys/auth/cert',{'type':'cert'},token=token) for role,bundle in json.loads(Path('operator/bundles.json').read_text()).items(): policy=f'path "secret/data/{role}" {{ capabilities = ["read"] }}\npath "auth/token/revoke-self" {{ capabilities = ["update"] }}\n' Path('infra/openbao/'+role+'.hcl').write_text(policy) request('sys/policies/acl/'+role,{'policy':policy},token=token) request('auth/cert/certs/'+role,{'display_name':role,'certificate':Path('secrets/'+role+'/service.crt').read_text(),'allowed_uri_sans':['spiffe://lab7/'+role],'token_policies':[role],'token_no_default_policy':True,'token_ttl':'5m','token_max_ttl':'10m'},token=token) request('secret/data/'+role,{'data':bundle},token=token) print('OpenBao initialized/unsealed; leaf-bound service policies configured, token TTL 5m/max 10m.')