Разделение mTLS идентификаторов
This commit is contained in:
@@ -71,6 +71,20 @@ RabbitMQ, Redis и telemetry backends используют mTLS с раздел
|
||||
PostgreSQL и MinIO принимают только проверяемый TLS, а runtime-роли получают
|
||||
разные credentials по матрице доверия.
|
||||
|
||||
Для уже созданного стенда после обновления конфигурации добавьте только новые
|
||||
gateway leaves от существующего локального service CA (полная ротация PKI не
|
||||
требуется), затем пересоздайте затронутые сервисы:
|
||||
|
||||
```powershell
|
||||
.\scripts\bootstrap-mtls-gateways.ps1
|
||||
.\scripts\test-service-mtls-identities.ps1
|
||||
```
|
||||
|
||||
RabbitMQ и OTel Collector имеют native mTLS, но не дают нужной точной привязки
|
||||
к роли leaf-сертификата. Поэтому перед ними стоят непубликуемые TLS gateways:
|
||||
API/worker identities проверяются раздельно, backend принимает только gateway
|
||||
client leaves, а локальный hop также остаётся TLS с verify-full.
|
||||
|
||||
Полная безопасная последовательность `init`/`unseal`, правила хранения root
|
||||
token и долей, ротация SecretID и policy allow/deny test описаны в
|
||||
[`infra/openbao/README.md`](infra/openbao/README.md). Root token задаётся только
|
||||
|
||||
@@ -20,12 +20,13 @@ TODO: схема процессов/хранилищ, источник исти
|
||||
| Argon2id storage и калибровка | `scripts/benchmark-argon2.ps1`, `PasswordConfigTest` | PASS: итоговый профиль 32768 KiB/t=2/p=1; p95 encode 150.3 мс, verify 142.7 мс при 0.75 CPU/768 MiB; PHC хранит параметры и уникальный 16-byte salt | `README.md`, benchmark output, unit test |
|
||||
| LB → каждая API-реплика | `scripts/test-mtls.ps1`, `TrustedClientCertificateFilterTest` | PASS: обе реплики отдельно отклоняют no-cert, foreign CA и доверенный cert с чужим URI SAN; LB identity принята; API port не опубликован | `compose.yaml`, runtime test, unit test |
|
||||
| Внутренние TLS-связи и service ACL | `scripts/test-internal-tls.ps1`; `docker compose --env-file .env --profile verification run --rm private-bucket-check` | PASS: PostgreSQL, MinIO, OpenBao, Redis, RabbitMQ, Collector, Loki, Tempo и Prometheus проверяют service CA и hostname; mTLS endpoints отвергают no-cert; PostgreSQL/Redis/RabbitMQ и MinIO API/worker identities разделены, запрещённые DDL/keys/commands/prefixes denied | `evidence/internal-tls.txt`, `contracts/trust-matrix.md` |
|
||||
| Broker/Collector mTLS role binding | `scripts/test-service-mtls-identities.ps1` | PASS: API/worker идут через разные broker gateways; OTLP gateway принимает обе разрешённые роли; same-CA migration/cross-role cert не получает AMQP/OTLP доступ; direct backend bypass отклонён | `evidence/service-mtls-identities.txt` |
|
||||
| OpenBao AppRole и policies | `scripts/test-openbao-policies.ps1` | PASS: API и worker читают только свой KV path; чужой path и запись policy отклонены | `evidence/openbao-policies.txt`, `contracts/trust-matrix.md` |
|
||||
| OpenBao runtime boundaries | `scripts/test-openbao-runtime-boundaries.ps1` | PASS: server mode + persistent Raft volume; отдельные AppRole/bootstrap/rendered volumes; API/worker получают только allowlisted keys через read-only file и не имеют root token/unseal material | `evidence/openbao-runtime-boundaries.txt`, `contracts/trust-matrix.md` |
|
||||
| Compose hardening | `scripts/check-compose-hardening.ps1` | PASS: только три loopback HTTPS-порта; limits/capability/read-only policy проверены | `compose.yaml`, самопроверка скрипта |
|
||||
| Runtime isolation и утечки secrets | `scripts/test-container-secret-boundaries.ps1` | PASS: API/worker фактически non-root; privileged/host network/Docker socket отсутствуют; runtime limits и только разрешённые loopback bindings подтверждены; локальные secret values не найдены в Git, image metadata/filesystem и логах; redaction включён для traces/metrics/logs | `evidence/container-secret-boundaries.txt` |
|
||||
| Публичная security-проверка и session lifecycle | `tests/security.py`, `tests/smoke.py`, `tests/session_expiry.py` | PASS: verified HTTPS и отказ пустого trust store; outsider ACL, attachment isolation, 10 MiB limit, session cap, `429 Retry-After`, logout/revocation и управляемое expiry → `401` | `evidence/public-security.txt` |
|
||||
| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 20 cert/key bundles валидны; expiry, SAN, пары ключей, Git ignore и возраст SecretID проверены | `evidence/security-lifecycle.txt` |
|
||||
| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 26 cert/key bundles валидны; expiry, SAN, пары ключей, Git ignore и возраст SecretID проверены | `evidence/security-lifecycle.txt` |
|
||||
| Публичный smoke | `scripts/verify-https-resilience.ps1` | PASS: полный API-сценарий, включая ACL и вложения, выполнен через HTTPS с проверкой CA и hostname | `evidence/verify-https-resilience.txt` |
|
||||
| Перезапуск с сохранением | тот же сценарий, mode `persistence` | PASS: после остановки и запуска stateful-сервисов, worker, двух API и LB сохранились сессия, сообщение и байты вложения | `evidence/verify-https-resilience.txt` |
|
||||
| Отказ одной API-реплики | тот же сценарий, mode `failover` | PASS: до отказа наблюдались 2 реплики; после остановки выбранной реплики — 7 успешных записей без неуспешных попыток, восстановление за 5.042 с (предыдущий прогон — 4.763 с); подтверждённые данные не потеряны | `evidence/verify-https-resilience.txt` |
|
||||
|
||||
+63
-3
@@ -3,7 +3,7 @@ name: hla-lab7
|
||||
x-api-environment: &api-environment
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-gateway:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
OTEL_TRACES_EXPORTER: otlp
|
||||
OTEL_METRICS_EXPORTER: otlp
|
||||
@@ -244,6 +244,42 @@ services:
|
||||
mem_limit: 1024m
|
||||
networks: [backend]
|
||||
|
||||
rabbit-api-gateway:
|
||||
<<: *runtime-hardening
|
||||
image: nginx:1.27.4-bookworm
|
||||
volumes:
|
||||
- ./infra/rabbitmq/api-gateway.conf:/etc/nginx/nginx.conf:ro
|
||||
- ./secrets/pki:/run/pki:ro
|
||||
depends_on:
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
user: "101:101"
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
tmpfs: ["/var/cache/nginx:size=16m,mode=1777", "/tmp:size=8m,mode=1777"]
|
||||
restart: unless-stopped
|
||||
cpus: 0.15
|
||||
mem_limit: 64m
|
||||
networks: [backend]
|
||||
|
||||
rabbit-worker-gateway:
|
||||
<<: *runtime-hardening
|
||||
image: nginx:1.27.4-bookworm
|
||||
volumes:
|
||||
- ./infra/rabbitmq/worker-gateway.conf:/etc/nginx/nginx.conf:ro
|
||||
- ./secrets/pki:/run/pki:ro
|
||||
depends_on:
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
user: "101:101"
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
tmpfs: ["/var/cache/nginx:size=16m,mode=1777", "/tmp:size=8m,mode=1777"]
|
||||
restart: unless-stopped
|
||||
cpus: 0.15
|
||||
mem_limit: 64m
|
||||
networks: [backend]
|
||||
|
||||
rabbitmq-init:
|
||||
<<: *runtime-hardening
|
||||
image: curlimages/curl:8.12.1
|
||||
@@ -481,6 +517,7 @@ services:
|
||||
CLIENT_TLS_PRIVATE_KEY: /run/pki/api-client/tls.key
|
||||
REDIS_USER: messenger-api
|
||||
RABBITMQ_USER: messenger-api
|
||||
RABBITMQ_HOST: rabbit-api-gateway
|
||||
OPENBAO_RENDERED_ENV: /run/openbao/runtime.env
|
||||
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/pki/service-ca/ca.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/pki/api-client/tls.crt
|
||||
@@ -495,7 +532,9 @@ services:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq-init:
|
||||
condition: service_completed_successfully
|
||||
otel-collector:
|
||||
rabbit-api-gateway:
|
||||
condition: service_started
|
||||
otel-gateway:
|
||||
condition: service_started
|
||||
openbao-agent-api:
|
||||
condition: service_started
|
||||
@@ -529,6 +568,7 @@ services:
|
||||
CLIENT_TLS_PRIVATE_KEY: /run/pki/worker-client/tls.key
|
||||
REDIS_USER: messenger-worker
|
||||
RABBITMQ_USER: messenger-worker
|
||||
RABBITMQ_HOST: rabbit-worker-gateway
|
||||
OPENBAO_RENDERED_ENV: /run/openbao/runtime.env
|
||||
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/pki/service-ca/ca.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/pki/worker-client/tls.crt
|
||||
@@ -543,7 +583,9 @@ services:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq-init:
|
||||
condition: service_completed_successfully
|
||||
otel-collector:
|
||||
rabbit-worker-gateway:
|
||||
condition: service_started
|
||||
otel-gateway:
|
||||
condition: service_started
|
||||
openbao-agent-worker:
|
||||
condition: service_started
|
||||
@@ -617,6 +659,24 @@ services:
|
||||
mem_limit: 512m
|
||||
networks: [backend]
|
||||
|
||||
otel-gateway:
|
||||
<<: *runtime-hardening
|
||||
image: nginx:1.27.4-bookworm
|
||||
volumes:
|
||||
- ./infra/otel/gateway.conf:/etc/nginx/nginx.conf:ro
|
||||
- ./secrets/pki:/run/pki:ro
|
||||
depends_on:
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
user: "101:101"
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
tmpfs: ["/var/cache/nginx:size=16m,mode=1777", "/tmp:size=8m,mode=1777"]
|
||||
restart: unless-stopped
|
||||
cpus: 0.15
|
||||
mem_limit: 64m
|
||||
networks: [backend]
|
||||
|
||||
prometheus:
|
||||
<<: *runtime-hardening
|
||||
image: prom/prometheus:v3.14.0
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
Матрица фиксирует целевую архитектуру и текущее покрытие. **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.
|
||||
Имена identities ниже являются контрактом для PKI/OpenBao bootstrap. Формат SAN — URI `spiffe://hla-lab7/<role>`; проверяются chain и EKU. LB проверяет точный URI SAN; service gateways привязывают точный subject CN отдельного leaf к разрешённой роли, при этом leaf также содержит role URI SAN. Private keys, root token, unseal shares и SecretID не хранятся в Git.
|
||||
|
||||
Все перечисленные продукты (PostgreSQL, MinIO, RabbitMQ, Redis, OpenTelemetry Collector, Prometheus, Loki, Tempo, Grafana и OpenBao) поддерживают native TLS, поэтому TLS proxy/sidecar в текущем стенде не используется. Если позже добавится компонент без native TLS, допускается только проверяющий сервер proxy/sidecar на отдельной identity и закрытый локальный hop; такой канал должен появиться в этой матрице с отрицательным тестом.
|
||||
Все перечисленные продукты поддерживают native TLS. RabbitMQ и OpenTelemetry Collector, однако, проверяют CA клиента без точного allowlist роли leaf; перед ними используются непубликуемые проверяющие TLS gateways. Gateway→backend также mTLS/verify-full, а backend CA принимает только gateway client leaves. Для другого компонента без native TLS или role binding допускается эквивалентный sidecar на отдельной identity и закрытый TLS/local hop с отрицательным тестом.
|
||||
|
||||
## Основные связи
|
||||
|
||||
@@ -16,11 +16,11 @@
|
||||
| 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-full; service CA + SAN `DNS:minio` | `messenger-api`, policy `messenger-attachments-api`: list разрешённых prefixes, read/delete final objects, write/delete только staging; без admin | Credential рендерит API AppRole; отдельно от root/worker | Anonymous/admin/final-object write denied; staging write succeeds | **PASS** |
|
||||
| Worker → MinIO | `https://minio:9000` | TLS verify-full; service CA + SAN `DNS:minio` | Отдельный `messenger-worker`, policy `messenger-attachments-worker`: read/delete staging, read/write final objects; без list/admin/final delete | Credential рендерит worker AppRole | Bucket list, admin и final-object delete denied; processing actions succeed | **PASS** |
|
||||
| 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 → RabbitMQ | `rabbit-api-gateway:5671` → TLS → `rabbitmq:5671` | mTLS на обоих hops; gateway verify-full и exact CN `api-client`; backend доверяет только service-CA gateway client leaf | `messenger-api`, cert URI SAN `.../api`, отдельный gateway leaf и regex permissions | Отдельный secret/cert; reconnect on rotation | No cert/foreign CA/same-CA `migration`/worker identity denied; direct backend API cert gets unknown CA; broker ACL ограничивает операции | **PASS на 4** |
|
||||
| Worker → RabbitMQ | `rabbit-worker-gateway:5671` → TLS → `rabbitmq:5671` | mTLS на обоих hops; exact CN `worker-client` | Отдельные `messenger-worker` cert/user/permissions и gateway leaf | Отдельный secret/cert | API cert того же CA получает 0 AMQP bytes; no-cert и direct bypass denied; forbidden ACL operations rejected | **PASS на 4** |
|
||||
| API/worker → Redis | mTLS `redis:6379` | service CA + workload client CA; plaintext port disabled | API: только `messenger:*`, connection/get/set/del/incr/expire/ttl/eval; worker: connection/ping без keys; разные cert/password | Отдельные secrets/certs | No cert/foreign CA; outside-prefix, worker GET, CONFIG/ACL/FLUSH 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)** |
|
||||
| API → Collector | `https://otel-gateway:4318` → TLS → `otel-collector:4318` | mTLS на обоих hops; gateway verify-full и exact CN allowlist; Collector доверяет только service-CA gateway client leaf | URI SAN `.../api`; distinct API leaf and `service.name` | Leaf 30 d | No cert rejected; same-CA migration CN → 403; direct Collector API cert → unknown CA; valid OTLP → 200 | **PASS на 4** |
|
||||
| Worker → Collector | тот же gateway | mTLS; exact CN `worker-client` разрешён отдельно | URI SAN `.../worker`; distinct leaf/service.name | Отдельный leaf/revoke | Same-CA foreign role rejected; worker OTLP → 200; direct bypass denied | **PASS на 4** |
|
||||
| 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** |
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# Certificate and secret lifecycle verification
|
||||
|
||||
Date: 2026-11-26
|
||||
Date: 2026-11-27
|
||||
Stand: local Docker Desktop, compose project hla-lab7
|
||||
Command:
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\check-security-lifecycle.ps1
|
||||
|
||||
Observed output:
|
||||
PASS: 20 certificate/key bundles are valid; private/operator secrets are untracked; present SecretIDs are within TTL.
|
||||
PASS: 26 certificate/key bundles are valid; private/operator secrets are untracked; present SecretIDs are within TTL.
|
||||
|
||||
Scope: certificate validity window, SAN presence, leaf validity limit, private-key/certificate pairing, Git tracking of private material, ignore rules for `.env` and TLS keys, absence of root/unseal artifacts, and AppRole SecretID age.
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
Service mTLS identity verification
|
||||
Date: 2026-11-27 (Europe/Moscow)
|
||||
|
||||
Commands:
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/test-service-mtls-identities.ps1
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/test-internal-tls.ps1
|
||||
python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
|
||||
|
||||
Observed:
|
||||
PASS: API/worker use distinct broker identities; trusted-CA wrong roles receive
|
||||
no AMQP access or OTel ingest; direct backend bypass is rejected.
|
||||
PASS: DB, S3, broker, Redis, Collector, telemetry backends and OpenBao verify
|
||||
server CA/hostname; all declared mTLS endpoints reject no-cert clients.
|
||||
PASS: PostgreSQL, Redis and RabbitMQ runtime identities are separate and
|
||||
forbidden operations are denied.
|
||||
PASS: lab7 public API scenario.
|
||||
|
||||
Negative identity probes:
|
||||
- migration-client is signed by the same workload CA as API/worker but receives
|
||||
no AMQP protocol response through the API gateway;
|
||||
- API client certificate receives no AMQP protocol response through the worker gateway;
|
||||
- migration-client receives HTTP 403 from the OTel gateway;
|
||||
- missing client certificate is rejected by both gateway types;
|
||||
- workload certificates cannot connect directly to RabbitMQ or OTel Collector;
|
||||
those backend listeners trust only service-CA gateway client leaves.
|
||||
|
||||
No certificate private key, password, token or telemetry payload is stored here.
|
||||
@@ -12,7 +12,7 @@ receivers:
|
||||
tls:
|
||||
cert_file: /run/pki/otel-collector/tls.crt
|
||||
key_file: /run/pki/otel-collector/tls.key
|
||||
client_ca_file: /run/pki/workload-client-ca/ca.crt
|
||||
client_ca_file: /run/pki/service-ca/ca.crt
|
||||
min_version: "1.2"
|
||||
|
||||
processors:
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
worker_processes 1;
|
||||
error_log /dev/stderr notice;
|
||||
pid /tmp/nginx.pid;
|
||||
|
||||
events { worker_connections 128; }
|
||||
|
||||
http {
|
||||
access_log off;
|
||||
map $ssl_client_s_dn $otel_identity_allowed {
|
||||
default 0;
|
||||
~(^|,)CN=api-client(,|$) 1;
|
||||
~(^|,)CN=worker-client(,|$) 1;
|
||||
}
|
||||
server {
|
||||
listen 4318 ssl;
|
||||
ssl_certificate /run/pki/otel-gateway/tls.crt;
|
||||
ssl_certificate_key /run/pki/otel-gateway/tls.key;
|
||||
ssl_client_certificate /run/pki/workload-client-ca/ca.crt;
|
||||
ssl_verify_client on;
|
||||
ssl_verify_depth 2;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
if ($otel_identity_allowed = 0) { return 403; }
|
||||
client_max_body_size 4m;
|
||||
location / {
|
||||
proxy_pass https://otel-collector:4318;
|
||||
proxy_http_version 1.1;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name otel-collector;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_trusted_certificate /run/pki/service-ca/ca.crt;
|
||||
proxy_ssl_certificate /run/pki/otel-gateway-client/tls.crt;
|
||||
proxy_ssl_certificate_key /run/pki/otel-gateway-client/tls.key;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
worker_processes 1;
|
||||
error_log /dev/stderr notice;
|
||||
pid /tmp/nginx.pid;
|
||||
|
||||
events { worker_connections 128; }
|
||||
|
||||
stream {
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
map $ssl_client_s_dn $broker_upstream {
|
||||
default 127.0.0.1:1;
|
||||
~(^|,)CN=api-client(,|$) rabbitmq:5671;
|
||||
}
|
||||
server {
|
||||
listen 5671 ssl;
|
||||
ssl_certificate /run/pki/rabbit-api-gateway/tls.crt;
|
||||
ssl_certificate_key /run/pki/rabbit-api-gateway/tls.key;
|
||||
ssl_client_certificate /run/pki/workload-client-ca/ca.crt;
|
||||
ssl_verify_client on;
|
||||
ssl_verify_depth 2;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
proxy_pass $broker_upstream;
|
||||
proxy_connect_timeout 3s;
|
||||
proxy_timeout 30s;
|
||||
proxy_ssl on;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name rabbitmq;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_trusted_certificate /run/pki/service-ca/ca.crt;
|
||||
proxy_ssl_certificate /run/pki/rabbit-api-gateway-client/tls.crt;
|
||||
proxy_ssl_certificate_key /run/pki/rabbit-api-gateway-client/tls.key;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
listeners.tcp = none
|
||||
listeners.ssl.default = 5671
|
||||
ssl_options.cacertfile = /run/pki/workload-client-ca/ca.crt
|
||||
ssl_options.cacertfile = /run/pki/service-ca/ca.crt
|
||||
ssl_options.certfile = /run/pki/rabbitmq/tls.crt
|
||||
ssl_options.keyfile = /run/pki/rabbitmq/tls.key
|
||||
ssl_options.verify = verify_peer
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
worker_processes 1;
|
||||
error_log /dev/stderr notice;
|
||||
pid /tmp/nginx.pid;
|
||||
|
||||
events { worker_connections 128; }
|
||||
|
||||
stream {
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
map $ssl_client_s_dn $broker_upstream {
|
||||
default 127.0.0.1:1;
|
||||
~(^|,)CN=worker-client(,|$) rabbitmq:5671;
|
||||
}
|
||||
server {
|
||||
listen 5671 ssl;
|
||||
ssl_certificate /run/pki/rabbit-worker-gateway/tls.crt;
|
||||
ssl_certificate_key /run/pki/rabbit-worker-gateway/tls.key;
|
||||
ssl_client_certificate /run/pki/workload-client-ca/ca.crt;
|
||||
ssl_verify_client on;
|
||||
ssl_verify_depth 2;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
proxy_pass $broker_upstream;
|
||||
proxy_connect_timeout 3s;
|
||||
proxy_timeout 30s;
|
||||
proxy_ssl on;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name rabbitmq;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_trusted_certificate /run/pki/service-ca/ca.crt;
|
||||
proxy_ssl_certificate /run/pki/rabbit-worker-gateway-client/tls.crt;
|
||||
proxy_ssl_certificate_key /run/pki/rabbit-worker-gateway-client/tls.key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
[CmdletBinding()]
|
||||
param([string]$PkiDirectory, [int]$LeafValidityDays = 30, [switch]$Force)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if([string]::IsNullOrWhiteSpace($PkiDirectory)){
|
||||
$PkiDirectory = Join-Path $PSScriptRoot '..\secrets\pki'
|
||||
}
|
||||
$pki = (Resolve-Path -LiteralPath $PkiDirectory).Path
|
||||
$caCertificate = Join-Path $pki 'service-ca\ca.crt'
|
||||
$caKey = Join-Path $pki 'service-ca\ca.key'
|
||||
if(-not (Test-Path -LiteralPath $caCertificate) -or -not (Test-Path -LiteralPath $caKey)){
|
||||
throw 'Existing local service CA certificate/private key is required'
|
||||
}
|
||||
|
||||
$opensslCommand = Get-Command openssl -ErrorAction SilentlyContinue
|
||||
$openssl = if($opensslCommand){ $opensslCommand.Source } else { $null }
|
||||
if(-not $openssl){
|
||||
$git = Get-Command git -ErrorAction SilentlyContinue
|
||||
if($git){
|
||||
$gitRoot = Split-Path (Split-Path $git.Source -Parent) -Parent
|
||||
$candidate = Join-Path $gitRoot 'usr\bin\openssl.exe'
|
||||
if(Test-Path -LiteralPath $candidate){ $openssl = $candidate }
|
||||
}
|
||||
}
|
||||
if(-not $openssl){ throw 'OpenSSL is required to extend the existing local PKI' }
|
||||
|
||||
function Invoke-OpenSsl([string[]]$Arguments) {
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
& $openssl @Arguments 2>$null
|
||||
$exitCode = $LASTEXITCODE
|
||||
} finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
if($exitCode -ne 0){ throw "OpenSSL command failed: $($Arguments[0])" }
|
||||
}
|
||||
|
||||
function New-SerialHex {
|
||||
$bytes = [byte[]]::new(16)
|
||||
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
try { $rng.GetBytes($bytes) } finally { $rng.Dispose() }
|
||||
$bytes[0] = $bytes[0] -band 0x7f
|
||||
return '0x' + (($bytes | ForEach-Object { $_.ToString('x2') }) -join '')
|
||||
}
|
||||
|
||||
function New-GatewayLeaf([string]$Name, [bool]$ServerAuth, [string]$DnsName, [string]$Uri) {
|
||||
$directory = Join-Path $pki $Name
|
||||
if((Test-Path -LiteralPath $directory) -and -not $Force){
|
||||
throw "$directory already exists; use -Force only for intentional gateway certificate rotation"
|
||||
}
|
||||
New-Item -ItemType Directory -Path $directory -Force | Out-Null
|
||||
$key = Join-Path $directory 'tls.key'
|
||||
$csr = Join-Path $directory 'request.csr'
|
||||
$certificate = Join-Path $directory 'tls.crt'
|
||||
$caCopy = Join-Path $directory 'ca.crt'
|
||||
$extensions = Join-Path $directory 'extensions.cnf'
|
||||
$eku = if($ServerAuth){ 'serverAuth' } else { 'clientAuth' }
|
||||
$sans = @()
|
||||
if($DnsName){ $sans += "DNS:$DnsName" }
|
||||
if($Uri){ $sans += "URI:$Uri" }
|
||||
$extensionText = @(
|
||||
'basicConstraints=critical,CA:FALSE',
|
||||
'keyUsage=critical,digitalSignature,keyEncipherment',
|
||||
"extendedKeyUsage=$eku",
|
||||
"subjectAltName=$($sans -join ',')",
|
||||
'authorityKeyIdentifier=keyid,issuer'
|
||||
) -join "`n"
|
||||
[System.IO.File]::WriteAllText($extensions, $extensionText + "`n", [System.Text.Encoding]::ASCII)
|
||||
try {
|
||||
Invoke-OpenSsl @('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:3072','-out',$key)
|
||||
Invoke-OpenSsl @('req','-new','-key',$key,'-subj',"/CN=$Name",'-out',$csr)
|
||||
Invoke-OpenSsl @('x509','-req','-in',$csr,'-CA',$caCertificate,'-CAkey',$caKey,
|
||||
'-set_serial',(New-SerialHex),'-days',"$LeafValidityDays",'-sha256','-extfile',$extensions,'-out',$certificate)
|
||||
Copy-Item -LiteralPath $caCertificate -Destination $caCopy -Force
|
||||
} finally {
|
||||
Remove-Item -LiteralPath $csr,$extensions -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
New-GatewayLeaf 'rabbit-api-gateway' $true 'rabbit-api-gateway' 'spiffe://hla-lab7/rabbit-api-gateway'
|
||||
New-GatewayLeaf 'rabbit-worker-gateway' $true 'rabbit-worker-gateway' 'spiffe://hla-lab7/rabbit-worker-gateway'
|
||||
New-GatewayLeaf 'otel-gateway' $true 'otel-gateway' 'spiffe://hla-lab7/otel-gateway'
|
||||
New-GatewayLeaf 'rabbit-api-gateway-client' $false '' 'spiffe://hla-lab7/rabbit-api-gateway'
|
||||
New-GatewayLeaf 'rabbit-worker-gateway-client' $false '' 'spiffe://hla-lab7/rabbit-worker-gateway'
|
||||
New-GatewayLeaf 'otel-gateway-client' $false '' 'spiffe://hla-lab7/otel-gateway'
|
||||
|
||||
Write-Host "Created six local gateway certificates under $pki; private keys were not printed."
|
||||
@@ -98,6 +98,9 @@ New-Leaf 'ingress' 'public-ca' $true @('localhost') @('127.0.0.1') @()
|
||||
foreach($name in 'api','postgres','redis','rabbitmq','minio','otel-collector','prometheus','loki','tempo'){
|
||||
New-Leaf $name 'service-ca' $true @($name) @() @("spiffe://hla-lab7/$name")
|
||||
}
|
||||
foreach($name in 'rabbit-api-gateway','rabbit-worker-gateway','otel-gateway'){
|
||||
New-Leaf $name 'service-ca' $true @($name) @() @("spiffe://hla-lab7/$name")
|
||||
}
|
||||
New-Leaf 'openbao' 'service-ca' $true @('openbao','localhost') @('127.0.0.1') @('spiffe://hla-lab7/openbao')
|
||||
New-Leaf 'grafana' 'service-ca' $true @('grafana','localhost') @('127.0.0.1') @('spiffe://hla-lab7/grafana')
|
||||
New-Leaf 'lb' 'lb-client-ca' $false @() @() @('spiffe://hla-lab7/lb')
|
||||
@@ -108,6 +111,9 @@ New-Leaf 'migration-client' 'workload-client-ca' $false @() @() @('spiffe://hla-
|
||||
New-Leaf 'collector-client' 'telemetry-client-ca' $false @() @() @('spiffe://hla-lab7/otel-collector')
|
||||
New-Leaf 'prometheus-client' 'telemetry-client-ca' $false @() @() @('spiffe://hla-lab7/prometheus')
|
||||
New-Leaf 'grafana-client' 'telemetry-client-ca' $false @() @() @('spiffe://hla-lab7/grafana')
|
||||
New-Leaf 'rabbit-api-gateway-client' 'service-ca' $false @() @() @('spiffe://hla-lab7/rabbit-api-gateway')
|
||||
New-Leaf 'rabbit-worker-gateway-client' 'service-ca' $false @() @() @('spiffe://hla-lab7/rabbit-worker-gateway')
|
||||
New-Leaf 'otel-gateway-client' 'service-ca' $false @() @() @('spiffe://hla-lab7/otel-gateway')
|
||||
|
||||
Write-Host "Created private PKI in $OutputDirectory"
|
||||
Write-Host "Public test CA: $(Join-Path $OutputDirectory 'public-ca\ca.crt')"
|
||||
|
||||
@@ -57,15 +57,15 @@ probe_ok redis redis:6379 redis \
|
||||
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
|
||||
probe_rejected redis redis:6379 redis
|
||||
|
||||
probe_ok rabbitmq rabbitmq:5671 rabbitmq \
|
||||
probe_ok rabbitmq-api rabbit-api-gateway:5671 rabbit-api-gateway \
|
||||
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
|
||||
probe_rejected rabbitmq rabbitmq:5671 rabbitmq
|
||||
probe_ok rabbitmq-worker rabbit-worker-gateway:5671 rabbit-worker-gateway \
|
||||
-cert /run/pki/worker-client/tls.crt -key /run/pki/worker-client/tls.key
|
||||
|
||||
probe_ok otel-ingest-api otel-collector:4318 otel-collector \
|
||||
probe_ok otel-ingest-api otel-gateway:4318 otel-gateway \
|
||||
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
|
||||
probe_ok otel-ingest-worker otel-collector:4318 otel-collector \
|
||||
probe_ok otel-ingest-worker otel-gateway:4318 otel-gateway \
|
||||
-cert /run/pki/worker-client/tls.crt -key /run/pki/worker-client/tls.key
|
||||
probe_rejected otel-ingest otel-collector:4318 otel-collector
|
||||
|
||||
probe_ok otel-metrics otel-collector:8889 otel-collector \
|
||||
-cert /run/pki/prometheus-client/tls.crt -key /run/pki/prometheus-client/tls.key
|
||||
@@ -127,4 +127,7 @@ if($permissions -match 'messenger-(api|worker)\s+\.\*\s+\.\*\s+\.\*'){
|
||||
throw 'RabbitMQ ACL failure: an application identity has unrestricted permissions'
|
||||
}
|
||||
|
||||
& (Join-Path $PSScriptRoot 'test-service-mtls-identities.ps1') -EnvFile $EnvFile
|
||||
if(-not $?){ throw 'Service mTLS identity verification failed' }
|
||||
|
||||
Write-Host 'PASS: PostgreSQL, Redis and RabbitMQ runtime identities are separate and forbidden operations are denied.'
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
[CmdletBinding()]
|
||||
param([string]$EnvFile = '.env')
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Join-Path $PSScriptRoot '..')
|
||||
|
||||
$configText = & docker compose --env-file $EnvFile config --format json
|
||||
if($LASTEXITCODE -ne 0){ throw 'docker compose config failed' }
|
||||
$config = ($configText -join "`n") | ConvertFrom-Json
|
||||
if($config.services.api.environment.RABBITMQ_HOST -ne 'rabbit-api-gateway'){
|
||||
throw 'API does not use its dedicated RabbitMQ identity gateway'
|
||||
}
|
||||
if($config.services.worker.environment.RABBITMQ_HOST -ne 'rabbit-worker-gateway'){
|
||||
throw 'Worker does not use its dedicated RabbitMQ identity gateway'
|
||||
}
|
||||
foreach($serviceName in 'api','worker'){
|
||||
if($config.services.$serviceName.environment.OTEL_EXPORTER_OTLP_ENDPOINT -ne 'https://otel-gateway:4318'){
|
||||
throw "$serviceName bypasses the OTel identity gateway"
|
||||
}
|
||||
}
|
||||
|
||||
$probe = @'
|
||||
set -eu
|
||||
|
||||
amqp_bytes() {
|
||||
target=$1; cert=$2
|
||||
set +e
|
||||
printf 'AMQP\000\000\011\001' | timeout 4 openssl s_client -quiet \
|
||||
-verify_return_error -verify_hostname "$target" -connect "$target:5671" \
|
||||
-servername "$target" -CAfile /run/pki/service-ca/ca.crt \
|
||||
-cert "/run/pki/$cert/tls.crt" -key "/run/pki/$cert/tls.key" \
|
||||
>/tmp/amqp.out 2>/tmp/amqp.err
|
||||
set -e
|
||||
wc -c </tmp/amqp.out
|
||||
}
|
||||
|
||||
api_valid=$(amqp_bytes rabbit-api-gateway api-client)
|
||||
worker_valid=$(amqp_bytes rabbit-worker-gateway worker-client)
|
||||
api_wrong_role=$(amqp_bytes rabbit-api-gateway migration-client)
|
||||
worker_wrong_role=$(amqp_bytes rabbit-worker-gateway api-client)
|
||||
[ "$api_valid" -gt 0 ]
|
||||
[ "$worker_valid" -gt 0 ]
|
||||
[ "$api_wrong_role" -eq 0 ]
|
||||
[ "$worker_wrong_role" -eq 0 ]
|
||||
set +e
|
||||
printf 'AMQP\000\000\011\001' | timeout 4 openssl s_client -quiet \
|
||||
-verify_return_error -verify_hostname rabbit-api-gateway \
|
||||
-connect rabbit-api-gateway:5671 -servername rabbit-api-gateway \
|
||||
-CAfile /run/pki/service-ca/ca.crt >/tmp/amqp-no-cert.out 2>/tmp/amqp-no-cert.err
|
||||
set -e
|
||||
[ "$(wc -c </tmp/amqp-no-cert.out)" -eq 0 ]
|
||||
|
||||
otel_status() {
|
||||
cert=$1
|
||||
set +e
|
||||
printf 'POST /v1/traces HTTP/1.1\r\nHost: otel-gateway\r\nContent-Type: application/x-protobuf\r\nContent-Length: 0\r\nConnection: close\r\n\r\n' | \
|
||||
timeout 5 openssl s_client -quiet -verify_return_error \
|
||||
-verify_hostname otel-gateway -connect otel-gateway:4318 -servername otel-gateway \
|
||||
-CAfile /run/pki/service-ca/ca.crt -cert "/run/pki/$cert/tls.crt" \
|
||||
-key "/run/pki/$cert/tls.key" >/tmp/otel.out 2>/tmp/otel.err
|
||||
set -e
|
||||
sed -n '1p' /tmp/otel.out | tr -d '\r'
|
||||
}
|
||||
|
||||
api_otel=$(otel_status api-client)
|
||||
worker_otel=$(otel_status worker-client)
|
||||
wrong_otel=$(otel_status migration-client)
|
||||
echo "$api_otel" | grep -Eq '^HTTP/1\.1 200 '
|
||||
echo "$worker_otel" | grep -Eq '^HTTP/1\.1 200 '
|
||||
echo "$wrong_otel" | grep -Eq '^HTTP/1\.1 403 '
|
||||
set +e
|
||||
printf 'POST /v1/traces HTTP/1.1\r\nHost: otel-gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n' | \
|
||||
timeout 4 openssl s_client -quiet -verify_return_error -verify_hostname otel-gateway \
|
||||
-connect otel-gateway:4318 -servername otel-gateway \
|
||||
-CAfile /run/pki/service-ca/ca.crt >/tmp/otel-no-cert.out 2>/tmp/otel-no-cert.err
|
||||
set -e
|
||||
grep -Eq '^HTTP/1\.1 400 ' /tmp/otel-no-cert.out
|
||||
grep -q 'No required SSL certificate was sent' /tmp/otel-no-cert.out
|
||||
|
||||
set +e
|
||||
openssl s_client -brief -tls1_2 -verify_return_error -verify_hostname rabbitmq \
|
||||
-connect rabbitmq:5671 -servername rabbitmq -CAfile /run/pki/service-ca/ca.crt \
|
||||
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key \
|
||||
</dev/null >/tmp/direct-rabbit 2>&1
|
||||
direct_rabbit=$?
|
||||
openssl s_client -brief -tls1_2 -verify_return_error -verify_hostname otel-collector \
|
||||
-connect otel-collector:4318 -servername otel-collector -CAfile /run/pki/service-ca/ca.crt \
|
||||
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key \
|
||||
</dev/null >/tmp/direct-otel 2>&1
|
||||
direct_otel=$?
|
||||
set -e
|
||||
[ "$direct_rabbit" -ne 0 ] && grep -Eq 'unknown ca|certificate unknown|bad certificate' /tmp/direct-rabbit
|
||||
[ "$direct_otel" -ne 0 ] && grep -Eq 'unknown ca|certificate unknown|bad certificate' /tmp/direct-otel
|
||||
|
||||
echo 'PASS: API/worker use distinct broker identities; trusted-CA wrong roles receive no AMQP access or OTel ingest; direct backend bypass is rejected.'
|
||||
'@
|
||||
|
||||
$normalizedProbe = $probe.Replace("`r", '')
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
$output = @($normalizedProbe | & docker compose --env-file $EnvFile run --rm -T --no-deps --entrypoint /bin/sh nginx -s 2>&1) -join "`n"
|
||||
$exitCode = $LASTEXITCODE
|
||||
} finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
if($exitCode -ne 0){ throw 'Service mTLS identity verification failed' }
|
||||
Write-Host $output
|
||||
Reference in New Issue
Block a user