forked from mtusi2026/mtusi2026lab7
51 lines
1.9 KiB
Python
51 lines
1.9 KiB
Python
"""Lab 7 API entrypoint: uvicorn with mandatory mTLS and a client-identity allowlist.
|
|
|
|
The CA check (ssl.CERT_REQUIRED) only proves "signed by our CA". Every service and the operator-issued
|
|
"outsider" certificate pass it, so the identity (SAN) is checked here, right after the handshake and
|
|
before a single HTTP byte is parsed. Not allowed => the connection is closed.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import ssl
|
|
|
|
import uvicorn
|
|
from uvicorn.protocols.http.h11_impl import H11Protocol
|
|
|
|
log = logging.getLogger("messenger.tls")
|
|
ALLOWED_SANS = {s.strip().lower() for s in os.getenv("ALLOWED_CLIENT_SANS", "lb").split(",") if s.strip()}
|
|
|
|
|
|
class AllowListProtocol(H11Protocol):
|
|
"""asyncio calls connection_made only after the TLS handshake finished, so getpeercert() is the verified certificate."""
|
|
_accepted = False
|
|
|
|
def connection_made(self, transport):
|
|
ssl_obj = transport.get_extra_info("ssl_object")
|
|
cert = ssl_obj.getpeercert() if ssl_obj else None
|
|
sans = {v.lower() for k, v in (cert or {}).get("subjectAltName", ()) if k == "DNS"}
|
|
if not sans & ALLOWED_SANS:
|
|
log.warning("mTLS identity rejected: %s", sorted(sans) or "no SAN")
|
|
transport.close()
|
|
return
|
|
self._accepted = True
|
|
super().connection_made(transport)
|
|
|
|
def connection_lost(self, exc):
|
|
if self._accepted:
|
|
super().connection_lost(exc)
|
|
|
|
|
|
def main() -> None:
|
|
config = uvicorn.Config(
|
|
os.getenv("APP", "src.main:app"), host=os.getenv("APP_HOST", "0.0.0.0"), port=int(os.getenv("APP_PORT", "8443")),
|
|
ssl_certfile=os.environ["TLS_CERT_FILE"], ssl_keyfile=os.environ["TLS_KEY_FILE"],
|
|
ssl_ca_certs=os.environ["TLS_CA_FILE"], ssl_cert_reqs=ssl.CERT_REQUIRED,
|
|
http=AllowListProtocol, proxy_headers=False, server_header=False, timeout_graceful_shutdown=10, access_log=False)
|
|
uvicorn.Server(config).run()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|