"""TLS процесса API (change `pki-ingress-mtls`, design, решения 5, 6, 10; спек `transport-security`): решение allowlist, проверка `[api_tls]` по режимам, настоящее рукопожатие с uvicorn на loopback и слушатель health. Сертификаты — `infra/pki/pki.sh` во временный каталог; без OpenSSL 3+ тесты рукопожатия пропускаются с причиной. """ import asyncio import os import shutil import socket import ssl import subprocess from collections.abc import Awaitable, Callable from pathlib import Path from typing import Any import pytest import uvicorn from src.api.health_listener import HealthListener from src.config import settings from src.config.settings import BASE_DIR, ApiTls from src.infra.tls import ( api_tls_problems, build_server_context, client_identities, is_allowed_client, ) from src.infra.tls import protocol as tls_protocol from src.schemas.enums import RunModeEnum pytestmark = pytest.mark.anyio PKI_SCRIPT = BASE_DIR / "infra" / "pki" / "pki.sh" REQUEST = b"GET /health/live HTTP/1.1\r\nHost: api\r\n\r\n" def _openssl() -> str | None: binary = os.environ.get("OPENSSL") or shutil.which("openssl") if not binary: return None version = subprocess.run( # noqa: S603 [binary, "version"], capture_output=True, text=True, check=False, ).stdout if not version.startswith("OpenSSL ") or int(version[8]) < 3: return None return binary def _pki(env: dict[str, str], *args: str) -> None: subprocess.run( # noqa: S603 ["/bin/sh", str(PKI_SCRIPT), *args], env={**os.environ, **env}, capture_output=True, check=True, ) @pytest.fixture(scope="module") def pki(tmp_path_factory: pytest.TempPathFactory) -> Path: binary = _openssl() if binary is None: pytest.skip("OpenSSL 3+ is required for TLS handshake tests") root = tmp_path_factory.mktemp("pki") env = { "OPENSSL": binary, "PKI_OPERATOR_DIR": str(root / "op"), "PKI_STAND_DIR": str(root / "stand"), } _pki(env, "stand") _pki( env, "issue", "mtls-probe", "--profile", "client", "--san", "mtls-probe", "--days", "1", "--out", str(root / "probe"), ) other = { "OPENSSL": binary, "PKI_OPERATOR_DIR": str(root / "other-op"), "PKI_STAND_DIR": str(root / "other"), } _pki(other, "stand") return root def _stand_tls(root: Path, **overrides: Any) -> ApiTls: stand = root / "stand" fields: dict[str, Any] = { "cert_file": str(stand / "api.crt"), "key_file": str(stand / "api.key"), "client_ca_file": str(stand / "ca.crt"), "crl_file": str(stand / "crl.pem"), } return ApiTls(**{**fields, **overrides}) def test_identities_from_dns_san_only() -> None: peercert = { "subject": ((("commonName", "api"),),), "subjectAltName": (("DNS", "haproxy"), ("IP Address", "10.0.0.1")), } assert client_identities(peercert) == ("haproxy",) assert client_identities(None) == () assert client_identities({"subject": ()}) == () @pytest.mark.parametrize( ("identities", "allowed", "expected"), [ (("haproxy",), ["haproxy"], True), (("mtls-probe",), ["haproxy"], False), (("x", "haproxy"), ["haproxy"], True), ((), ["haproxy"], False), (("haproxy",), [], False), ], ) def test_allowlist_decision( identities: tuple[str, ...], allowed: list[str], expected: bool, ) -> None: assert is_allowed_client(identities, allowed) is expected def test_docker_requires_all_files_and_client_auth(tmp_path: Path) -> None: missing = str(tmp_path / "missing.pem") tls = ApiTls( cert_file=missing, key_file="", client_ca_file=missing, crl_file="", client_auth=False, allowed_clients=[], ) assert api_tls_problems(tls, RunModeEnum.DOCKER) == [ "cert_file", "key_file", "client_ca_file", "crl_file", "client_auth", "allowed_clients", ] def test_console_requires_certificate_and_key_only(tmp_path: Path) -> None: tls = ApiTls(cert_file="", key_file="", client_auth=False) assert api_tls_problems(tls, RunModeEnum.CONSOLE) == [ "cert_file", "key_file", ] def test_stand_files_pass_both_modes(pki: Path) -> None: assert api_tls_problems(_stand_tls(pki), RunModeEnum.DOCKER) == [] console = _stand_tls( pki, client_auth=False, client_ca_file="", crl_file="", ) assert api_tls_problems(console, RunModeEnum.CONSOLE) == [] def test_docker_without_crl_or_client_auth(pki: Path) -> None: assert api_tls_problems( _stand_tls(pki, crl_file=""), RunModeEnum.DOCKER, ) == ["crl_file"] assert api_tls_problems( _stand_tls(pki, client_auth=False), RunModeEnum.DOCKER, ) == ["client_auth"] assert api_tls_problems( _stand_tls(pki, allowed_clients=[]), RunModeEnum.DOCKER, ) == ["allowed_clients"] def test_key_of_other_certificate(pki: Path) -> None: tls = _stand_tls(pki, key_file=str(pki / "stand" / "haproxy.key")) assert api_tls_problems(tls, RunModeEnum.DOCKER) == ["api_tls"] class _Recorder: def __init__(self) -> None: self.records: list[tuple[str, dict[str, Any]]] = [] def warning(self, event: str, **fields: Any) -> None: self.records.append((event, fields)) async def _ok_app(scope: dict[str, Any], _receive: Any, send: Any) -> None: assert scope["type"] == "http" await send({"type": "http.response.start", "status": 200, "headers": []}) await send({"type": "http.response.body", "body": b"ok"}) def _free_port() -> int: with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) return sock.getsockname()[1] def _client_exchange( port: int, root: Path, cert: tuple[Path, Path] | None, ) -> str: """Ответ сервера (начало) или имя класса TLS-ошибки клиента.""" context = ssl.create_default_context(cafile=root / "stand" / "ca.crt") if cert is not None: context.load_cert_chain(certfile=cert[0], keyfile=cert[1]) try: with ( socket.create_connection(("127.0.0.1", port), timeout=5) as raw, context.wrap_socket(raw, server_hostname="api") as conn, ): conn.sendall(REQUEST) data = conn.recv(64) except (ssl.SSLError, ConnectionError) as e: return type(e).__name__ return data.decode("latin-1") or "closed" @pytest.fixture async def mtls_server( pki: Path, monkeypatch: pytest.MonkeyPatch, ) -> Any: recorder = _Recorder() monkeypatch.setattr(tls_protocol, "logger", recorder) tls = _stand_tls(pki) for name in ("client_auth", "allowed_clients"): monkeypatch.setattr(settings.api_tls, name, getattr(tls, name)) port = _free_port() config = uvicorn.Config( _ok_app, host="127.0.0.1", port=port, lifespan="off", log_config=None, ssl_context_factory=lambda _c, _d: build_server_context(tls), http=tls_protocol.AllowlistHttpToolsProtocol, ) server = uvicorn.Server(config) task = asyncio.create_task(server.serve()) for _ in range(100): if server.started: break await asyncio.sleep(0.05) yield port, recorder server.should_exit = True await task async def test_handshake_outcomes( pki: Path, mtls_server: tuple[int, _Recorder], ) -> None: port, recorder = mtls_server stand = pki / "stand" async def exchange(cert: tuple[Path, Path] | None) -> str: return await asyncio.to_thread(_client_exchange, port, pki, cert) allowed = await exchange((stand / "haproxy.crt", stand / "haproxy.key")) assert allowed.startswith("HTTP/1.1 200") # без сертификата, чужой CA, серверный сертификат — TLS-ошибка у клиента for cert in ( None, (pki / "other" / "haproxy.crt", pki / "other" / "haproxy.key"), (stand / "ingress.crt", stand / "ingress.key"), ): outcome = await exchange(cert) assert not outcome.startswith("HTTP/"), (cert, outcome) assert recorder.records == [] # запрещённая identity того же CA — закрыто без ответа и запись probe = pki / "probe" denied = await exchange( (probe / "mtls-probe.crt", probe / "mtls-probe.key"), ) assert not denied.startswith("HTTP/"), denied assert recorder.records == [ ( "Rejected TLS client", { "client_identity": ["mtls-probe"], "reason": "identity_not_allowed", }, ), ] async def _raw_request(port: int, request: bytes) -> bytes: reader, writer = await asyncio.open_connection("127.0.0.1", port) writer.write(request) await writer.drain() data = await reader.read() writer.close() return data async def _with_listener( ready: bool, action: Callable[[int], Awaitable[None]], ) -> None: calls: list[int] = [] async def check() -> bool: calls.append(1) return ready listener = HealthListener(ready=check, instance_id="alias", port=0) await listener.start() try: await action(listener.port) finally: await listener.close() async def test_health_listener_answers_health_only() -> None: async def action(port: int) -> None: live = await _raw_request(port, b"GET /health/live HTTP/1.1\r\n\r\n") ready = await _raw_request(port, b"GET /health/ready HTTP/1.1\r\n\r\n") me = await _raw_request( port, b"GET /api/v1/users/me HTTP/1.1\r\nAuthorization: Bearer x\r\n\r\n", ) create = await _raw_request( port, b"POST /api/v1/users HTTP/1.1\r\nContent-Length: 2\r\n\r\n{}", ) assert live.startswith(b"HTTP/1.1 200") assert b"Connection: close" in live assert b"X-Instance-Id: alias" in live assert ready.startswith(b"HTTP/1.1 200") assert me.startswith(b"HTTP/1.1 404") assert create.startswith(b"HTTP/1.1 404") await _with_listener(True, action) async def test_health_listener_not_ready() -> None: async def action(port: int) -> None: ready = await _raw_request(port, b"GET /health/ready HTTP/1.1\r\n\r\n") assert ready.startswith(b"HTTP/1.1 503") assert b'"code": "unavailable"' in ready await _with_listener(False, action) async def test_health_listener_on_loopback_only() -> None: listener = HealthListener(ready=_never_called, instance_id="a", port=0) await listener.start() try: host = listener._server.sockets[0].getsockname()[0] # noqa: SLF001 assert host == "127.0.0.1" finally: await listener.close() async def _never_called() -> bool: raise AssertionError