#!/usr/bin/env python3 """Verify real runtime secrets using scoped OpenBao AppRole.""" import hmac import json import ssl import stat import subprocess import sys import urllib.error import urllib.request from pathlib import Path BASE = Path.home() / ".local/share/mtusi2026lab7" BAO_URL = "https://localhost:8200/v1" INIT_FILE = BASE / "operator/openbao-init.json" FIELDS = { "api": ( "DATABASE_URL", "S3_ACCESS_KEY", "S3_SECRET_KEY", ), "worker": ( "DATABASE_URL", "RABBITMQ_USER", "RABBITMQ_PASSWORD", "S3_ACCESS_KEY", "S3_SECRET_KEY", ), } TOKENS = [] TLS = ssl.create_default_context( cafile=str(BASE / "pki/ca.crt") ) def check(condition, message): if not condition: raise RuntimeError(message) print("PASS:", message) def request(method, path, token=None, payload=None): body = None headers = {} if token is not None: headers["X-Vault-Token"] = token if payload is not None: body = json.dumps(payload).encode("utf-8") headers["Content-Type"] = "application/json" req = urllib.request.Request( BAO_URL + path, data=body, headers=headers, method=method, ) with urllib.request.urlopen( req, context=TLS, timeout=15, ) as response: raw = response.read() return ( response.status, json.loads(raw) if raw else {}, ) def same_secrets(actual, expected): if set(actual) != set(expected): return False return all( isinstance(actual[key], str) and hmac.compare_digest( actual[key], expected[key], ) for key in expected ) def get_service_token(role, root_token): name = "messenger-" + role _, role_response = request( "GET", f"/auth/approle/role/{name}/role-id", root_token, ) role_id = role_response["data"]["role_id"] _, secret_response = request( "POST", f"/auth/approle/role/{name}/secret-id", root_token, {}, ) secret_id = secret_response["data"]["secret_id"] _, login_response = request( "POST", "/auth/approle/login", payload={ "role_id": role_id, "secret_id": secret_id, }, ) auth = login_response["auth"] token = auth["client_token"] TOKENS.append(token) check( name in auth["policies"] and "root" not in auth["policies"], f"{role}: correct scoped policy", ) check( 0 < auth["lease_duration"] <= 1200, f"{role}: limited token TTL", ) return token def must_deny(token, path, label): try: request("GET", path, token) except urllib.error.HTTPError as exc: check( exc.code == 403, label + " (HTTP 403)", ) else: raise RuntimeError( label + ": forbidden read unexpectedly allowed" ) def main(root_token): print("OpenBao endpoint:", BAO_URL) print("TLS verification: enabled") result = subprocess.run( ["docker", "compose", "config", "--format", "json"], check=True, capture_output=True, text=True, ) services = json.loads(result.stdout)["services"] expected = { "api": { key: services["api1"]["environment"][key] for key in FIELDS["api"] }, "worker": { key: services["worker"]["environment"][key] for key in FIELDS["worker"] }, } check( all( services["api1"]["environment"][key] == services["api2"]["environment"][key] for key in FIELDS["api"] ), "API replicas use matching credentials", ) api_token = get_service_token("api", root_token) worker_token = get_service_token("worker", root_token) for role, token in ( ("api", api_token), ("worker", worker_token), ): status, response = request( "GET", f"/lab7/data/{role}/runtime", token, ) actual = response["data"]["data"] check( status == 200 and same_secrets(actual, expected[role]), f"{role}: runtime secrets match Compose", ) must_deny( api_token, "/lab7/data/worker/runtime", "API cannot read worker runtime secrets", ) must_deny( worker_token, "/lab7/data/api/runtime", "Worker cannot read API runtime secrets", ) must_deny( api_token, "/sys/policies/acl/messenger-api", "API cannot read policy configuration", ) must_deny( worker_token, "/sys/policies/acl/messenger-worker", "Worker cannot read policy configuration", ) print("PASS: all OpenBao runtime access tests passed") print("PASS: no credential values printed") try: if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600: raise RuntimeError("Operator file permissions must be 600") with INIT_FILE.open(encoding="utf-8") as file: root_token = json.load(file)["root_token"] try: main(root_token) finally: for token in TOKENS: try: request( "POST", "/auth/token/revoke", root_token, {"token": token}, ) print("PASS: temporary service token revoked") except Exception: print("WARNING: service token revocation failed") except Exception as exc: print( "FAIL: OpenBao runtime test:", type(exc).__name__, file=sys.stderr, ) raise SystemExit(1)