wip: fix verify remarks for pki-ingress-mtls

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 11:58:12 +03:00
co-authored by Claude Opus 5.5
parent 50cb54f0a1
commit 2649eb24b4
22 changed files with 309 additions and 52 deletions
+154 -11
View File
@@ -7,18 +7,21 @@
"""
import asyncio
import contextlib
import os
import shutil
import socket
import ssl
import subprocess
from collections.abc import Awaitable, Callable
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
@@ -30,10 +33,18 @@ from src.infra.tls import (
)
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"
@@ -218,7 +229,7 @@ def _client_exchange(
root: Path,
cert: tuple[Path, Path] | None,
) -> str:
"""Ответ сервера (начало) или имя класса TLS-ошибки клиента."""
"""Ответ сервера (начало) или класс и причина 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])
@@ -230,18 +241,18 @@ def _client_exchange(
conn.sendall(REQUEST)
data = conn.recv(64)
except (ssl.SSLError, ConnectionError) as e:
return type(e).__name__
return f"{type(e).__name__}: {getattr(e, 'reason', None)}"
return data.decode("latin-1") or "closed"
@pytest.fixture
async def mtls_server(
pki: Path,
@contextlib.asynccontextmanager
async def _serving(
tls: ApiTls,
monkeypatch: pytest.MonkeyPatch,
) -> Any:
) -> AsyncIterator[tuple[int, _Recorder]]:
"""uvicorn с TLS API (контекст и протокол процесса) на loopback."""
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()
@@ -260,9 +271,20 @@ async def mtls_server(
if server.started:
break
await asyncio.sleep(0.05)
yield port, recorder
server.should_exit = True
await task
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(
@@ -303,6 +325,87 @@ async def test_handshake_outcomes(
]
@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 == []
async def _raw_request(port: int, request: bytes) -> bytes:
reader, writer = await asyncio.open_connection("127.0.0.1", port)
writer.write(request)
@@ -361,6 +464,46 @@ async def test_health_listener_not_ready() -> None:
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()