#!/usr/bin/env python3 """Public TLS check on :8443, then mTLS identity checks against api:8443. The stand must already be up. Private keys are read from certs/ and are not printed. `--internal` is used by this script when it re-enters through the Docker network. """ from __future__ import annotations import socket import ssl import subprocess import sys import urllib.error import urllib.request from pathlib import Path PROBE = Path(__file__).resolve() ROOT = PROBE.parents[1] if len(PROBE.parents) > 1 else PROBE.parent CERTS = Path("/certs") if "--internal" in sys.argv else ROOT / "certs" PORT = 8443 def handshake(host: str, server_name: str, cert: Path | None, key: Path | None, ca: Path | None) -> str: context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) context.minimum_version = ssl.TLSVersion.TLSv1_2 if ca is not None: context.load_verify_locations(ca) context.check_hostname = True context.verify_mode = ssl.CERT_REQUIRED else: context.check_hostname = False context.verify_mode = ssl.CERT_NONE if cert is not None and key is not None: context.load_cert_chain(cert, key) try: with socket.create_connection((host, PORT), timeout=5) as raw: with context.wrap_socket(raw, server_hostname=server_name) as tls: request = ( "GET /health/ready HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" % server_name ).encode("ascii") tls.sendall(request) data = b"" while True: chunk = tls.recv(4096) if not chunk: break data += chunk head = data.split(b"\r\n", 1)[0].decode("ascii", "replace") return head or "empty" except ssl.SSLError as exc: return "ssl:" + exc.__class__.__name__ except OSError as exc: return "os:" + exc.__class__.__name__ def expect_fail(label: str, result: str) -> None: if result.startswith("HTTP/1.1 200"): raise SystemExit("FAIL %s unexpectedly returned %s" % (label, result)) print("PASS", label, result) def public_checks() -> None: ca = CERTS / "ca.crt" ok = handshake("127.0.0.1", "localhost", None, None, ca) if not ok.startswith("HTTP/1.1 200"): raise SystemExit("FAIL public TLS: %s" % ok) print("PASS public TLS without a client certificate", ok) try: context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) context.check_hostname = True context.verify_mode = ssl.CERT_REQUIRED urllib.request.urlopen("https://localhost:%s/health/ready" % PORT, context=context, timeout=5) raise SystemExit("FAIL empty trust store was accepted") except urllib.error.URLError as exc: if not isinstance(exc.reason, ssl.SSLCertVerificationError): raise SystemExit("FAIL empty trust store failed for a non-certificate reason") from exc print("PASS empty trust store rejected") def internal_checks() -> None: ca = CERTS / "ca.crt" ok = handshake("api", "api", CERTS / "lb-client.crt", CERTS / "lb-client.key", ca) if not ok.startswith("HTTP/1.1 200"): raise SystemExit("FAIL allowed LB identity: %s" % ok) print("PASS allowed LB identity", ok) expect_fail("no client cert", handshake("api", "api", None, None, ca)) expect_fail("other CA", handshake("api", "api", CERTS / "other-client.crt", CERTS / "other-client.key", ca)) expect_fail("same CA wrong identity", handshake("api", "api", CERTS / "stranger.crt", CERTS / "stranger.key", ca)) expect_fail("revoked fingerprint", handshake("api", "api", CERTS / "lb-revoked.crt", CERTS / "lb-revoked.key", ca)) def main() -> None: if "--internal" in sys.argv: internal_checks() return if not (CERTS / "ca.crt").is_file(): raise SystemExit("missing certs/ca.crt; run scripts/bootstrap.ps1") public_checks() probe = Path(__file__).resolve() completed = subprocess.run( [ "docker", "compose", "--env-file", ".env", "run", "--rm", "--no-deps", "--entrypoint", "python", "-v", "%s:/probe.py:ro" % probe, "-v", "%s:/certs:ro" % CERTS, "api", "/probe.py", "--internal", ], cwd=ROOT, check=False, ) if completed.returncode != 0: raise SystemExit(completed.returncode) if __name__ == "__main__": sys.exit(main() or 0)