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:
@@ -69,6 +69,7 @@ from src.infra.db import ( # noqa: E402
|
||||
)
|
||||
from src.infra.db.models.base import Base # noqa: E402
|
||||
from src.infra.db.uow import SqlAlchemyUnitOfWork # noqa: E402
|
||||
from src.infra.tls import build_client_context # noqa: E402
|
||||
|
||||
_created = False
|
||||
|
||||
@@ -99,6 +100,9 @@ async def _admin_connection(database: str = "postgres") -> asyncpg.Connection:
|
||||
password=source.password.get_secret_value(),
|
||||
database=database,
|
||||
timeout=source.connect_timeout_seconds,
|
||||
# PostgreSQL стенда по сети — только TLS (change storage-tls): тот же
|
||||
# контекст клиента, что у процессов, CA — CLIENT_TLS__CA_FILE от make
|
||||
ssl=build_client_context(settings.client_tls.ca_file),
|
||||
)
|
||||
|
||||
|
||||
@@ -137,8 +141,13 @@ def anyio_backend() -> str:
|
||||
|
||||
|
||||
def make_engine(**overrides: object) -> AsyncEngine:
|
||||
"""Свой engine к временной базе: тот же `create_engine`, что у процессов."""
|
||||
return create_engine(settings.database.model_copy(update=overrides))
|
||||
"""Свой engine к временной базе: тот же `create_engine`, что у процессов,
|
||||
по TLS с CA стенда. Через `TcpProxy` — `host="localhost"`: прокси передаёт
|
||||
байты TLS как есть, имя сервера проверяется по SAN identity postgres."""
|
||||
return create_engine(
|
||||
settings.database.model_copy(update=overrides),
|
||||
ca_file=settings.client_tls.ca_file,
|
||||
)
|
||||
|
||||
|
||||
def make_uow(
|
||||
|
||||
@@ -382,8 +382,9 @@ async def test_deadline_in_second_block_single_record(
|
||||
async with TcpProxy(*proxy_target) as proxy:
|
||||
proxied = create_engine(
|
||||
dependencies.settings.database.model_copy(
|
||||
update={"host": "127.0.0.1", "port": proxy.port},
|
||||
update={"host": "localhost", "port": proxy.port},
|
||||
),
|
||||
ca_file=dependencies.settings.client_tls.ca_file,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dependencies,
|
||||
@@ -506,7 +507,10 @@ async def test_code_order_with_postgres_down(
|
||||
down_settings = dependencies.settings.database.model_copy(
|
||||
update={"port": 1, "connect_timeout_seconds": 1},
|
||||
)
|
||||
down = create_engine(down_settings)
|
||||
down = create_engine(
|
||||
down_settings,
|
||||
ca_file=dependencies.settings.client_tls.ca_file,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dependencies,
|
||||
"session_factory",
|
||||
|
||||
@@ -172,7 +172,7 @@ async def test_frozen_on_rollback(
|
||||
) -> None:
|
||||
"""Сценарий «PostgreSQL заморожен при откате»."""
|
||||
async with TcpProxy(*proxy_target) as proxy:
|
||||
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
|
||||
engine = make_engine(host="localhost", port=proxy.port, pool_size=1)
|
||||
uow = make_uow(make_factory(engine), timeout_seconds=0.5)
|
||||
started = None
|
||||
with pytest.raises(exceptions.ServiceUnavailable):
|
||||
@@ -192,7 +192,7 @@ async def test_frozen_at_exception_in_block(proxy_target) -> None:
|
||||
"""Исключение при замороженном сервере: откат под сроком блока, отказ БД
|
||||
заменяет доменное исключение, а не висит до разморозки."""
|
||||
async with TcpProxy(*proxy_target) as proxy:
|
||||
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
|
||||
engine = make_engine(host="localhost", port=proxy.port, pool_size=1)
|
||||
uow = make_uow(make_factory(engine), timeout_seconds=0.5)
|
||||
started = time.monotonic()
|
||||
with pytest.raises(exceptions.ServiceUnavailable):
|
||||
@@ -210,7 +210,7 @@ async def test_frozen_at_exception_in_block(proxy_target) -> None:
|
||||
async def test_cancel_with_open_transaction(proxy_target) -> None:
|
||||
"""Сценарий «Отмена при открытой транзакции»."""
|
||||
async with TcpProxy(*proxy_target) as proxy:
|
||||
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
|
||||
engine = make_engine(host="localhost", port=proxy.port, pool_size=1)
|
||||
uow = make_uow(make_factory(engine), timeout_seconds=30)
|
||||
inside = asyncio.Event()
|
||||
|
||||
@@ -284,7 +284,7 @@ async def test_no_sessions_over_pool_after_freeze(proxy_target) -> None:
|
||||
baseline = await _app_sessions(connection)
|
||||
async with TcpProxy(*proxy_target) as proxy:
|
||||
engine = make_engine(
|
||||
host="127.0.0.1",
|
||||
host="localhost",
|
||||
port=proxy.port,
|
||||
pool_size=pool_size,
|
||||
)
|
||||
@@ -329,7 +329,7 @@ async def test_soft_close_is_graceful(proxy_target) -> None:
|
||||
baseline = await _app_sessions(connection)
|
||||
async with TcpProxy(*proxy_target) as proxy:
|
||||
engine = make_engine(
|
||||
host="127.0.0.1",
|
||||
host="localhost",
|
||||
port=proxy.port,
|
||||
pool_size=1,
|
||||
)
|
||||
@@ -340,8 +340,11 @@ async def test_soft_close_is_graceful(proxy_target) -> None:
|
||||
await engine.dispose()
|
||||
sessions = await _settled_sessions(connection, limit=baseline)
|
||||
assert sessions == baseline
|
||||
# единственная порция клиента после проверки — Terminate
|
||||
assert proxy.client_writes == before + 1
|
||||
# после проверки клиент шлёт только Terminate; с TLS к PostgreSQL
|
||||
# (change storage-tls) за ним — запись close_notify мягкого
|
||||
# закрытия TLS: две записи, прокси может прочитать их одной
|
||||
# порцией. Запроса после Terminate нет — иначе порций больше
|
||||
assert before + 1 <= proxy.client_writes <= before + 2
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
@@ -393,7 +396,7 @@ async def test_ping_detects_dropped_connection_through_proxy(
|
||||
`_handle_exception` адаптера настоящие. Смена их имён ломает разбор обрыва, и
|
||||
следующий блок падает ошибкой вместо нового соединения (design, решение 7)."""
|
||||
async with TcpProxy(*proxy_target) as proxy:
|
||||
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
|
||||
engine = make_engine(host="localhost", port=proxy.port, pool_size=1)
|
||||
pings: list[bool] = []
|
||||
real_ping = engine.dialect.do_ping
|
||||
|
||||
@@ -424,7 +427,7 @@ async def test_ping_detects_dropped_connection_through_proxy(
|
||||
async def test_ping_is_one_exchange(proxy_target) -> None:
|
||||
"""Проверка при выдаче — один обмен, а не `BEGIN`, `;`, `ROLLBACK`."""
|
||||
async with TcpProxy(*proxy_target) as proxy:
|
||||
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
|
||||
engine = make_engine(host="localhost", port=proxy.port, pool_size=1)
|
||||
async with engine.connect():
|
||||
pass
|
||||
# первая проверка готовит выражение, вторая — повторная
|
||||
|
||||
Reference in New Issue
Block a user