"""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 contextlib import os import shutil import socket import ssl import subprocess import time from collections.abc import AsyncIterator, Awaitable, Callable from pathlib import Path from typing import Any import pytest import uvicorn from src.api import health_listener 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 from src.utils.constants import ( DB_CLOSE_TIMEOUT_SECONDS, HEALTH_LISTENER_READY_TIMEOUT_SECONDS, READINESS_DB_TIMEOUT_SECONDS, ) pytestmark = pytest.mark.anyio PKI_SCRIPT = BASE_DIR / "infra" / "pki" / "pki.sh" PKI_CONFIG = BASE_DIR / "infra" / "pki" / "openssl.cnf" # срок просроченного CRL: nextUpdate через секунду, проверка — после него EXPIRED_CRL_SECONDS = 1 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 f"{type(e).__name__}: {getattr(e, 'reason', None)}" return data.decode("latin-1") or "closed" @contextlib.asynccontextmanager async def _serving( tls: ApiTls, monkeypatch: pytest.MonkeyPatch, app: Callable[..., Awaitable[None]] = _ok_app, ) -> AsyncIterator[tuple[int, _Recorder]]: """uvicorn с TLS API (контекст и протокол процесса) на loopback.""" recorder = _Recorder() monkeypatch.setattr(tls_protocol, "logger", recorder) for name in ("client_auth", "allowed_clients"): monkeypatch.setattr(settings.api_tls, name, getattr(tls, name)) port = _free_port() config = uvicorn.Config( 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) try: yield port, recorder finally: server.should_exit = True await task @pytest.fixture async def mtls_server( pki: Path, monkeypatch: pytest.MonkeyPatch, ) -> AsyncIterator[tuple[int, _Recorder]]: async with _serving(_stand_tls(pki), monkeypatch) as served: yield served 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", }, ), ] def _server_reason(root: Path, cert: tuple[Path, Path]) -> str: """Причина отказа клиенту контекстом сервера API (рукопожатие через буферы в памяти, без uvicorn).""" to_server, to_client = ssl.MemoryBIO(), ssl.MemoryBIO() context = ssl.create_default_context(cafile=root / "stand" / "ca.crt") context.load_cert_chain(certfile=cert[0], keyfile=cert[1]) client = context.wrap_bio(to_client, to_server, server_hostname="api") server = build_server_context(_stand_tls(root)).wrap_bio( to_server, to_client, server_side=True, ) for _ in range(4): with contextlib.suppress(ssl.SSLWantReadError): client.do_handshake() try: server.do_handshake() except ssl.SSLWantReadError: continue except ssl.SSLCertVerificationError as e: return e.verify_message return "accepted" return "no outcome" async def test_expired_client_leaf( pki: Path, mtls_server: tuple[int, _Recorder], ) -> None: """Сценарий «Истёкший leaf» (change `rotation-revocation`, design, решение 12): leaf разрешённой identity с концом срока через секунды принят до него и отвергнут после.""" port, recorder = mtls_server end = time.time() + 4 _pki( { "OPENSSL": _openssl() or "openssl", "PKI_OPERATOR_DIR": str(pki / "op"), "PKI_STAND_DIR": str(pki / "stand"), }, "issue", "haproxy", "--profile", "client", "--san", "haproxy", "--not-after", time.strftime("%Y%m%d%H%M%SZ", time.gmtime(end)), "--out", str(pki / "short"), ) cert = (pki / "short" / "haproxy.crt", pki / "short" / "haproxy.key") before = await asyncio.to_thread(_client_exchange, port, pki, cert) assert before.startswith("HTTP/1.1 200"), before await asyncio.sleep(max(0.0, end - time.time()) + 1.5) after = await asyncio.to_thread(_client_exchange, port, pki, cert) assert not after.startswith("HTTP/"), after # alert asyncio не отправляет: причину называет контекст сервера reason = await asyncio.to_thread(_server_reason, pki, cert) assert reason == "certificate has expired" stand = pki / "stand" fresh = (stand / "haproxy.crt", stand / "haproxy.key") alive = await asyncio.to_thread(_client_exchange, port, pki, fresh) assert alive.startswith("HTTP/1.1 200"), alive assert recorder.records == [] @pytest.fixture(scope="module") def revocation(tmp_path_factory: pytest.TempPathFactory) -> Path: """Свой PKI (общий `pki` не трогаем): отозванный `haproxy` (копия пары до `revoke`), новый `haproxy` от `stand` и CRL того же CA с истёкшим nextUpdate (спек `pki`, «Отзыв и CRL»).""" binary = _openssl() if binary is None: pytest.skip("OpenSSL 3+ is required for TLS handshake tests") root = tmp_path_factory.mktemp("revocation") env = { "OPENSSL": binary, "PKI_OPERATOR_DIR": str(root / "op"), "PKI_STAND_DIR": str(root / "stand"), } _pki(env, "stand") revoked = root / "revoked" revoked.mkdir() for name in ("haproxy.crt", "haproxy.key"): shutil.copy(root / "stand" / name, revoked / name) _pki(env, "revoke", "haproxy") # отозванный leaf `stand` перевыпускает, CRL — заново с отозванным _pki(env, "stand") subprocess.run( # noqa: S603 [ binary, "ca", "-config", str(PKI_CONFIG), "-gencrl", "-crlsec", str(EXPIRED_CRL_SECONDS), "-out", str(root / "expired-crl.pem"), ], env={**os.environ, **env, "PKI_SAN": "DNS:unused"}, capture_output=True, check=True, ) time.sleep(EXPIRED_CRL_SECONDS + 1) return root async def test_revoked_client_and_expired_crl( revocation: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: stand = revocation / "stand" revoked = revocation / "revoked" fresh = (stand / "haproxy.crt", stand / "haproxy.key") async def exchange(port: int, cert: tuple[Path, Path]) -> str: return await asyncio.to_thread( _client_exchange, port, revocation, cert, ) async with _serving(_stand_tls(revocation), monkeypatch) as (port, rec): # действующий CRL: новый haproxy проходит, отозванный — отказ на # рукопожатии (до HTTP и до проверки allowlist: записи нет) assert (await exchange(port, fresh)).startswith("HTTP/1.1 200") outcome = await exchange( port, (revoked / "haproxy.crt", revoked / "haproxy.key"), ) # причину alert клиент не видит (asyncio закрывает соединение), но # тот же сервер принял новую пару того же CA — отказ дал CRL assert not outcome.startswith("HTTP/"), outcome assert rec.records == [] expired = _stand_tls( revocation, crl_file=str(revocation / "expired-crl.pem"), ) async with _serving(expired, monkeypatch) as (port, rec): # просроченный CRL: даже действующий haproxy не проходит outcome = await exchange(port, fresh) assert not outcome.startswith("HTTP/"), outcome assert rec.records == [] def _bytes_after_handshake( server_context: ssl.SSLContext, client_context: ssl.SSLContext, server_hostname: str, ) -> int: """Рукопожатие в памяти до конца с обеих сторон; сколько байт сервер отдал клиенту сверх того, что клиент прочитал в рукопожатии.""" s_in, s_out, c_in, c_out = (ssl.MemoryBIO() for _ in range(4)) server = server_context.wrap_bio(s_in, s_out, server_side=True) client = client_context.wrap_bio( c_in, c_out, server_hostname=server_hostname, ) done = {"client": False, "server": False} for _ in range(10): for name, conn in (("client", client), ("server", server)): if not done[name]: with contextlib.suppress(ssl.SSLWantReadError): conn.do_handshake() done[name] = True s_in.write(c_out.read()) c_in.write(s_out.read()) if all(done.values()): break assert all(done.values()), done return c_in.pending @pytest.mark.parametrize("client_auth", [True, False]) def test_no_messages_after_handshake(pki: Path, client_auth: bool) -> None: """Verify C1 change `https-tooling`: билеты сессии TLS 1.3 после рукопожатия — непрочитанные байты у клиента, который только пишет тело; его обрыв тогда — RST, и процесс API его не замечал.""" stand = pki / "stand" client_context = ssl.create_default_context(cafile=stand / "ca.crt") if client_auth: tls = _stand_tls(pki) client_context.load_cert_chain( certfile=stand / "haproxy.crt", keyfile=stand / "haproxy.key", ) name = "api" else: tls = _stand_tls( pki, client_auth=False, cert_file=str(stand / "ingress.crt"), key_file=str(stand / "ingress.key"), ) name = "localhost" after = _bytes_after_handshake( build_server_context(tls), client_context, name, ) assert after == 0 # тело обрываемой загрузки и срок, за который сервер обязан заметить обрыв ABORTED_BODY = b"\x89PNG\r\n\x1a\n" + bytes(1024 * 1024) ABORT_NOTICED_S = 1.0 ABORT_ROUNDS = 3 def _aborted_upload(port: int, root: Path) -> None: """Клиент в роли LB: заголовки, 1 MiB тела частью chunked, закрытие сокета без чтения ответа (как httpx на исключении итератора тела).""" stand = root / "stand" context = ssl.create_default_context(cafile=stand / "ca.crt") context.load_cert_chain( certfile=stand / "haproxy.crt", keyfile=stand / "haproxy.key", ) with ( socket.create_connection(("127.0.0.1", port), timeout=5) as raw, context.wrap_socket(raw, server_hostname="api") as conn, ): conn.sendall( b"POST /upload HTTP/1.1\r\nHost: api\r\n" b"Transfer-Encoding: chunked\r\n\r\n", ) conn.sendall( f"{len(ABORTED_BODY):x}\r\n".encode() + ABORTED_BODY + b"\r\n", ) async def test_aborted_body_noticed( pki: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """Обрыв тела по mTLS доходит до приложения как `http.disconnect` сразу, а не по сроку (verify C1 change `https-tooling`).""" outcomes: list[str] = [] async def body_app(_scope: Any, receive: Any, send: Any) -> None: outcome = "complete" try: async with asyncio.timeout(ABORT_NOTICED_S * 5): while True: message = await receive() if message["type"] == "http.disconnect": outcome = "disconnect" break if not message.get("more_body"): break except TimeoutError: outcome = "timeout" outcomes.append(outcome) with contextlib.suppress(OSError): await send( {"type": "http.response.start", "status": 200, "headers": []}, ) await send({"type": "http.response.body", "body": b""}) async with _serving(_stand_tls(pki), monkeypatch, body_app) as (port, _): for attempt in range(ABORT_ROUNDS): await asyncio.to_thread(_aborted_upload, port, pki) loop = asyncio.get_running_loop() deadline = loop.time() + ABORT_NOTICED_S while len(outcomes) <= attempt and loop.time() < deadline: await asyncio.sleep(0.02) assert outcomes[attempt:] == ["disconnect"], (attempt, outcomes) 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_slow_readiness_gets_503( monkeypatch: pytest.MonkeyPatch, ) -> None: """Verify S2: ответ готовности не под сроком чтения запроса, а под своим сроком больше срока готовности; срок вышел — 503, а не обрыв.""" assert HEALTH_LISTENER_READY_TIMEOUT_SECONDS > ( READINESS_DB_TIMEOUT_SECONDS + DB_CLOSE_TIMEOUT_SECONDS ) monkeypatch.setattr( health_listener, "HEALTH_LISTENER_READ_TIMEOUT_SECONDS", 0.1, ) monkeypatch.setattr( health_listener, "HEALTH_LISTENER_READY_TIMEOUT_SECONDS", 0.5, ) request = b"GET /health/ready HTTP/1.1\r\n\r\n" async def answer(delay: float) -> bytes: async def check() -> bool: await asyncio.sleep(delay) return False listener = HealthListener(ready=check, instance_id="a", port=0) await listener.start() try: return await _raw_request(listener.port, request) finally: await listener.close() # проверка дольше срока чтения, но в своём сроке — её 503 assert (await answer(0.3)).startswith(b"HTTP/1.1 503") # проверка дольше срока готовности — тоже 503, не дожидаясь её started = time.monotonic() assert (await answer(5)).startswith(b"HTTP/1.1 503") assert time.monotonic() - started < 2 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