forked from mtusi2026/mtusi2026lab7
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>
310 lines
23 KiB
Markdown
310 lines
23 KiB
Markdown
# TLS к хранилищам (change `storage-tls`)
|
||
|
||
Спеки `transport-security`, `pki`, `service-configuration`, `student-tests`, `load-benchmark`
|
||
(дельты change); design, решения 1–14 и «Уточнения apply». Путь репозитория — `<repo>`,
|
||
временные каталоги — `<tmp>`.
|
||
|
||
Код на момент съёмки: 2026-11-18, **рабочее дерево поверх `25f5d98`** (`docs: propose
|
||
storage-tls`) с правками apply change `storage-tls`, снято до коммита (commit кода назовёт
|
||
основная сессия). Хост — Docker Desktop, ВМ 12 CPU / 11 902 МиБ, Compose 5.6.1, OpenSSL 3+.
|
||
Ключей, PEM и паролей в файле нет.
|
||
|
||
## 1. Пробы образов (задача 1.1)
|
||
|
||
Временный проект compose, leaf на 1 день (`pki.sh issue <имя> --profile server --san <имя>
|
||
--san localhost --days 1 --out <tmp>`), удалён после проб. Итог — `QUESTIONS.md`, `##
|
||
storage-tls`, «Решения»: все три прошли, запасные пути design не понадобились.
|
||
|
||
```
|
||
postgres: /run/secrets/* 0:0 0600, процесс uid=999; init complete; SHOW ssl → on; TLSv1.3
|
||
sslmode=disable по TCP → FATAL: pg_hba.conf rejects connection ... no encryption
|
||
verify-full host=postgres hostaddr=127.0.0.1 → pg_stat_ssl t|TLSv1.3
|
||
host=127.0.0.1 → server certificate for "postgres" ... does not match host name "127.0.0.1"
|
||
pg_isready verify-full без пароля → accepting connections, журнал без строки
|
||
s3: Start Seaweed S3 API Server ... at https port 8333
|
||
http://127.0.0.1:8333/ → 400 Client sent an HTTP request to an HTTPS server.
|
||
https + CA + --resolve s3 → 200 TLSv1.3; https://127.0.0.1 → no alternative subject name
|
||
netstat вне loopback: :::8333, :::18333 (gRPC шлюза)
|
||
valkey: Ready to accept connections tls; без --tls → I/O error / reset;
|
||
посторонний CA → certificate verify failed; --sni other и без --sni → PONG (имя не проверяет)
|
||
```
|
||
|
||
## 2. Identity хранилищ (задача 1.2)
|
||
|
||
`make pki_stand` после строк `postgres`, `valkey`, `s3` в `infra/pki/identities.conf`:
|
||
|
||
```
|
||
valid haproxy: serial 01A9A23205315927156C54D25B0DFAD8 (прежний)
|
||
valid api: serial 01A9A23205315927156C54D25B0DFAD9 (прежний)
|
||
valid ingress: serial 01A9A23205315927156C54D25B0DFAE4 (прежний)
|
||
reissue postgres: missing → issued postgres (server, SAN postgres,localhost): serial ...DFAEF, not after 2027-02-16
|
||
reissue valkey: missing → issued valkey (server, SAN valkey,localhost): serial ...DFAF0
|
||
reissue s3: missing → issued s3 (server, SAN s3,localhost): serial ...DFAF1
|
||
повтор make pki_stand: valid у всех шести, серийные номера те же
|
||
openssl verify -CAfile ca.crt: postgres/valkey/s3 OK, TLS Web Server Authentication, DNS:<имя>, DNS:localhost
|
||
ключи .pki/stand/*.key — 0600
|
||
```
|
||
|
||
## 3. Переход стенда (задача 10.2)
|
||
|
||
`make run_docker` на прежних volumes (данные лабы 7): хранилища и все сервисы образа API
|
||
пересозданы, с первой попытки. `s3-bootstrap` — «checks passed» по HTTPS; `migrate` — «Finished
|
||
alembic» по TLS. Все контейнеры `healthy` / `Up`.
|
||
|
||
```
|
||
make test → PASS: lab7 public API scenario
|
||
make test-security → PASS: trusted HTTPS works; untrusted CA rejected
|
||
make student_test → 1 failed, 234 passed, 158 deselected
|
||
(failed — известный test_exclusion_evidence_exists)
|
||
make test-persistence ACTION_SCRIPT=scripts/restart.sh → PASS
|
||
StartedAt до → после: postgres 17:26:15 → 17:46:59, valkey 17:06:49 → 17:46:59, s3 17:06:50 → 17:47:14
|
||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh → PASS
|
||
{"observed_instances_before": 2, "successful_writes": 117, "failed_attempts": 0, "first_recovery_seconds": 1.224}
|
||
STOP_ONE_LOG: TARGET_INSTANCE_ID=0b36e61072601a9b mode=stop; затем make replicas
|
||
make mtls_check → PASS (2 probe containers removed, key directory removed)
|
||
make s3_check → PASS: 90 checks, bucket messenger is private
|
||
host (https://localhost:8334, CA стенда): аноним GET/HEAD/список/PUT — 403
|
||
network (curl --cacert): то же 403; порты 8333 и 18333 open, 8080 8888 9333 18080 18888 19333 closed
|
||
pg_stat_ssl × pg_stat_activity (сеть): mtusi-messenger | ssl t | TLSv1.3 | 5; psql (сокет) — без TLS
|
||
psql sslmode=disable из сети стенда → FATAL: pg_hba.conf rejects connection ... no encryption
|
||
valkey-cli без --tls → I/O error; с посторонним CA → certificate verify failed
|
||
curl http://127.0.0.1:$S3_PORT/ в контейнере s3 → Client sent an HTTP request to an HTTPS server.
|
||
```
|
||
|
||
## 4. `make storage_tls_check` (задача 8.2)
|
||
|
||
```
|
||
storage from case expected got
|
||
postgres network no TLS refused: no encryption refused: no encryption
|
||
postgres network foreign CA certificate rejected certificate rejected
|
||
postgres network address not in SAN name rejected name rejected
|
||
postgres network stand CA and name SELECT 1 ok, TLSv1.3 SELECT 1 ok, TLSv1.3
|
||
valkey network no TLS no RESP reply no RESP reply
|
||
valkey network foreign CA certificate rejected certificate rejected
|
||
valkey network address not in SAN name rejected name rejected
|
||
valkey network stand CA and name PONG PONG
|
||
s3 network no TLS 400: HTTP request to an HTTPS server 400: HTTP request to an HTTPS server
|
||
s3 network foreign CA certificate rejected certificate rejected
|
||
s3 network address not in SAN name rejected name rejected
|
||
s3 network stand CA and name HEAD object 404 HEAD object 404
|
||
postgres host no TLS refused: no encryption refused: no encryption
|
||
postgres host foreign CA certificate rejected certificate rejected
|
||
postgres host address not in SAN name rejected name rejected
|
||
postgres host stand CA and name password requested, TLSv1.3 password requested, TLSv1.3
|
||
valkey host no TLS no RESP reply no RESP reply
|
||
valkey host foreign CA certificate rejected certificate rejected
|
||
valkey host address not in SAN name rejected name rejected
|
||
valkey host stand CA and name -NOAUTH -NOAUTH
|
||
s3 host no TLS 400: HTTP request to an HTTPS server 400: HTTP request to an HTTPS server
|
||
s3 host foreign CA certificate rejected certificate rejected
|
||
s3 host address not in SAN name rejected name rejected
|
||
s3 host stand CA and name anonymous GET 403 anonymous GET 403
|
||
postgres pg_stat_ssl network sessions over TLS 1.3: 6 0 without TLS 1.3 0 without TLS 1.3
|
||
postgres server listening outside loopback 5432 5432
|
||
valkey server listening outside loopback 6379 6379
|
||
s3 server listening outside loopback 8333 18333 8333 18333
|
||
PASS: storages accept only TLS with the stand CA and their names; network sessions with PostgreSQL are TLS 1.3
|
||
cleanup: probe containers left 0, temporary directory removed: True
|
||
```
|
||
|
||
Изнутри сети — одноразовый контейнер сервиса `api` (без алиаса), учётные данные — его окружение;
|
||
адрес вне SAN — IP контейнера хранилища, с хоста — `127.0.0.1`; посторонний CA — `pki.sh init`
|
||
во временном каталоге (ключ удалён до пробы).
|
||
|
||
**Контроль различения** — `postgres`, пересозданный с override на временный `pg_hba.conf`
|
||
(`hostssl … scram-sha-256` и `host all all all scram-sha-256` — TLS необязателен), затем
|
||
`docker compose up -d postgres` штатного файла (`hostnossl … reject`):
|
||
|
||
```
|
||
postgres network no TLS refused: no encryption SELECT 1 ok, None FAIL
|
||
postgres host no TLS refused: no encryption password requested, FAIL
|
||
FAIL: 2 check(s) failed (make: код 1 команды → 2)
|
||
```
|
||
|
||
**Прерывание** — SIGINT драйверу во время пробы изнутри (через 1,8 с) и во время проб с хоста
|
||
(через 3 с):
|
||
|
||
```
|
||
probe containers at SIGINT: 1 → storage-tls-check: interrupted (SIGINT); cleanup: probe containers left 0, temporary directory removed: True; exit 1
|
||
probe containers at SIGINT: 0 → то же, exit 1
|
||
после обоих: probe containers left 0; new temporary directories left 0
|
||
```
|
||
|
||
## 5. Отказ TLS = недоступность (задача 10.3)
|
||
|
||
Разовые контейнеры `docker compose run --no-deps api` (сеть стенда, без алиаса `api`), консоль на
|
||
`127.0.0.1:8080` внутри контейнера с сертификатом `api`, запросы — из того же контейнера с CA
|
||
стенда; телеметрия выключена.
|
||
|
||
```
|
||
== A: CLIENT_TLS__CA_FILE — посторонний CA (PostgreSQL, Valkey, S3) ==
|
||
"GET /health/ready": 503, "POST /api/v1/users": "503 unavailable", "GET /health/live (after)": 200
|
||
process: running restarts=0
|
||
journal: 1 x ('Database is unavailable', 'database', 'SSLCertVerificationError')
|
||
lines with password|secret|BEGIN: 0
|
||
== B: CA стенда; Valkey и S3 по имени контейнера (нет в SAN) ==
|
||
"GET /health/ready": 200, "POST /api/v1/users": "201", "POST /api/v1/auth/sessions": 201,
|
||
"POST /api/v1/chats": 201, "GET /api/v1/chats/{id} #1": 200, "GET /api/v1/chats/{id} #2": 200,
|
||
"POST /api/v1/chats/{id}/attachments": "503 unavailable", "GET /health/live (after)": 200
|
||
process: running restarts=0
|
||
journal: 'Cache is unavailable' (cache, ConnectionError) ×1, 'Login limiter uses process counters' ×1,
|
||
'Object storage is unavailable' (object_storage, SSLError) ×1, 'Attachment upload left pending' ×1
|
||
lines with password|secret|BEGIN: 0
|
||
```
|
||
|
||
Строку `pending` загрузки с отказом S3 убирает уборщик (как при прежнем отказе S3).
|
||
|
||
Замороженный шлюз S3 (`docker compose pause s3`) и `ObjectStorage.put` в разовом контейнере
|
||
API: и после разогрева, и с нового клиента — `unavailable in 1.01 s`, запись «Object storage is
|
||
unavailable», `error_type: ConnectTimeoutError`: рукопожатие TLS — часть соединения, его обрывает
|
||
`[s3] connect_timeout_seconds` (1 с), а не срок вызова (5 с). Ответ API прежний — 503, раньше.
|
||
|
||
## 6. Проверка при старте и быстрые тесты (задачи 2.x, 10.1)
|
||
|
||
```
|
||
make lint → All checks passed!
|
||
make service_test → 457 passed
|
||
make service_test_db → 89 passed (три прогона подряд, ~34 с; на TLS-PostgreSQL стенда)
|
||
make check → PASS: offline skeleton structure ...
|
||
make validate PYTHON=.venv/bin/python → PASS: full OpenAPI 3.1 and JSON Schema validation
|
||
openspec validate storage-tls --strict → valid
|
||
```
|
||
|
||
Новые тесты и как они падали до кода — тесты из рабочего дерева против кода `25f5d98` (`git
|
||
archive 25f5d98` во временный каталог, тесты и `identities.conf` скопированы, venv проекта):
|
||
|
||
```
|
||
service-tests/unit/test_client_tls.py — ERROR collecting: ImportError: cannot import name
|
||
'TlsConnection' from 'src.infra.cache.client' (как и build_client_context, client_tls_problems)
|
||
service-tests/unit/test_settings.py — FAILED test_client_tls_from_environment (нет [client_tls]),
|
||
FAILED test_s3_endpoint_is_https (http://s3:8333)
|
||
```
|
||
|
||
`test_client_tls.py` (26 проверок): флаги контекста и ровно один CA, пустой путь — ни одного CA;
|
||
`client_tls_problems` — пустой, отсутствующий и не-PEM CA, IP-адрес по наборам процессов
|
||
(API — 3 поля, worker / уборщик — 2, relay / миграции — 1), `localhost` и имя сервиса проходят;
|
||
`create_engine` передаёт asyncpg `SSLContext`; пул кэша — `TlsConnection` с контекстом CA; клиент
|
||
S3 — `https://…` и `verify`, без CA — `ValueError`; настоящее рукопожатие клиента кэша с TLS-сервером
|
||
RESP на leaf `valkey` временной PKI — CA и `localhost` — значение, посторонний CA и `127.0.0.1` —
|
||
промах и одна запись «Cache is unavailable» с `CERTIFICATE_VERIFY_FAILED`; точки входа процессом
|
||
(API, worker, relay, уборщик, миграции) с пустым `CLIENT_TLS__CA_FILE` и с
|
||
`DATABASE__HOST=127.0.0.1` — код 2, запись «Invalid client TLS settings», `fields` —
|
||
`client_tls.ca_file` / `database.host`, пути PKI в выводе нет.
|
||
|
||
`service-tests/db/test_uow.py::test_soft_close_is_graceful` упал на TLS (`assert 17 == (15 + 1)`):
|
||
после Terminate — запись `close_notify` мягкого закрытия TLS; проверка — 1–2 порции клиента
|
||
(design, «Уточнения apply», п. 8).
|
||
|
||
## 7. Консоль (задача 6.1)
|
||
|
||
`.env` рабочего дерева: `DATABASE__HOST`, `CACHE__HOST`, `S3__HOST` — `localhost` (правка руками,
|
||
не в git).
|
||
|
||
```
|
||
make -n run_dev run_worker run_relay upgrade service_test_db:
|
||
CLIENT_TLS__CA_FILE="<repo>/.pki/stand/ca.crt" uv run alembic upgrade head
|
||
APP__RUN_MODE=console API_TLS__CERT_FILE=... CLIENT_TLS__CA_FILE="<repo>/.pki/stand/ca.crt" uv run python -m src
|
||
S3__ACCESS_KEY_ID=*** ... CLIENT_TLS__CA_FILE=... uv run python -m src.worker
|
||
APP__RUN_MODE=console CLIENT_TLS__CA_FILE=... uv run python -m src.relay
|
||
CLIENT_TLS__CA_FILE=... uv run pytest -c service-tests/pytest.ini service-tests/db
|
||
make upgrade → "Finished alembic"
|
||
make run_dev APP__PORT=8091 → Started API (database_host localhost, cache_host localhost, ...)
|
||
curl --cacert ca.crt https://localhost:8091/health/ready → {"status":"ok"} 200
|
||
make test BASE_URL=https://localhost:8091 → PASS (загрузка вложения и скачивание; записей
|
||
«Cache / Object storage / Database is unavailable» нет)
|
||
```
|
||
|
||
Порт 8091 вместо 8080: на хосте IPv6 `*:8080` занят чужим проектом Docker, `localhost` уходил на
|
||
`::1` к нему (`tlsv1 alert protocol version`) — не дефект кода (`run-modes.md`, Troubleshooting).
|
||
|
||
## 8. Команды драйвера (задача 8.1)
|
||
|
||
| Команда | Код | Итог |
|
||
|---|---|---|
|
||
| `attachment-storage` | 0 | metadata in PostgreSQL, bytes only in the private bucket (аноним по HTTPS — 403) |
|
||
| `cache-check` | 0 | one read of chats, the rest from Valkey; TTL is bounded |
|
||
| `auth-storage` | 0 | Argon2id, SHA-256 токена, пересчёт хэша; credentials in the journal: none |
|
||
| `s3-idle` | 0 | image client keeps no read timer in the pool; every PUT after the idle passed |
|
||
| `upload-consistency` | 0 | pending rows are invisible, compensation, cleaner removed both uploads |
|
||
| `freeze-sessions` | 0 | after a frozen database: no sessions over the pool (прокси — имя `localhost`) |
|
||
| `defense-faults` | 0 | every window finished with the same result, no duplicate effect |
|
||
| `stand-from-scratch --runs 1` | 0 | make run_docker on empty volumes passed at the first attempt |
|
||
| `freeze-lb` | 1 → 0 | первый прогон: PostgreSQL временного проекта не стартовал (override сбрасывал bind `pg_hba.conf`); после правки override — PASS, контейнеров и volumes проекта 0 |
|
||
| `telemetry-check` | 1 | одна строка FAIL — `service.version` 1.6.0 против 1.7.0 (прежний `KNOWN_ISSUES.md`); строка «S3 span duration» первым прогоном упала (span ~1 с при заморозке S3, раздел 5) — диапазон 0,8–7,5 с, вторым прогоном `yes` |
|
||
| `reconcile-signal --pace` | 0 | временный проект `mtusi-lab7-rs` (PostgreSQL, S3, миграции, bootstrap): exit 1 within a second, listed_objects 8 |
|
||
| `reconcile-signal --pace --apply` | 0 | every deleted object fixed (5); проект удалён `down -v` |
|
||
| `s3-check`, `mtls-check`, `storage-tls-check` | 0 | разделы 3–4 |
|
||
|
||
`grep 'http://\|sslmode=disable'` по драйверу — к S3 и PostgreSQL пусто (остались адреса Grafana,
|
||
Collector и комментарий).
|
||
|
||
## 9. Временные стенды (задачи 7.1–7.2)
|
||
|
||
```
|
||
make test_isolated → results: {'test': 0, 'student_test': 2}
|
||
student_test: 1 failed (test_exclusion_evidence_exists), 227 passed, 7 skipped, 158 deselected
|
||
pg_stat_ssl во время прогона: test_messenger | mtusi-messenger | net t | ssl t | TLSv1.3
|
||
уборка: объекты test_messenger/ и очередь test_messenger.attachment.process.v1 удалены
|
||
make failure_checks FAULT_ARGS='-k "valkey or postgres or database or s3 or object_storage or put_object or reconcile_finds"'
|
||
19 passed, 374 deselected in 209.27s; postgres log: crash markers 0, "too many clients" 0
|
||
(token_while_database_stopped, database_stopped_and_back, readiness_without_database,
|
||
readiness_without_object_storage[stop|pause], valkey_stopped|paused|back, database_outage_keeps_key_free,
|
||
upload_with_object_storage_stopped, object_storage_stopped|paused, upload_after_idle_s3,
|
||
database_outage_during_processing, reconcile_finds_and_fixes, reconcile_object_storage_stopped,
|
||
reconcile_interrupted_by_database, relay_survives_database_outage, login_limit_without_valkey)
|
||
make failure_checks FAULT_ARGS='-k "valkey_back or readiness_without_database or object_storage_stopped"'
|
||
(после счётчика отказов без TLS в сводке журнала) 5 passed;
|
||
postgres log: 79 lines, crash markers 0; "too many clients" 0, "administrator command" 7, "no encryption" 0
|
||
```
|
||
|
||
## 10. `bench/` на TLS-хранилищах (задача 7.3)
|
||
|
||
Рабочий стенд остановлен (`make stop`). Хост выгружал память в swap (предупреждения `host
|
||
swapped out … pages` у загрузок и очереди) — времена quick-профилей не доказательство; проверяется
|
||
код и путь по TLS. Метки `quick-*` в git не идут.
|
||
|
||
```
|
||
make bench_uploads_quick → rc=0, 313 s, 6/6 runs (quick-uploads-20261118T175331Z)
|
||
limited-10MiB-c40: 202 182, 429 401, 5xx 0; limited-10MiB-c1: 202 222, p95 119.3 ms
|
||
unlimited-10MiB-c40: OOM (результат варианта «без лимита», не сбой команды)
|
||
make bench_login_quick → rc=0, 212 s, 4/4 runs (quick-login-20261118T175844Z)
|
||
baseline: good 201 30/30; before-l40: flood 401 275, good 201 9/30 (образ 56ccb79 по TLS
|
||
к PostgreSQL, без кэша); full-l40: flood 429 1200, good 30/30; budget-l40: good 28/30
|
||
make bench_queue_quick → rc=0, 738 s, 6/6 cells (quick-queue-20261118T180216Z)
|
||
сэмплер queue (psql \watch по TLS, CA прогона): peak и ready/s посчитаны во всех ячейках
|
||
stand.tls (все три метки): {"ingress": "https", "lb_to_api": "mtls", "pki": "per-run CA",
|
||
"storages": {"postgres": "tls1.3 only, verify-full", "valkey": "tls1.3 only, verify-full",
|
||
"s3": "https only, verify-full"}}
|
||
meta.login.storage_transport: before — "postgres: tls (sslmode=prefer, server not verified);
|
||
valkey: unavailable (plaintext refused), cache bypassed"; budget, full — "postgres, valkey:
|
||
tls1.3, verify-full"
|
||
grep -rl 'PRIVATE KEY' по трём меткам → 0; каталогов mtusi-bench-pki-* в $TMPDIR → 0
|
||
```
|
||
|
||
Вариант «до» профиля загрузок (`Profile.uploads_before`) — после коммита кода (задача 7.3
|
||
открыта, `QUESTIONS.md`); quick-профиль его не запускает.
|
||
|
||
## 11. Эмуляция job CI (задача 7.4)
|
||
|
||
Отдельный проект `mtusi-lab7-ci-local`, `COMPOSE_FILE=docker-compose.yml:.github/ci/compose.yml`,
|
||
PKI прогона во временных каталогах (`make pki_stand` с `PKI_OPERATOR_DIR` / `PKI_STAND_DIR`),
|
||
`. .github/ci/stand-env.sh`, `make run_docker`:
|
||
|
||
```
|
||
LB slots: api-1 UP L7OK, api-2 UP L7OK
|
||
/run/secrets (uid:gid mode name):
|
||
api 10001:10001 444 api.crt, 400 api.key, 444 ca.crt, 444 crl.pem (обе реплики)
|
||
haproxy 99:99 444 ca.crt, 444 crl.pem, 400 haproxy.pem, 400 ingress.pem
|
||
postgres 999:999 444 ca.crt, 444 postgres.crt, 400 postgres.key
|
||
valkey 999:999 444 ca.crt, 444 valkey.crt, 400 valkey.key
|
||
s3 1000:1000 444 ca.crt, 444 s3.crt, 400 s3.key
|
||
cleaner, relay, worker 10001:10001 444 ca.crt
|
||
migrate, s3-bootstrap (завершены; список через docker cp) — только ca.crt
|
||
grafana, prometheus, rabbitmq — нет; loki, otel-collector, tempo — оболочки нет (файлов PKI им compose не передаёт)
|
||
containers with PRIVATE KEY in env: 0
|
||
pg_stat_ssl: mtusi-messenger | t | TLSv1.3 | 4
|
||
public smoke (https://ingress:8443, CA прогона) → PASS
|
||
job step «Bucket is closed»: anonymous GET https://s3:8333/, /messenger, ?list-type=2 → 403 ×3
|
||
emulation rc=0; cleanup: containers 0, volumes 0, temporary directory removed
|
||
```
|