#!/usr/bin/env python3 """Lab 7 OpenBao, Secrets Lifecycle & Certificate Rotation/Revocation Suite (Grade 3 + Grade 4). Verifies: - Non-dev Raft OpenBao mode, initialized & unsealed, root token revoked, zero root/unseal/secrets in containers - Policy allow/deny matrix for messenger-api and messenger-worker (NC-5) - Live DB secret rotation without image rebuild (scripts/rotate-secret.sh api-db) - Live leaf cert rotation + client cert revocation on NEW connection (scripts/rotate-cert.sh, NC-6) - Token revocation & clean auth/cert re-authentication - Sealed OpenBao bounded behavior + container restart (boots sealed) + manual operator unseal recovery Writes sanitized JSON + TXT report to evidence/lab7/openbao-lifecycle.{json,txt}. """ import argparse import shutil import sys import tempfile import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import common # noqa: E402 from client import Client, Failure # noqa: E402 def _probe_api_tls(ca_pem, cert_pem, key_pem): """Fresh-connection mTLS probe to https://api:8443/health/ready from lb_api; returns peer cert serial.""" js = """ const https = require('https'); const crypto = require('crypto'); const p = payload; return await new Promise((resolve) => { const req = https.request({ hostname: 'api', port: 8443, path: '/health/ready', method: 'GET', ca: p.ca_pem, cert: p.cert_pem, key: p.key_pem, servername: 'api', rejectUnauthorized: true, minVersion: 'TLSv1.2', secureOptions: crypto.constants.SSL_OP_NO_TICKET, headers: { Connection: 'close' }, timeout: 6000, }, (res) => { const peer = res.socket.getPeerX509Certificate(); const chunks = []; res.on('data', (c) => chunks.push(c)); res.on('end', () => resolve({ status: res.statusCode, serial: peer ? peer.serialNumber : null, fingerprint256: peer ? peer.fingerprint256 : null, tlsError: null, })); }); req.on('timeout', () => req.destroy(new Error('ETIMEDOUT'))); req.on('error', (err) => resolve({ status: null, serial: null, fingerprint256: null, tlsError: err.code || err.message || String(err), })); req.end(); }); """ return common.run_node_probe( js, {'ca_pem': ca_pem, 'cert_pem': cert_pem, 'key_pem': key_pem}, network='lb_api' ) def _probe_pg_password(ca_pem, user, password): js = """ const { Client } = require('pg'); const c = new Client({ host: 'postgres', port: 5432, database: 'messenger', user: payload.user, password: payload.password, connectionTimeoutMillis: 5000, ssl: { ca: payload.ca_pem, rejectUnauthorized: true, servername: 'postgres', minVersion: 'TLSv1.2' }, }); try { await c.connect(); await c.query('SELECT 1'); await c.end(); return { ok: true, code: null }; } catch (err) { try { await c.end(); } catch (_) {} return { ok: false, code: err.code || null, error: err.message || String(err) }; } """ return common.run_node_probe( js, {'ca_pem': ca_pem, 'user': user, 'password': password}, network='app_data' ) def _read_pem(path): return Path(path).read_text(encoding='utf-8') def check_openbao_posture(args, rc, op_crt, op_key, rogue_crt, rogue_key): bao = common.OpenBaoClient(args.openbao_url, args.ca_file) st, health = bao.health() ok_health = st == 200 and isinstance(health, dict) and health.get('initialized') and not health.get('sealed') rc.add('BAO-1-NONDEV-HEALTH', 'openbao_posture', 'OpenBao is initialized, unsealed, and reachable over verified HTTPS', ok_health, 'HTTP 200 initialized=True sealed=False', f'status={st} health={health}') # Verify non-dev Raft config & persistent volume bao_cids = common.container_ids('openbao') non_dev_ok = False raft_vol_ok = False if bao_cids: insp = common.container_inspect(bao_cids[0]) cmd_all = ' '.join((insp.get('Config') or {}).get('Cmd') or []) entry_all = ' '.join((insp.get('Config') or {}).get('Entrypoint') or []) non_dev_ok = ('-dev' not in cmd_all) and ('-dev' not in entry_all) and ('openbao.hcl' in cmd_all) mounts = insp.get('Mounts') or [] raft_vol_ok = any(m.get('Destination') == '/openbao/file' and m.get('Type') == 'volume' for m in mounts) hcl_path = common.ROOT / 'infra/openbao/openbao.hcl' hcl_raft = hcl_path.is_file() and 'storage "raft"' in hcl_path.read_text(encoding='utf-8') rc.add('BAO-2-RAFT-NONDEV', 'openbao_posture', 'OpenBao runs non-dev mode with persistent Raft volume (openbao-data:/openbao/file)', non_dev_ok and raft_vol_ok and hcl_raft, 'non-dev + Raft volume mounted', f'non_dev={non_dev_ok}, raft_vol={raft_vol_ok}, hcl_raft={hcl_raft}') # Verify no root token / unseal shares saved in repo or mounted in api/worker repo_leaks = [] for cand in ('root_token', 'root-token', 'unseal-share-1', 'unseal_keys', 'init.json'): for base in (common.ROOT, common.ROOT / 'secrets', common.ROOT / 'secrets/infra'): if (base / cand).exists(): repo_leaks.append(str((base / cand).relative_to(common.ROOT))) op_root_file = Path(args.operator_dir) / 'openbao/root-token' if op_root_file.exists(): # If any root token file exists, verify it is revoked (403) tok = op_root_file.read_text(encoding='utf-8').strip() rc.register_secret(tok) st_rt, _ = common.OpenBaoClient(args.openbao_url, args.ca_file, token=tok).lookup_self() root_ok = st_rt == 403 root_note = f'root-token file present but revoked (lookup status={st_rt})' else: root_ok = True root_note = 'no persisted root token file (revoked at bootstrap)' rc.add('BAO-3-NO-ROOT-PERSISTED', 'openbao_posture', 'Initial root token revoked and zero root/unseal files in repo or workload containers', root_ok and not repo_leaks, 'no repo root/unseal files & root revoked', f'{root_note}; repo_leaks={repo_leaks}') # Operator cert login works; rogue-client cert rejected op_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=op_crt, key_file=op_key) st_op, _ = op_bao.cert_login('messenger-operator') if op_bao.token: rc.register_secret(op_bao.token) rogue_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=rogue_crt, key_file=rogue_key) st_rogue, _ = rogue_bao.cert_login('messenger-api') rc.add('BAO-4-OPERATOR-AND-ROGUE-AUTH', 'openbao_auth', 'Operator mTLS cert authenticates; trusted-CA rogue-client rejected by auth/cert', st_op == 200 and st_rogue in (400, 403), 'operator=200, rogue=400/403', f'operator={st_op}, rogue={st_rogue}') return op_bao def check_policy_matrix(args, rc): api_crt, api_key = common.service_client_pair('api') wrk_crt, wrk_key = common.service_client_pair('worker') api_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=api_crt, key_file=api_key) st_a, data_a = api_bao.cert_login('messenger-api') if api_bao.token: rc.register_secret(api_bao.token) api_pols = (data_a or {}).get('auth', {}).get('policies', []) api_ttl = (data_a or {}).get('auth', {}).get('lease_duration') a_own, a_kv = api_bao.kv_read('secret/data/messenger/api') a_wrk, _ = api_bao.kv_read('secret/data/messenger/worker') a_mig, _ = api_bao.kv_read('secret/data/messenger/migrator') a_adm, _ = api_bao.kv_read('secret/data/messenger/operator-admin') a_pol, _ = api_bao.request('PUT', '/v1/sys/policies/acl/api-policy', body={'policy': 'path "*" { capabilities = ["sudo"] }'}) a_crt, _ = api_bao.request('GET', '/v1/auth/cert/certs/messenger-api') a_cross_login, _ = api_bao.request('POST', '/v1/auth/cert/login', body={'name': 'messenger-worker'}, token='') api_sec = ((a_kv or {}).get('data') or {}).get('data') or {} for v in api_sec.values(): if isinstance(v, str): rc.register_secret(v) api_ok = ( st_a == 200 and a_own == 200 and all(code == 403 for code in (a_wrk, a_mig, a_adm, a_pol, a_crt)) and a_cross_login in (400, 403) and 'default' not in api_pols ) rc.add('BAO-5-API-POLICY-MATRIX', 'openbao_policy', 'messenger-api reads ONLY secret/data/messenger/api and is denied worker/migrator/admin/sys/auth', api_ok, 'own=200, all foreign/sys/auth=403, cross_role_login=400, no default policy', f'login={st_a} policies={api_pols} ttl={api_ttl}s own={a_own} wrk={a_wrk} mig={a_mig} adm={a_adm} pol={a_pol} cert={a_crt} cross={a_cross_login}') wrk_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=wrk_crt, key_file=wrk_key) st_w, data_w = wrk_bao.cert_login('messenger-worker') if wrk_bao.token: rc.register_secret(wrk_bao.token) wrk_pols = (data_w or {}).get('auth', {}).get('policies', []) wrk_ttl = (data_w or {}).get('auth', {}).get('lease_duration') w_own, w_kv = wrk_bao.kv_read('secret/data/messenger/worker') w_api, _ = wrk_bao.kv_read('secret/data/messenger/api') w_mig, _ = wrk_bao.kv_read('secret/data/messenger/migrator') w_adm, _ = wrk_bao.kv_read('secret/data/messenger/operator-admin') w_pol, _ = wrk_bao.request('PUT', '/v1/sys/policies/acl/worker-policy', body={'policy': 'path "*" { capabilities = ["sudo"] }'}) w_seal, _ = wrk_bao.request('PUT', '/v1/sys/seal') w_cross_login, _ = wrk_bao.request('POST', '/v1/auth/cert/login', body={'name': 'messenger-api'}, token='') wrk_sec = ((w_kv or {}).get('data') or {}).get('data') or {} for v in wrk_sec.values(): if isinstance(v, str): rc.register_secret(v) no_api_keys_in_wrk = not any(k in wrk_sec for k in ('redis_password', 'redis_user', 'metrics_token')) wrk_ok = ( st_w == 200 and w_own == 200 and no_api_keys_in_wrk and all(code == 403 for code in (w_api, w_mig, w_adm, w_pol, w_seal)) and w_cross_login in (400, 403) and 'default' not in wrk_pols ) rc.add('BAO-6-WORKER-POLICY-MATRIX', 'openbao_policy', 'messenger-worker reads ONLY secret/data/messenger/worker (no Redis/metrics) and is denied api/migrator/admin/sys', wrk_ok, 'own=200, no redis/metrics keys, all foreign/sys=403, no default policy', f'login={st_w} policies={wrk_pols} ttl={wrk_ttl}s own={w_own} api={w_api} mig={w_mig} adm={w_adm} pol={w_pol} seal={w_seal} cross={w_cross_login} no_redis_metrics={no_api_keys_in_wrk}') return api_bao, a_kv def check_secret_rotation(args, rc, api_bao, api_kv_before, ca_pem): img_before = common.app_image_id() ver_before = (((api_kv_before or {}).get('data') or {}).get('metadata') or {}).get('version') old_sec = (((api_kv_before or {}).get('data') or {}).get('data') or {}) old_db_user = old_sec.get('db_user', 'messenger_api') old_db_pass = old_sec.get('db_password', '') rc.register_secret(old_db_pass) common.run_host_script('scripts/rotate-secret.sh', 'api-db', operator_dir=args.operator_dir) st_after, api_kv_after = api_bao.kv_read('secret/data/messenger/api') ver_after = (((api_kv_after or {}).get('data') or {}).get('metadata') or {}).get('version') new_db_pass = ((((api_kv_after or {}).get('data') or {}).get('data') or {}).get('db_password')) or '' rc.register_secret(new_db_pass) img_after = common.app_image_id() # Prove OLD DB password rejected on NEW TLS connection old_pg = (_probe_pg_password(ca_pem, old_db_user, old_db_pass).get('result') or {}) old_rejected = old_pg.get('ok') is False and ( old_pg.get('code') == '28P01' or 'authentication failed' in str(old_pg.get('error', '')).lower() ) # Prove API seamlessly serves writes over HTTPS without rebuild client = Client(args.base_url, args.ca_file) api_serving = False deadline = time.monotonic() + 20 while time.monotonic() < deadline: try: u = client.user('rotdb') rc.register_secret(u['registration']['password']) rc.register_secret(u['token']) api_serving = True break except Failure: time.sleep(1) ok = ( st_after == 200 and img_before == img_after and isinstance(ver_before, int) and isinstance(ver_after, int) and ver_after > ver_before and new_db_pass != old_db_pass and old_rejected and api_serving ) rc.add('BAO-7-SECRET-ROTATION-NO-REBUILD', 'secret_rotation', 'Live API DB password rotation increments KV version, rejects old password (28P01), keeps API serving without image rebuild', ok, 'same Image SHA, KV version++, old PG password 28P01, API serves 201', f'same_image={img_before == img_after} secret_version_before={ver_before} secret_version_after={ver_after} old_password_rejected={old_rejected} api_serving={api_serving}') def check_cert_rotation_and_revocation(args, rc, ca_pem): hap_crt, hap_key = common.haproxy_client_pair() hap_crt_pem = _read_pem(hap_crt) hap_key_pem = _read_pem(hap_key) if hap_key else hap_crt_pem img_before = common.app_image_id() before = (_probe_api_tls(ca_pem, hap_crt_pem, hap_key_pem).get('result') or {}) serial_before = before.get('serial') common.run_host_script('scripts/rotate-cert.sh', 'api', '--revoke', operator_dir=args.operator_dir) disk_serial = common.pem_cert_info(common.ROOT / 'secrets/pki/api/server.crt')['serial'] serial_after = None deadline = time.monotonic() + 15 while time.monotonic() < deadline: after = (_probe_api_tls(ca_pem, hap_crt_pem, hap_key_pem).get('result') or {}) if after.get('status') == 200 and after.get('serial') and after.get('serial') != serial_before: serial_after = after.get('serial') break time.sleep(1) img_after = common.app_image_id() client = Client(args.base_url, args.ca_file) ext_ok = client.call('GET', '/health/ready', 200, schema='Health')['status'] == 200 rc.add('BAO-8-LEAF-CERT-ROTATION-NO-REBUILD', 'cert_rotation', 'Live API leaf cert rotation changes presented TLS serial without image rebuild or downtime', bool(serial_before and serial_after and serial_after != serial_before and serial_after.lstrip('0') == disk_serial.lstrip('0') and img_before == img_after and ext_ok), 'serial changed & matches disk cert, same Image SHA, external HTTPS 200', f'serial_before={serial_before} serial_after={serial_after} disk_serial={disk_serial} same_image={img_before == img_after} ext_ok={ext_ok}') # Client cert revocation on NEW connection (NC-6): issue temporary haproxy-lb SAN client cert, prove 200, revoke, prove rejected! tmpdir = Path(tempfile.mkdtemp(prefix='mtusi-lab7-revtest-')) try: common.run_host_script( 'scripts/rotate-cert.sh', '--issue-test-client', 'revtest', 'haproxy-lb-revtest', 'DNS:haproxy-lb', str(tmpdir), operator_dir=args.operator_dir, ) t_crt = tmpdir / 'revtest.crt' t_key = tmpdir / 'revtest.key' t_crt_pem = _read_pem(t_crt) t_key_pem = _read_pem(t_key) pre = (_probe_api_tls(ca_pem, t_crt_pem, t_key_pem).get('result') or {}) common.run_host_script( 'scripts/rotate-cert.sh', '--revoke-cert', str(t_crt), operator_dir=args.operator_dir, ) # Allow live SIGHUP/5s CRL reload to settle, then open BRAND-NEW TCP+TLS connection post = None deadline = time.monotonic() + 12 while time.monotonic() < deadline: post = (_probe_api_tls(ca_pem, t_crt_pem, t_key_pem).get('result') or {}) if post.get('status') != 200: break time.sleep(1) revoked_ok = pre.get('status') == 200 and post is not None and ( post.get('status') == 403 or bool(post.get('tlsError')) ) rc.add('BAO-9-CERT-REVOCATION-NEW-CONN', 'cert_revocation', 'Revoked client cert rejected on BRAND-NEW TCP+TLS connection (no TLS session resumption)', revoked_ok, 'pre_revoke=200, post_revoke=TLS revoked or 403', f"pre={pre.get('status')} post_status={post.get('status') if post else None} post_err={post.get('tlsError') if post else None}") finally: shutil.rmtree(tmpdir, ignore_errors=True) def check_token_revocation(args, rc, op_bao): api_crt, api_key = common.service_client_pair('api') tmp_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=api_crt, key_file=api_key) st_login, _ = tmp_bao.cert_login('messenger-api') if tmp_bao.token: rc.register_secret(tmp_bao.token) st_look, look = tmp_bao.lookup_self() accessor = ((look or {}).get('data') or {}).get('accessor') ttl = ((look or {}).get('data') or {}).get('ttl') st_pre, _ = tmp_bao.kv_read('secret/data/messenger/api') st_rev, _ = op_bao.revoke_accessor(accessor) if accessor else (0, None) st_post, _ = tmp_bao.kv_read('secret/data/messenger/api') # Prove service cleanly re-authenticates via auth/cert st_reauth, _ = tmp_bao.cert_login('messenger-api') if tmp_bao.token: rc.register_secret(tmp_bao.token) st_after, _ = tmp_bao.kv_read('secret/data/messenger/api') ok = ( st_login == 200 and st_look == 200 and st_pre == 200 and st_rev in (200, 204) and st_post == 403 and st_reauth == 200 and st_after == 200 ) rc.add('BAO-10-TOKEN-REVOKE-AND-REAUTH', 'token_lifecycle', 'Revoked OpenBao token fails immediately (403) and service re-authenticates via auth/cert', ok, 'pre=200, revoke=204, post_revoke=403, reauth=200', f'ttl={ttl}s pre={st_pre} revoke={st_rev} post={st_post} reauth={st_reauth} after={st_after}') def check_sealed_openbao_and_recovery(args, rc, op_bao): api_crt, api_key = common.service_client_pair('api') _, pre_kv = op_bao.kv_read('secret/data/messenger/api') ver_before = (((pre_kv or {}).get('data') or {}).get('metadata') or {}).get('version') restarts_before = { cid[:12]: common.container_inspect(cid)['RestartCount'] for cid in common.container_ids('api') } client = Client(args.base_url, args.ca_file) sealed_ok = False degraded_api_ok = False cold_fail_closed = False booted_sealed = False unsealed_ok = False raft_persisted = False try: # 1. Seal OpenBao st_seal, _ = op_bao.seal() st_h1, h1 = common.OpenBaoClient(args.openbao_url, args.ca_file).health() sealed_ok = st_seal in (200, 204) and st_h1 == 503 and bool((h1 or {}).get('sealed')) # 2. Prove running API continues serving cleanly on cached RAM credentials/pools with 0 secret leaks in logs r_ready = client.call('GET', '/health/ready', 200, schema='Health') u = client.user('sealed') rc.register_secret(u['registration']['password']) rc.register_secret(u['token']) restarts_mid = { cid[:12]: common.container_inspect(cid)['RestartCount'] for cid in common.container_ids('api') } api_logs = common.compose('logs', '--since', '2m', '--no-color', 'api', check_result=False).stdout or '' log_leaks = ( common._PEM_KEY_RE.search(api_logs) is not None or common._BAO_TOKEN_RE.search(api_logs) is not None or common._ARGON2_RE.search(api_logs) is not None ) degraded_api_ok = r_ready['status'] == 200 and restarts_mid == restarts_before and not log_leaks # 3. Prove cold auth/cert login fails closed (503 Vault is sealed) probe_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=api_crt, key_file=api_key) st_cold, _ = probe_bao.cert_login('messenger-api') cold_fail_closed = st_cold == 503 # 4. Restart OpenBao container -> MUST boot SEALED (proving no unprotected auto-unseal!) common.compose('restart', 'openbao') deadline = time.monotonic() + 30 while time.monotonic() < deadline: try: st_h2, h2 = common.OpenBaoClient(args.openbao_url, args.ca_file).health() if st_h2 == 503 and (h2 or {}).get('sealed') is True: booted_sealed = True break except Exception: pass time.sleep(0.5) finally: # 5. ALWAYS manually unseal OpenBao via operator script so stand recovers cleanly common.run_host_script('scripts/openbao-unseal.sh', operator_dir=args.operator_dir) deadline = time.monotonic() + 30 while time.monotonic() < deadline: try: st_h3, h3 = common.OpenBaoClient(args.openbao_url, args.ca_file).health() if st_h3 == 200 and (h3 or {}).get('sealed') is False: unsealed_ok = True break except Exception: pass time.sleep(0.5) # Verify Raft secrets & policies survived restart intact op_bao2 = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=op_bao.cert_file, key_file=op_bao.key_file) st_op2, _ = op_bao2.cert_login('messenger-operator') if op_bao2.token: rc.register_secret(op_bao2.token) st_kv2, post_kv = op_bao2.kv_read('secret/data/messenger/api') ver_after = (((post_kv or {}).get('data') or {}).get('metadata') or {}).get('version') raft_persisted = st_op2 == 200 and st_kv2 == 200 and ver_after == ver_before post_ready = client.call('GET', '/health/ready', 200, schema='Health')['status'] == 200 rc.add('BAO-11-SEALED-BOUNDED-BEHAVIOR', 'sealed_recovery', 'When OpenBao is sealed, running API stays bounded (0 restarts) and cold login fails closed (503)', sealed_ok and degraded_api_ok and cold_fail_closed, 'sealed=503, api_ok=True, cold_login=503', f'sealed={sealed_ok}, api_ok={degraded_api_ok}, cold_fail_closed={cold_fail_closed}') rc.add('BAO-12-RESTART-SEALED-AND-MANUAL-UNSEAL', 'sealed_recovery', 'Restarted OpenBao boots sealed, manual scripts/openbao-unseal.sh restores Raft state & API health', booted_sealed and unsealed_ok and raft_persisted and post_ready, 'booted_sealed=True, unsealed=True, raft_kv_intact=True, api=200', f'booted_sealed={booted_sealed}, unsealed={unsealed_ok}, ver_before={ver_before}, ver_after={ver_after}, api_ready={post_ready}') def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) common.add_common_args(parser) args = parser.parse_args(argv) rc = common.ResultCollector('lab7-openbao-lifecycle') ca_pem = _read_pem(args.ca_file) op_crt, op_key = common.operator_cert_pair(args.operator_dir) rogue_crt, rogue_key = common.rogue_cert_pair(args.operator_dir) op_bao = check_openbao_posture(args, rc, op_crt, op_key, rogue_crt, rogue_key) api_bao, api_kv = check_policy_matrix(args, rc) check_secret_rotation(args, rc, api_bao, api_kv, ca_pem) check_cert_rotation_and_revocation(args, rc, ca_pem) check_token_revocation(args, rc, op_bao) check_sealed_openbao_and_recovery(args, rc, op_bao) rc.summary = {'openbao_url': args.openbao_url, 'base_url': args.base_url} (json_path, txt_path), rep = rc.save(args.output_dir, 'openbao-lifecycle') print(f"Report written: {json_path} & {txt_path} (passed={rep['passed']} {rep['passed_count']}/{rep['total']})") return 0 if rep['passed'] else 1 if __name__ == '__main__': try: sys.exit(main()) except Failure as exc: print('FAIL:', common.redact_text(str(exc)), file=sys.stderr) sys.exit(1)