forked from mtusi2026/mtusi2026lab7
30 lines
1.4 KiB
Python
30 lines
1.4 KiB
Python
"""Small AppRole client used at process startup; no root token is accepted here."""
|
|
import json, os, urllib.request
|
|
from pathlib import Path
|
|
|
|
_cache = {}
|
|
|
|
def _read(name):
|
|
path = os.getenv(name)
|
|
return Path(path).read_text().strip() if path else None
|
|
|
|
def _call(path, method='GET', payload=None, token=None):
|
|
body = None if payload is None else json.dumps(payload).encode()
|
|
req = urllib.request.Request(os.environ.get('BAO_ADDR', 'http://openbao:8200') + path,
|
|
data=body, method=method,
|
|
headers={'Content-Type':'application/json', **({'X-Vault-Token': token} if token else {})})
|
|
with urllib.request.urlopen(req, timeout=3) as response:
|
|
return json.loads(response.read() or b'{}')
|
|
|
|
def secret(name):
|
|
if name in _cache: return _cache[name]
|
|
role_id, secret_id = _read('BAO_ROLE_ID_FILE'), _read('BAO_SECRET_ID_FILE')
|
|
if not role_id or not secret_id:
|
|
raise RuntimeError('AppRole credentials are required; refusing file-secret fallback')
|
|
login = _call('/v1/auth/approle/login', 'POST', {'role_id': role_id, 'secret_id': secret_id})
|
|
token = login['auth']['client_token']
|
|
data = _call('/v1/secret/data/' + os.getenv('BAO_SECRET_PATH', 'messenger/api'), token=token).get('data', {}).get('data', {})
|
|
if name not in data: raise RuntimeError('secret is not present in OpenBao: ' + name)
|
|
_cache[name] = data[name]
|
|
return data[name]
|