#!/usr/bin/env python3 """Negative/positive checks for the lab7 trust matrix. Covers: * LB -> API mTLS: no client cert, foreign CA, trusted CA but wrong identity, correct LB identity; * external HTTPS: untrusted CA is rejected (make test-security also covers it); * OpenBao: the application policy reads only kv/messenger and is denied elsewhere; the AppRole login works with the issued credentials. Run from the repository root after the stand is up: python scripts/security_internal.py """ import json import ssl import sys import urllib.error import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PKI = ROOT / "pki" CA = str(PKI / "ca.crt") GATEWAY_URL = "https://localhost:9443/health/live" OPENBAO = "https://127.0.0.1:8200" def client_context(cert: str | None, key: str | None = None) -> ssl.SSLContext: ctx = ssl.create_default_context(cafile=CA) ctx.check_hostname = True ctx.verify_mode = ssl.CERT_REQUIRED if cert: ctx.load_cert_chain(certfile=str(PKI / cert), keyfile=str(PKI / (key or cert.replace(".crt", ".key")))) return ctx def get(url: str, ctx: ssl.SSLContext, token: str | None = None): headers = {"X-Vault-Token": token} if token else {} request = urllib.request.Request(url, headers=headers) try: with urllib.request.urlopen(request, context=ctx, timeout=10) as response: return response.status, response.read().decode()[:200] except urllib.error.HTTPError as error: return error.code, error.read().decode()[:200] except (ssl.SSLError, urllib.error.URLError) as error: return None, type(error).__name__ + ": " + str(getattr(error, "reason", error)) def attempt(label: str, cert: str | None, expected, key: str | None = None): ctx = client_context(cert, key) status, body = get(GATEWAY_URL, ctx) ok = (status in expected) if isinstance(expected, (list, tuple, set)) else (status == expected) print(f"{'PASS' if ok else 'FAIL'} {label}: status={status} detail={body[:80]}") return ok def openbao_checks() -> bool: role_id = (ROOT / "secrets" / "openbao_role_id.txt").read_text().strip() secret_id = (ROOT / "secrets" / "openbao_secret_id.txt").read_text().strip() ctx = client_context(None) login = urllib.request.Request( OPENBAO + "/v1/auth/approle/login", data=json.dumps({"role_id": role_id, "secret_id": secret_id}).encode(), headers={"Content-Type": "application/json"}, method="POST") with urllib.request.urlopen(login, context=ctx, timeout=10) as response: token = json.loads(response.read())["auth"]["client_token"] own_status, _ = get(OPENBAO + "/v1/kv/data/messenger", ctx, token) other_status, _ = get(OPENBAO + "/v1/kv/data/other", ctx, token) ok = own_status == 200 and other_status == 403 print(f"{'PASS' if ok else 'FAIL'} openbao policy: own={own_status} forbidden={other_status}") return ok def main() -> None: if not (PKI / "ca.crt").exists(): raise SystemExit("PKI is missing: run scripts/pki.sh first") results = [ attempt("no client certificate", None, [400, 495, 496, 497, None]), attempt("foreign CA certificate", "foreign-client.crt", [400, 403, 495, 496, 497, None]), attempt("trusted CA, wrong identity", "other.crt", [403]), attempt("trusted CA, LB identity", "lb.crt", [200]), ] results.append(openbao_checks()) if not all(results): raise SystemExit("security checks failed") print("PASS: trust matrix negatives and positives verified") if __name__ == "__main__": main()