"""Exercise the per-replica mTLS sidecar from its isolated network namespace.""" import ssl import urllib.error import urllib.request import os BASE = os.getenv("MTLS_PROBE_URL", "https://api1:8443/health/live") def probe(cert=None, key=None): context = ssl.create_default_context(cafile="/run/tls/service-ca.crt") context.check_hostname = True if cert: context.load_cert_chain(cert, key) try: with urllib.request.urlopen(BASE, context=context, timeout=4) as response: return response.status except urllib.error.HTTPError as exc: return exc.code def rejected_at_client_auth(cert=None, key=None): try: status = probe(cert, key) except urllib.error.URLError as exc: if not isinstance(exc.reason, ssl.SSLError): raise SystemExit("FAIL: client-auth probe failed for a non-TLS reason") from exc return True # Nginx may complete the TLS handshake and answer 400 before proxying when # ssl_verify_client is on and the peer sends no acceptable certificate. return status == 400 if not rejected_at_client_auth(): raise SystemExit("FAIL: API sidecar accepted a connection without a client certificate") print("PASS: no client certificate rejected") if not rejected_at_client_auth("/test/foreign-client.crt", "/test/foreign-client.key"): raise SystemExit("FAIL: API sidecar accepted a foreign-CA client certificate") print("PASS: foreign CA rejected") if probe("/test/wrong-lb-client.crt", "/test/wrong-lb-client.key") != 403: raise SystemExit("FAIL: trusted but wrong client identity was not denied with 403") print("PASS: wrong identity from the trusted LB CA denied") if probe("/test/lb-client.crt", "/test/lb-client.key") != 200: raise SystemExit("FAIL: allowlisted LB identity did not reach API") print("PASS: allowlisted LB identity accepted")