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>
This commit is contained in:
2026-11-18 21:17:49 +03:00
co-authored by Claude Opus 5.5
parent 25f5d981c0
commit 8bca5543fd
56 changed files with 2562 additions and 176 deletions
+39 -3
View File
@@ -13,12 +13,15 @@ Valkey переоткрывается сразу, а таймаут не пов
import asyncio
import hashlib
import ssl
import time
from collections.abc import Sequence
from collections.abc import Mapping, Sequence
from types import MappingProxyType
from typing import Any
from opentelemetry.trace import Span
from redis.asyncio import BlockingConnectionPool, Redis
from redis.asyncio.connection import SSLConnection
from redis.asyncio.retry import Retry
from redis.backoff import NoBackoff
from redis.exceptions import ConnectionError as RedisConnectionError
@@ -27,6 +30,7 @@ from redis.exceptions import NoScriptError, RedisError
from src.config.settings import Cache as CacheSettings
from src.infra import telemetry
from src.infra.logger import AbstractLogger, get_logger
from src.infra.tls.client import build_client_context
from src.utils.constants import ATTR_CACHE_RESULT
logger: AbstractLogger = get_logger().bind(module="cache")
@@ -192,14 +196,46 @@ class Cache:
logger.info("Cache is available again")
def create_cache(cache: CacheSettings, *, namespace: str) -> Cache:
"""Кэш с пулом и таймаутами из `[cache]`; соединения — лениво."""
class TlsConnection(SSLConnection):
"""Соединение пула только по TLS с контекстом `build_client_context`
(change `storage-tls`, design, решение 5): CA стенда, имя хоста, TLS 1.3,
`VERIFY_X509_STRICT`. Свой контекст, а не `RedisSSLContext`: тот строит
`create_default_context()` и к CA стенда добавил бы системные корни.
Отказ рукопожатия — `ConnectionError` redis-py, тот же обход кэша."""
def __init__(
self,
*,
client_context: ssl.SSLContext,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
self._client_context = client_context
def _connection_arguments(self) -> Mapping[str, Any]:
# аргументы TCP-соединения родителя SSLConnection: его контекст не
# строится вовсе
kwargs = dict(super(SSLConnection, self)._connection_arguments())
kwargs["ssl"] = self._client_context
return kwargs
def create_cache(
cache: CacheSettings,
*,
namespace: str,
ca_file: str,
) -> Cache:
"""Кэш с пулом и таймаутами из `[cache]`, по TLS с CA `ca_file`;
соединения — лениво."""
# BlockingConnectionPool: при всплеске запросов ждёт свободное
# соединение, а обычный пул сразу бросал бы MaxConnectionsError, и
# здоровый Valkey пропускался бы как отказавший.
# Retry — из redis.asyncio: синхронный класс асинхронное соединение
# вызывает через await, и повтор молча не выполняется
pool = BlockingConnectionPool(
connection_class=TlsConnection,
client_context=build_client_context(ca_file),
host=cache.host,
port=cache.port,
password=cache.password.get_secret_value() or None,
+5 -1
View File
@@ -10,4 +10,8 @@
from src.config import settings
from src.infra.cache.client import create_cache
cache = create_cache(settings.cache, namespace=settings.database.name)
cache = create_cache(
settings.cache,
namespace=settings.database.name,
ca_file=settings.client_tls.ca_file,
)
+9 -2
View File
@@ -20,6 +20,7 @@ from sqlalchemy.pool import AsyncAdaptedQueuePool
from sqlalchemy.util import await_
from src.config.settings import Database
from src.infra.tls.client import build_client_context
from src.utils.constants import DB_APPLICATION_NAME, DB_CLOSE_TIMEOUT_SECONDS
@@ -104,8 +105,13 @@ def _ping_once(dbapi_connection: Any) -> bool:
return True
def create_engine(database: Database) -> AsyncEngine:
"""Engine с ограниченным пулом и таймаутами из `[database]`."""
def create_engine(database: Database, *, ca_file: str) -> AsyncEngine:
"""Engine с ограниченным пулом и таймаутами из `[database]`.
TLS обязателен (change `storage-tls`, design, решение 5): с `SSLContext`
asyncpg не переходит на открытый текст, сервер проверяется по CA стенда
(`[client_tls] ca_file`) и имени `database.host`; ошибка рукопожатия —
`OSError`, тот же путь недоступности (`is_db_unavailable`, 503)."""
server_settings = {
"application_name": DB_APPLICATION_NAME,
"statement_timeout": str(database.statement_timeout_ms),
@@ -137,6 +143,7 @@ def create_engine(database: Database) -> AsyncEngine:
"timeout": database.connect_timeout_seconds,
"connection_class": BoundedCloseConnection,
"server_settings": server_settings,
"ssl": build_client_context(ca_file),
},
)
engine.dialect.do_ping = _ping_once
+1 -1
View File
@@ -11,5 +11,5 @@
from src.config import settings
from src.infra.db.engine import create_engine, create_session_factory
engine = create_engine(settings.database)
engine = create_engine(settings.database, ca_file=settings.client_tls.ca_file)
session_factory = create_session_factory(engine)
+25 -4
View File
@@ -214,10 +214,18 @@ class ObjectStorage:
открываются при первом запросе.
"""
def __init__(self, s3: S3Settings, *, namespace: str) -> None:
def __init__(
self,
s3: S3Settings,
*,
namespace: str,
ca_file: str,
) -> None:
self.namespace = namespace
self.bucket = s3.bucket
self._settings = s3
# CA стенда (`[client_tls] ca_file`): шлюз — только HTTPS
self._ca_file = ca_file
self._endpoint = f"{s3.host}:{s3.port}"
self._timeout_seconds = s3.timeout_seconds
self._client: Any = None
@@ -363,6 +371,12 @@ class ObjectStorage:
def _create_client(self) -> Any:
s3 = self._settings
# TLS к шлюзу (change storage-tls, design, решение 5): botocore
# проверяет цепочку только по этому CA и имя s3.host. Пустой путь
# botocore понял бы как verify=False — без CA клиента нет (точки
# входа проверяют поле до старта, `client_tls_problems`)
if not self._ca_file:
raise ValueError("client_tls.ca_file is required for S3")
config = AioConfig(
# виртуальные хосты bucket.s3 Docker DNS не разрешает
s3={"addressing_style": "path"},
@@ -387,6 +401,7 @@ class ObjectStorage:
return get_session().create_client(
"s3",
endpoint_url=s3.endpoint_url,
verify=self._ca_file,
region_name=s3.region,
aws_access_key_id=s3.access_key_id.get_secret_value(),
aws_secret_access_key=s3.secret_access_key.get_secret_value(),
@@ -562,6 +577,12 @@ class ObjectStorage:
return round((time.monotonic() - started) * 1000)
def create_object_storage(s3: S3Settings, *, namespace: str) -> ObjectStorage:
"""Хранилище объектов по `[s3]`; клиент и соединения — лениво."""
return ObjectStorage(s3, namespace=namespace)
def create_object_storage(
s3: S3Settings,
*,
namespace: str,
ca_file: str,
) -> ObjectStorage:
"""Хранилище объектов по `[s3]` по HTTPS с CA `ca_file`; клиент и
соединения — лениво."""
return ObjectStorage(s3, namespace=namespace, ca_file=ca_file)
+1
View File
@@ -14,4 +14,5 @@ from src.infra.s3.client import create_object_storage
object_storage = create_object_storage(
settings.s3,
namespace=settings.database.name,
ca_file=settings.client_tls.ca_file,
)
+24 -4
View File
@@ -1,8 +1,21 @@
"""TLS процесса API (change `pki-ingress-mtls`): контекст сервера и проверка
`[api_tls]` — `context.py` (без логгера); протокол с allowlist identity —
`protocol.py`, его импортирует только uvicorn по строке
`PROTOCOL_IMPORT_PATH`."""
"""TLS процесса (без логгера: пакет импортирует и `migrations/env.py`).
- Сервер API (change `pki-ingress-mtls`): контекст сервера и проверка
`[api_tls]` — `context.py`; протокол с allowlist identity — `protocol.py`,
его импортирует только uvicorn по строке `PROTOCOL_IMPORT_PATH`.
- Клиенты хранилищ (change `storage-tls`): контекст клиента и проверка
`[client_tls]` при старте процесса — `client.py`.
"""
from src.infra.tls.client import (
API_STORAGES,
CLEANER_STORAGES,
MIGRATION_STORAGES,
RELAY_STORAGES,
WORKER_STORAGES,
build_client_context,
client_tls_problems,
)
from src.infra.tls.context import (
api_tls_problems,
build_server_context,
@@ -14,10 +27,17 @@ from src.infra.tls.context import (
PROTOCOL_IMPORT_PATH = "src.infra.tls.protocol:AllowlistHttpToolsProtocol"
__all__ = [
"API_STORAGES",
"CLEANER_STORAGES",
"MIGRATION_STORAGES",
"PROTOCOL_IMPORT_PATH",
"RELAY_STORAGES",
"WORKER_STORAGES",
"api_tls_problems",
"build_client_context",
"build_server_context",
"client_identities",
"client_tls_problems",
"is_allowed_client",
"ssl_context_factory",
]
+85
View File
@@ -0,0 +1,85 @@
"""TLS клиентов процесса к серверам зависимостей: PostgreSQL, Valkey и S3
(change `storage-tls`, design, решения 5, 6; спек `transport-security`, «TLS
к хранилищам стенда»; правило `.claude/rules/tls.md`).
Один построитель контекста на всех клиентов, где контекст задаём мы (asyncpg,
redis-py): доверие — только CA стенда из `[client_tls] ca_file` (системное
хранилище не загружается), проверка цепочки и имени хоста, TLS 1.3,
`VERIFY_X509_STRICT`. CRL клиенты хранилищ не читают (решение 6): отзыв
серверных identity хранилищ — change `rotation-revocation`. Выключателя
проверки нет.
Клиент S3 (aiobotocore) получает путь к тому же CA (`verify=ca_file`):
контекст строит botocore (только этот CA, проверка имени, TLS ≥ 1.2;
шлюз и клиент договариваются о 1.3).
`client_tls_problems` — проверка при старте точки входа, до первого
подключения: CA задан и загружается, адрес каждого хранилища процесса — DNS-
имя (сертификаты хранилищ несут только DNS SAN, IP-адрес не пройдёт проверку
имени).
"""
import ipaddress
import ssl
from collections.abc import Iterable
from src.config.settings import Settings
# хранилища по процессам: имена секций настроек с полем host
API_STORAGES = ("database", "cache", "s3")
WORKER_STORAGES = ("database", "s3")
CLEANER_STORAGES = ("database", "s3")
RELAY_STORAGES = ("database",)
MIGRATION_STORAGES = ("database",)
def build_client_context(ca_file: str) -> ssl.SSLContext:
"""`SSLContext` клиента хранилища: CA стенда, имя хоста, TLS 1.3.
Системные корни не загружаются никогда: без `ca_file` в контексте нет
ни одного доверенного CA, и любое рукопожатие отказывает (fail-closed;
`create_default_context` с пустым путём загрузил бы системное
хранилище). Ошибки файла — `OSError` и `ssl.SSLError` (их ловит
проверка при старте)."""
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
if ca_file:
context.load_verify_locations(cafile=ca_file)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
context.minimum_version = ssl.TLSVersion.TLSv1_3
context.verify_flags |= ssl.VERIFY_X509_STRICT
return context
def _is_ip_literal(host: str) -> bool:
try:
ipaddress.ip_address(host.strip("[]"))
except ValueError:
return False
return True
def client_tls_problems(
settings: Settings,
storages: Iterable[str],
) -> list[str]:
"""Имена неверных полей для старта процесса (без значений и путей).
`client_tls.ca_file` — пусто, не читается или не PEM сертификата;
`<секция>.host` — IP-адрес вместо имени хранилища, к которому ходит
процесс."""
problems: list[str] = []
ca_file = settings.client_tls.ca_file
if not ca_file:
problems.append("client_tls.ca_file")
else:
try:
build_client_context(ca_file)
except (OSError, ssl.SSLError, ValueError):
problems.append("client_tls.ca_file")
problems += [
f"{name}.host"
for name in storages
if _is_ip_literal(getattr(settings, name).host)
]
return problems