Files
mtusi2026lab7-safronov/service-tests/unit/test_client_tls.py
T
ricoromaandClaude Opus 5.5 8bca5543fd feat: require TLS to PostgreSQL, Valkey and S3
Storage servers accept only TLS 1.3 (pg_hba hostssl / hostnossl reject,
Valkey port 0, S3 gateway HTTPS only) with stand identities postgres,
valkey and s3. Clients trust only the stand CA from [client_tls] ca_file
and check the host name; no switch to disable verification. Processes
exit with code 2 without a CA or with an IP storage address. Temporary
stands, CI and bench/ run on TLS storages; make storage_tls_check adds
negative checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:17:49 +03:00

401 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""TLS клиентов к хранилищам (change `storage-tls`, design, решения 5, 13;
спек `transport-security`, «TLS к хранилищам стенда», и
`service-configuration`, «Доверие к серверам зависимостей»).
Флаги контекста, проверка при старте по хранилищам процесса, проводка
клиентов (asyncpg, redis-py, aiobotocore) и настоящее рукопожатие клиента
кэша с локальным TLS-сервером RESP: CA стенда и имя — успех, посторонний CA и
адрес вне SAN — отказ, и отказ — промах кэша, а не исключение.
Сертификаты — `infra/pki/pki.sh` во временный каталог (identity `valkey` из
списка); без OpenSSL 3+ тесты рукопожатия пропускаются с причиной.
"""
import asyncio
import contextlib
import json
import os
import shutil
import ssl
import subprocess
import sys
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Any
import pytest
from src.config import settings
from src.config.settings import BASE_DIR, S3, Cache, Database, Settings
from src.infra.cache import client as cache_client
from src.infra.cache.client import TlsConnection, create_cache
from src.infra.db import engine as db_engine
from src.infra.s3 import client as s3_client
from src.infra.s3.client import create_object_storage
from src.infra.tls import (
API_STORAGES,
CLEANER_STORAGES,
MIGRATION_STORAGES,
RELAY_STORAGES,
WORKER_STORAGES,
build_client_context,
client_tls_problems,
)
pytestmark = pytest.mark.anyio
PKI_SCRIPT = BASE_DIR / "infra" / "pki" / "pki.sh"
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
@pytest.fixture(scope="module")
def pki(tmp_path_factory: pytest.TempPathFactory) -> Path:
"""Два CA: стенда (`stand`, leaf по списку identity) и посторонний."""
binary = _openssl()
if binary is None:
pytest.skip("OpenSSL 3+ is required for TLS handshake tests")
root = tmp_path_factory.mktemp("pki")
for name in ("stand", "other"):
subprocess.run( # noqa: S603
["/bin/sh", str(PKI_SCRIPT), "stand"],
env={
**os.environ,
"OPENSSL": binary,
"PKI_OPERATOR_DIR": str(root / f"{name}-op"),
"PKI_STAND_DIR": str(root / name),
},
capture_output=True,
check=True,
)
return root
def test_context_flags(tmp_path: Path, pki: Path) -> None:
context = build_client_context(str(pki / "stand" / "ca.crt"))
assert context.verify_mode == ssl.CERT_REQUIRED
assert context.check_hostname is True
assert context.minimum_version == ssl.TLSVersion.TLSv1_3
assert context.verify_flags & ssl.VERIFY_X509_STRICT
# отзыв серверных identity хранилищ клиенты не проверяют (решение 6)
assert not context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF
# доверие — ровно CA стенда, системных корней нет
assert len(context.get_ca_certs()) == 1
assert tmp_path.exists()
def test_context_without_ca_trusts_nothing() -> None:
"""Пустой путь не включает системное хранилище: fail-closed."""
context = build_client_context("")
assert context.get_ca_certs() == []
assert context.verify_mode == ssl.CERT_REQUIRED
def _settings(**sections: Any) -> Settings:
return Settings.model_construct(
client_tls=settings.client_tls.model_copy(
update=sections.pop("client_tls", {}),
),
database=Database(host=sections.pop("database_host", "postgres")),
cache=Cache(host=sections.pop("cache_host", "valkey")),
s3=S3(host=sections.pop("s3_host", "s3")),
)
def test_problems_ca_file(tmp_path: Path, pki: Path) -> None:
garbage = tmp_path / "garbage.crt"
garbage.write_text("not a certificate\n")
cases = {
"": ["client_tls.ca_file"],
str(tmp_path / "missing.crt"): ["client_tls.ca_file"],
str(garbage): ["client_tls.ca_file"],
str(pki / "stand" / "ca.crt"): [],
}
for path, expected in cases.items():
loaded = _settings(client_tls={"ca_file": path})
problems = client_tls_problems(loaded, API_STORAGES)
assert problems == expected, path
# сообщения — имена полей, без путей
assert all(path not in name for name in problems if path)
@pytest.mark.parametrize(
("storages", "expected"),
[
(API_STORAGES, ["database.host", "cache.host", "s3.host"]),
(WORKER_STORAGES, ["database.host", "s3.host"]),
(CLEANER_STORAGES, ["database.host", "s3.host"]),
(RELAY_STORAGES, ["database.host"]),
(MIGRATION_STORAGES, ["database.host"]),
],
)
def test_problems_ip_host_per_process(
pki: Path,
storages: tuple[str, ...],
expected: list[str],
) -> None:
"""IP-адрес вместо имени (`.env` до change) — поле хранилища процесса."""
loaded = _settings(
client_tls={"ca_file": str(pki / "stand" / "ca.crt")},
database_host="127.0.0.1",
cache_host="::1",
s3_host="10.0.0.5",
)
assert client_tls_problems(loaded, storages) == expected
def test_names_pass(pki: Path) -> None:
for host in ("localhost", "postgres"):
loaded = _settings(
client_tls={"ca_file": str(pki / "stand" / "ca.crt")},
database_host=host,
cache_host=host,
s3_host=host,
)
assert client_tls_problems(loaded, API_STORAGES) == []
def test_engine_requires_tls_context(
pki: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""`create_engine` передаёт asyncpg `SSLContext`: с ним TLS обязателен
(семантика `verify-full`), и это контекст CA стенда."""
captured: dict[str, Any] = {}
def fake_engine(_url: Any, **kwargs: Any) -> Any:
captured.update(kwargs)
class _Dialect:
do_ping = None
class _Engine:
dialect = _Dialect()
return _Engine()
monkeypatch.setattr(db_engine, "create_async_engine", fake_engine)
db_engine.create_engine(Database(), ca_file=str(pki / "stand" / "ca.crt"))
context = captured["connect_args"]["ssl"]
assert isinstance(context, ssl.SSLContext)
assert context.check_hostname is True
assert len(context.get_ca_certs()) == 1
def test_cache_pool_uses_tls_connection(pki: Path) -> None:
cache = create_cache(
Cache(host="valkey"),
namespace="db",
ca_file=str(pki / "stand" / "ca.crt"),
)
pool = cache._client.connection_pool
assert pool.connection_class is TlsConnection
connection = pool.make_connection()
context = connection._connection_arguments()["ssl"]
assert context is pool.connection_kwargs["client_context"]
assert context.minimum_version == ssl.TLSVersion.TLSv1_3
assert len(context.get_ca_certs()) == 1
def test_s3_client_https_and_verify(
pki: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
captured: dict[str, Any] = {}
class _Session:
def create_client(self, *_args: Any, **kwargs: Any) -> None:
captured.update(kwargs)
monkeypatch.setattr(s3_client, "get_session", _Session)
ca_file = str(pki / "stand" / "ca.crt")
storage = create_object_storage(
S3(host="s3", port=8333),
namespace="db",
ca_file=ca_file,
)
storage._create_client()
assert captured["endpoint_url"] == "https://s3:8333"
assert captured["verify"] == ca_file
def test_s3_client_without_ca_refuses() -> None:
"""Пустой путь botocore понял бы как `verify=False`: клиента нет."""
storage = create_object_storage(S3(), namespace="db", ca_file="")
with pytest.raises(ValueError, match="client_tls.ca_file"):
storage._create_client()
ENTRYPOINTS = {
"api": (["-m", "src"], "startup"),
"worker": (["-m", "src.worker"], "worker"),
"relay": (["-m", "src.relay"], "relay"),
"cleaner": (["-m", "src.cleaner", "--once"], "cleaner"),
"migrations": (["-m", "alembic", "upgrade", "head"], "migrations"),
}
def _run_entrypoint(
name: str,
pki: Path,
**env: str,
) -> tuple[int, list[dict[str, Any]]]:
"""Точка входа процессом до первого подключения: код и записи JSON."""
args, _module = ENTRYPOINTS[name]
stand = pki / "stand"
result = subprocess.run( # noqa: S603
[sys.executable, *args],
cwd=BASE_DIR,
env={
**os.environ,
"APP__RUN_MODE": "console",
# консольный TLS API — чтобы дойти до проверки клиентов хранилищ
"API_TLS__CERT_FILE": str(stand / "api.crt"),
"API_TLS__KEY_FILE": str(stand / "api.key"),
"API_TLS__CLIENT_AUTH": "false",
"DATABASE__HOST": "localhost",
"CACHE__HOST": "localhost",
"S3__HOST": "localhost",
"TELEMETRY__ENABLED": "false",
**env,
},
capture_output=True,
text=True,
timeout=60,
check=False,
)
records = []
for line in result.stdout.splitlines():
with contextlib.suppress(ValueError):
records.append(json.loads(line))
return result.returncode, records
@pytest.mark.parametrize("name", sorted(ENTRYPOINTS))
@pytest.mark.parametrize(
("case", "env", "field"),
[
("no_ca", {"CLIENT_TLS__CA_FILE": ""}, "client_tls.ca_file"),
("ip_host", {"DATABASE__HOST": "127.0.0.1"}, "database.host"),
],
)
def test_entrypoint_refuses_before_connecting(
pki: Path,
name: str,
case: str,
env: dict[str, str],
field: str,
) -> None:
"""Спек `service-configuration`, «Процесс без CA» и «IP-адрес вместо
имени хранилища»: код 2, запись «Invalid client TLS settings» называет
поле, пути CA в выводе нет."""
env = {"CLIENT_TLS__CA_FILE": str(pki / "stand" / "ca.crt"), **env}
code, records = _run_entrypoint(name, pki, **env)
assert code == 2, (case, records)
refusal = [
r for r in records if r["event"] == "Invalid client TLS settings"
]
assert len(refusal) == 1, records
assert refusal[0]["fields"] == [field]
assert refusal[0]["module"] == ENTRYPOINTS[name][1]
assert str(pki) not in json.dumps(records)
async def _resp_session(
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
) -> None:
"""Сервер RESP из двух ответов: `GET` — значение, прочее — `+OK`."""
with contextlib.suppress(Exception):
while line := await reader.readline():
count = int(line[1:])
parts = []
for _ in range(count):
size = int((await reader.readline())[1:])
parts.append((await reader.readexactly(size + 2))[:-2])
if parts[0].upper() == b"GET":
writer.write(b"$5\r\nvalue\r\n")
else:
writer.write(b"+OK\r\n")
await writer.drain()
writer.close()
@contextlib.asynccontextmanager
async def _valkey_tls(pki: Path) -> AsyncIterator[int]:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
stand = pki / "stand"
context.load_cert_chain(stand / "valkey.crt", stand / "valkey.key")
server = await asyncio.start_server(
_resp_session,
host="127.0.0.1",
port=0,
ssl=context,
)
try:
yield server.sockets[0].getsockname()[1]
finally:
server.close()
await server.wait_closed()
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))
def info(self, event: str, **fields: Any) -> None:
self.records.append((event, fields))
@pytest.mark.parametrize(
("ca", "host", "expected"),
[
("stand", "localhost", "value"),
("other", "localhost", None),
("stand", "127.0.0.1", None),
],
)
async def test_cache_handshake(
pki: Path,
monkeypatch: pytest.MonkeyPatch,
ca: str,
host: str,
expected: str | None,
) -> None:
"""CA стенда и имя из SAN — ответ Valkey; посторонний CA или адрес вне
SAN — промах и одна запись «Cache is unavailable», без исключения."""
recorder = _Recorder()
monkeypatch.setattr(cache_client, "logger", recorder)
async with _valkey_tls(pki) as port:
cache = create_cache(
Cache(host=host, port=port, timeout_seconds=2),
namespace="db",
ca_file=str(pki / ca / "ca.crt"),
)
try:
assert await cache.get("key") == expected
finally:
await cache.aclose()
events = [event for event, _ in recorder.records]
if expected is None:
assert events == ["Cache is unavailable"]
assert "CERTIFICATE_VERIFY_FAILED" in recorder.records[0][1]["error"]
else:
assert events == []