192 lines
6.7 KiB
Python
192 lines
6.7 KiB
Python
"""Minimal OpenBao (Vault-compatible) client: AppRole login and KV v2 reads.
|
|
|
|
Only the standard library is used, so the application image needs no extra
|
|
Vault SDK and no root token. The API/worker authenticate with a short-lived
|
|
AppRole role_id/secret_id pair delivered as files (Docker secrets) and receive
|
|
a token that carries a *scoped* policy: the token can read exactly one KV path
|
|
and nothing else (see infra/openbao/policies).
|
|
|
|
Failure model (lab7): if OpenBao is sealed or unreachable, bootstrap() logs and
|
|
returns False. The process keeps the file-based bootstrap values it already has,
|
|
so a sealed OpenBao degrades observably instead of taking the API down. A
|
|
background refresher re-logs in before token expiry and re-reads the secret,
|
|
which is what makes secret rotation work without rebuilding images.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import ssl
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from typing import Dict, Optional
|
|
|
|
from .config import settings
|
|
|
|
logger = logging.getLogger("messenger.openbao")
|
|
|
|
_lock = threading.RLock()
|
|
_token = ""
|
|
_token_expires_at = 0.0
|
|
_payload: Dict[str, str] = {}
|
|
|
|
_stop = threading.Event()
|
|
_thread: Optional[threading.Thread] = None
|
|
|
|
# Settings that a KV secret of the same name may override at runtime.
|
|
_OVERRIDABLE = {
|
|
"database_url",
|
|
"broker_url",
|
|
"s3_access_key_id",
|
|
"s3_secret_access_key",
|
|
"s3_endpoint",
|
|
"cache_url",
|
|
}
|
|
|
|
|
|
class OpenBaoError(RuntimeError):
|
|
"""Raised when OpenBao cannot be reached or the policy denies the read."""
|
|
|
|
|
|
def _ssl_context() -> ssl.SSLContext:
|
|
context = ssl.create_default_context(cafile=settings.bao_cacert or None)
|
|
if settings.bao_client_cert and settings.bao_client_key:
|
|
context.load_cert_chain(settings.bao_client_cert, settings.bao_client_key)
|
|
return context
|
|
|
|
|
|
def _call(method: str, path: str, token: str = "", body: Optional[dict] = None, timeout: float = 5.0) -> dict:
|
|
url = settings.bao_addr.rstrip("/") + path
|
|
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
request = urllib.request.Request(url, 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, timeout=timeout, context=_ssl_context()) as response:
|
|
raw = response.read()
|
|
return json.loads(raw) if raw else {}
|
|
except urllib.error.HTTPError as exc: # policy denied / bad path / sealed
|
|
detail = exc.read().decode("utf-8", "replace")[:200]
|
|
raise OpenBaoError(method + " " + path + " -> HTTP " + str(exc.code) + ": " + detail) from exc
|
|
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
raise OpenBaoError(method + " " + path + " -> " + type(exc).__name__) from exc
|
|
|
|
|
|
def login(force: bool = False) -> str:
|
|
"""Authenticate with AppRole and return a scoped client token."""
|
|
global _token, _token_expires_at
|
|
with _lock:
|
|
now = time.time()
|
|
if not force and _token and now < _token_expires_at - settings.bao_token_grace_seconds:
|
|
return _token
|
|
if not settings.bao_role_id or not settings.bao_secret_id:
|
|
raise OpenBaoError("AppRole role_id/secret_id are not configured")
|
|
response = _call(
|
|
"POST",
|
|
"/v1/auth/approle/login",
|
|
body={"role_id": settings.bao_role_id, "secret_id": settings.bao_secret_id},
|
|
)
|
|
auth = response.get("auth") or {}
|
|
token = auth.get("client_token") or ""
|
|
if not token:
|
|
raise OpenBaoError("AppRole login returned no client_token")
|
|
lease = int(auth.get("lease_duration") or 0)
|
|
_token = token
|
|
_token_expires_at = now + (lease if lease > 0 else 300)
|
|
# Log the policy names and TTL, never the token itself.
|
|
logger.info(
|
|
"OpenBao AppRole login ok (policies=%s ttl=%ss renewable=%s)",
|
|
auth.get("token_policies"),
|
|
lease,
|
|
auth.get("renewable"),
|
|
)
|
|
return _token
|
|
|
|
|
|
def read_kv(path: Optional[str] = None) -> Dict[str, str]:
|
|
"""Read a KV v2 secret and return its inner data mapping."""
|
|
target = path or settings.bao_secret_path
|
|
if "/data/" in target:
|
|
api_path = "/v1/" + target
|
|
else:
|
|
mount, _, remainder = target.partition("/")
|
|
api_path = "/v1/" + mount + "/data/" + remainder
|
|
response = _call("GET", api_path, token=login())
|
|
data = ((response.get("data") or {}).get("data")) or {}
|
|
if not isinstance(data, dict):
|
|
raise OpenBaoError("unexpected KV payload")
|
|
return {str(k): str(v) for k, v in data.items()}
|
|
|
|
|
|
def _apply(data: Dict[str, str]) -> None:
|
|
global _payload
|
|
_payload = dict(data)
|
|
for key, value in data.items():
|
|
if key in _OVERRIDABLE and isinstance(getattr(settings, key, None), str) and value:
|
|
setattr(settings, key, value)
|
|
|
|
|
|
def bootstrap() -> bool:
|
|
"""Fetch the service secret once at startup; never fatal."""
|
|
if not settings.bao_enabled:
|
|
logger.info("OpenBao not configured; using file-based bootstrap secrets")
|
|
return False
|
|
with _lock:
|
|
try:
|
|
data = read_kv()
|
|
except OpenBaoError as exc:
|
|
logger.error("OpenBao secret fetch failed (%s); keeping file values", exc)
|
|
return False
|
|
_apply(data)
|
|
logger.info("OpenBao secret %s applied (%d keys)", settings.bao_secret_path, len(data))
|
|
return True
|
|
|
|
|
|
def refresh_once() -> bool:
|
|
"""Re-login if needed and re-read the secret (rotation/renewal path)."""
|
|
if not settings.bao_enabled:
|
|
return False
|
|
with _lock:
|
|
try:
|
|
data = read_kv()
|
|
except OpenBaoError as exc:
|
|
logger.warning("OpenBao refresh failed (%s)", exc)
|
|
return False
|
|
_apply(data)
|
|
return True
|
|
|
|
|
|
def value(key: str, default: str = "") -> str:
|
|
return _payload.get(key, default)
|
|
|
|
|
|
def _loop() -> None:
|
|
while not _stop.wait(settings.bao_refresh_seconds):
|
|
try:
|
|
refresh_once()
|
|
except Exception as exc: # noqa: BLE001 - refresher must never die
|
|
logger.warning("OpenBao refresher error: %s", type(exc).__name__)
|
|
|
|
|
|
def start_refresher() -> None:
|
|
global _thread
|
|
if not settings.bao_enabled or settings.bao_refresh_seconds <= 0:
|
|
return
|
|
if _thread is not None and _thread.is_alive():
|
|
return
|
|
_stop.clear()
|
|
_thread = threading.Thread(target=_loop, name="openbao-refresher", daemon=True)
|
|
_thread.start()
|
|
logger.info("OpenBao refresher started (every %ss)", settings.bao_refresh_seconds)
|
|
|
|
|
|
def stop_refresher() -> None:
|
|
global _thread
|
|
_stop.set()
|
|
if _thread is not None:
|
|
_thread.join(timeout=2)
|
|
_thread = None
|