#!/usr/bin/env python3 """Rotate a real API database password and OpenBao client leaf on the lab stand.""" import json import os import secrets import ssl import subprocess import time from pathlib import Path from urllib.error import HTTPError from urllib.parse import urlsplit, urlunsplit from check_bao_roles import request ROOT = Path(__file__).resolve().parents[1] FILES = ROOT / "secrets" TLS = FILES / "tls" CA = TLS / "lab7-ca.crt" def run(*args, **kwargs): return subprocess.run(args, cwd=ROOT, check=True, **kwargs) def identity(cert, key): context = ssl.create_default_context(cafile=str(CA)) context.load_cert_chain(cert, key) return context def main(): admin = json.loads((FILES / "bao-operator.json").read_text())["root_token"] base = ssl.create_default_context(cafile=str(CA)) old = identity(TLS / "bao-api.crt", TLS / "bao-api.key") login = lambda ctx: request(ctx, "auth/cert/login", body={"name": "api"})["auth"] policy_path = "auth/cert/certs/api" secret_path = "messenger/data/api" old_auth = login(old) values = request(old, secret_path, token=old_auth["client_token"])["data"]["data"] old_password = urlsplit(values["database_url"]).password password = secrets.token_hex(24) for name in ("bao-api-next.crt", "bao-api-next.key"): if (TLS / name).exists(): (TLS / name).unlink() run("openssl", "req", "-new", "-newkey", "ed25519", "-nodes", "-subj", "/CN=bao-api", "-keyout", str(TLS / "bao-api-next.key"), "-out", str(TLS / "bao-api-next.csr"), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) run("openssl", "x509", "-req", "-in", str(TLS / "bao-api-next.csr"), "-CA", str(CA), "-CAkey", str(TLS / "lab7-ca.key"), "-CAcreateserial", "-days", "30", "-extfile", "/dev/stdin", "-out", str(TLS / "bao-api-next.crt"), input= "basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=clientAuth\n" "subjectAltName=URI:urn:lab7:bao:api\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid:always\n", text=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) new_cert, new_key = TLS / "bao-api-next.crt", TLS / "bao-api-next.key" new = identity(new_cert, new_key) leaf = new_cert.read_text() def role(ttl): request(base, policy_path, token=admin, status=204, body={ "certificate": leaf, "token_policies": ["api"], "token_no_default_policy": True, "token_ttl": ttl, "token_max_ttl": ttl, }) def db_login(candidate, allowed): result = subprocess.run(["docker", "compose", "exec", "-T", "db", "sh", "-ec", 'IFS= read -r PGPASSWORD; export PGPASSWORD PGCHANNELBINDING=disable ' 'PGSSLMODE=verify-full PGSSLROOTCERT=/run/tls/ca.crt; ' 'psql -X -h db -U messenger_api "$POSTGRES_DB" -Atc "SELECT 1"'], cwd=ROOT, input=candidate+"\n", text=True, capture_output=True) assert (result.returncode == 0 and result.stdout.strip() == "1") == allowed if not allowed: assert "password authentication failed" in result.stderr role("3s") try: request(old, "auth/cert/login", body={"name": "api"}, status=400) request(base, "auth/token/revoke-accessor", token=admin, status=204, body={"accessor": old_auth["accessor"]}) request(old, secret_path, token=old_auth["client_token"], status=403) auth = login(new) request(new, secret_path, token=auth["client_token"]) time.sleep(auth["lease_duration"] + 1) request(new, secret_path, token=auth["client_token"], status=403) print("PASS: replaced leaf, revoked old token, expired short-lived token") finally: role("15m") for source, target in ((new_cert, TLS / "bao-api.crt"), (new_key, TLS / "bao-api.key")): source.chmod(0o644) os.replace(source, target) (TLS / "bao-api-next.csr").unlink(missing_ok=True) db_login(old_password, True) run("docker", "compose", "exec", "-T", "db", "sh", "-ec", 'psql -X -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" "$POSTGRES_DB"', text=True, input=f"ALTER ROLE messenger_api PASSWORD '{password}';\n", stdout=subprocess.DEVNULL) parts = urlsplit(values["database_url"]) values["database_url"] = urlunsplit(parts._replace(netloc=f"{parts.username}:{password}@{parts.hostname}:{parts.port}")) request(base, secret_path, token=admin, status=200, body={"data": values}) for path, content in (("database_api_password", password), ("database_api_url", values["database_url"])): (FILES / path).write_text(content + "\n") db_login(old_password, False) db_login(password, True) run("docker", "compose", "up", "-d", "--no-deps", "--no-build", "--force-recreate", "api") run("./scripts/wait_ingress.sh") print("PASS: database secret rotated, old password refused, API ready without rebuilding") try: request(base, "sys/seal", token=admin, status=204, body={}) request(new, "auth/cert/login", body={"name": "api"}, status=503) run("./scripts/wait_ingress.sh") print("PASS: sealed OpenBao denies new login; running API remains ready using loaded credentials") finally: run("python3", "scripts/bao_operator.py", "unseal") run("python3", "scripts/check_bao_roles.py") if __name__ == "__main__": main()