forked from mtusi2026/mtusi2026lab7
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:
Vendored
+39
-3
@@ -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,
|
||||
|
||||
Vendored
+5
-1
@@ -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,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user