63 lines
3.0 KiB
Python
Executable File
63 lines
3.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Operator-only init/unseal/policies and scoped workload provisioning. Never print secrets."""
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import ssl
|
|
import time
|
|
import urllib.request
|
|
import urllib.error
|
|
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
SECRETS=ROOT/'secrets'
|
|
OPERATOR=SECRETS/'operator'
|
|
|
|
|
|
def request(method,path,body=None,token=True):
|
|
context=ssl.create_default_context(cafile=str(SECRETS/'trust/ca.crt'))
|
|
context.load_cert_chain(str(SECRETS/'pki/operator/tls.crt'),str(SECRETS/'pki/operator/tls.key'))
|
|
headers={'Content-Type':'application/json'}
|
|
if token:
|
|
headers['X-Vault-Token']=json.loads((OPERATOR/'bao-init.json').read_text())['root_token']
|
|
req=urllib.request.Request('https://localhost:8200/v1/'+path,data=None if body is None else json.dumps(body).encode(),headers=headers,method=method)
|
|
with urllib.request.urlopen(req,context=context,timeout=5) as response:
|
|
raw=response.read()
|
|
return json.loads(raw) if raw else {}
|
|
|
|
|
|
def bootstrap():
|
|
end=time.monotonic()+60
|
|
while True:
|
|
try: status=request('GET','sys/init',token=False);break
|
|
except (OSError,urllib.error.URLError):
|
|
if time.monotonic()>end: raise RuntimeError('OpenBao TLS endpoint not ready') from None
|
|
time.sleep(.5)
|
|
path=OPERATOR/'bao-init.json'
|
|
if not status['initialized']:
|
|
result=request('POST','sys/init',{'secret_shares':1,'secret_threshold':1},token=False)
|
|
path.write_text(json.dumps(result));path.chmod(0o600)
|
|
if not path.exists(): raise RuntimeError('Operator init material is required; no automatic reset')
|
|
status=request('GET','sys/seal-status',token=False)
|
|
if status['sealed']:
|
|
result=json.loads(path.read_text())
|
|
request('POST','sys/unseal',{'key':result['keys_base64'][0]},token=False)
|
|
mounts=request('GET','sys/mounts')
|
|
if 'secret/' not in mounts: request('POST','sys/mounts/secret',{'type':'kv','options':{'version':'2'}})
|
|
auth=request('GET','sys/auth')
|
|
if 'cert/' not in auth: request('POST','sys/auth/cert',{'type':'cert'})
|
|
values=json.loads((OPERATOR/'workloads.json').read_text())
|
|
for role in ('api','worker','relay'):
|
|
policy='path "secret/data/'+role+'" { capabilities = ["read"] }'
|
|
request('PUT','sys/policies/acl/'+role,{'policy':policy})
|
|
request('POST','auth/cert/certs/'+role,{'certificate':(SECRETS/'pki'/role/'tls.crt').read_text(),
|
|
'allowed_common_names':[role],'allowed_dns_sans':[role],
|
|
'token_policies':[role],'token_ttl':'60s','token_max_ttl':'300s','token_explicit_max_ttl':'300s'})
|
|
request('POST','secret/data/'+role,{'data':values[role]})
|
|
print('OpenBao initialized/unsealed; scoped cert auth and KV policies ready. Values hidden.')
|
|
|
|
|
|
if __name__=='__main__':
|
|
parser=argparse.ArgumentParser();parser.add_argument('action',choices=['bootstrap','seal','unseal'],default='bootstrap',nargs='?');args=parser.parse_args()
|
|
if args.action=='seal': request('PUT','sys/seal',{});print('OpenBao sealed')
|
|
else: bootstrap()
|