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
+7 -5
View File
@@ -14,10 +14,12 @@
# не трогает (change https-tooling, design, решение 2).
#
# Healthcheck PostgreSQL проверяет служебную базу postgres, а не базу
# приложения: с 127.0.0.1 образ пускает без пароля (trust), и каждая
# проверка — сессия в pg_stat_database базы. Иначе раз в 5 с она попадала
# бы в счётчик теста «Соединения пула не переоткрываются» (действие hook
# db-sessions).
# приложения: до change storage-tls с 127.0.0.1 образ пускал без пароля
# (trust), и каждая проверка была сессией в pg_stat_database базы. Иначе раз
# в 5 с она попадала бы в счётчик теста «Соединения пула не переоткрываются»
# (действие hook db-sessions). С change storage-tls — по TLS с проверкой CA
# этой PKI и имени, как healthcheck рабочего стенда (pg_hba.conf стенда:
# без TLS — отказ).
#
# У PostgreSQL — init (tini) с PID 1, postmaster — его потомок. fault_hook.py
# fill-connections отвязывает psql в фоне sh, запущенного docker compose exec;
@@ -32,7 +34,7 @@ services:
init: true
ports: !reset []
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U \"$$POSTGRES_USER\" -d postgres"]
test: ["CMD-SHELL", "pg_isready -d \"host=$$POSTGRES_HOST hostaddr=127.0.0.1 port=$$PGPORT dbname=postgres user=$$POSTGRES_USER sslmode=verify-full sslrootcert=/run/secrets/ca.crt\""]
valkey:
ports: !reset []
# свой S3 со своим volume, порт API S3 не публикуется. Срок остановки
+23 -6
View File
@@ -243,17 +243,24 @@ SERVICES = ("postgres", "valkey", "s3", "rabbitmq")
# (failures.compose.yml), а проба после start / unpause ходит в базу
# приложения и добавляет в её pg_stat_database одну сессию: тест «Соединения
# пула не переоткрываются» start в своём окне не вызывает
# С change storage-tls хранилища по сети — только TLS: пробы той же формы,
# что healthcheck, с проверкой CA стенда отказов (secrets ca.crt хранилища)
# и имени сервиса; адрес — loopback контейнера
PROBES = {
"postgres": 'pg_isready -q -h 127.0.0.1 -U "$POSTGRES_USER" '
'-d "$POSTGRES_DB"',
"valkey": 'test "$(valkey-cli -p "$VALKEY_PORT" ping)" = PONG',
"postgres": 'pg_isready -q -d "host=$POSTGRES_HOST hostaddr=127.0.0.1 '
"port=$PGPORT dbname=$POSTGRES_DB user=$POSTGRES_USER "
'sslmode=verify-full sslrootcert=/run/secrets/ca.crt"',
"valkey": 'test "$(valkey-cli --tls --cacert /run/secrets/ca.crt '
'--sni "$VALKEY_HOST" -h 127.0.0.1 -p "$VALKEY_PORT" ping)" = PONG',
# master выбран, том зарегистрирован у master, filer и шлюз S3
# отвечают — как healthcheck сервиса s3
# отвечают — как healthcheck сервиса s3 (шлюз — HTTPS с CA и именем)
"s3": "wget -q -O /dev/null http://127.0.0.1:9333/cluster/healthz && "
"wget -q -O - http://127.0.0.1:9333/dir/status | "
"grep -qF '\"DataNodes\":[{' && "
"wget -q -O /dev/null http://127.0.0.1:8888/healthz && "
'wget -q -O /dev/null "http://127.0.0.1:$S3_PORT/healthz"',
"curl -fsS -o /dev/null --cacert /run/secrets/ca.crt "
'--resolve "$S3_HOST:$S3_PORT:127.0.0.1" '
'"https://$S3_HOST:$S3_PORT/healthz"',
"rabbitmq": "rabbitmq-diagnostics -q check_port_connectivity",
}
PROBE_TIMEOUT_S = 30
@@ -700,9 +707,13 @@ import botocore.session
from botocore.config import Config
from src.config import settings
s3 = settings.s3
ca_file = settings.client_tls.ca_file
if not ca_file:
sys.exit("client_tls.ca_file is not set")
client = botocore.session.get_session().create_client(
"s3",
endpoint_url=s3.endpoint_url,
verify=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(),
@@ -746,9 +757,13 @@ from botocore.config import Config
from botocore.exceptions import ClientError
from src.config import settings
s3 = settings.s3
ca_file = settings.client_tls.ca_file
if not ca_file:
sys.exit("client_tls.ca_file is not set")
client = botocore.session.get_session().create_client(
"s3",
endpoint_url=s3.endpoint_url,
verify=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(),
@@ -941,7 +956,9 @@ def valkey(project: str, *args: str) -> str:
"valkey",
"sh",
"-c",
'exec valkey-cli -p "$VALKEY_PORT" "$@"',
# только TLS (change storage-tls): цепочка по CA стенда отказов
'exec valkey-cli --tls --cacert /run/secrets/ca.crt --sni "$VALKEY_HOST" '
'-h 127.0.0.1 -p "$VALKEY_PORT" "$@"',
"sh",
*args,
)
+12 -4
View File
@@ -85,6 +85,9 @@ CRASH_MARKERS = (
"automatic recovery in progress",
)
CRASH_LINES_MAX = 20
# отказ pg_hba.conf стенда соединению без TLS (change storage-tls): в журнале
# прогона его быть не должно — healthcheck и пробы hook ходят по TLS
PLAINTEXT_REFUSAL = "no encryption"
# «тесный» API: короткие сроки сессии и ключа идемпотентности, пул из
# одного соединения
TIGHT_ENV = {
@@ -389,14 +392,19 @@ def postgres_log_check(project: str) -> int:
crashes = [line for line in lines if any(m in line for m in CRASH_MARKERS)]
too_many = sum("too many clients" in line for line in lines)
admin = sum("administrator command" in line for line in lines)
# отказы соединений без TLS (change storage-tls): healthcheck, пробы hook и
# процессы стенда ходят по TLS — такой строки быть не должно
plaintext = [line for line in lines if PLAINTEXT_REFUSAL in line]
say(
f"postgres log: {len(lines)} lines, crash markers {len(crashes)}; "
f'"too many clients" {too_many}, "administrator command" {admin}',
f'"too many clients" {too_many}, "administrator command" {admin}, '
f'"{PLAINTEXT_REFUSAL}" {len(plaintext)}',
)
if not crashes:
if not crashes and not plaintext:
return 0
say("crash markers in the postgres log:")
for line in crashes[:CRASH_LINES_MAX]:
if crashes:
say("crash markers in the postgres log:")
for line in (crashes + plaintext)[:CRASH_LINES_MAX]:
print(line, flush=True)
return 1