feat: audit the whole trust matrix in one command and complete the threat model

- make security_audit runs the existing negative checks per trust-matrix
  row plus an ingress TLS probe and prints one summary
- close the threat model TODOs and stale references
- re-take the coverage exclusion evidence on the lab 7 stand

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 07:08:10 +03:00
co-authored by Claude Opus 5.5
parent bb20855f34
commit 7b2defab01
19 changed files with 1564 additions and 12 deletions
+48
View File
@@ -0,0 +1,48 @@
# Принявшая реплика остановлена
- Команда: `python3 .claude/skills/run-mtusi-messenger/driver.py --port 8443 attachment-failover --mode stop`, затем то же с `--mode kill` (`make replicas` драйвер выполняет сам в `finally`)
- Дата: 2026-12-02, 03:42:57–03:43:12 UTC; оба прогона — код выхода 0
- Commit: `bb20855` (ветка `feat/lab7-final`); рабочее дерево — правки последнего шага, часть 2 (аудит матрицы, документы, файлы `evidence/`), код образа = `HEAD`
- Стенд: проект compose `mtusi-lab7`, две реплики за HAProxy (mTLS LB → API), снаружи `https://localhost:8443` с CA стенда, телеметрия включена, собран `make run_docker` из рабочего дерева; пользователи синтетические
- Сценарий: `attachments` «Принявшая реплика остановлена»
- Вывод сокращён: убраны снимки `docker compose ps` до и после (все сервисы `Up`, реплики `healthy`). `X-Instance-Id` с лабы 7 — случайный alias процесса, а не ID контейнера (`evidence/security/instance-alias.md`): реплику, вернувшуюся после `stop`, прогон `kill` видит под новым alias `a88edeb704dc8bf7`
## `stop`
```text
mode: stop; fixture sample.png: 111817 bytes
sha256 uploaded: 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75
sha256 downloaded: 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75
step expected got x-instance-id
alice uploads 202 202 169929a788d4880a
attachment is ready ready ready
alice sends message 201 201 a207ff38444c7f43
stop-one.sh stop 0 0 169929a788d4880a
bob downloads 200 200 a207ff38444c7f43
bob reads metadata 200 200 a207ff38444c7f43
eve reads metadata 404 404 a207ff38444c7f43
eve downloads 404 404 a207ff38444c7f43
make replicas 0 0
LB slots UP 2 2
PASS: accepted by 169929a788d4880a, served by a207ff38444c7f43 after stop, sha256 matches, outsider gets 404
```
## `kill`
```text
mode: kill; fixture sample.png: 111817 bytes
sha256 uploaded: 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75
sha256 downloaded: 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75
step expected got x-instance-id
alice uploads 202 202 a88edeb704dc8bf7
attachment is ready ready ready
alice sends message 201 201 a207ff38444c7f43
stop-one.sh kill 0 0 a88edeb704dc8bf7
bob downloads 200 200 a207ff38444c7f43
bob reads metadata 200 200 a207ff38444c7f43
eve reads metadata 404 404 a207ff38444c7f43
eve downloads 404 404 a207ff38444c7f43
make replicas 0 0
LB slots UP 2 2
PASS: accepted by a88edeb704dc8bf7, served by a207ff38444c7f43 after kill, sha256 matches, outsider gets 404
```
+131
View File
@@ -0,0 +1,131 @@
# Вложения: метаданные, байты и ограничения обработки
- Команда: `python3 .claude/skills/run-mtusi-messenger/driver.py --port 8443 attachment-storage`
- Дата: 2026-12-02, 03:42:50–03:42:57 UTC; код выхода 0
- Commit: `bb20855` (ветка `feat/lab7-final`); рабочее дерево — правки последнего шага, часть 2 (аудит матрицы, документы, файлы `evidence/`), код образа = `HEAD`
- Стенд: проект compose `mtusi-lab7`, две реплики за HAProxy, телеметрия включена, собран `make run_docker` из рабочего дерева. Контейнеры `docker diff`: реплики `33d403c38cdd`, `9e7d80b101e9` и worker `b91ad296e6d8`
- Сценарии: `attachments` «Байты не в БД и не на диске API», `data-storage` «Ограничения обработки в схеме» (пробы в откатываемой транзакции, запись аудита с неизвестным заданием)
- С лабы 7 в `docker diff` есть ещё файлы PKI стенда в `/run/secrets` (`secrets` compose: CA, CRL и пара identity сервиса — у реплик `api` и `api-client`, у worker — `worker`); в выводе — только имена файлов. Колонка `lost_at` — сверка bucket и БД (лаба 4), `staging_key` и `error_code` — конвейер лабы 5
- Вывод сокращён: таблица второго вложения повторяет первую и совпала с ожидаемым
Итог: байты — только объекты приватного bucket (анонимный GET 403), в PostgreSQL — метаданные и SHA-256 (`bytea`, 32 байта), в файловых системах реплик и worker — только смонтированный `config.toml` и файлы PKI; четыре пробы ограничений дают названные коды, после отката — одно задание и три варианта.
```text
columns of attachment tables:
attachment_job_replays id uuid
attachment_job_replays job_id uuid
attachment_job_replays operator text
attachment_job_replays error_code text
attachment_job_replays reason text
attachment_job_replays attempt integer
attachment_job_replays created_at timestamp with time zone
attachment_jobs id uuid
attachment_jobs attachment_id uuid
attachment_jobs pipeline_version integer
attachment_jobs state text
attachment_jobs attempt integer
attachment_jobs last_error_code text
attachment_jobs next_attempt_at timestamp with time zone
attachment_jobs lease_expires_at timestamp with time zone
attachment_jobs published_at timestamp with time zone
attachment_jobs updated_at timestamp with time zone
attachment_jobs finished_at timestamp with time zone
attachment_jobs created_at timestamp with time zone
attachment_jobs attempt_base integer
attachment_jobs traceparent text
attachment_jobs tracestate text
attachment_variants attachment_id uuid
attachment_variants pipeline_version integer
attachment_variants variant text
attachment_variants object_key text
attachment_variants content_type text
attachment_variants size_bytes integer
attachment_variants width integer
attachment_variants height integer
attachment_variants sha256 bytea
attachment_variants created_at timestamp with time zone
attachments id uuid
attachments chat_id uuid
attachments owner_id uuid
attachments filename text
attachments content_type text
attachments size_bytes integer
attachments sha256 bytea
attachments object_key text
attachments status text
attachments updated_at timestamp with time zone
attachments created_at timestamp with time zone
attachments lost_at timestamp with time zone
attachments staging_key text
attachments error_code text
message_attachments message_id uuid
message_attachments position smallint
message_attachments attachment_id uuid
message_attachments created_at timestamp with time zone
upload via 169929a788d4880a: object_key messenger/attachments/6c9479d5-86a5-4f70-a860-302b7fb813c5/original, staging_key messenger/staging/6c9479d5-86a5-4f70-a860-302b7fb813c5/original
sha256 uploaded 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75, downloaded by a member (200) 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75
upload via 169929a788d4880a: object_key messenger/attachments/a30769b4-1521-4ce3-a7fd-e670b3229206/original, staging_key messenger/staging/a30769b4-1521-4ce3-a7fd-e670b3229206/original
sha256 uploaded 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75, downloaded by a member (200) 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75
constraint probes (rolled back):
second job of the version: 23505 uq_attachment_jobs_attachment_id_pipeline_version
second variant of the name: 23505 pk_attachment_variants
error_code on not failed: 23514 ck_attachments_error_code_failed
replay audit of an unknown job: 23503 fk_attachment_job_replays_job_id_attachment_jobs
docker diff 33d403c38cdd: 10 changes
C /run
A /run/secrets
A /run/secrets/api-client.crt
A /run/secrets/api-client.key
A /run/secrets/api.crt
A /run/secrets/api.key
A /run/secrets/ca.crt
A /run/secrets/crl.pem
C /app
A /app/config.toml
docker diff 9e7d80b101e9: 10 changes
C /app
A /app/config.toml
C /run
A /run/secrets
A /run/secrets/api.crt
A /run/secrets/api.key
A /run/secrets/ca.crt
A /run/secrets/crl.pem
A /run/secrets/api-client.crt
A /run/secrets/api-client.key
docker diff b91ad296e6d8: 8 changes
C /app
A /app/config.toml
C /run
A /run/secrets
A /run/secrets/ca.crt
A /run/secrets/crl.pem
A /run/secrets/worker.crt
A /run/secrets/worker.key
bytea columns expected attachment_variants.sha256,attachments.sha256 got attachment_variants.sha256,attachments.sha256
octet_length(sha256) expected 32 got 32
object_key form expected messenger/attachments/6c9479d5-86a5-4f70-a860-302b7fb813c5/original got messenger/attachments/6c9479d5-86a5-4f70-a860-302b7fb813c5/original
staging_key: its form or already empty expected yes got yes
filename not in key expected no got no
variant rows expected crop,optimized,thumbnail got crop,optimized,thumbnail
crop in bucket expected yes got yes
anonymous GET of crop expected 403 got 403
optimized in bucket expected yes got yes
anonymous GET of optimized expected 403 got 403
thumbnail in bucket expected yes got yes
anonymous GET of thumbnail expected 403 got 403
object in bucket, bytes expected 111817 got 111817
anonymous GET of the key expected 403 got 403
downloaded sha256 = uploaded expected yes got yes
… (второе вложение, a30769b4-…: те же 13 строк, все совпали)
probe: second job of the version expected 23505 uq_attachment_jobs_attachment_id_pipeline_version got 23505 uq_attachment_jobs_attachment_id_pipeline_version
probe: second variant of the name expected 23505 pk_attachment_variants got 23505 pk_attachment_variants
probe: error_code on not failed expected 23514 ck_attachments_error_code_failed got 23514 ck_attachments_error_code_failed
probe: replay audit of an unknown job expected 23503 fk_attachment_job_replays_job_id_attachment_jobs got 23503 fk_attachment_job_replays_job_id_attachment_jobs
jobs | variants after the probes expected 1|3 got 1|3
original files in 33d403c38cdd expected 0 got 0
original files in 9e7d80b101e9 expected 0 got 0
original files in b91ad296e6d8 expected 0 got 0
sha256 of the fixture: 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75
PASS: metadata in PostgreSQL, bytes only in the private bucket messenger, none in the API containers
```
+103
View File
@@ -0,0 +1,103 @@
# Очереди разных баз разделены
- Команды по порядку: `make test_isolated KEEP_TEST_DB=1`, `python3 .claude/skills/run-mtusi-messenger/driver.py --port 8443 broker-check --require-test-queue`, `make test_isolated`
- Дата: 2026-12-02; первый прогон 03:39:12–03:41:50 UTC, `broker-check` 03:42:18–03:42:35 UTC (код 0), второй прогон 03:43:57–03:46:30 UTC. Между первым прогоном и вторым сняты другие доказательства (`evidence/cache/hits.md`, `evidence/broker/stand.md` с остановкой брокера, `make test-persistence` с рестартом брокера): очередь временной базы — durable и их пережила
- Commit: `bb20855` (ветка `feat/lab7-final`); рабочее дерево — правки последнего шага, часть 2 (аудит матрицы, документы, файлы `evidence/`), код образа = `HEAD`
- Стенд: рабочий `mtusi-lab7`, поверх него — контейнеры `mtusi-lab7-test-lb`, `mtusi-lab7-test-api`, `mtusi-lab7-test-worker`, `mtusi-lab7-test-relay` на временной базе `test_messenger` (телеметрия у них выключена; тестовый API — только mTLS за своим LB на `https://localhost:18088`, relay и worker — identity `relay` / `worker` стенда, их права в брокере покрывают `test_<база>`)
- Сценарий: `message-broker` «Очереди разных баз разделены»
- Код 2 обоих `make test_isolated`: smoke — 0, набор — 2 только из-за `test_exclusion_evidence_exists` (в первом — 9 файлов исключений, во втором — этот файл и два замера `bench/`, которые снимает часть 3 последнего шага). Оба прогона: 1 failed, 227 passed, 7 skipped, 166 deselected, ~113 с
## Очереди брокера: `rabbitmqctl -q list_queues name durable messages consumers --formatter json`
До первого прогона — только рабочая очередь:
```json
[
{"messages":0,"name":"messenger.attachment.process.v1","consumers":1,"durable":true}
]
```
После `make test_isolated KEEP_TEST_DB=1` — очередь временной базы есть, рабочая не затронута:
```json
[
{"messages":0,"name":"test_messenger.attachment.process.v1","consumers":0,"durable":true}
,{"messages":0,"name":"messenger.attachment.process.v1","consumers":1,"durable":true}
]
```
После второго `make test_isolated` — очереди временной базы нет:
```json
[
{"messages":0,"name":"messenger.attachment.process.v1","consumers":1,"durable":true}
]
```
## Вывод `make test_isolated`
Первый прогон (`KEEP_TEST_DB=1`):
```text
[test_isolated] database=test_messenger objects=/buckets/messenger/test_messenger/ queue=test_messenger.attachment.process.v1 containers=mtusi-lab7-test-lb mtusi-lab7-test-api mtusi-lab7-test-worker mtusi-lab7-test-relay base_url=https://localhost:18088 ca=…/.pki/stand/ca.crt
[test_isolated] remove objects /buckets/messenger/test_messenger/ and queue test_messenger.attachment.process.v1
[test_isolated] build image
[test_isolated] create database test_messenger
[test_isolated] database roles for test_messenger
[test_isolated] migrations
[test_isolated] start api container
[test_isolated] start balancer container
[test_isolated] start worker container
[test_isolated] start relay container
[test_isolated] ready
[test_isolated] make test
[test_isolated] make student_test
…
[test_isolated] cleanup
[test_isolated] kept database test_messenger, objects /buckets/messenger/test_messenger/ and queue test_messenger.attachment.process.v1
[test_isolated] results: {'test': 0, 'student_test': 2}
```
Второй прогон:
```text
[test_isolated] database=test_messenger objects=/buckets/messenger/test_messenger/ queue=test_messenger.attachment.process.v1 containers=mtusi-lab7-test-lb mtusi-lab7-test-api mtusi-lab7-test-worker mtusi-lab7-test-relay base_url=https://localhost:18088 ca=…/.pki/stand/ca.crt
[test_isolated] remove objects /buckets/messenger/test_messenger/ and queue test_messenger.attachment.process.v1
…
[test_isolated] make student_test
…
[test_isolated] cleanup
[test_isolated] remove objects /buckets/messenger/test_messenger/ and queue test_messenger.attachment.process.v1
[test_isolated] results: {'test': 0, 'student_test': 2}
```
## `broker-check --require-test-queue` между прогонами (код 0)
```text
image rabbitmq:4.3.7@sha256:6c988780c85e08b7f12395973b89bda8fb3fe2f656498a74b1479a37f9903e48
memory high watermark 419430400, container limit 536870912
queues (name durable messages consumers):
test_messenger.attachment.process.v1 True 0 0
messenger.attachment.process.v1 True 0 1
docker compose stop rabbitmq: 1.5 s
image is tag and digest expected yes got yes
container health expected healthy got healthy
data volume expected mtusi-lab7_rabbitmq_data got mtusi-lab7_rabbitmq_data
docker port expected 5671/tcp -> 127.0.0.1:5673 got 5671/tcp -> 127.0.0.1:5673
container memory limit expected 536870912 got 536870912
watermark below container limit expected yes got yes
broker password holders expected none got none
broker identity key holders expected rabbitmq:rabbitmq.key,relay:relay.key,worker:worker.key got rabbitmq:rabbitmq.key,relay:relay.key,worker:worker.key
BROKER__* in the api service expected no got no
work queue exists expected yes got yes
work queue durable expected yes got yes
queue test_messenger.attachment.process.v1 expected yes got yes
docker compose stop exit code expected 0 got 0
container exit code expected 0 got 0
stopped before the 20 s grace expected yes got yes
broker back (up --wait) expected 0 got 0
work queue after restart expected yes got yes
worker consumes again expected yes got yes
relay survived the outage (StartedAt) expected yes got yes
PASS: the broker stand matches the spec
```
+37
View File
@@ -0,0 +1,37 @@
# Брокер рабочего стенда
- Команда: `python3 .claude/skills/run-mtusi-messenger/driver.py --port 8443 broker-check`
- Дата: 2026-12-02, 03:42:35–03:42:50 UTC; код выхода 0
- Commit: `bb20855` (ветка `feat/lab7-final`); рабочее дерево — правки последнего шага, часть 2 (аудит матрицы, документы, файлы `evidence/`), код образа = `HEAD`
- Стенд: проект compose `mtusi-lab7`, телеметрия включена, собран `make run_docker` из рабочего дерева. Очередь `test_messenger.…` в списке — остаток `make test_isolated KEEP_TEST_DB=1` (`evidence/broker/isolated.md`)
- Сценарии спека `message-broker`: «Сервис брокера запущен», «Предел памяти брокера», «Остановка брокера»
- `watermark` 419430400 байт — 400 МиБ из `infra/rabbitmq/rabbitmq.conf`; лимит контейнера 512 МиБ. С лабы 7 (change `messaging-telemetry-mtls`) паролей брокера нет ни у кого, порт — TLS-слушатель 5671 (публикация только `127.0.0.1:5673`), ключи identity — только у `rabbitmq`, `relay`, `worker`; у реплик API настроек брокера нет
```text
image rabbitmq:4.3.7@sha256:6c988780c85e08b7f12395973b89bda8fb3fe2f656498a74b1479a37f9903e48
memory high watermark 419430400, container limit 536870912
queues (name durable messages consumers):
test_messenger.attachment.process.v1 True 0 0
messenger.attachment.process.v1 True 0 1
temporary database queue test_messenger.attachment.process.v1: not checked
docker compose stop rabbitmq: 1.5 s
image is tag and digest expected yes got yes
container health expected healthy got healthy
data volume expected mtusi-lab7_rabbitmq_data got mtusi-lab7_rabbitmq_data
docker port expected 5671/tcp -> 127.0.0.1:5673 got 5671/tcp -> 127.0.0.1:5673
container memory limit expected 536870912 got 536870912
watermark below container limit expected yes got yes
broker password holders expected none got none
broker identity key holders expected rabbitmq:rabbitmq.key,relay:relay.key,worker:worker.key got rabbitmq:rabbitmq.key,relay:relay.key,worker:worker.key
BROKER__* in the api service expected no got no
work queue exists expected yes got yes
work queue durable expected yes got yes
docker compose stop exit code expected 0 got 0
container exit code expected 0 got 0
stopped before the 20 s grace expected yes got yes
broker back (up --wait) expected 0 got 0
work queue after restart expected yes got yes
worker consumes again expected yes got yes
relay survived the outage (StartedAt) expected yes got yes
PASS: the broker stand matches the spec
```
+24
View File
@@ -0,0 +1,24 @@
# Кэш карточки чата
- Команды: `make test_isolated KEEP_TEST_DB=1` (ключи временной базы), затем `python3 .claude/skills/run-mtusi-messenger/driver.py --port 8443 cache-check --require-test-keys`
- Дата: 2026-12-02; `make test_isolated` 03:39:12–03:41:50 UTC, `cache-check` 03:41:52–03:42:18 UTC, код выхода `cache-check` 0
- Код выхода `make test_isolated` 2 и только по одной причине: `test_exclusion_evidence_exists` (этого файла и соседних исключений лабы 7 ещё не было: `evidence/` в новую лабу не переносится); публичный `make test` в нём — код 0, набор — 1 failed, 227 passed, 7 skipped. Снятие файла этой команды требует её прогона, поэтому поменять порядок нельзя
- Commit: `bb20855` (ветка `feat/lab7-final`); рабочее дерево — правки последнего шага, часть 2 (аудит матрицы, документы, файлы `evidence/`), код образа = `HEAD`
- Стенд: проект compose `mtusi-lab7`, две реплики за HAProxy по mTLS, внешний HTTPS `https://localhost:8443` с CA стенда, телеметрия включена, собран `make run_docker` из рабочего дерева; кэш Valkey — по TLS пользователем ACL `api`; пользователи и чат синтетические
- Спеки: `chat-cache`, «Чтение из кэша», «Срок записи», «Временная база» (исключения сверки покрытия: по HTTP ответ из кэша не отличить от ответа из PostgreSQL)
- Перед прогоном Valkey перезапускался (возврат контроля аудита, `evidence/security/security-audit.md`): ключи рабочей базы — только созданные после него
Итог: на 50 чтений карточки через LB — одно чтение таблицы `chats` (первое, ключ перед этим удалён), +49 попаданий и +1 промах Valkey; срок ключа не больше настроенного (3600 с), чтения его не продлевают; ключи рабочей и временной базы — под разными префиксами (1 и 171).
```text
users alice_… (creator) and bob_… (reader), chat d80c50f6-79f8-45df-997f-8c2a9fe209cf
key messenger:v1:messenger:chat:d80c50f6-79f8-45df-997f-8c2a9fe209cf
right after 201: EXISTS 1, TTL 3600 s (configured [cache] chat_ttl_seconds 3600 s in the replica); value keys ['created_at', 'id', 'member_ids', 'title'], member_ids in creation order: yes
DEL key: the first read is a miss; waiting 11 s
50 × GET /api/v1/chats/{id} by the reader through LB: 50 equal to the creation response; by replica 169929a788d4880a 25, a207ff38444c7f43 25
after 11 s: reads of table chats (seq_scan + idx_scan) +1, keyspace_hits +49, keyspace_misses +1
TTL 3588 s, then 10 more reads, TTL 3588 s: reads do not extend the key
keys messenger:v1:messenger:chat:*: 1
keys messenger:v1:test_messenger:chat:*: 171
PASS: one read of chats, the rest from Valkey; TTL is bounded; temporary database: 171 keys under its own prefix
```
@@ -0,0 +1,92 @@
# Повтор отправки после рестарта API
- Шаги: синтетический пользователь (регистрация, вход по Basic) и чат; `POST /api/v1/chats/<chat>/messages` с `Idempotency-Key`; `docker compose up -d --force-recreate api`; ожидание `/health/ready` 200 через LB; тот же `POST` с тем же ключом и токеном; другое тело с тем же ключом; `GET` истории. Шаги выполнил разовый скрипт на stdlib вне репозитория (те же запросы, что `driver.py --port 8443 req … --key <ключ>` скилла, по HTTPS с CA стенда), шаги выше повторяются руками
- Дата: 2026-12-02, 03:43:12–03:43:24 UTC; код выхода 0
- Commit: `bb20855` (ветка `feat/lab7-final`); рабочее дерево — правки последнего шага, часть 2 (аудит матрицы, документы, файлы `evidence/`), код образа = `HEAD`
- Стенд: проект compose `mtusi-lab7`, две реплики за HAProxy (mTLS LB → API), снаружи `https://localhost:8443`, телеметрия включена, собран `make run_docker` из рабочего дерева; пользователь и чат синтетические
- Спек: `idempotency`, «Повтор после рестарта API» (исключение сверки покрытия: тесты сервер не трогают)
- Вывод обезличен: ключ заменён на `<key>`; токена и пароля в выводе нет
Итог: новые контейнеры обеих реплик (другие `id` и `StartedAt`), повтор — тот же 201 и тот же `Message` от процесса, которого при первой отправке не было (`X-Instance-Id` с лабы 7 — случайный alias процесса: `513dedf9ffc4317b` → `fa5f73f7d6951ad6`). В истории одно сообщение; другое тело с тем же ключом — 409. Сессия и ключ лежат в PostgreSQL, поэтому пересоздание реплик на них не влияет. Новые реплики прочитали секреты из OpenBao (распечатан) и стартовали без оператора; compose пересоздал только реплики, зависимости (`postgres-bootstrap`, `migrate`, `s3-bootstrap`) лишь повторно запустил — no-op; PostgreSQL не перезапускался.
```text
--- before: api containers (name, id, StartedAt)
/mtusi-lab7-api-183 33d403c38cdd 2026-12-02T03:43:08.102264877Z
/mtusi-lab7-api-184 9e7d80b101e9 2026-12-02T03:33:20.806664799Z
--- first send
idempotency-key: <key>
201 x-request-id: 5a7c8b7337274b8aa081ce8e11ee2727 x-instance-id: 513dedf9ffc4317b
{
"id": "1be56546-251c-4dd2-b279-121894784ee7",
"chat_id": "912216c8-cd7b-41c6-a1a6-759015053198",
"sender_id": "6897efca-ae5f-4fb1-b7b5-fba47487ecad",
"text": "replay after restart",
"created_at": "2026-12-02T03:43:13.160820Z",
"attachment_ids": []
}
--- docker compose up -d --force-recreate api
Container mtusi-lab7-openbao-1 Running
Container mtusi-lab7-valkey-1 Running
Container mtusi-lab7-postgres-1 Running
Container mtusi-lab7-s3-1 Running
Container mtusi-lab7-api-183 Recreate
Container mtusi-lab7-api-184 Recreate
Container mtusi-lab7-api-183 Recreated
Container mtusi-lab7-api-184 Recreated
Container mtusi-lab7-postgres-1 Waiting
Container mtusi-lab7-s3-1 Waiting
Container mtusi-lab7-valkey-1 Waiting
Container mtusi-lab7-openbao-1 Waiting
Container mtusi-lab7-valkey-1 Healthy
Container mtusi-lab7-openbao-1 Healthy
Container mtusi-lab7-s3-1 Healthy
Container mtusi-lab7-postgres-1 Healthy
Container mtusi-lab7-s3-bootstrap-1 Starting
Container mtusi-lab7-postgres-bootstrap-1 Starting
Container mtusi-lab7-postgres-bootstrap-1 Started
Container mtusi-lab7-postgres-bootstrap-1 Waiting
Container mtusi-lab7-s3-bootstrap-1 Started
Container mtusi-lab7-s3-bootstrap-1 Waiting
Container mtusi-lab7-postgres-bootstrap-1 Exited
Container mtusi-lab7-migrate-1 Starting
Container mtusi-lab7-migrate-1 Started
Container mtusi-lab7-migrate-1 Waiting
Container mtusi-lab7-s3-bootstrap-1 Exited
Container mtusi-lab7-migrate-1 Exited
Container mtusi-lab7-api-183 Starting
Container mtusi-lab7-api-183 Started
Container mtusi-lab7-api-184 Starting
Container mtusi-lab7-api-184 Started
exit 0
LB ready: 200
--- after: api containers (name, id, StartedAt)
/mtusi-lab7-api-183 321799d1c4b6 2026-12-02T03:43:22.3324823Z
/mtusi-lab7-api-184 1ceaa51d8fc5 2026-12-02T03:43:22.472023925Z
--- repeat with the same key, the same session
idempotency-key: <key>
201 x-request-id: a11d8258564d4dd5ba1ceb0236bac8e4 x-instance-id: fa5f73f7d6951ad6
{
"id": "1be56546-251c-4dd2-b279-121894784ee7",
"chat_id": "912216c8-cd7b-41c6-a1a6-759015053198",
"sender_id": "6897efca-ae5f-4fb1-b7b5-fba47487ecad",
"text": "replay after restart",
"created_at": "2026-12-02T03:43:13.160820Z",
"attachment_ids": []
}
--- other body with the same key
idempotency-key: <key>
409 x-request-id: 77f9ce5e6f354c97aa4945c217442f0c x-instance-id: fa5f73f7d6951ad6
{
"error": {
"code": "conflict",
"message": "Idempotency key was already used with another request",
"request_id": "77f9ce5e6f354c97aa4945c217442f0c"
}
}
--- history
{"count": 1, "ids": ["1be56546-251c-4dd2-b279-121894784ee7"]}
--- compare
Message of the repeat = Message of the first send: yes
other instance answered the repeat: yes
PASS
```
+40
View File
@@ -0,0 +1,40 @@
# Сохранность при рестарте стенда
- Команда: `make test-persistence ACTION_SCRIPT=scripts/restart.sh` (Makefile передаёт `--base-url https://localhost:8443 --ca-file .pki/stand/ca.crt`)
- Дата: 2026-12-02, 03:43:25–03:43:56 UTC; код выхода 0
- Commit: `bb20855` (ветка `feat/lab7-final`); рабочее дерево — правки последнего шага, часть 2 (аудит матрицы, документы, файлы `evidence/`), код образа = `HEAD`
- Стенд: проект compose `mtusi-lab7`, телеметрия включена, собран `make run_docker` из рабочего дерева; OpenBao распечатан и hook его не трогает
- Что проверяет публичная проверка: данные, прежний токен и с лабы 4 оригинал вложения после hook (`tests/README.md`)
- Что перезапустил hook (сверка `docker inspect` до и после, `RestartCount` у всех 0): `api-183`, `api-184`, `haproxy`, `postgres`, `rabbitmq`, `s3`, `valkey` — новый `StartedAt`; `relay`, `worker` и `cleaner` hook не трогает, `StartedAt` прежний; сервисы телеметрии, их шлюзы и `openbao` — тоже прежний. Одноразовые `postgres-bootstrap`, `migrate` и `s3-bootstrap` повторяет `start api` (no-op). Реплики после рестарта прочитали секреты из OpenBao без действий оператора. Volumes не удалялись
```text
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
```
| Контейнер | `StartedAt` до | `StartedAt` после |
|---|---|---|
| `api-183` | 03:43:22.332 | 03:43:53.039 |
| `api-184` | 03:43:22.472 | 03:43:53.187 |
| `haproxy-1` | 03:33:20.990 | 03:43:53.345 |
| `postgres-1` | 03:33:11.992 | 03:43:28.080 |
| `rabbitmq-1` | 03:42:40.120 | 03:43:29.043 |
| `s3-1` | 03:33:11.131 | 03:43:42.954 |
| `valkey-1` | 03:38:26.477 | 03:43:27.944 |
| `postgres-bootstrap-1` | 03:43:15.401 | 03:43:47.536 |
| `migrate-1` | 03:43:19.682 | 03:43:50.792 |
| `s3-bootstrap-1` | 03:43:15.577 | 03:43:47.675 |
| `relay-1` | 03:33:20.377 | 03:33:20.377 |
| `worker-1` | 03:33:20.509 | 03:33:20.509 |
| `cleaner-1` | 03:33:20.260 | 03:33:20.260 |
| `openbao-1` | 03:33:00.990 | 03:33:00.990 |
| `otel-gateway-1` | 03:33:12.279 | 03:33:12.279 |
| `otel-collector-1` | 03:37:11.769 | 03:37:11.769 |
| `loki-gateway-1` | 03:33:10.947 | 03:33:10.947 |
| `loki-1` | 03:37:12.349 | 03:37:12.349 |
| `tempo-gateway-1` | 03:33:11.034 | 03:33:11.034 |
| `tempo-1` | 03:37:14.758 | 03:37:14.758 |
| `prometheus-gateway-1` | 03:33:11.662 | 03:33:11.662 |
| `prometheus-1` | 03:37:11.768 | 03:37:11.768 |
| `grafana-1` | 03:33:11.815 | 03:33:11.815 |
Значения «до» позже старта стенда (03:33): `valkey-1` — 03:38, его перезапустил возврат контроля аудита (`evidence/security/security-audit.md`); `otel-collector`, `loki`, `tempo`, `prometheus` — 03:37, их перезапустил `telemetry-check` аудита; `rabbitmq-1` — 03:42, его остановил и вернул `driver.py broker-check` (`evidence/broker/stand.md`); `api-183` и `api-184` — 03:43, их пересоздал повтор отправки (`evidence/idempotency/replay-after-restart.md`).
+164
View File
@@ -0,0 +1,164 @@
# Аудит матрицы доверия одной командой
- Команда: `make security_audit AUDIT_LOGS=<временный каталог вне репозитория>` (`infra/audit/audit.py`)
- Дата: 2026-12-02, 03:33:30–03:37:39 UTC (~4 мин: `telemetry-check` — 129 с, остальное — 0–29 с на
проверку); код выхода 0
- Commit: `bb20855` (ветка `feat/lab7-final`); рабочее дерево — правки последнего шага, часть 2 (сам
аудит, его быстрый тест, документы); код образа (`src/`, `migrations/`, `Dockerfile`) = `HEAD`
- Стенд: рабочий `mtusi-lab7`, собран `make run_docker` (OpenBao распечатан `make bao_unseal`), две реплики
за HAProxy, телеметрия включена, стенд проработал ~3 мин до начала
- Рубрика «4»: «TLS-аудит проверяет всю заявленную матрицу, ACL и отсутствие утечек в telemetry»
Аудит не проверяет сам: он зовёт по одной существующие отрицательные проверки (команды драйвера скилла
`run-mtusi-messenger` и публичный `tests/security.py`) и сводит их коды по строкам
`contracts/trust-matrix.md`. Своя проба — только внешний TLS ingress (`ingress-tls`, вывод ниже). Строка
утечек берёт из `telemetry-check` только пробу приватности: 9 образцов (username, пароль, токен, текст
сообщения, ключ идемпотентности, `filename`, `Bearer `, `Basic `, чужой trace-id) в 49 записях Loki, 30
трассах Tempo и 472 сериях Prometheus — 0 совпадений. Две другие строки `telemetry-check` красные и вердикт
утечек не меняют: `resource service.version = contract` (известная, `KNOWN_ISSUES.md`) и «panel queries
with data after traffic» — правила записи SLO по окнам 5 мин / 1 ч на стенде, проработавшем 3 мин, ещё
пусты.
Каждая строка таблицы матрицы (12) и три строки вне её имеют проверку; строк без проверки нет. Строка
«Replication» — N/A (по одному серверу), её проверки — что кластерные и служебные порты закрыты из сети.
Что строку доказывает вне аудита (ротация и отзыв — `make rotation_check`, сессии и предел входа — `make
student_test` / `make failure_checks`, уязвимости — `make scan`), сводка называет полем «outside the
audit»: эти команды меняют leaf и секреты стенда или требуют стенда отказов.
## Сводка
```text
check ingress-tls: PASS (code 0, 0 s)
check test-security: PASS (code 0, 0 s)
check mtls-check: PASS (code 0, 18 s)
check storage-tls-check: PASS (code 0, 4 s)
check storage-roles-check: PASS (code 0, 18 s)
check s3-check: PASS (code 0, 6 s)
check broker-mtls-check: PASS (code 0, 29 s)
check telemetry-tls-check: PASS (code 0, 11 s)
check openbao-check: PASS (code 0, 11 s)
check auth-storage: PASS (code 0, 6 s)
check telemetry-leaks: PASS (code 0, 129 s); 9 needles in 49 records, 30 traces; other telemetry-check rows FAIL: resource service.version = contract; panel queries with data after traffic
check hardening-check: PASS (code 0, 17 s)
summary: matrix row → check → result
[trust matrix]
Клиент → ingress/LB: PASS
- TLS ≥ 1.2, CA и hostname, нет HTTP → ingress-tls: PASS
- пустое хранилище корней — отказ → test-security: PASS
- журнал API без credentials → auth-storage: PASS
outside the audit: сессии, предел входа, предел тела — make student_test, make failure_checks; ротация ingress — make rotation_check
LB → API (все реплики): PASS
- mTLS 1.3, allowlist haproxy, чужой сервер api → mtls-check: PASS
outside the audit: ротация leaf haproxy / api — make rotation_check
API/worker → PostgreSQL: PASS
- TLS 1.3 verify-full, нет hostnossl → storage-tls-check: PASS
- роли процессов = матрица, DDL и чужое — 42501 → storage-roles-check: PASS
- пароль роли только из OpenBao → openbao-check: PASS
outside the audit: ротация пароля — make rotation_check
API/worker → S3: PASS
- HTTPS, чужой CA и имя — отказ → storage-tls-check: PASS
- пользователи и префиксы, gRPC шлюза mTLS → s3-check: PASS
- ключи только из OpenBao → openbao-check: PASS
outside the audit: ротация ключа — make rotation_check
API/worker → broker: PASS
- mTLS 1.3, EXTERNAL, права relay / worker → broker-mtls-check: PASS
outside the audit: отзыв identity брокера — make rotation_check
API/worker → Collector: PASS
- mTLS шлюза OTLP, allowlist api / worker / relay → telemetry-tls-check: PASS
Collector → telemetry backends: PASS
- mTLS шлюзов, allowlist и права по пути → telemetry-tls-check: PASS
Grafana → data sources: PASS
- grafana-client только чтение → telemetry-tls-check: PASS
API/worker/agent → OpenBao: PASS
- mTLS, cert auth, политика на процесс → openbao-check: PASS
outside the audit: отзыв токенов и CRL под нагрузкой — make rotation_check
Оператор → OpenBao/Grafana/S3 admin: PASS
- OpenBao на 127.0.0.1, root token не у сервисов → openbao-check: PASS
- Grafana только HTTPS на 127.0.0.1 → telemetry-tls-check: PASS
- служебные порты S3 из сети закрыты → s3-check: PASS
- CLI брокера только на loopback → broker-mtls-check: PASS
- публикации только 127.0.0.1 → hardening-check: PASS
API → Redis/Valkey, если используется: PASS
- TLS 1.3, нет порта без TLS → storage-tls-check: PASS
- ACL api, default off → storage-roles-check: PASS
outside the audit: ротация пароля — make rotation_check
Replication/кластерные каналы, если добавлены: PASS
- N/A: raft OpenBao 8201 из сети закрыт → openbao-check: PASS
- N/A: master / filer S3 на loopback → s3-check: PASS
[outside the table]
Каналы scrape, health и bootstrap: PASS
- :8404 LB, :8888 / :8889, :8405, :14318 → telemetry-tls-check: PASS
- health 8210 OpenBao из сети закрыт → openbao-check: PASS
- распределение Erlang на loopback → broker-mtls-check: PASS
- слушатели хранилищ вне loopback → storage-tls-check: PASS
- слушатели всех контейнеров = список → hardening-check: PASS
Контейнеры: capabilities, root, корень, pids: PASS
- docker inspect, процессы, EROFS, pids → hardening-check: PASS
outside the audit: уязвимости образов — make scan
Утечки в телеметрии: PASS
- Loki, Tempo, Prometheus без credentials и тел → telemetry-leaks: PASS
- журнал API без credentials → auth-storage: PASS
- аудит OpenBao без токенов → openbao-check: PASS
PASS: every matrix row is proven by its checks
```
Проба внешнего TLS (`ingress-tls.log`):
```text
stand CA, localhost: /health/ready expected 200 got 200
empty trust store expected verify got verify
stand CA, name 127.0.0.1 expected hostname mismatch got hostname mismatch
HTTP without TLS expected no HTTP response got no HTTP response
TLS 1.1 only expected protocol version alert got protocol version alert
```
## Контроль: снятая мера — красный
Мера — ACL пользователя `api` в Valkey (строка «API → Redis/Valkey»). Оператор дал `api` право `FLUSHALL`
(`ACL SETUSER api +flushall` внутри контейнера `valkey` пользователем `operator`), затем аудит двумя
проверками этой строки; возврат — `docker compose restart valkey` (`infra/valkey/start.sh` строит файл ACL
заново из `.env`). 2026-12-02, 03:38:04–03:39:20 UTC. Проверка `storage-roles-check` выполнила настоящий
`FLUSHALL` на рабочем Valkey (кэш и счётчики входа пусты, как после рестарта Valkey; данные — в PostgreSQL).
```text
### control: ACL SETUSER api +flushall (operator)
OK
$ make security_audit ONLY=storage-tls-check,storage-roles-check
check storage-tls-check: PASS (code 0, 4 s)
check storage-roles-check: FAIL (code 1, 18 s)
api valkey api FLUSHALL NOPERM OK FAIL
api valkey api EVAL redis.call FLUSHALL NOPERM (script) OK FAIL
FAIL: 2 check(s) failed
…
API/worker → PostgreSQL: FAIL
- TLS 1.3 verify-full, нет hostnossl → storage-tls-check: PASS
- роли процессов = матрица, DDL и чужое — 42501 → storage-roles-check: FAIL
…
API → Redis/Valkey, если используется: FAIL
- TLS 1.3, нет порта без TLS → storage-tls-check: PASS
- ACL api, default off → storage-roles-check: FAIL
…
FAIL: audit code 1
make: *** [security_audit] Error 1
### docker compose restart valkey (ACL file rebuilt by start.sh)
$ ACL GETUSER api (commands)
-@all +get +set +eval +evalsha +ttl +expire +incr +decr +del
$ make security_audit ONLY=storage-tls-check,storage-roles-check
check storage-tls-check: PASS (code 0, 4 s)
check storage-roles-check: PASS (code 0, 18 s)
…
API → Redis/Valkey, если используется: PASS
PASS: every matrix row is proven by its checks
```
Ограничение сводки: проверка, общая для нескольких строк, краснит каждую из них — здесь
`storage-roles-check` (роли PostgreSQL и ACL Valkey одной командой) сделал красной и строку PostgreSQL;
какое хранилище нарушено, называют строки FAIL самой проверки под её именем.
Быстрый контроль полноты — `service-tests/unit/test_security_audit.py`: строка матрицы без строки аудита,
лишняя строка аудита и неизвестная проверка — красный тест с именем (`test_missing_or_extra_row_is_named`);
так же `audit.py` до проверок отказывает кодом 2.