diff --git a/compose.yaml b/compose.yaml index 00fff4f..aefc64d 100644 --- a/compose.yaml +++ b/compose.yaml @@ -296,6 +296,13 @@ services: environment: <<: [*api-env, *otel-env] OTEL_SERVICE_NAME: messenger-api + # Lab 7: the only network listener is mTLS on 8443 (tls.py); plaintext health on loopback. + APP_PORT: 8443 + APP_HEALTH_PORT: 8081 + TLS_CERT_FILE: /run/secrets/api.crt + TLS_KEY_FILE: /run/secrets/api.key + TLS_CLIENT_CA_FILE: /run/secrets/internal-ca.crt + MTLS_ALLOWED_CLIENTS: ${MTLS_ALLOWED_CLIENTS:-lb} secrets: - database_url - cache_url @@ -303,9 +310,12 @@ services: target: s3_access_key_id - source: s3_api_secret_access_key target: s3_secret_access_key + - {source: pki_api_crt, target: api.crt} + - {source: pki_api_key, target: api.key} + - {source: pki_internal_ca, target: internal-ca.crt} # No `ports` and no container_name: replicas are reachable only through `lb`, - # and `--scale api=N` / deploy.replicas works. X-Instance-Id = container hostname. - expose: ["8080"] + # and `--scale api=N` / deploy.replicas works. + expose: ["8443"] healthcheck: test: ["CMD", "python", "-m", "messenger.healthcheck"] interval: 2s @@ -343,6 +353,10 @@ services: secrets: - source: pki_ingress_pem # public-ca leaf + key, SAN localhost/127.0.0.1/::1 target: ingress.pem + - source: pki_lb_pem # client identity towards the API (internal CA, SAN lb) + target: lb.pem + - source: pki_internal_ca + target: internal-ca.crt # verifies the replicas (SAN api) ports: # The ONLY public entry point: HTTPS, on the loopback interfaces only. Both IPv4 and IPv6: # on Windows `localhost` resolves to ::1 first, and a refused ::1 connection costs ~2 s @@ -505,6 +519,31 @@ services: resources: limits: {cpus: "0.5", memory: 128m} + # Lab 7: proof of the LB -> API mTLS against every replica directly (scripts/mtls_check.py): + # docker compose run --rm mtls-check + # Joins `edge` like the LB. Test-only material: the LB client key (positive case), the worker + # certificate (trusted CA, wrong role) and a certificate of a foreign CA with SAN lb. + mtls-check: + profiles: ["tools"] + image: ${API_IMAGE:-mtusi-messenger:lab7} + entrypoint: ["python", "/opt/check/mtls_check.py"] + command: [] + volumes: + - ./scripts/mtls_check.py:/opt/check/mtls_check.py:ro + secrets: + - {source: pki_internal_ca, target: internal-ca.crt} + - {source: pki_lb_crt, target: lb.crt} + - {source: pki_lb_key, target: lb.key} + - {source: pki_worker_crt, target: worker.crt} + - {source: pki_worker_key, target: worker.key} + - {source: pki_foreign_lb_crt, target: foreign-lb.crt} + - {source: pki_foreign_lb_key, target: foreign-lb.key} + restart: "no" + networks: [edge] + deploy: + resources: + limits: {cpus: "0.5", memory: 128m} + # ------------------------------------------------------------------ lab 6: observability # Receives OTLP from api/relay/worker, limits memory, batches, forwards to the three stores. # Distroless image (no shell): its health is the `up{job="otel-collector"}` scrape of :8888. @@ -687,3 +726,23 @@ secrets: # verifies peers with; the CA private keys are mounted nowhere. pki_ingress_pem: file: ./secrets/pki/ingress.pem + pki_lb_pem: + file: ./secrets/pki/lb.pem + pki_internal_ca: + file: ./secrets/pki/internal-ca.crt + pki_api_crt: + file: ./secrets/pki/api.crt + pki_api_key: + file: ./secrets/pki/api.key + pki_lb_crt: + file: ./secrets/pki/lb.crt + pki_lb_key: + file: ./secrets/pki/lb.key + pki_worker_crt: + file: ./secrets/pki/worker.crt + pki_worker_key: + file: ./secrets/pki/worker.key + pki_foreign_lb_crt: # test only: foreign CA, SAN lb + file: ./secrets/pki/foreign-lb.crt + pki_foreign_lb_key: + file: ./secrets/pki/foreign-lb.key diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg index 2e01763..05a5428 100644 --- a/infra/haproxy/haproxy.cfg +++ b/infra/haproxy/haproxy.cfg @@ -28,6 +28,14 @@ # because the API has not seen them. Nothing that may have reached the API is retried by # the LB: an uncertain POST is retried by the CLIENT with the same Idempotency-Key. # No sticky sessions: sessions live in Valkey, every replica serves every user. +# +# Lab 7, LB -> API = mandatory mTLS (contracts/trust-matrix.md). Every server line (traffic AND the +# active health checks, which inherit `ssl`): +# ssl verify required ca-file internal-ca.crt verifyhost api the replica must present a certificate +# of the internal CA with SAN `api`: no MITM, no fake replica; +# crt lb.pem our client identity (internal CA, SAN `lb`, EKU clientAuth). +# The replica checks the chain AND the SAN allowlist (src/messenger/tls.py). Plaintext to the API is +# impossible: the replicas have no plaintext listener on the network. global log stdout format raw local0 info @@ -95,8 +103,8 @@ backend api option httpchk http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api http-check expect status 200 - default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 - server-template api 8 api:8080 + default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 ssl verify required ca-file /run/secrets/internal-ca.crt verifyhost api crt /run/secrets/lb.pem ssl-min-ver TLSv1.2 + server-template api 8 api:8443 # Degraded mode only (see the header): used when NO replica is fully ready. backend api_core @@ -106,8 +114,8 @@ backend api_core option httpchk http-check send meth GET uri /health/ready/core ver HTTP/1.1 hdr Host api http-check expect status 200 - default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 - server-template core 8 api:8080 + default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 ssl verify required ca-file /run/secrets/internal-ca.crt verifyhost api crt /run/secrets/lb.pem ssl-min-ver TLSv1.2 + server-template core 8 api:8443 # Status page for the container healthcheck only: bound to the container's own loopback and NOT # published (lab 7: only the TLS ingress leaves the host). Operators use the admin socket diff --git a/scripts/mtls_check.cmd b/scripts/mtls_check.cmd new file mode 100644 index 0000000..ebba4fd --- /dev/null +++ b/scripts/mtls_check.cmd @@ -0,0 +1,4 @@ +@echo off +rem Windows wrapper: runs scripts\mtls_check.sh (LB -> API mTLS proof) with Git Bash. +"%ProgramFiles%\Git\bin\bash.exe" "%~dp0mtls_check.sh" +exit /b %ERRORLEVEL% diff --git a/scripts/mtls_check.py b/scripts/mtls_check.py new file mode 100644 index 0000000..5b2af6d --- /dev/null +++ b/scripts/mtls_check.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Negative/positive proof of the LB -> API mTLS, against EVERY API replica directly (no LB). + +Runs inside the compose network `edge` (the LB's network), as the tools service `mtls-check`: + + docker compose run --rm mtls-check (wrappers: make mtls-check, scripts/mtls_check.cmd) + +For every IP of the DNS name `api` (one per running replica) it opens fresh connections that +always verify the SERVER (internal CA, hostname `api`) and present, as the client: + + 1. no certificate -> refused in the TLS handshake + 2. certificate of a foreign CA, SAN `lb` (right name) -> refused in the TLS handshake (unknown CA) + 3. certificate of OUR CA, SAN `worker` (wrong role) -> handshake OK, connection closed by the + API before any HTTP response (allowlist) + 4. certificate of OUR CA, SAN `lb` (the LB identity) -> HTTP 200 from GET /health/ready +plus two bypass probes: plaintext HTTP to the mTLS port and the loopback health port from another +container (both must fail). Case 4 on the same address proves the refusals are not "network down". + +Which check refused: the API logs `mtls_identity_rejected` (with the client SAN) ONLY for the +allowlist (case 3); cases 1-2 never reach the application - the TLS layer drops them. The wrapper +scripts/mtls_check.sh prints those log lines after the run. + +Exit 0 only if every expectation holds. Prints no key material. Test-only: this container mounts the +LB's client key (to prove the positive case) and the worker's certificate (a trusted but wrong role). +""" +from __future__ import annotations + +import os +import socket +import ssl +import sys + +PORT = int(os.environ.get("API_PORT", "8443")) +HEALTH_PORT = int(os.environ.get("API_HEALTH_PORT", "8081")) +CA = os.environ.get("INTERNAL_CA", "/run/secrets/internal-ca.crt") +CERTS = { + "none": None, + "foreign-ca SAN=lb": ("/run/secrets/foreign-lb.crt", "/run/secrets/foreign-lb.key"), + "internal-ca SAN=worker": ("/run/secrets/worker.crt", "/run/secrets/worker.key"), + "internal-ca SAN=lb": ("/run/secrets/lb.crt", "/run/secrets/lb.key"), +} +EXPECT = {"none": "refused", "foreign-ca SAN=lb": "refused", "internal-ca SAN=worker": "refused", + "internal-ca SAN=lb": "200"} +REQUEST = b"GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n" + + +def attempt(ip: str, cert, version: ssl.TLSVersion) -> tuple[str, str]: + """(outcome, detail): outcome is the HTTP status code, or 'refused'/'error'. + + TLS 1.3: the client finishes its side of the handshake BEFORE the server has checked the client + certificate, so a refusal shows up as an alert/EOF on the first read. TLS 1.2: the server + checks the client certificate inside the handshake, so the alert names the reason + (certificate required / unknown CA). Both versions must refuse; the identity allowlist always + acts after a successful handshake (the chain is fine there). + """ + ctx = ssl.create_default_context(cafile=CA) # server verification is ALWAYS on + ctx.check_hostname = True + ctx.minimum_version = ctx.maximum_version = version + if cert: + ctx.load_cert_chain(*cert) + stage = "tcp" + try: + with socket.create_connection((ip, PORT), timeout=5) as raw: + stage = "handshake" + with ctx.wrap_socket(raw, server_hostname="api") as tls: + stage = "http" + tls.sendall(REQUEST) + data = tls.recv(4096) + if not data: + return "refused", "closed by the server after the handshake (no HTTP response)" + status = data.split(b" ", 2)[1].decode("ascii", "replace") + return status, f"HTTP {status}; server cert SAN api verified" + except ssl.SSLCertVerificationError as exc: + return "error", f"SERVER certificate not trusted: {exc.verify_message}" + except ssl.SSLError as exc: + if exc.reason == "UNEXPECTED_EOF_WHILE_READING": + return "refused", f"server closed the connection during the {stage} (no HTTP response)" + return "refused", f"TLS alert at {stage}: {exc.reason or exc}" + except (ConnectionResetError, BrokenPipeError, ConnectionAbortedError) as exc: + return "refused", f"connection reset at {stage}: {type(exc).__name__}" + except OSError as exc: + return "error", f"{stage}: {type(exc).__name__}: {exc}" # unreachable etc. is NOT a refusal + + +def plaintext(ip: str, port: int) -> tuple[bool, str]: + """True if a plaintext HTTP request got an HTTP answer (= a bypass).""" + try: + with socket.create_connection((ip, port), timeout=3) as s: + s.sendall(REQUEST) + data = s.recv(64) + if data.startswith(b"HTTP/"): + return True, "answered plaintext HTTP: " + data.split(b"\r\n")[0].decode("latin-1") + return False, "no HTTP answer (TLS-only listener)" + except OSError as exc: + return False, f"{type(exc).__name__}" + + +def main() -> int: + ips = sorted({info[4][0] for info in socket.getaddrinfo("api", PORT, socket.AF_INET, socket.SOCK_STREAM)}) + print(f"API replicas behind DNS name `api`: {len(ips)}") + failures = 0 + for ip in ips: + print(f"\nreplica {ip}:{PORT}") + for version in (ssl.TLSVersion.TLSv1_3, ssl.TLSVersion.TLSv1_2): + tag = "1.3" if version == ssl.TLSVersion.TLSv1_3 else "1.2" + for label, cert in CERTS.items(): + outcome, detail = attempt(ip, cert, version) + good = outcome == EXPECT[label] + failures += not good + print(f" {'PASS' if good else 'FAIL'} TLS {tag} client cert {label:24s} -> {outcome:8s} {detail}") + for port, what in ((PORT, "plaintext HTTP to the mTLS port"), (HEALTH_PORT, "loopback health port from outside")): + bypass, detail = plaintext(ip, port) + failures += bypass + print(f" {'FAIL' if bypass else 'PASS'} {what:51s} -> {detail}") + if not ips: + failures += 1 + print(f"\n{'PASS' if failures == 0 else 'FAIL'}: mTLS LB->API, {len(ips)} replica(s), {failures} failure(s)") + return 0 if failures == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/mtls_check.sh b/scripts/mtls_check.sh new file mode 100644 index 0000000..3211811 --- /dev/null +++ b/scripts/mtls_check.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# LB -> API mTLS proof: scripts/mtls_check.py in the `edge` network + the API's own record of the +# identity refusals (event mtls_identity_rejected, SAN of the refused client) since the run started. +set -eu +cd "$(dirname "$0")/.." +since="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +rc=0 +docker compose run --rm mtls-check 2>/dev/null || rc=$? +echo +echo "API log since $since, identity allowlist refusals (cases 1-2 are dropped by TLS and never logged):" +docker compose logs --no-log-prefix --since "$since" api 2>/dev/null | grep mtls_identity_rejected || echo " (none)" +exit "$rc" diff --git a/src/messenger/__main__.py b/src/messenger/__main__.py index badcc59..7760d07 100644 --- a/src/messenger/__main__.py +++ b/src/messenger/__main__.py @@ -20,7 +20,7 @@ from types import FrameType import uvicorn -from . import __version__, logging_setup, telemetry +from . import __version__, logging_setup, telemetry, tls from .app import create_app from .config import ConfigError, Settings @@ -64,8 +64,18 @@ def main() -> int: logging_setup.configure(settings.log_level) telemetry.setup("messenger-api", settings.instance_id, __version__) app = create_app(settings) + mtls: dict = {} + if settings.tls_cert_file: + # Lab 7: mandatory mTLS (client certificate of the internal CA) + identity allowlist + # MTLS_ALLOWED_CLIENTS checked by the protocol class right after the handshake (tls.py). + context = tls.server_context(settings.tls_cert_file, settings.tls_key_file, settings.tls_client_ca_file) + protocol = tls.protocol_class() + mtls = {"ssl_context_factory": lambda _config, _default: context, "http": protocol, + "ssl_certfile": settings.tls_cert_file} + log.info("mtls_enabled", extra={"fields": {"allowed_clients": sorted(protocol.allowed)}}) config = uvicorn.Config( app, + **mtls, host=settings.host, port=settings.port, log_config=None, diff --git a/src/messenger/app.py b/src/messenger/app.py index cfc902f..db9c99e 100644 --- a/src/messenger/app.py +++ b/src/messenger/app.py @@ -22,7 +22,7 @@ from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Sen from opentelemetry import context as otel_context from opentelemetry import trace -from . import attachments, authhdr, cursor, docs, passwords, repo, telemetry, validation +from . import attachments, authhdr, cursor, docs, passwords, repo, telemetry, tls, validation from .config import Settings from .db import Database from .errors import BASIC_CHALLENGE, ApiError, Conflict, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable @@ -275,19 +275,28 @@ async def ready(request: Request) -> JSONResponse: """200 only if the WHOLE mandatory synchronous path can be served: PostgreSQL, Valkey (SESSION_STORE=valkey) and, since lab 4, the S3 bucket (upload/download of attachments) answer. 503 while draining after SIGTERM. HAProxy routes to such replicas first.""" - if request.app.state.draining: - raise Unavailable("Сервер завершает работу") - db_ok, store_ok, s3_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping(), - storage_of(request).ping()) - if not db_ok: - raise Unavailable("PostgreSQL недоступен") - if not store_ok: - raise Unavailable("Хранилище сессий недоступно") - if not s3_ok: - raise Unavailable("Хранилище файлов (S3) недоступно") + problem = await readiness_problem(request.app) + if problem is not None: + raise Unavailable(problem) return ok({"status": "ok"}) +async def readiness_problem(app: Starlette) -> str | None: + """None if ready, otherwise the (public, secret-free) reason. Shared by GET /health/ready and the + loopback health listener of the Docker healthcheck (tls.health_listener, lab 7).""" + if app.state.draining: + return "Сервер завершает работу" + db_ok, store_ok, s3_ok = await asyncio.gather(app.state.db.ping(), app.state.sessions.ping(), + app.state.storage.ping()) + if not db_ok: + return "PostgreSQL недоступен" + if not store_ok: + return "Хранилище сессий недоступно" + if not s3_ok: + return "Хранилище файлов (S3) недоступно" + return None + + async def ready_core(request: Request) -> JSONResponse: """Not in the contract: readiness WITHOUT S3, for the load balancer's degraded mode only. If S3 is down for every replica, /health/ready is 503 everywhere; HAProxy then routes to @@ -633,9 +642,18 @@ def create_app(settings: Settings | None = None) -> Starlette: tasks.append(asyncio.create_task(janitor_loop(settings.janitor_interval_seconds))) if settings.stats_log_seconds > 0: tasks.append(asyncio.create_task(stats_loop(settings.stats_log_seconds))) + health_server = None + if settings.health_port: + async def probe(path: str) -> int: + if path == "/health/live": + return 200 + return 200 if await readiness_problem(app) is None else 503 + health_server = await tls.health_listener(settings.health_port, probe) try: yield finally: + if health_server is not None: + health_server.close() for task in tasks: task.cancel() await sessions.close() diff --git a/src/messenger/config.py b/src/messenger/config.py index b93802e..c7752e7 100644 --- a/src/messenger/config.py +++ b/src/messenger/config.py @@ -154,6 +154,11 @@ class Settings: queued_republish_seconds: float = 300.0 fault_points: frozenset[str] = frozenset() fault_values: dict[str, int] = field(default_factory=dict) + # Lab 7: TLS of the API listener (mTLS, src/messenger/tls.py) and the loopback health port. + tls_cert_file: str = "" + tls_key_file: str = "" + tls_client_ca_file: str = "" + health_port: int = 0 def fault_value(self, point: str, default: int = 0) -> int: return self.fault_values.get(point, default) @@ -210,6 +215,7 @@ class Settings: message_write_path=_choice("MESSAGE_WRITE_PATH", "function", {"function", "multi"}), **s3_settings(credentials_required=s3_credentials), **jobs_settings(broker_required=False), + **tls_settings(), ) @@ -304,6 +310,24 @@ def s3_settings(*, credentials_required: bool = True) -> dict: ) +def _path(name: str) -> str: + """Optional file path setting; if set, the file must exist (fail at start, not at first use).""" + value = os.environ.get(name, "").strip() + if value and not Path(value).is_file(): + raise ConfigError(f"{name}={value} does not exist") + return value + + +def tls_settings() -> dict: + """Lab 7, API listener: TLS_CERT_FILE/TLS_KEY_FILE = the replica's certificate (SAN `api`), + TLS_CLIENT_CA_FILE = the internal CA that client certificates must chain to. All three or none.""" + cert, key, ca = _path("TLS_CERT_FILE"), _path("TLS_KEY_FILE"), _path("TLS_CLIENT_CA_FILE") + if any((cert, key, ca)) and not all((cert, key, ca)): + raise ConfigError("TLS_CERT_FILE, TLS_KEY_FILE and TLS_CLIENT_CA_FILE must be set together") + return dict(tls_cert_file=cert, tls_key_file=key, tls_client_ca_file=ca, + health_port=_int("APP_HEALTH_PORT", 0, 0, 65535)) + + def jobs_settings(*, broker_required: bool) -> dict: """Lab 5 pipeline: retries, lease, worker limits, cleanup, relay (docs/PIPELINE.md).""" from .pipeline import PIPELINES # local import: pipeline.py imports nothing from here diff --git a/src/messenger/healthcheck.py b/src/messenger/healthcheck.py index 37b0040..f064e02 100644 --- a/src/messenger/healthcheck.py +++ b/src/messenger/healthcheck.py @@ -1,6 +1,7 @@ """Docker HEALTHCHECK probe without curl/wget in the image: `python -m messenger.healthcheck`. - (no arguments) API: GET /health/ready on the local port + (no arguments) API: GET /health/ready on the loopback health port + (APP_HEALTH_PORT, lab 7: the main port requires mTLS) --file /tmp/heartbeat --max-age 30 relay/worker: the main loop wrote its heartbeat recently (it writes it only while its database/broker work) """ @@ -19,7 +20,7 @@ def main(argv: list[str]) -> int: return 0 if time.time() - float(f.read().strip()) <= float(argv[3]) else 1 except (OSError, ValueError): return 1 - port = os.environ.get("APP_PORT", "8080").strip() or "8080" + port = os.environ.get("APP_HEALTH_PORT", "").strip() or os.environ.get("APP_PORT", "8080").strip() or "8080" try: with urllib.request.urlopen(f"http://127.0.0.1:{port}/health/ready", timeout=2) as response: return 0 if response.status == 200 else 1 diff --git a/src/messenger/tls.py b/src/messenger/tls.py new file mode 100644 index 0000000..9d064ad --- /dev/null +++ b/src/messenger/tls.py @@ -0,0 +1,123 @@ +"""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)