"""API process entrypoint (lab7): uvicorn behind MANDATORY mutual TLS with an identity allowlist. TLS layer (ssl.SSLContext, CERT_REQUIRED): the client must present a certificate chained to the lab root CA. Identity layer (this module, right after the handshake, for every connection including resumed TLS sessions): * DNS SAN must be in ALLOWED_CLIENT_IDENTITIES (only the LB: lb.client.messenger); * the certificate serial must not be in REVOKED_SERIALS_FILE (re-read when it changes, no restart needed). A certificate from the same CA with another identity (worker, api, intruder) is closed before any HTTP byte is read. There is no plaintext listener on the network; the Docker healthcheck uses 127.0.0.1:8081 (app.main). """ import logging import os import ssl import time import uvicorn from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol from app import config, telemetry log = logging.getLogger("messenger.mtls") class Revocations: def __init__(self, path: str) -> None: self.path, self.mtime, self.checked, self.serials = path, None, 0.0, frozenset() def current(self) -> frozenset: now = time.monotonic() if self.path and now - self.checked > 1.0: self.checked = now try: mtime = os.stat(self.path).st_mtime if mtime != self.mtime: with open(self.path, encoding="utf-8") as handle: self.serials = frozenset(line.strip().upper() for line in handle if line.strip()) self.mtime = mtime log.info("mtls_revocations_loaded count=%d", len(self.serials)) except OSError: pass # keep the last known list return self.serials REVOKED = Revocations(config.REVOKED_SERIALS_FILE) rejected = telemetry.meter.create_counter("messenger.mtls.rejected", unit="{connection}", description="API mTLS connections closed by the identity check, by reason") def identity_check(cert: dict) -> tuple: """(allowed, reason, identity, serial) for a validated peer certificate dict (ssl.getpeercert()).""" sans = [value for kind, value in cert.get("subjectAltName", ()) if kind == "DNS"] serial = str(cert.get("serialNumber", "")).upper() identity = sans[0] if sans else "-" if serial in REVOKED.current(): return False, "revoked", identity, serial if not config.ALLOWED_CLIENT_IDENTITIES.intersection(sans): return False, "identity_not_allowed", identity, serial return True, "ok", identity, serial class MutualTLSProtocol(HttpToolsProtocol): def connection_made(self, transport) -> None: super().connection_made(transport) ssl_object = transport.get_extra_info("ssl_object") cert = ssl_object.getpeercert() if ssl_object is not None else None allowed, reason, identity, serial = identity_check(cert or {}) if cert else (False, "no_certificate", "-", "-") if not allowed: rejected.add(1, {"reason": reason}) log.warning("mtls_client_rejected reason=%s identity=%s serial=%s", reason, identity, serial) transport.abort() def ssl_context() -> ssl.SSLContext: ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=config.TLS_CA_FILE) ctx.load_cert_chain(config.TLS_SERVER_CERT_FILE, config.TLS_SERVER_KEY_FILE) ctx.verify_mode = ssl.CERT_REQUIRED ctx.minimum_version = ssl.TLSVersion.TLSv1_2 return ctx class Config(uvicorn.Config): def load(self) -> None: super().load() self.ssl = ssl_context() # replace uvicorn's context: CA + CERT_REQUIRED + TLS >= 1.2 def main() -> None: cfg = Config("app.main:app", host=os.environ.get("APP_HOST", "0.0.0.0"), port=int(os.environ.get("APP_PORT", "8080")), http=MutualTLSProtocol, access_log=False, timeout_graceful_shutdown=int(config.GRACEFUL_TIMEOUT), ssl_certfile=config.TLS_SERVER_CERT_FILE, ssl_keyfile=config.TLS_SERVER_KEY_FILE, ssl_ca_certs=config.TLS_CA_FILE, ssl_cert_reqs=ssl.CERT_REQUIRED) uvicorn.Server(cfg).run() if __name__ == "__main__": main()