forked from mtusi2026/mtusi2026lab7
519 lines
16 KiB
Python
519 lines
16 KiB
Python
"""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,
|
||
) -> 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(
|
||
_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)
|
||
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",
|
||
},
|
||
),
|
||
]
|
||
|
||
|
||
@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)
|
||
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
|