"""Fail-closed OpenBao AppRole bootstrap; token exists only in process memory. Never fall back to .env, a root token, or plaintext if OpenBao is sealed. Credentials are fetched on startup; rotating a KV value requires a controlled service restart, not a Docker image rebuild. Running processes keep their last valid DB/S3 credentials through a temporary Bao outage. """ import json import os import ssl from pathlib import Path from urllib.request import Request, urlopen ALLOWED = { 'api': {'DATABASE_URL','REDIS_URL','S3_ENDPOINT','S3_BUCKET','S3_ACCESS_KEY','S3_SECRET_KEY'}, 'worker': {'DATABASE_URL','S3_ENDPOINT','S3_BUCKET','S3_ACCESS_KEY','S3_SECRET_KEY', 'BROKER_HOST','BROKER_PORT','BROKER_USER','BROKER_PASSWORD'}, 'dispatcher': {'DATABASE_URL','S3_ENDPOINT','S3_BUCKET','S3_ACCESS_KEY','S3_SECRET_KEY', 'BROKER_HOST','BROKER_PORT','BROKER_USER','BROKER_PASSWORD'}, } def _json_request(url, context, payload=None, token=None): headers={'Accept':'application/json'} if payload is not None: headers['Content-Type']='application/json' if token: headers['X-Vault-Token']=token req=Request(url, data=json.dumps(payload).encode('utf-8') if payload is not None else None, headers=headers,method='POST' if payload is not None else 'GET') with urlopen(req,context=context,timeout=7) as r: return json.load(r) def load_runtime_secrets(role=None): role=role or os.getenv('BAO_ROLE') if role not in ALLOWED: raise RuntimeError('Invalid service secret role') addr=os.environ.get('BAO_ADDR','https://openbao:8200').rstrip('/') if not addr.startswith('https://'): raise RuntimeError('OpenBao transport must be TLS') context=ssl.create_default_context(cafile=os.environ['TLS_CA_FILE']) role_id=Path(os.environ['BAO_ROLE_ID_FILE']).read_text().strip() secret_id=Path(os.environ['BAO_SECRET_ID_FILE']).read_text().strip() if not role_id or not secret_id: raise RuntimeError('Missing AppRole credentials') auth=_json_request(addr+'/v1/auth/approle/login',context,{'role_id':role_id,'secret_id':secret_id}) token=auth['auth']['client_token'] if int(auth['auth']['lease_duration'])<=0: raise RuntimeError('AppRole token must have finite TTL') data=_json_request(addr+'/v1/kv/data/'+role,context,token=token)['data']['data'] if set(data)!=ALLOWED[role] or not all(isinstance(x,str) and x for x in data.values()): raise RuntimeError('OpenBao returned missing/extra/invalid credential fields') os.environ.update(data) return role