#!/usr/bin/env python3 """Test OpenBao bootstrap from isolated API and worker containers.""" import json import os import ssl import stat import subprocess import sys import tempfile import urllib.request import urllib.error from pathlib import Path BASE = Path.home() / ".local/share/mtusi2026lab7" OPERATOR = BASE / "operator" INIT_FILE = OPERATOR / "openbao-init.json" PROJECT = Path.cwd() BAO_URL = "https://localhost:8200/v1" SERVICES = { "api1": "messenger-api", "api2": "messenger-api", "worker": "messenger-worker", } CONTAINER_TEST = """ import hmac import os from src.openbao_client import read_runtime_secrets secrets = read_runtime_secrets() role = os.environ["BAO_SECRET_PATH"].split("/")[2] fields = ( "DATABASE_URL", "S3_ACCESS_KEY", "S3_SECRET_KEY", ) if role == "worker": fields += ( "RABBITMQ_USER", "RABBITMQ_PASSWORD", ) assert set(secrets) == set(fields), "Unexpected secret fields" for field in fields: assert hmac.compare_digest( secrets[field], os.environ[field], ), "Secret mismatch: " + field print("PASS: AppRole authentication completed") print("PASS: runtime secrets match service credentials") print("PASS: scoped KV v2 secret loaded") print("PASS: no secret values printed") """ def request(method, path, token, tls, payload=None): body = None if payload is not None: body = json.dumps(payload).encode("utf-8") headers = {"X-Vault-Token": token} if body is not None: 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: data = response.read() return json.loads(data) if data else {} def private_file(path, value): with path.open("x", encoding="utf-8") as file: file.write(value + "\n") path.chmod(0o600) def main(): if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600: raise RuntimeError("Operator file must have mode 600") with INIT_FILE.open(encoding="utf-8") as file: root_token = json.load(file)["root_token"] tls = ssl.create_default_context( cafile=str(BASE / "pki/ca.crt") ) module = PROJECT / "src/openbao_client.py" if not module.is_file(): raise RuntimeError("OpenBao client module not found") os.umask(0o077) for service, role in SERVICES.items(): print("=== {} ===".format(service), flush=True) role_response = request( "GET", "/auth/approle/role/{}/role-id".format(role), root_token, tls, ) role_id = role_response["data"]["role_id"] secret_response = request( "POST", "/auth/approle/role/{}/secret-id".format(role), root_token, tls, {}, ) secret_data = secret_response["data"] secret_id = secret_data["secret_id"] accessor = secret_data["secret_id_accessor"] try: with tempfile.TemporaryDirectory( prefix=".openbao-test-", dir=OPERATOR, ) as temporary: directory = Path(temporary) private_file(directory / "role-id", role_id) private_file(directory / "secret-id", secret_id) command = [ "docker", "compose", "run", "--rm", "-T", "--no-deps", "-v", "{}:/run/lab7/approle:ro".format( directory ), "-v", "{}:/app/src/openbao_client.py:ro".format( module ), "-e", "BAO_ADDR=https://openbao:8200", "-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt", "-e", "BAO_ROLE_ID_FILE=/run/lab7/approle/role-id", "-e", "BAO_SECRET_ID_FILE=/run/lab7/approle/secret-id", "-e", "BAO_SECRET_PATH=lab7/data/{}/runtime".format( "worker" if service == "worker" else "api" ), "--entrypoint", "python", service, "-", ] result = subprocess.run( command, input=CONTAINER_TEST, text=True, capture_output=True, check=False, ) if result.returncode != 0: print( "FAIL: temporary container test failed", file=sys.stderr, ) print( "INFO: container exit code:", result.returncode, file=sys.stderr, ) raise RuntimeError( "{} bootstrap test failed".format(service) ) for line in result.stdout.splitlines(): if line.startswith("PASS:"): print(line) print( "PASS: {} bootstrap verified".format(service), flush=True, ) finally: # A single-use SecretID is normally removed # automatically after successful authentication. accessor_path = ( "/auth/approle/role/{}/secret-id-accessor".format( role ) ) try: request( "POST", accessor_path + "/lookup", root_token, tls, {"secret_id_accessor": accessor}, ) except urllib.error.HTTPError as exc: if exc.code == 404: print( "PASS: consumed SecretID already absent", flush=True, ) else: print( "WARNING: SecretID lookup HTTP {}".format( exc.code ), file=sys.stderr, ) else: # Destroy only if the SecretID still exists. try: request( "POST", accessor_path + "/destroy", root_token, tls, {"secret_id_accessor": accessor}, ) print( "PASS: unused SecretID revoked", flush=True, ) except urllib.error.HTTPError as exc: print( "WARNING: SecretID cleanup HTTP {}".format( exc.code ), file=sys.stderr, ) print("PASS: three independent bootstrap tests completed") print("PASS: temporary credential files removed") if __name__ == "__main__": try: main() except Exception as exc: print( "FAIL: OpenBao bootstrap:", type(exc).__name__, file=sys.stderr, ) raise SystemExit(1)