Files
mtusi2026lab7/app/openbao.py
T
Artu-Rito ab7b467957
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Implement lab 7 security and mTLS
2026-11-26 16:55:53 +03:00

31 lines
1.2 KiB
Python

"""Small dependency-free OpenBao KV client used during the lab defense."""
import json, os, urllib.request
def enabled():
return os.getenv("OPENBAO_ENABLED", "0").lower() in {"1", "true", "yes"}
def read(path: str, key: str) -> str:
addr = os.getenv("OPENBAO_ADDR", "http://openbao:8200").rstrip("/")
token_file = os.getenv("OPENBAO_TOKEN_FILE", "/run/secrets/openbao_token")
token = open(token_file, encoding="utf-8").read().strip()
req = urllib.request.Request(f"{addr}/v1/{path.lstrip('/')}", headers={"X-Vault-Token": token})
try:
with urllib.request.urlopen(req, timeout=3) as response:
payload = json.load(response)
except Exception as exc:
raise RuntimeError("OpenBao secret unavailable; refusing fallback") from exc
value = payload.get("data", {}).get("data", {}).get(key)
if not value:
raise RuntimeError(f"OpenBao key missing: {path}/{key}")
return str(value)
def healthy() -> bool:
if not enabled():
return True
addr = os.getenv("OPENBAO_ADDR", "http://openbao:8200").rstrip("/")
try:
with urllib.request.urlopen(f"{addr}/v1/sys/health", timeout=2) as response:
return response.status == 200
except Exception:
return False