"""Pilot stub of mozdit-checker (design D1): /check/tls with the unified response. stdlib only; trusts the pilot CA so the self-signed test certificates validate.""" import json, socket, ssl, sys, time from datetime import datetime, timezone from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import urlparse, parse_qs def check_tls(host, port): now = datetime.now(timezone.utc) base = {"target": f"{host}:{port}", "check": "tls", "measured_at": now.isoformat()} try: ctx = ssl.create_default_context() ctx.load_verify_locations("/certs/ca.pem") with socket.create_connection((host, port), timeout=5) as sock: with ctx.wrap_socket(sock, server_hostname=host) as tls: cert = tls.getpeercert() expires = datetime.fromtimestamp(ssl.cert_time_to_seconds(cert["notAfter"]), timezone.utc) days = (expires - now).days status = "critical" if days < 7 else "warning" if days < 21 else "ok" return {**base, "status": status, "values": {"days_left": days, "not_after": expires.isoformat()}} except Exception as exc: # unreachable or invalid -> critical per D5 return {**base, "status": "critical", "values": {"error": str(exc)[:200]}} class Handler(BaseHTTPRequestHandler): def _send(self, code, body): data = json.dumps(body).encode() self.send_response(code); self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) def do_GET(self): url = urlparse(self.path); q = parse_qs(url.query) if url.path == "/health": return self._send(200, {"ok": True}) if url.path == "/check/tls": host = (q.get("host") or [""])[0]; port = int((q.get("port") or ["443"])[0]) if not host: return self._send(400, {"error": "host required"}) return self._send(200, check_tls(host, port)) self._send(404, {"error": "not found"}) def log_message(self, *a): pass HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()