lab 7 openbao

This commit is contained in:
2026-11-23 14:39:13 +03:00
parent 20afc2c790
commit 912a874f00
118 changed files with 12464 additions and 5108 deletions
+78
View File
@@ -0,0 +1,78 @@
"""Secrets for api/worker/dispatcher/sweeper from OpenBao (AppRole -> short-lived scoped token -> one KV v2 secret).
Bootstrap trust: the only things on disk are the PUBLIC CA, the RoleID (not a secret) and a SecretID with a 24 h TTL that the
operator issues into /run/approle. The service logs in, reads exactly one path allowed by its policy, revokes its own token and
keeps the values only in process memory / environment. No root token, no unseal key, no long-lived token is ever present.
Sealed/unreachable OpenBao at start => bounded retries, then exit (compose restarts the container); a running process is not affected.
"""
from __future__ import annotations
import json
import os
import ssl
import time
import urllib.error
import urllib.request
BAO_ADDR = os.getenv("BAO_ADDR", "https://openbao:8200").rstrip("/")
BAO_CACERT = os.getenv("BAO_CACERT", "/run/pki/ca.crt")
APPROLE_DIR = os.getenv("APPROLE_DIR", "/run/approle")
# secret field in OpenBao -> environment variable consumed by the unchanged lab 6 code (psycopg reads PGPASSWORD itself).
ENV_MAP = {
"api": {"db_password": "PGPASSWORD", "redis_password": "REDIS_PASSWORD", "s3_access_key": "S3_ACCESS_KEY_ID", "s3_secret_key": "S3_SECRET_ACCESS_KEY"},
"worker": {"db_password": "PGPASSWORD", "s3_access_key": "S3_ACCESS_KEY_ID", "s3_secret_key": "S3_SECRET_ACCESS_KEY"},
"dispatcher": {"db_password": "PGPASSWORD"},
"sweeper": {"db_password": "PGPASSWORD", "s3_access_key": "S3_ACCESS_KEY_ID", "s3_secret_key": "S3_SECRET_ACCESS_KEY"},
}
class VaultError(RuntimeError):
"""Message never contains secret values or tokens."""
def _call(method: str, path: str, body: dict | None = None, token: str | None = None) -> dict:
ctx = ssl.create_default_context(cafile=BAO_CACERT) # CA + hostname (SAN) verification, never disabled
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(f"{BAO_ADDR}/v1/{path}", data=data, method=method)
if token:
req.add_header("X-Vault-Token", token)
try:
with urllib.request.urlopen(req, timeout=5, context=ctx) as resp:
raw = resp.read()
except urllib.error.HTTPError as exc:
raise VaultError(f"OpenBao {method} {path}: HTTP {exc.code}") from None
except (urllib.error.URLError, OSError) as exc:
raise VaultError(f"OpenBao unreachable: {type(exc).__name__}") from None
return json.loads(raw) if raw else {}
def _read(name: str) -> str:
with open(os.path.join(APPROLE_DIR, name), encoding="utf-8") as fh:
return fh.read().strip()
def fetch(role: str) -> dict[str, str]:
"""One login -> one read -> token revoked. Raises VaultError if sealed, SecretID expired/destroyed, or policy denies."""
login = _call("POST", "auth/approle/login", {"role_id": _read("role_id"), "secret_id": _read("secret_id")})
token = login["auth"]["client_token"]
try:
return _call("GET", f"kv/data/{role}", token=token)["data"]["data"]
finally:
try:
_call("POST", "auth/token/revoke-self", token=token)
except VaultError:
pass # the token expires by TTL anyway
def load_into_env(role: str, attempts: int = 30, delay: float = 2.0) -> None:
last = None
for _ in range(attempts):
try:
secret = fetch(role)
for field, env in ENV_MAP[role].items():
os.environ[env] = secret[field]
return
except (VaultError, KeyError, OSError) as exc:
last = exc
time.sleep(delay)
raise SystemExit(f"cannot obtain secrets for {role} from OpenBao: {last}")