forked from mtusi2026/mtusi2026lab7
lab7: обязательное mTLS LB->API с allowlist identity (SAN lb), health только на loopback, скрипт отрицательных проверок mtls_check
This commit is contained in:
@@ -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,
|
||||
|
||||
+29
-11
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:<port> 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)
|
||||
Reference in New Issue
Block a user