"""TLS server in front of the local API. The proxy requires a client certificate from our CA, the LB URI SAN, and a fingerprint that is still listed in the allow file. Uvicorn stays on 127.0.0.1. """ from __future__ import annotations import asyncio import hashlib import logging import ssl from app import config logger = logging.getLogger("messenger.tls") ALLOWED_URI = "spiffe://messenger/lb" def _allowed_fingerprints() -> set[str]: path = config.MTLS_ALLOW_FILE if not path: return set() try: text = open(path, encoding="utf-8").read() except OSError: logger.warning("mTLS allow file is not readable") return set() return {line.strip().lower() for line in text.splitlines() if line.strip()} def _identity_ok(ssl_object: ssl.SSLObject) -> bool: cert = ssl_object.getpeercert() if not cert: return False names = [value for kind, value in cert.get("subjectAltName", ()) if kind == "URI"] if ALLOWED_URI not in names: return False der = ssl_object.getpeercert(binary_form=True) if not der: return False fingerprint = hashlib.sha256(der).hexdigest() return fingerprint in _allowed_fingerprints() async def _pipe(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: try: while True: chunk = await reader.read(65536) if not chunk: break writer.write(chunk) await writer.drain() except Exception: pass finally: try: writer.close() await writer.wait_closed() except Exception: pass async def _handle(client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter) -> None: ssl_object = client_writer.get_extra_info("ssl_object") if ssl_object is None or not _identity_ok(ssl_object): client_writer.close() await client_writer.wait_closed() return try: upstream_reader, upstream_writer = await asyncio.open_connection("127.0.0.1", config.PORT) except Exception: client_writer.close() await client_writer.wait_closed() return await asyncio.gather( _pipe(client_reader, upstream_writer), _pipe(upstream_reader, client_writer), ) def _context() -> ssl.SSLContext: cert = config.TLS_SERVER_CERT_FILE or config.TLS_CERT_FILE key = config.TLS_SERVER_KEY_FILE or config.TLS_KEY_FILE context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) # TLS 1.3 in this OpenSSL finishes the handshake before the client # certificate is checked, so a missing cert or a foreign CA still connects. # TLS 1.2 rejects both during the handshake. Identity is checked after that. context.minimum_version = ssl.TLSVersion.TLSv1_2 context.maximum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(cert, key) context.load_verify_locations(config.TLS_CA_FILE) context.verify_mode = ssl.CERT_REQUIRED return context async def serve() -> None: cert = config.TLS_SERVER_CERT_FILE or config.TLS_CERT_FILE key = config.TLS_SERVER_KEY_FILE or config.TLS_KEY_FILE if not (cert and key and config.TLS_CA_FILE and config.MTLS_ALLOW_FILE): raise SystemExit("server certificate, CA and MTLS_ALLOW_FILE are required") server = await asyncio.start_server(_handle, "0.0.0.0", config.MTLS_PORT, ssl=_context()) logger.info("mTLS proxy listening on %s", config.MTLS_PORT) async with server: await server.serve_forever() def main() -> None: logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") asyncio.run(serve()) if __name__ == "__main__": main()