"""Lab 7: TLS contexts of the services and mandatory mTLS with an identity allowlist on the API. Three separate questions on the LB -> API hop (README "Вопросы на защите"): 1. Encryption + server identity: TLS. HAProxy verifies the replica's certificate (internal CA, SAN `api`), so nobody in between can read or impersonate the API. 2. Client identity: the API's TLS context has CERT_REQUIRED and trusts ONLY the internal CA, so the handshake fails without a client certificate or with a certificate of any other CA. A valid chain says only "this certificate was issued by our CA". The same CA also issued the certificates of the worker, the relay, the Collector, ... - so after the handshake `MtlsHttpProtocol.connection_made` compares the client certificate's SAN (DNS names) with MTLS_ALLOWED_CLIENTS (default: `lb`) and closes the connection before a single HTTP byte is read if none matches. A stolen worker key therefore cannot talk to the API directly. 3. Permission for an action: the user's Bearer session (app.py), unchanged. mTLS proves which PROCESS is calling, never which USER. Docker's own healthcheck runs inside the container and has no client certificate: it uses a separate plaintext listener bound to the container's loopback (127.0.0.1:APP_HEALTH_PORT), which serves only GET /health/live and /health/ready (`health_listener`). Another container cannot reach the loopback of this one, so it is not a bypass of the mTLS port. """ from __future__ import annotations import asyncio import logging import os import ssl from collections.abc import Awaitable, Callable from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol log = logging.getLogger("messenger.tls") def client_context(ca_file: str, cert_file: str | None = None, key_file: str | None = None) -> ssl.SSLContext: """Client side of every internal hop: verify the server chain (internal CA) AND its hostname.""" ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=ca_file) ctx.minimum_version = ssl.TLSVersion.TLSv1_2 ctx.check_hostname = True ctx.verify_mode = ssl.CERT_REQUIRED if cert_file: ctx.load_cert_chain(cert_file, key_file) return ctx def server_context(cert_file: str, key_file: str, client_ca_file: str) -> ssl.SSLContext: """API listener: TLS 1.2+, client certificate REQUIRED and verified against the internal CA only.""" ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.minimum_version = ssl.TLSVersion.TLSv1_2 ctx.load_cert_chain(cert_file, key_file) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(cafile=client_ca_file) # no system CAs: only our internal CA return ctx def dns_names(peercert: dict | None) -> list[str]: """DNS SAN entries of a certificate as returned by SSLSocket/SSLObject.getpeercert().""" if not peercert: return [] return [value for kind, value in peercert.get("subjectAltName", ()) if kind == "DNS"] def allowed_clients() -> frozenset[str]: raw = os.environ.get("MTLS_ALLOWED_CLIENTS", "lb") names = frozenset(item.strip() for item in raw.split(",") if item.strip()) if not names: raise ValueError("MTLS_ALLOWED_CLIENTS must list at least one identity") return names class MtlsHttpProtocol(HttpToolsProtocol): """uvicorn's httptools protocol + identity check right after the TLS handshake. asyncio calls connection_made() only when the handshake has completed (TLS 1.3 included), so the verified client certificate is available here. A peer outside the allowlist is aborted: it never reaches the ASGI application, the router or the session check. """ allowed: frozenset[str] = frozenset({"lb"}) def connection_made(self, transport: asyncio.Transport) -> None: # type: ignore[override] ssl_object = transport.get_extra_info("ssl_object") names = dns_names(ssl_object.getpeercert() if ssl_object is not None else None) if ssl_object is None or not self.allowed.intersection(names): peer = transport.get_extra_info("peername") log.warning("mtls_identity_rejected", extra={"fields": { "client_san": names[:4], "peer": peer[0] if peer else None, "allowed": sorted(self.allowed)}}) transport.abort() return super().connection_made(transport) def protocol_class() -> type[MtlsHttpProtocol]: allowed = allowed_clients() return type("MtlsHttpProtocol", (MtlsHttpProtocol,), {"allowed": allowed}) # ------------------------------------------------------------------ loopback health listener async def health_listener(port: int, probe: Callable[[str], Awaitable[int]]) -> asyncio.base_events.Server: """Minimal HTTP/1.0 server on 127.0.0.1: for the Docker healthcheck only. `probe(path)` returns the status code of /health/live or /health/ready (the same checks as the API endpoints). Any other path gets 404 and nothing else of the API is reachable here. """ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: status = 400 try: line = await asyncio.wait_for(reader.readline(), 2) parts = line.decode("latin-1").split() if len(parts) >= 2 and parts[0] == "GET": status = await probe(parts[1]) if parts[1] in ("/health/live", "/health/ready") else 404 except Exception: # noqa: BLE001 - a broken probe connection is the prober's problem status = 503 body = b'{"status":"ok"}' if status == 200 else b'{"status":"unavailable"}' try: writer.write(b"HTTP/1.0 %d X\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s" % (status, len(body), body)) await writer.drain() finally: writer.close() return await asyncio.start_server(handle, "127.0.0.1", port)