fix: address storage-tls verify findings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 00:55:33 +03:00
co-authored by Claude Opus 5.5
parent 9f01fcce4b
commit a1bfb8dde2
16 changed files with 340 additions and 62 deletions
+145 -1
View File
@@ -282,7 +282,8 @@ grep -rl 'PRIVATE KEY' по трём меткам → 0; каталогов mtus
```
Вариант «до» профиля загрузок (`Profile.uploads_before`) — после коммита кода (задача 7.3
открыта, `QUESTIONS.md`); quick-профиль его не запускает.
открыта, `QUESTIONS.md`); quick-профиль его не запускает. Закрыта на правках verify — `8bca554`,
раздел «Правки verify», 11.1.
## 11. Эмуляция job CI (задача 7.4)
@@ -307,3 +308,146 @@ 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
```
## Правки verify (задачи 11.1–11.8)
Код: 2026-11-19, рабочее дерево поверх `9f01fcc` (`docs: name the storage-tls code commit in its
evidence`) с правками verify, снято до коммита (commit назовёт основная сессия). Находки verify —
на `8bca554`.
### 11.2, 11.5 — нечитаемый CA и CA без сертификата CA (W1, S1)
Новые случаи быстрых тестов `service-tests/unit/test_client_tls.py` — до правки кода (красные):
```
test_problems_ca_file FAILED (crl.pem: [] вместо ["client_tls.ca_file"])
test_entrypoint_refuses_before_connecting[missing_ca-…-api] FAILED (код 1, записей JSON нет: traceback
test_entrypoint_refuses_before_connecting[garbage_ca-…-api] FAILED FileNotFoundError / SSLError при импорте src.main)
worker, relay, cleaner, migrations — те же случаи зелёные и до правки
```
Ручная проба до правки: `python -m src` консоли с `CLIENT_TLS__CA_FILE=/nonexistent/ca.crt` — код 1,
последняя строка `FileNotFoundError: [Errno 2] No such file or directory` из
`build_client_context` (импорт `src/infra/db/session.py`).
После правки (проверка в `src/__main__.py` до импорта `src.main`, `x509_ca` > 0 в
`client_tls_problems`): `test_client_tls.py` — все зелёные, `make service_test` — 467 passed. На
стенде — одноразовый контейнер сервиса `api` (образ рабочего дерева):
```
docker compose run --rm --no-deps -T -e CLIENT_TLS__CA_FILE=<файл> api
/run/secrets/missing.crt (нет файла) exit=2 fields ["client_tls.ca_file"]
/run/secrets/api.key (не сертификат) exit=2 fields ["client_tls.ca_file"]
/run/secrets/crl.pem (только CRL) exit=2 fields ["client_tls.ca_file"]
/run/secrets/api.crt (только leaf) exit=2 fields ["client_tls.ca_file"]
{"event": "Invalid client TLS settings", "instance_id": "<alias>", "module": "startup",
"fields": ["client_tls.ca_file"], "run_mode": "docker", "level": "error", "timestamp": "<t>"}
```
Пути CA в записи нет.
### 11.3 — `driver.py start` (W2)
На `8bca554` консольный API драйвера не получал `CLIENT_TLS__CA_FILE` и выходил с кодом 2. После
правки (CA стенда в окружении API, как `CLIENT_TLS_ENV` у `make run_dev`):
```
python3 driver.py --port 18081 start → up on https://localhost:18081 …, exit 0; ready: True
make test BASE_URL=https://localhost:18081 → PASS (загрузка 202 и ready: S3, worker и relay консоли)
журнал API: «Started API», ни «Invalid client TLS settings», ни «Cache is unavailable»
python3 driver.py --port 18081 stop → stopped 18081, exit 0; слушателей на порту 0
```
### 11.6 — примеры `SKILL.md` (S2)
`valkey-cli` по TLS-порту (`--port 0`), `psql` оператора через сокет, шлюз S3 по HTTPS — на стенде:
```
docker compose exec valkey sh -c 'valkey-cli --tls --cacert /run/secrets/ca.crt --sni "$VALKEY_HOST" -h 127.0.0.1 -p "$VALKEY_PORT" --scan --pattern "messenger:*" | head -3'
→ 3 ключа (messenger:v1:…:chat:…, messenger:login:ua:…, messenger:login:a:…), exit 0
прежний пример без --tls → «I/O error»
docker compose exec postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "select 1"' → 1 (1 row)
docker compose exec s3 sh -c 'curl -sS --cacert /run/secrets/ca.crt --resolve "$S3_HOST:$S3_PORT:127.0.0.1" "https://$S3_HOST:$S3_PORT/healthz"' → 200
grep примеров valkey-cli без --tls и http:// к S3 в SKILL.md и .claude/rules → пусто
```
### 11.7 — строка `pg_stat_ssl` (S4)
Контроль: только хранилища и брокер (`driver.py start`/`stop` оставил их без клиентов) — строка
падает, команда — код 1:
```
postgres pg_stat_ssl network sessions over TLS 1.3 (0) >= 1 0 FAIL
postgres pg_stat_ssl network sessions without TLS 1.3 0 0
FAIL: 1 check(s) failed (остальные 27 строк — как в разделе 4)
```
Штатный стенд (`make run_docker`) — `make storage_tls_check` код 0:
```
postgres pg_stat_ssl network sessions over TLS 1.3 (6) >= 1 >= 1
postgres pg_stat_ssl network sessions without TLS 1.3 0 0
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
```
### 11.8 — сломанный TLS хранилища виден (S5)
Временный проект `mtusi-lab7-tlsbroken` (порты хоста переназначены), своя синтетическая PKI —
два CA `pki.sh stand` во временном каталоге (ключи стенда и оператора не читались); `docker
compose up -d --no-build valkey migrate s3-bootstrap`. Проект, volumes и каталог удалены.
```
== A: у postgres, valkey, s3 — пары постороннего CA под теми же именами
up: dependency failed to start: container …-postgres-1 is unhealthy (через 76 с)
postgres running unhealthy | valkey running unhealthy | s3 running unhealthy
migrate created (не стартовал) | s3-bootstrap created (не стартовал)
postgres healthcheck: 127.0.0.1:5432 - no response; журнал: could not accept SSL connection: tlsv1 alert unknown ca
valkey healthcheck: SSL_connect failed: certificate verify failed; журнал: tlsv1 alert unknown ca
s3 healthcheck: curl — сертификат не прошёл проверку по CA стенда
== B: сертификаты стенда, пустые файлы ключей
up: dependency failed to start: container …-postgres-1 is unhealthy (через 113 с)
postgres restarting (11 перезапусков, exit 1): FATAL: could not load private key file "/run/secrets/postgres.key"
valkey restarting (11, exit 1): Failed to load private key … Failed to configure TLS
s3 running unhealthy: шлюз не отвечает (Health check exceeded timeout (3s))
migrate created | s3-bootstrap created
cleanup: containers 0, volumes 0, tmp exists: no
```
Без файла `secrets` вовсе compose не создаёт контейнер (раздел 3, «стенд без файлов»).
### 11.1 — вариант «до» профиля загрузок (7.3)
`Profile.uploads_before` = `8bca554`. Один прогон варианта «до» без полного профиля (рабочий стенд
остановлен; хост выгружал память — `host swapped out … pages`, времена не доказательство):
```
uv run python bench/run.py --profile uploads --label quick-uploads-before-20261118T213707Z \
--telemetry off --variants before --concurrency 1 --repeats 1 → exit 0, 2 мин 9 с
uploads: image of 8bca554 built; postgres and valkey healthy; s3 healthy, bootstrap done;
1 api replicas UP behind haproxy
before-1MiB-c1-r1: 202 861, 429 0, 5xx 0, conn 0, 38.8/s, p95 36.0 ms
before-10MiB-c1-r1: 202 202, 429 0, 5xx 0, conn 0, 9.0/s, p95 139.1 ms
meta.uploads.before_commit: 8bca554; stand.tls.storages: postgres/valkey "tls1.3 only, verify-full",
s3 "https only, verify-full"
grep -rl 'PRIVATE KEY' по метке → 0; метка в .gitignore; контейнеров mtusi-bench после → 0
```
### 11.4 — дельта `load-benchmark` (W3)
Требование «Стенд по HTTPS и mTLS» и сценарий «Образ до TLS к хранилищам» — PostgreSQL профиля
входа только TLS, образ `56ccb79` по TLS без проверки сервера, Valkey ему недоступен (факт —
раздел 10, `meta.login.storage_transport`). `openspec validate storage-tls --strict` — valid.
### Проверки в конце правок
```
make lint → All checks passed
make service_test → 467 passed
make service_test_db → 89 passed
openspec validate storage-tls --strict → valid
make run_docker; make test → PASS
make student_test → 1 failed, 234 passed: test_exclusion_evidence_exists (известный, evidence
исключений — последний шаг лабы)
make storage_tls_check → PASS (выше)
```