#!/usr/bin/env python3 """Initialize/unseal the local OpenBao as operator without printing credentials.""" import argparse import json import os from pathlib import Path import ssl import urllib.error import urllib.request ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / 'secrets' / 'openbao-operator.json' BASE = os.environ.get('BAO_OPERATOR_ADDR', 'https://localhost:18200').rstrip('/') TLS = ssl.create_default_context(cafile=str(ROOT / 'secrets' / 'ca.crt')) def request(path, body=None): data = None if body is None else json.dumps(body).encode() req = urllib.request.Request(BASE + '/v1/' + path, data=data, headers={'Content-Type': 'application/json'}, method='GET' if body is None else 'PUT') with urllib.request.urlopen(req, context=TLS, timeout=10) as response: return json.load(response) def main(): parser = argparse.ArgumentParser() parser.add_argument('action', choices=['init', 'unseal', 'status']) args = parser.parse_args() if args.action == 'init': if DATA.exists(): raise SystemExit('Operator credentials file exists; refusing to overwrite it.') if request('sys/init')['initialized']: raise SystemExit('OpenBao is already initialized. Recover operator credentials; do not reinitialize.') fd = os.open(DATA, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, 'w') as stream: result = request('sys/init', {'secret_shares': 3, 'secret_threshold': 2}) json.dump(result, stream) stream.flush() os.fsync(stream.fileno()) print('Initialized. Operator credentials stored locally in secrets/openbao-operator.json; protect and back them up.') elif args.action == 'unseal': data = json.loads(DATA.read_text()) for key in data['keys_base64'][:2]: state = request('sys/unseal', {'key': key}) if not state['sealed']: break if state['sealed']: raise SystemExit('OpenBao remains sealed.') print('OpenBao unsealed.') else: state = request('sys/seal-status') print('initialized=' + str(state['initialized']) + ' sealed=' + str(state['sealed'])) if __name__ == '__main__': main()