Files
mtusi2026lab7/contracts/trust-matrix.md
T

76 lines
13 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Матрица доверия HLA Lab 7
Матрица фиксирует целевую архитектуру и текущее покрытие. **PASS** — контроль реализован; **PARTIAL** — реализована часть; **GAP** — связь пока не удовлетворяет минимуму lab7. Docker-сеть сама по себе не является аутентификацией.
Имена identities ниже являются контрактом для PKI/OpenBao bootstrap. Формат SAN — URI `spiffe://hla-lab7/<role>`; проверяются chain, EKU и точное разрешённое значение SAN. Private keys, root token, unseal shares и SecretID не хранятся в Git.
## Основные связи
| Связь | Endpoint / порт | Протокол и server trust | Client identity и минимальные права | Lifecycle | Проверяемый отказ / доказательство | Статус |
| --- | --- | --- | --- | --- | --- | --- |
| Клиент → nginx | `https://localhost:8443` | TLS 1.2/1.3; `secrets/tls/ca.crt`; SAN `localhost`; hostname verification | Public registration/health, Basic login, Bearer business API; `X-User-Id` не identity | Session 3600 s, максимум 3 активных; logout/replacement revoke; leaf 30 d | `make test-security`; чужой/пустой CA, wrong hostname, expired leaf → certificate error; revoked token → 401; login burst → 429 + Retry-After | **PASS** для внешнего TLS/auth/session/rate-limit контракта |
| nginx → API replicas | `https://api:8443` | mTLS; service CA + SAN `spiffe://hla-lab7/api`; API доверяет отдельному LB client CA | nginx SAN `spiffe://hla-lab7/lb`; точный URI SAN проверяет `TrustedClientCertificateFilter`; API port не публикуется | Leaf 30 d, local regeneration/restart | `scripts/test-mtls.ps1`: no cert, foreign CA, trusted cert SAN `.../worker` rejected; LB cert → health 200 | **PASS** |
| API → PostgreSQL | `postgres:5432` | TLS `verify-full`; service CA + SAN `DNS:postgres`; plaintext rejected by `pg_hba.conf` | `messenger_api`: runtime CRUD без superuser/DDL/role management | Static stand secret, rotate/reconnect; dynamic credentials remain extension | Wrong CA/hostname fails; DDL/role management denied | **PASS (уровень 3)** |
| Worker → PostgreSQL | `postgres:5432` | TLS `verify-full` | `messenger_worker`: jobs/attachments/variants; нет users password/session/membership | Отдельный secret | `SELECT password_hash`, update membership denied; job transitions allowed | **PASS (уровень 3)** |
| API → MinIO | `https://minio:9000` | TLS verify; service CA + SAN `DNS:minio` | `messenger-api`, без admin/policy | Static stand secret, отдельно от root | Anonymous и `mc admin` denied; allowed prefix succeeds | **PASS на 3; GAP:** OpenBao rotation/prefix split |
| Worker → MinIO | `https://minio:9000` | TLS verify | Отдельный `messenger-worker` key; без admin | Отдельный static secret | `mc admin` denied | **PARTIAL:** identity отдельная, prefix policy пока общая |
| API → RabbitMQ | `rabbitmq:5671` | mTLS: service CA + workload client CA | `messenger-api`, отдельный cert SAN `.../api` и regex permissions | Отдельный secret/cert; reconnect on rotation | No cert/foreign CA denied; broker ACL ограничивает операции | **PASS на 4** |
| Worker → RabbitMQ | `rabbitmq:5671` | mTLS | Отдельные `messenger-worker` cert/user/permissions | Отдельный secret/cert | No cert/foreign CA и запрещённые ACL operations rejected | **PASS на 4** |
| API/worker → Redis | mTLS `redis:6379` | service CA + workload client CA; plaintext port disabled | Раздельные cert/ACL users; admin/flush commands removed | Отдельные secrets/certs | No cert/foreign CA, CONFIG/ACL/FLUSHALL denied | **PASS на 4** |
| API → Collector | `https://otel-collector:4318` | mTLS, service/server CA + workload client CA | SAN `spiffe://hla-lab7/api`; distinct client leaf | Leaf 30 d | No cert/foreign CA rejected; valid OTLP accepted | **PASS на 4 (раздельный cert)** |
| Worker → Collector | `https://otel-collector:4318` | mTLS | SAN `spiffe://hla-lab7/worker`; distinct cert/service.name | Отдельный leaf/revoke | Foreign CA rejected; API/worker различимы | **PASS на 4 (раздельный cert)** |
| Prometheus → Collector metrics exporter | `https://otel-collector:8889` | mTLS, service CA + telemetry client CA | Отдельный cert SAN `spiffe://hla-lab7/prometheus` | Leaf 30 d | No cert/foreign CA denied | **PASS на 4** |
| Collector → Loki | `https://loki:3100/otlp` | mTLS, Loki service cert + telemetry client CA | Cert SAN `spiffe://hla-lab7/otel-collector` | Leaf 30 d | No cert/foreign CA denied | **PASS на 4** |
| Collector → Tempo | `https://tempo:4318` | mTLS, Tempo service cert + telemetry client CA | Cert SAN `spiffe://hla-lab7/otel-collector` | Leaf 30 d | No cert/foreign CA denied | **PASS на 4** |
| Grafana → backends | HTTPS/mTLS service endpoints | Service CA verify-full; datasource CA/cert/key injected at runtime from files | Отдельный cert SAN `spiffe://hla-lab7/grafana`; Prometheus exact SAN allowlist | Leaf 30 d, not stored in provisioning Git | No cert/foreign CA denied; query allowed | **PASS для transport/identity; backend fine-grained query ACL ограничен single-tenant режимом** |
| API Agent → OpenBao | `https://openbao:8200` | TLS verify; service CA + SAN `DNS:openbao` | AppRole `messenger-api`: read только собственного KV data/metadata; нет sys/auth/root/worker | Renewable token 15 min, max 1 h; re-auth; SecretID 24 h | `test-openbao-policies.ps1`: чужой path/policy write denied; own path allowed | **PASS по конфигурации; runtime test требует initialized стенд** |
| Worker Agent → OpenBao | `https://openbao:8200` | TLS verify | AppRole `messenger-worker`: read только собственного KV data/metadata | Независимые token, RoleID и SecretID с теми же TTL | API path/policy write denied; own path allowed | **PASS по конфигурации; runtime test требует initialized стенд** |
| Agent → API/worker runtime file | Отдельные named volumes | Локальный file handoff; volume не общий между ролями | Agent рендерит allowlisted keys; app mount read-only; неожиданный key отклоняется entrypoint | Render interval 5 min; приложение перечитывает при restart | Нет файла → controlled startup failure после 120 s; чужой volume не mounted | **PASS** |
| Operator → OpenBao | `https://localhost:8200`, только loopback | TLS + service CA, SAN `localhost` | Init/unseal/root только bootstrap/recovery; file audit включён | 3 shares, threshold 2; shares/root offline; root env удаляется после bootstrap | AppRole не может init/unseal/write policy; извне хоста порт не опубликован | **PASS по конфигурации; init/unseal остаётся ручной операцией** |
| Operator → Grafana | `https://localhost:3000` | TLS verify, service CA, SAN localhost, loopback only | Named admin; anonymous/signup disabled | Local generated password/rotation | Anonymous/app credential denied | **PASS** |
| Operator → MinIO admin | Не публикуется; bootstrap внутри сети | TLS verify | Root/operator отдельно; API/worker его не получают | Rotate after bootstrap/exposure | API/worker `mc admin info` denied | **PARTIAL:** port закрыт/policy test есть; HTTP и root env у init |
| Replication channels | N/A: все stateful services single-node | N/A | N/A | N/A | При добавлении replicas матрица пересматривается | **N/A** |
## Health, scrape и bootstrap
| Канал | Разрешение | Запрет / тест | Статус |
| --- | --- | --- | --- |
| Public `/health/live`, `/health/ready` | Только `{"status":"ok"}` без topology/secrets | Business routes требуют Bearer | **PASS** по API contract |
| nginx `/nginx-health` | Только probe | Не должен быть backend proxy; предпочтителен internal listener | **PARTIAL:** сейчас на public listener |
| API container health | Тот же mTLS `api:8443`, доступен только LB/probe identity | Health не создаёт plaintext bypass; отдельный listener остаётся hardening | **PARTIAL:** health и business routes разделяют listener, но оба закрыты mTLS |
| Collector `:13133` | Только orchestrator/internal network | Не принимает OTLP и не публикуется host | **PARTIAL:** общая backend network широкая |
| Store healthchecks | Минимальная readiness без secret output | Не создают anonymous admin access | **PARTIAL:** TLS ещё не включён |
| MinIO bootstrap | One-shot operator workflow | Root не печатается и не остаётся API/worker | **PARTIAL:** root через env; заменить secret file/OpenBao workflow |
| Flyway migrate | Отдельная `messenger_migration` DDL identity и client cert | API/worker без DDL; migration container one-shot | **PASS;** static stand password rotation ещё ручная |
## Обязательные отрицательные сценарии
Каждый тест сохраняет команду, timestamp, ожидаемый и наблюдаемый результат без secret values.
1. Доверенный CA + `localhost` проходит; пустой trust store, чужой CA, expired leaf и wrong hostname дают certificate verification error. `curl -k` запрещён.
2. Для каждой API replica: no client cert, foreign CA и trusted CA с SAN `.../worker` отклоняются; только SAN `.../lb` проходит.
3. Bob не читает metadata/content чата Alice, не отправляет туда сообщение и не прикрепляет attachment другого чата. Forged `X-User-Id` не меняет Bearer identity.
4. API DB role не выполняет DDL/role management; worker не читает users/session hashes и не меняет membership; migration credential отсутствует runtime.
5. Anonymous S3 list/get запрещены; API/worker без admin; worker не выходит за staging/variant prefixes.
6. API не consume/ack broker queue; worker не configure и не publish произвольный key. На уровне 4 повторяются no-cert/foreign-CA/wrong-SAN tests.
7. Неизвестная identity не ingest telemetry; ingest credential не query/delete; Grafana read-only. Canary Authorization/token отсутствует во всех signals.
8. API/worker OpenBao policies читают только свои paths; `sys/policies/*`, чужой KV и admin credentials дают 403. После revoke проверяется новое соединение с учётом pool/cache.
9. При rotation новый leaf/secret вводится overlap, clients reconnect, старый credential доказанно отклоняется, новый работает.
10. При остановке TLS proxy/OpenBao нет downgrade на plaintext/hardcoded fallback: сервис controlled-unready либо работает лишь до documented lease TTL.
## Bootstrap и владение
- В Git находятся только открытые configs, policy templates, scripts и при необходимости public CA. Private keys/secrets создаются в `secrets/` с ограниченными ACL и исключены из build context.
- Владелец root CA, OpenBao init/root token и unseal shares — оператор. Ручной unseal допустим; shares не лежат рядом со storage volume.
- API, worker, migration, Collector, Grafana datasource и operator имеют разные identities. Общий credential между ролями — дефект даже при TLS.
- OpenBao работает с persistent storage не в dev-mode. Root token не передаётся приложению. Service token ограничен named policy/TTL/max TTL.
- Rotation доказана только после закрытия старого соединения: pools, TLS resumption и caches могут маскировать отзыв.
## Приоритет устранения GAP
1. Выделить отдельный безопасный API health listener, не содержащий business routes.
2. Разделить MinIO prefix policies API/worker и автоматизировать rotation runtime credentials.
3. Добавить отдельную узкую operator policy для ротации AppRole вместо root token после первичного bootstrap.
4. Добавить backend query-level ACL поверх уже включённого telemetry mTLS.
5. Расширить автоматизированные mTLS/rotation tests на broker, Redis и telemetry; внешний ACL/session/rate-limit сценарий находится в `tests/security.py`.