#!/usr/bin/env python3 """Operator init/unseal/policies and cert-auth KV bootstrap. Root stays on host.""" import argparse,json,ssl,time,urllib.error,urllib.request from pathlib import Path ROOT=Path(__file__).resolve().parents[1];OPS=ROOT/'secrets/operator' def call(path,data=None,token=None,method=None): ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca/ca.crt')) ctx.load_cert_chain(str(ROOT/'secrets/tls/operator/server.crt'),str(ROOT/'secrets/tls/operator/server.key')) headers={'Content-Type':'application/json'} if token:headers['X-Vault-Token']=token req=urllib.request.Request('https://localhost:18200/v1/'+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=5) as response: body=response.read();return json.loads(body) if body else {} def root_token():return json.loads((OPS/'bao_init.json').read_text())['root_token'] def unseal(): if not call('sys/init')['initialized']: material=call('sys/init',{'secret_shares':1,'secret_threshold':1},method='PUT') p=OPS/'bao_init.json';p.write_text(json.dumps(material));p.chmod(0o600) if call('sys/seal-status')['sealed']: call('sys/unseal',{'key':json.loads((OPS/'bao_init.json').read_text())['keys'][0]}) def configure(): unseal();token=root_token() mounts=call('sys/mounts',token=token) if 'secret/' not in mounts:call('sys/mounts/secret',{'type':'kv','options':{'version':'2'}},token) auth=call('sys/auth',token=token) if 'cert/' not in auth:call('sys/auth/cert',{'type':'cert'},token) roles=json.loads((OPS/'roles.json').read_text()) for role,values in roles.items(): policy=(ROOT/'infra/openbao/policies'/(role+'.hcl')).read_text() call('sys/policies/acl/'+role,{'policy':policy},token,method='PUT') names=['api-a','api-b'] if role=='api' else [role] call('auth/cert/certs/'+role,{'certificate':(ROOT/'secrets/ca/ca.crt').read_text(),'allowed_common_names':names,'token_policies':[role],'token_ttl':60,'token_max_ttl':120},token) call('secret/data/'+role,{'data':values},token) print('PASS: OpenBao initialized/unsealed; scoped cert roles and KV configured') if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('action',choices=['init','unseal','seal']);args=p.parse_args() if args.action=='init':configure() elif args.action=='unseal':unseal();print('PASS: operator unseal complete') else:call('sys/seal',{},root_token());print('PASS: OpenBao sealed')