"""Read runtime secrets from OpenBao with AppRole. The root token is never used.""" from __future__ import annotations import json import logging import ssl import urllib.error import urllib.request from app import config logger = logging.getLogger("messenger.bao") _token = "" _ttl = 0 def _context() -> ssl.SSLContext: cafile = config.BAO_CACERT or config.TLS_CA_FILE if not cafile: raise RuntimeError("OpenBao CA file is not set") context = ssl.create_default_context(cafile=cafile) context.check_hostname = True context.verify_mode = ssl.CERT_REQUIRED context.minimum_version = ssl.TLSVersion.TLSv1_2 return context def _request(method: str, path: str, body: dict | None = None, token: str = "") -> dict: data = None if body is None else json.dumps(body).encode("utf-8") request = urllib.request.Request( config.BAO_ADDR.rstrip("/") + path, data=data, method=method, ) request.add_header("Content-Type", "application/json") if token: request.add_header("X-Vault-Token", token) try: with urllib.request.urlopen(request, context=_context(), timeout=5) as response: raw = response.read() except urllib.error.HTTPError as exc: raise RuntimeError("OpenBao request failed with HTTP %s" % exc.code) from None except urllib.error.URLError: raise RuntimeError("OpenBao is unreachable or the TLS check failed") from None if not raw: return {} return json.loads(raw.decode("utf-8")) def _assign(data: dict) -> None: mapping = { "database_url": "DATABASE_URL", "redis_url": "REDIS_URL", "broker_url": "BROKER_URL", "s3_access_key_id": "S3_ACCESS_KEY_ID", "s3_secret_access_key": "S3_SECRET_ACCESS_KEY", } for field, attr in mapping.items(): value = data.get(field) if isinstance(value, str) and value: setattr(config, attr, value) def apply() -> None: """Login and overlay secrets. No-op when BAO_ADDR is empty (local process without the stand).""" global _token, _ttl if not config.BAO_ADDR: return if not config.BAO_ROLE_ID or not config.BAO_SECRET_ID: raise RuntimeError("OpenBao AppRole role_id and secret_id files are required") login = _request( "POST", "/v1/auth/approle/login", {"role_id": config.BAO_ROLE_ID, "secret_id": config.BAO_SECRET_ID}, ) auth = login.get("auth") or {} token = auth.get("client_token") or "" if not token: raise RuntimeError("OpenBao login did not return a client token") payload = _request("GET", "/v1/" + config.BAO_SECRET_PATH.strip("/"), token=token) data = ((payload.get("data") or {}).get("data")) or {} if not isinstance(data, dict) or not data: raise RuntimeError("OpenBao secret is empty or the policy denied it") _assign(data) _token = token _ttl = int(auth.get("lease_duration") or 0) logger.info("loaded OpenBao secret path=%s ttl=%s", config.BAO_SECRET_PATH, _ttl) def renew_once() -> None: global _token if not config.BAO_ADDR or not _token: return try: _request("POST", "/v1/auth/token/renew-self", {}, token=_token) logger.info("renewed OpenBao token") except RuntimeError: logger.warning("OpenBao renew failed; logging in again") apply() async def renew_loop() -> None: import asyncio while True: delay = max(30, int(_ttl / 3) if _ttl else 60) await asyncio.sleep(delay) await asyncio.to_thread(renew_once)