lab7: OpenBao 2.7.3 (не dev, raft на volume, TLS, audit), AppRole и scoped policy для api/relay/worker, секреты только из OpenBao, скрипт оператора и проверка allow/deny

This commit is contained in:
Alexey Bodanyuk
2026-11-27 16:41:57 +03:00
parent 93f4ed1013
commit 876f610847
16 changed files with 623 additions and 45 deletions
+1
View File
@@ -56,6 +56,7 @@ class GracefulServer(uvicorn.Server):
def main() -> int:
logging_setup.configure_early()
try:
settings = Settings.from_env()
except ConfigError as exc:
+116
View File
@@ -0,0 +1,116 @@
"""Lab 7: secrets of a service from OpenBao (AppRole login -> read own KV path -> revoke token).
Used by config._secret(): when BAO_ADDR is set, DATABASE_URL / CACHE_URL / S3_* / BROKER_URL come from
`BAO_SECRET_PATH` (e.g. messenger/data/api) instead of files. Startup sequence (once per process):
1. read role_id + secret_id from BAO_ROLE_ID_FILE / BAO_SECRET_ID_FILE (Docker secrets of THIS
service only; the "first secret" delivered by the operator, scripts/bao_operator.py);
2. POST auth/approle/login over HTTPS (server verified: BAO_CACERT = internal CA, hostname openbao)
-> a service token with ONE policy (read its own path), TTL 1 h;
3. GET the KV path -> the values stay in process memory only (never logged, never written);
4. POST auth/token/revoke-self: the token is dead seconds after it was created.
Failure modes (README "что происходит при ..."):
* OpenBao sealed/stopped at start: retried for BAO_STARTUP_TIMEOUT_SECONDS, then the process exits
(configuration error) and Docker restarts it; replicas that are already running are not
affected - they do not need OpenBao after startup.
* Token expiry: irrelevant after startup (revoked anyway); every new process logs in again.
* Wrong/expired secret_id or a policy denial: fail at once with the HTTP status, no retry.
No root token, no unseal key and no long-lived token ever exist in an application container.
"""
from __future__ import annotations
import json
import logging
import os
import ssl
import time
import urllib.error
import urllib.request
from pathlib import Path
log = logging.getLogger("messenger.bao")
_cache: dict[str, str] | None = None
class BaoError(RuntimeError):
pass
def enabled() -> bool:
return bool(os.environ.get("BAO_ADDR", "").strip())
def _file(name: str) -> str:
path = os.environ.get(name, "").strip()
if not path:
raise BaoError(f"{name} must be set when BAO_ADDR is set")
try:
return Path(path).read_text(encoding="utf-8").strip()
except OSError as exc:
raise BaoError(f"{name}={path} cannot be read: {exc.strerror}") from None
class Client:
def __init__(self, addr: str, ca_file: str, timeout: float = 5.0):
self.addr = addr.rstrip("/")
self.timeout = timeout
self.context = ssl.create_default_context(cafile=ca_file or None) # verify chain + hostname
self.context.minimum_version = ssl.TLSVersion.TLSv1_2
def call(self, method: str, path: str, token: str | None = None, body: dict | None = None) -> dict:
data = json.dumps(body).encode() if body is not None else (b"" if method == "POST" else None)
request = urllib.request.Request(f"{self.addr}/v1/{path}", data=data, method=method)
request.add_header("Content-Type", "application/json")
if token:
request.add_header("X-Vault-Token", token)
with urllib.request.urlopen(request, timeout=self.timeout, context=self.context) as response:
raw = response.read()
return json.loads(raw) if raw else {}
def _status(exc: Exception) -> int | None:
return exc.code if isinstance(exc, urllib.error.HTTPError) else None
def fetch() -> dict[str, str]:
"""Login, read the service's KV path, revoke the token. Values are cached for the process."""
global _cache
if _cache is not None:
return _cache
client = Client(os.environ["BAO_ADDR"], os.environ.get("BAO_CACERT", "").strip())
path = os.environ.get("BAO_SECRET_PATH", "").strip()
if not path:
raise BaoError("BAO_SECRET_PATH must be set when BAO_ADDR is set")
role_id, secret_id = _file("BAO_ROLE_ID_FILE"), _file("BAO_SECRET_ID_FILE")
deadline = time.monotonic() + float(os.environ.get("BAO_STARTUP_TIMEOUT_SECONDS", "60"))
while True:
try:
auth = client.call("POST", "auth/approle/login", body={"role_id": role_id, "secret_id": secret_id})["auth"]
token = auth["client_token"]
try:
data = client.call("GET", path, token=token)["data"]["data"]
finally:
try:
client.call("POST", "auth/token/revoke-self", token=token)
except (urllib.error.URLError, OSError):
pass # TTL (1 h) bounds the token anyway
break
except (urllib.error.URLError, OSError, KeyError, ValueError) as exc:
status = _status(exc)
# 503 = sealed / standby, no status = unreachable: wait for the operator. 4xx = our
# credentials or the policy are wrong: retrying would not help.
if status is not None and status != 503:
raise BaoError(f"OpenBao refused {path!r} for this service: HTTP {status}") from None
if time.monotonic() > deadline:
raise BaoError(f"OpenBao unavailable (sealed or unreachable): {type(exc).__name__}") from None
log.warning("openbao_unavailable", extra={"fields": {"status": status, "error": type(exc).__name__}})
time.sleep(2)
if not isinstance(data, dict):
raise BaoError(f"OpenBao path {path!r} has no KV data")
log.info("secrets_loaded", extra={"fields": {
"path": path, "keys": sorted(data), "policies": auth.get("token_policies"),
"token_ttl_s": auth.get("lease_duration"), "token_revoked": True}})
_cache = {str(k): str(v) for k, v in data.items()}
return _cache
+12 -1
View File
@@ -77,7 +77,18 @@ def _choice(name: str, default: str, allowed: set[str]) -> str:
def _secret(name: str, required: bool) -> str:
"""Value of <NAME>_FILE (preferred, Docker secret) or <NAME> (local runs/tests)."""
"""Value of a secret setting, in this order:
1. OpenBao (lab 7, BAO_ADDR set): key name.lower() of the service's KV path (bao.py);
2. <NAME>_FILE (Docker secret file: bootstrap jobs and operator tools);
3. <NAME> (local runs/tests)."""
from . import bao
if bao.enabled():
try:
values = bao.fetch()
except bao.BaoError as exc:
raise ConfigError(str(exc)) from None
if name.lower() in values:
return values[name.lower()]
path = os.environ.get(f"{name}_FILE", "").strip()
if path:
try:
+8
View File
@@ -7,6 +7,7 @@ from __future__ import annotations
import datetime as dt
import json
import logging
import os
import sys
from . import telemetry
@@ -42,3 +43,10 @@ def configure(level: str) -> None:
for name in ("uvicorn", "uvicorn.error"):
logging.getLogger(name).handlers[:] = []
logging.getLogger(name).propagate = True
def configure_early() -> None:
"""Before Settings exist (lab 7: secrets are fetched from OpenBao while the settings load, and
those log lines must not be lost). Settings.from_env() validates LOG_LEVEL properly later."""
raw = os.environ.get("LOG_LEVEL", "info").strip().lower()
configure(raw if raw in {"debug", "info", "warning", "error"} else "info")
+1
View File
@@ -214,6 +214,7 @@ class Relay:
def main() -> int:
logging_setup.configure_early()
try:
settings = Settings.from_env(s3_credentials=False)
if not settings.broker_url:
+1
View File
@@ -379,6 +379,7 @@ class Worker:
def main() -> int:
logging_setup.configure_early()
try:
settings = Settings.from_env()
if not settings.broker_url: