Files
mtusi2026lab7/contracts/trust-matrix.md
T
2026-11-22 23:33:11 +03:00

39 lines
9.8 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.
# Матрица доверия — lab7, уровень 4
Локальный root CA создаётся `scripts/init-secrets.sh`: CA действует 3650 дней, leaf certificates — 365 дней. Private keys находятся только в ignored `secrets/pki` с mode 0600/0640; CA certificate может передаваться клиенту. TLS gateways допускают plaintext только на отдельной `internal: true` сети между gateway и одним backend без опубликованного обхода.
| Связь | Порт/endpoint и server trust | Client/service identity и права | Срок credential | Положительный/отрицательный тест и конфиг |
| --- | --- | --- | --- | --- |
| Клиент → ingress/LB | `127.0.0.1:8443`, TLS 1.3; local CA; SAN `DNS:localhost, IP:127.0.0.1` | Bearer session; Basic только `POST /auth/sessions`; session в общей PostgreSQL | session 3600 s; leaf 365 d | `make test-security`: CA pass, empty trust store certificate error. `make test`: outsider/X-User-Id/logout. `infrastructure/haproxy/haproxy.cfg` |
| LB → API (обе реплики) | `api:8444`, TLS 1.3; ingress проверяет local CA и `verifyhost api` | mTLS cert с версионируемой URI SAN; API требует CA и точную URI allowlist из runtime secret | leaf 365 d; operator rotation | `make test-security-grade3`; `make rotate-leaf-grade4`: no/foreign/wrong/old/expired deny, active LB allow, host binding отсутствует. `internal/security/mtls.go` |
| API/worker/dispatcher → PostgreSQL | `postgres:5432`, native TLS, `sslmode=verify-full`, local CA, SAN `postgres` | Отдельные `messenger_api`, `messenger_worker`, `messenger_dispatcher`; явные table/sequence GRANT, без admin | static lab password до operator rotation; получается через AppRole token 15m | `scripts/bootstrap-dependencies.sh`; `secrets/postgres-roles.sql` генерируется локально; `compose.yaml` не передаёт admin secret приложению |
| API/worker → S3 | `dependency-gateway:9000`, TLS 1.3, CA + SAN gateway; дальше только закрытая `s3_local` сеть к MinIO 9000 | API: Put `staging/*`, Get `attachments/*`; worker: Get/Delete staging, CRUD attachments; разные access keys | static lab key до operator rotation; выдаётся через scoped OpenBao path | `./tests/minio_policy.sh`: staging read deny, attachment write deny, bucket create/anonymous GET deny. `infrastructure/minio/*-policy.template.json` |
| Dispatcher/worker → broker | `dependency-gateway:5671`, TLS 1.3, CA + SAN gateway; локальный hop к RabbitMQ 5672 только `broker_local` | mTLS exact CN `dispatcher`/`worker` с разными URI SAN; затем `dispatcher` publish-only и `worker` consume-only Rabbit ACL. API cert намеренно deny: API пишет transactional outbox, а не broker | leaf 365 d; password operator-rotated через scoped KV | `make test-security-grade4`: no cert, same-CA intruder/API deny; worker/dispatcher allow. `make test-acl-grade4`; `make rotate-secret-grade4` old password deny |
| API/worker/dispatcher → Collector | `telemetry-gateway:4318`, TLS 1.3, CA + SAN `telemetry-gateway`; локальный hop только `collector_local` | mTLS exact CN ACL; отдельные `api`, `worker`, `dispatcher` clientAuth leaf/URI identities; ingest port не published; headers/body не экспортируются | leaf 365 d | `make test-security-grade4`: no cert и same-CA intruder deny; все три scoped identities allow. `make test-telemetry-leak-grade4` |
| Collector → telemetry backends | HTTPS gateway `3100` (Loki), `4319` (Tempo); CA + SAN gateway | mTLS CN `otel-collector`, URI `spiffe://mtusi/lab7/collector`; Loki допускает collector write/Grafana read, Tempo ingest — только collector | leaf 365 d | HAProxy `verify required` + exact CN ACL. Missing/other client cert rejected; live Collector reports `Everything is ready` |
| Prometheus → Collector metrics | HTTPS gateway `8888/8889`; CA + SAN gateway | mTLS CN `prometheus`, URI `spiffe://mtusi/lab7/prometheus`; эти ports допускают только Prometheus | leaf 365 d | `prometheus.yaml` cert/key; targets scrape через `telemetry-gateway`; no-cert gateway connection rejected |
| Grafana → data sources | HTTPS gateway `9090/3100/3200`; CA + SAN gateway | mTLS CN `grafana`, URI `spiffe://mtusi/lab7/grafana`; generated ignored datasource provisioning embeds local client key, backend ACL разрешает только Grafana (Loki также collector) | leaf 365 d; Grafana admin password static local | `make test-security-grade3`: no cert и LB cert deny, Grafana cert allow на Prometheus. `secrets/grafana-datasources.yaml` не в Git |
| API/worker/dispatcher → OpenBao | `openbao:8200`, native TLS 1.3, CA + SAN `openbao` | AppRole `api`, `worker`, `dispatcher`; каждая policy — read только `secret/data/<role>`; root/unseal отсутствуют в app | token TTL 15m/max 30m; SecretID 168h; lifecycle test uses bounded 10s/24s token and one-use SecretID | policy allow/deny plus `make test-openbao-lifecycle-grade4`: reuse/expiry/seal/fresh-start fail-closed/unseal recovery |
| Оператор → OpenBao/Grafana/S3 admin | OpenBao `127.0.0.1:18200` TLS; Grafana `127.0.0.1:13000` TLS; S3 admin port не published | OpenBao root/unseal только `.operator` 0600; Grafana login password file; MinIO root только one-shot bootstrap service | operator material до ручной rotation; Grafana/MinIO static local | `docker compose ps` показывает loopback binding; API containers не имеют MinIO root/OpenBao root. `./tests/minio_policy.sh` |
| API → Redis | `dependency-gateway:6380`, TLS 1.3, CA + SAN gateway; локальный hop только `redis_local` | Redis ACL user `api`: `~chat:v2:*`, команды get/set/del/ping; default user off | static lab password до operator rotation; scoped API OpenBao path | generated ignored `secrets/redis.conf`; Redis 6379 не published; readiness/cache tests проходят |
| Replication/cluster channels | N/A: PostgreSQL, Redis, MinIO, RabbitMQ, OpenBao и telemetry stores одноузловые | Кластерная/host HA не заявлена; две API-реплики разделяют stores | N/A | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` доказывает только API process failover, не отказ host/store |
## Обязательные отрицательные проверки
1. `make test-security` различает успешный HTTPS и ошибку certificate verification с пустым trust store.
2. `make test-security-grade3` выполняет четыре LB→API случая и проверяет отсутствие host binding API. Тем же скриптом telemetry backend отвергает отсутствие cert и доверенный LB cert, но принимает Grafana identity.
3. `make test` проверяет, что пользователь вне чата не читает metadata/content, а `X-User-Id` не переопределяет Bearer identity.
4. `make test-openbao-policy` доказывает allow/deny scoped AppRole без передачи root token приложению.
5. `./tests/minio_policy.sh` проверяет реальные prefix rights и отсутствие root credentials в API.
6. `make test-security-grade4` проверяет mTLS broker/Collector, включая чужой сертификат той же CA; `make test-acl-grade4` проверяет DB/Redis/Rabbit permissions.
7. `make rotate-leaf-grade4` удаляет старую LB URI из allowlist, проверяет old/expired deny и active leaf allow без rebuild.
8. `make test-telemetry-leak-grade4` сверяет Loki с credential probe и всеми локальными secret values, не печатая их.
## Bootstrap и эксплуатация
В Git находятся только генераторы, policy templates и public CA configuration. `secrets/`, `.operator/` и `volumes/` игнорируются. CA key, leaf keys, passwords, SecretID, root token и unseal share не входят в image layers и отчёт.
Оператор выполняет `make up`. При первой инициализации OpenBao root/unseal JSON сохраняется отдельно от storage в `.operator` mode 0700/0600. App images не содержат постоянный bootstrap secret: service получает ограниченный по сроку SecretID через runtime mount, обменивает его на bounded token и читает один allowlisted KV path. После рестарта OpenBao sealed; `scripts/bootstrap-openbao.sh` читает operator file, выполняет unseal и обновляет policies/KV/SecretID, после чего app containers пересоздаются. Потеря operator file при initialized storage требует внешней резервной копии unseal material; приложение восстановить trust само не может.
`scripts/rotate-secret-grade4.sh` меняет worker RabbitMQ password в backend и scoped KV, пересоздаёт только worker с `--no-build` и доказывает old deny. `scripts/rotate-leaf-grade4.sh` выпускает новый LB client leaf, атомарно меняет cert/allowlist, пересоздаёт edge с `--no-build` и доказывает old/expired deny. Образа CA/root material не получают; фонового renewal agent нет, поэтому штатные 7 d SecretID и 365 d leaf обновляет оператор до expiry.