forked from mtusi2026/mtusi2026lab7
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия: - внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial; - TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL), Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA; - OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь; - роли БД, S3-политики и права брокера по принципу минимальных прав; - Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS; - hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия; - отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
162 lines
7.5 KiB
Python
162 lines
7.5 KiB
Python
"""OpenBao client for the services (lab7): cert auth -> short-lived token -> read ONE scoped KV v2 secret.
|
|
|
|
Bootstrap trust: the only material a service gets from the operator is its TLS client certificate (Docker secret).
|
|
It is also its identity for RabbitMQ (EXTERNAL) and LB->API mTLS is separate. There is no "secret to get secrets"
|
|
in the image or in .env: no token, no AppRole SecretID.
|
|
|
|
login POST /v1/auth/cert/login (client certificate, role = BAO_AUTH_ROLE) -> token (TTL 15 min, max 1 h)
|
|
read GET /v1/messenger/data/<BAO_KV_PATH> (policy messenger-<role>: read own path only)
|
|
refresh every BAO_REFRESH_SECONDS: renew-self (or re-login near max TTL), re-read metadata; a new KV version
|
|
(rotation) is delivered to registered callbacks without a restart
|
|
sealed / unreachable OpenBao: the process keeps the secrets it already holds (bounded: existing DB/S3/broker
|
|
sessions continue); a NEW process waits up to BAO_STARTUP_TIMEOUT_SECONDS and then exits non-zero.
|
|
Secret values are never logged; only paths, versions, TTLs and error classes.
|
|
"""
|
|
import json
|
|
import logging
|
|
import os
|
|
import ssl
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from typing import Callable, Dict, List, Optional
|
|
|
|
log = logging.getLogger("messenger.openbao")
|
|
|
|
|
|
class OpenBaoError(Exception):
|
|
pass
|
|
|
|
|
|
class OpenBao:
|
|
def __init__(self) -> None:
|
|
self.addr = os.environ["BAO_ADDR"].rstrip("/")
|
|
self.role = os.environ["BAO_AUTH_ROLE"]
|
|
self.path = os.environ["BAO_KV_PATH"]
|
|
self.mount = os.environ.get("BAO_KV_MOUNT", "messenger")
|
|
self.ctx = ssl.create_default_context(cafile=os.environ.get("TLS_CA_FILE", "/run/secrets/ca.crt"))
|
|
self.ctx.load_cert_chain(os.environ.get("TLS_CLIENT_CERT_FILE", "/run/secrets/client.crt"),
|
|
os.environ.get("TLS_CLIENT_KEY_FILE", "/run/secrets/client.key"))
|
|
self.token: Optional[str] = None
|
|
self.token_expires = 0.0
|
|
self.data: Dict[str, str] = {}
|
|
self.version = 0
|
|
self.callbacks: List[Callable[[Dict[str, str]], None]] = []
|
|
self.state = {"available": False, "last_ok": 0.0, "errors": 0, "logins": 0, "renewals": 0}
|
|
self.lock = threading.Lock()
|
|
|
|
# ------------------------------------------------------------------ HTTP
|
|
def _call(self, method: str, path: str, body: Optional[dict] = None, token: Optional[str] = None) -> dict:
|
|
req = urllib.request.Request(self.addr + path, method=method,
|
|
data=json.dumps(body).encode() if body is not None else None)
|
|
req.add_header("Content-Type", "application/json")
|
|
if token:
|
|
req.add_header("X-Vault-Token", token)
|
|
try:
|
|
with urllib.request.urlopen(req, context=self.ctx, timeout=5) as response:
|
|
raw = response.read()
|
|
except urllib.error.HTTPError as exc:
|
|
# 503 = sealed / standby, 403 = denied or expired token, 400 = cert not accepted for the role
|
|
raise OpenBaoError("HTTP %d on %s" % (exc.code, path.split("?")[0])) from None
|
|
except (urllib.error.URLError, OSError) as exc:
|
|
raise OpenBaoError("%s on %s" % (type(getattr(exc, "reason", exc)).__name__, path)) from None
|
|
return json.loads(raw) if raw else {}
|
|
|
|
def login(self) -> None:
|
|
auth = self._call("POST", "/v1/auth/cert/login", {"name": self.role})["auth"]
|
|
now = time.time()
|
|
self.token = auth["client_token"]
|
|
self.token_expires = now + auth["lease_duration"]
|
|
self.state["logins"] += 1
|
|
log.info("openbao_login role=%s policies=%s ttl=%ds", self.role, ",".join(auth.get("policies", [])),
|
|
auth["lease_duration"])
|
|
|
|
def _ensure_token(self, interval: float) -> None:
|
|
now = time.time()
|
|
if self.token is None or now > self.token_expires - 1:
|
|
self.login()
|
|
return
|
|
if self.token_expires - now < 2 * interval + 5:
|
|
try:
|
|
auth = self._call("POST", "/v1/auth/token/renew-self", {}, self.token)["auth"]
|
|
self.token_expires = time.time() + auth["lease_duration"]
|
|
self.state["renewals"] += 1
|
|
if auth["lease_duration"] < 2 * interval + 5: # reached max TTL: authenticate again
|
|
self.login()
|
|
except OpenBaoError:
|
|
self.login()
|
|
|
|
def _read(self) -> None:
|
|
body = self._call("GET", "/v1/%s/data/%s" % (self.mount, self.path), token=self.token)["data"]
|
|
version = int(body["metadata"]["version"])
|
|
changed = version != self.version
|
|
with self.lock:
|
|
self.data, self.version = dict(body["data"]), version
|
|
self.state.update(available=True, last_ok=time.time())
|
|
if changed:
|
|
log.info("openbao_secret_loaded path=%s/%s version=%d keys=%s", self.mount, self.path, version,
|
|
",".join(sorted(self.data)))
|
|
for callback in list(self.callbacks):
|
|
try:
|
|
callback(dict(self.data))
|
|
except Exception:
|
|
log.exception("openbao_rotation_callback_failed")
|
|
|
|
# ------------------------------------------------------------------ lifecycle
|
|
def load_blocking(self, timeout: float) -> Dict[str, str]:
|
|
deadline = time.monotonic() + timeout
|
|
delay = 1.0
|
|
while True:
|
|
try:
|
|
self.login()
|
|
self._read()
|
|
return dict(self.data)
|
|
except (OpenBaoError, KeyError, ValueError) as exc:
|
|
self.state["errors"] += 1
|
|
if time.monotonic() > deadline:
|
|
log.error("openbao_unavailable_at_start role=%s error=%s: giving up", self.role, exc)
|
|
raise SystemExit(78)
|
|
log.warning("openbao_not_ready role=%s error=%s (sealed or down?), retry in %.0fs", self.role, exc, delay)
|
|
time.sleep(delay)
|
|
delay = min(delay * 2, 10.0)
|
|
|
|
def on_change(self, callback: Callable[[Dict[str, str]], None]) -> None:
|
|
self.callbacks.append(callback)
|
|
|
|
def start_refresher(self, interval: float) -> None:
|
|
def loop():
|
|
while True:
|
|
time.sleep(interval)
|
|
try:
|
|
self._ensure_token(interval)
|
|
meta = self._call("GET", "/v1/%s/metadata/%s" % (self.mount, self.path), token=self.token)
|
|
if int(meta["data"]["current_version"]) != self.version:
|
|
self._read()
|
|
else:
|
|
self.state.update(available=True, last_ok=time.time())
|
|
except (OpenBaoError, KeyError, ValueError) as exc:
|
|
self.state["errors"] += 1
|
|
if self.state["available"]:
|
|
log.warning("openbao_unavailable role=%s error=%s: keeping cached secret version %d",
|
|
self.role, exc, self.version)
|
|
self.state["available"] = False
|
|
if "403" in str(exc):
|
|
self.token = None # expired/revoked token: log in again next round
|
|
|
|
threading.Thread(target=loop, name="openbao-refresh", daemon=True).start()
|
|
|
|
|
|
_client: Optional[OpenBao] = None
|
|
|
|
|
|
def client() -> Optional[OpenBao]:
|
|
return _client
|
|
|
|
|
|
def load(timeout: float) -> Dict[str, str]:
|
|
"""Called once by app.config at import time when BAO_ADDR is set."""
|
|
global _client
|
|
_client = OpenBao()
|
|
return _client.load_blocking(timeout)
|