Files
mtusi2026lab7/app/secrets_loader.py
T
vika baafe2a3ae
Skeleton contracts / contracts (pull_request) Canceled after 0s
Добавить стенд лабораторной 7 с mTLS, OpenBao и least privilege worker.
Закрывает обязательный минимум и трек 1: ротация leaf и секрета, sealed OpenBao и сохранность queued-задачи.
2026-11-07 20:46:02 +03:00

138 lines
4.2 KiB
Python

"""OpenBao cert-auth login and scoped KV reads. No root token and no token in the environment."""
import json
import os
import ssl
import threading
import time
import urllib.error
import urllib.request
_lock = threading.Lock()
_token = None
_lease = 0
_healthy = False
_reason = "not-loaded"
def healthy():
return _healthy
def reason():
return _reason
def _context():
ctx = ssl.create_default_context(cafile=os.environ["TLS_CA_FILE"])
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.load_cert_chain(os.environ["CLIENT_CERT_FILE"], os.environ["CLIENT_KEY_FILE"])
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
return ctx
def _request(method, path, body=None, token=None):
data = None if body is None else json.dumps(body).encode("utf-8")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
request = urllib.request.Request(os.environ["BAO_ADDR"].rstrip("/") + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, context=_context(), timeout=5) as response:
raw = response.read()
except urllib.error.HTTPError as exc:
detail = exc.read(512)
raise RuntimeError("openbao http " + str(exc.code) + " " + path) from exc
if not raw:
return {}
return json.loads(raw.decode("utf-8"))
def _login():
global _token, _lease, _healthy, _reason
payload = _request("POST", "/v1/auth/cert/login", {})
auth = payload.get("auth") or {}
token = auth.get("client_token")
policies = auth.get("policies") or auth.get("token_policies") or []
if isinstance(policies, str):
policies = [policies]
if not token or not policies:
raise RuntimeError("openbao cert login returned no scoped token")
if "root" in policies:
raise RuntimeError("refusing a root token")
_token = token
_lease = int(auth.get("lease_duration") or 0)
_healthy = True
_reason = "ok"
def _read(path):
payload = _request("GET", "/v1/secret/data/" + path, token=_token)
data = ((payload.get("data") or {}).get("data") or {})
if not data:
raise RuntimeError("openbao empty secret " + path)
return data
def _apply(role):
db = _read(role + "/db")
s3 = _read(role + "/s3")
ca = os.environ["TLS_CA_FILE"]
os.environ["DATABASE_URL"] = (
"postgresql://{username}:{password}@{host}:5432/{dbname}?sslmode=verify-full&sslrootcert={ca}".format(
username=db["username"],
password=db["password"],
host=db["host"],
dbname=db["dbname"],
ca=ca,
)
)
os.environ["S3_ACCESS_KEY_ID"] = s3["access_key"]
os.environ["S3_SECRET_ACCESS_KEY"] = s3["secret_key"]
if role == "api":
cache = _read("api/valkey")
os.environ["VALKEY_PASSWORD"] = cache["password"]
os.environ["VALKEY_USERNAME"] = cache.get("username") or "api"
os.environ["VALKEY_HOST"] = cache.get("host") or "valkey"
else:
os.environ["VALKEY_PASSWORD"] = ""
def _renew_loop():
global _healthy, _reason, _lease
while True:
time.sleep(15)
try:
with _lock:
payload = _request("POST", "/v1/auth/token/renew-self", {}, token=_token)
auth = payload.get("auth") or {}
_lease = int(auth.get("lease_duration") or _lease or 0)
_healthy = True
_reason = "ok"
except Exception:
try:
with _lock:
_login()
except Exception as exc:
_healthy = False
_reason = type(exc).__name__
def hydrate():
"""Authenticate with the service leaf and pull only that role's KV paths."""
role = os.environ.get("APP_ROLE", "api")
if role not in {"api", "worker"}:
raise RuntimeError("unsupported role")
last = None
for _ in range(40):
try:
with _lock:
_login()
_apply(role)
threading.Thread(target=_renew_loop, name="bao-renew", daemon=True).start()
return
except Exception as exc:
last = exc
time.sleep(2)
raise last