Защита внутренних соединений и сервисных прав

This commit is contained in:
EgorAnti
2026-11-27 09:22:26 +03:00
parent 3c412926e5
commit a7463797e6
15 changed files with 453 additions and 54 deletions
+9
View File
@@ -150,6 +150,15 @@ read-only. Stateful entrypoints сохраняют только минималь
он укладывается в локальный latency budget и RAM-limit API. Benchmark не печатает
пароль или PHC-строки и отдельно проверяет уникальность salt во всех 21 образцах.
Внутренние TLS-связи и минимальные runtime-права проверяются без вывода
credential values:
```powershell
.\scripts\test-internal-tls.ps1
docker compose --env-file .env --profile verification run --rm private-bucket-check
.\scripts\test-openbao-policies.ps1
```
Примеры запросов доступны в `examples/requests.http`, примеры JSON — в `contracts/examples.json`. Для полной проверки схемы (по желанию локально; CI делает её автоматически):
+6 -4
View File
@@ -19,11 +19,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` |
| OpenBao AppRole и policies | `scripts/test-openbao-policies.ps1` | PASS: API и worker читают только свой KV path; чужой path и запись policy отклонены | `evidence/openbao-policies.txt`, `contracts/trust-matrix.md` |
| Compose hardening | `scripts/check-compose-hardening.ps1` | PASS: только три loopback HTTPS-порта; limits/capability/read-only policy проверены | `compose.yaml`, самопроверка скрипта |
| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 20 cert/key bundles валидны; expiry, SAN, пары ключей, Git ignore и возраст SecretID проверены | вывод команды без secret values |
| Публичный smoke | `scripts/verify-https-resilience.ps1` | PASS: полный API-сценарий, включая ACL и вложения, выполнен через HTTPS с проверкой CA и hostname | вывод команды |
| Перезапуск с сохранением | тот же сценарий, mode `persistence` | PASS: после остановки и запуска stateful-сервисов, worker, двух API и LB сохранились сессия, сообщение и байты вложения | вывод команды |
| Отказ одной API-реплики | тот же сценарий, mode `failover` | PASS: до отказа наблюдались 2 реплики; после остановки выбранной реплики — 7 успешных записей без неуспешных попыток, восстановление за 4.763 с; подтверждённые данные не потеряны | вывод команды |
| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 20 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` |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
+38 -7
View File
@@ -204,7 +204,7 @@ services:
- |
set -eu
umask 077
printf 'user default off\nuser messenger-api on >%s ~* +@all -@admin -flushall -flushdb\nuser messenger-worker on >%s ~* +@all -@admin -flushall -flushdb\n' "$$REDIS_API_PASSWORD" "$$REDIS_WORKER_PASSWORD" >/tmp/users.acl
printf 'user default off\nuser messenger-api on >%s ~messenger:* +@connection +get +set +del +incr +expire +ttl +eval +evalsha\nuser messenger-worker on >%s resetkeys +@connection +ping\n' "$$REDIS_API_PASSWORD" "$$REDIS_WORKER_PASSWORD" >/tmp/users.acl
exec redis-server --port 0 --tls-port 6379 --tls-cert-file /run/pki/redis/tls.crt --tls-key-file /run/pki/redis/tls.key --tls-ca-cert-file /run/pki/workload-client-ca/ca.crt --tls-auth-clients yes --aclfile /tmp/users.acl --appendonly no --save 60 1 --rdbcompression yes
volumes:
- redis-data:/data
@@ -318,6 +318,7 @@ services:
S3_WORKER_SECRET_ACCESS_KEY: ${S3_WORKER_SECRET_ACCESS_KEY:?Set S3_WORKER_SECRET_ACCESS_KEY in .env}
volumes:
- ./infra/minio-api-policy.json:/policy/minio-api-policy.json:ro
- ./infra/minio-worker-policy.json:/policy/minio-worker-policy.json:ro
- ./secrets/pki/service-ca/ca.crt:/run/ca.crt:ro
entrypoint: ["/bin/sh", "-c"]
command:
@@ -326,6 +327,7 @@ services:
mkdir -p "$$MC_CONFIG_DIR/certs/CAs"
cp /run/ca.crt "$$MC_CONFIG_DIR/certs/CAs/service-ca.crt"
sed "s/__S3_BUCKET__/$$S3_BUCKET/g" /policy/minio-api-policy.json > /tmp/minio-api-policy.json
sed "s/__S3_BUCKET__/$$S3_BUCKET/g" /policy/minio-worker-policy.json > /tmp/minio-worker-policy.json
attempt=0
until mc alias set -- local https://minio:9000 "$$MINIO_ROOT_USER" "$$MINIO_ROOT_PASSWORD" \
&& mc mb --ignore-existing "local/$$S3_BUCKET" \
@@ -334,10 +336,14 @@ services:
|| mc admin user info local "$$S3_ACCESS_KEY_ID") \
&& (mc admin user add -- local "$$S3_WORKER_ACCESS_KEY_ID" "$$S3_WORKER_SECRET_ACCESS_KEY" \
|| mc admin user info local "$$S3_WORKER_ACCESS_KEY_ID") \
&& (mc admin policy create local messenger-attachments-rw /tmp/minio-api-policy.json \
|| mc admin policy info local messenger-attachments-rw) \
&& mc admin policy attach local messenger-attachments-rw --user "$$S3_ACCESS_KEY_ID" \
&& mc admin policy attach local messenger-attachments-rw --user "$$S3_WORKER_ACCESS_KEY_ID"
&& (mc admin policy create local messenger-attachments-api /tmp/minio-api-policy.json \
|| mc admin policy info local messenger-attachments-api) \
&& (mc admin policy create local messenger-attachments-worker /tmp/minio-worker-policy.json \
|| mc admin policy info local messenger-attachments-worker) \
&& mc admin policy attach local messenger-attachments-api --user "$$S3_ACCESS_KEY_ID" \
&& mc admin policy attach local messenger-attachments-worker --user "$$S3_WORKER_ACCESS_KEY_ID" \
&& (mc admin policy detach local messenger-attachments-rw --user "$$S3_ACCESS_KEY_ID" || true) \
&& (mc admin policy detach local messenger-attachments-rw --user "$$S3_WORKER_ACCESS_KEY_ID" || true)
do
attempt=$$((attempt + 1))
if [ "$$attempt" -ge 30 ]; then
@@ -366,6 +372,8 @@ services:
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env}
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env}
S3_WORKER_ACCESS_KEY_ID: ${S3_WORKER_ACCESS_KEY_ID:?Set S3_WORKER_ACCESS_KEY_ID in .env}
S3_WORKER_SECRET_ACCESS_KEY: ${S3_WORKER_SECRET_ACCESS_KEY:?Set S3_WORKER_SECRET_ACCESS_KEY in .env}
volumes:
- ./secrets/pki/service-ca/ca.crt:/run/ca.crt:ro
entrypoint: ["/bin/sh", "-c"]
@@ -380,12 +388,35 @@ services:
exit 1
fi
mc alias set -- restricted https://minio:9000 "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY"
mc ls "restricted/$$S3_BUCKET" >/dev/null
mc ls "restricted/$$S3_BUCKET/attachments/" >/dev/null
mc ls "restricted/$$S3_BUCKET/staging/" >/dev/null
if mc admin info restricted >/dev/null 2>&1; then
echo "FAIL: API credentials have administrative access" >&2
exit 1
fi
echo "PASS: bucket is private and API credentials are non-admin"
printf api-probe | mc pipe "restricted/$$S3_BUCKET/staging/policy-api-probe" >/dev/null
if printf forbidden | mc pipe "restricted/$$S3_BUCKET/attachments/policy-api-forbidden" >/dev/null 2>&1; then
echo "FAIL: API credentials can write final attachment objects" >&2
exit 1
fi
mc alias set -- worker https://minio:9000 "$$S3_WORKER_ACCESS_KEY_ID" "$$S3_WORKER_SECRET_ACCESS_KEY"
if mc ls "worker/$$S3_BUCKET" >/dev/null 2>&1; then
echo "FAIL: worker credentials can list the bucket" >&2
exit 1
fi
if mc admin info worker >/dev/null 2>&1; then
echo "FAIL: worker credentials have administrative access" >&2
exit 1
fi
mc cat "worker/$$S3_BUCKET/staging/policy-api-probe" >/dev/null
printf worker-probe | mc pipe "worker/$$S3_BUCKET/attachments/policy-worker-probe" >/dev/null
if mc rm "worker/$$S3_BUCKET/attachments/policy-worker-probe" >/dev/null 2>&1; then
echo "FAIL: worker credentials can delete final attachment objects" >&2
exit 1
fi
mc rm "restricted/$$S3_BUCKET/staging/policy-api-probe" >/dev/null
mc rm "restricted/$$S3_BUCKET/attachments/policy-worker-probe" >/dev/null
echo "PASS: bucket is private; API and worker use separate non-admin prefix/action policies"
restart: "no"
cap_drop: [ALL]
read_only: true
+10 -8
View File
@@ -4,6 +4,8 @@
Имена identities ниже являются контрактом для PKI/OpenBao bootstrap. Формат SAN — URI `spiffe://hla-lab7/<role>`; проверяются chain, EKU и точное разрешённое значение 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; такой канал должен появиться в этой матрице с отрицательным тестом.
## Основные связи
| Связь | Endpoint / порт | Протокол и server trust | Client identity и минимальные права | Lifecycle | Проверяемый отказ / доказательство | Статус |
@@ -12,19 +14,19 @@
| 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 до auth проверяет `TrustedClientCertificateFilter`; API port не публикуется | Leaf 30 d, local regeneration/restart | `scripts/test-mtls.ps1` обращается к каждой реплике отдельно: no cert и foreign CA отклоняются handshake; trusted cert SAN `.../worker` получает 403; LB cert → health 200; прямой published port отсутствует | **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 → 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/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/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)** |
| 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 стенд** |
| 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`: own path allowed; чужой path/policy write denied | **PASS (runtime test на initialized стенде)** |
| Worker Agent → OpenBao | `https://openbao:8200` | TLS verify | AppRole `messenger-worker`: read только собственного KV data/metadata | Независимые token, RoleID и SecretID с теми же TTL | Own path allowed; API path/policy write denied | **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** |
@@ -39,7 +41,7 @@
| 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 ещё не включён |
| Store healthchecks | PostgreSQL verify-full, Redis mTLS, MinIO HTTPS verify; broker локальный process ping | Не создают plaintext listener или anonymous admin access | **PASS** |
| 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 ещё ручная |
@@ -69,7 +71,7 @@
## Приоритет устранения GAP
1. Выделить отдельный безопасный API health listener, не содержащий business routes.
2. Разделить MinIO prefix policies API/worker и автоматизировать rotation runtime credentials.
2. Автоматизировать rotation runtime credentials MinIO с overlap/reconnect.
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`.
5. Расширить rotation tests; TLS/no-cert и runtime ACL для внутренних сервисов проверяет `scripts/test-internal-tls.ps1`.
+18
View File
@@ -0,0 +1,18 @@
# Internal TLS and service ACL verification
Date: 2026-11-26
Stand: local Docker Desktop, compose project hla-lab7
Commit: working tree (uncommitted changes on top of 3c41292)
Commands:
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-internal-tls.ps1
docker compose --env-file .env --profile verification run --rm private-bucket-check
Observed output:
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: bucket is private; API and worker use separate non-admin prefix/action policies
Scope: PostgreSQL, MinIO, OpenBao, Redis, RabbitMQ, OTel Collector, Loki, Tempo and Prometheus are verified against the service CA and hostname. Declared mTLS endpoints reject clients without a certificate. API/worker DB, Redis, RabbitMQ and MinIO identities are separate; forbidden DDL, cache keys, broker operations, admin calls and final-object writes are denied.
No secret values, tokens, private keys or credential material are included.
+14
View File
@@ -0,0 +1,14 @@
# OpenBao AppRole and policy verification
Date: 2026-11-26
Stand: local Docker Desktop, compose project hla-lab7, OpenBao initialized and unsealed
Command:
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-openbao-policies.ps1
Observed output:
OpenBao policy checks passed: own path allowed; foreign path and policy changes denied.
Scope: `messenger-api` and `messenger-worker` AppRoles authenticate with separate RoleID/SecretID, read only their own KV v2 path, cannot read the other role's KV path, and cannot write an OpenBao policy.
No root token, SecretID, token or secret value is included.
+13
View File
@@ -0,0 +1,13 @@
# Certificate and secret lifecycle verification
Date: 2026-11-26
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.
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.
No secret values, private keys, root token or unseal shares are included.
+23
View File
@@ -0,0 +1,23 @@
# HTTPS smoke, persistence restart and API replica failover
Date: 2026-11-26
Stand: local Docker Desktop, compose project hla-lab7
Command:
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\verify-https-resilience.ps1
Observed output:
PASS: ports, privileges, capabilities, filesystems and resource limits satisfy the local hardening contract.
PASS: 20 certificate/key bundles are valid; private/operator secrets are untracked; present SecretIDs are within TTL.
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
{"observed_instances_before": 2, "successful_writes": 7, "failed_attempts": 0, "first_recovery_seconds": 5.042}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
PASS: HTTPS smoke, persistence restart and one-replica failure completed with CA and hostname verification enabled.
Hook scope:
scripts/restart.cmd stops nginx, api, worker, redis, postgres, minio and rabbitmq,
then starts the stateful services, runs minio-init and rabbitmq-init, and restores
worker, two API replicas and nginx. Volumes are not removed.
scripts/stop-one.cmd resolves exactly one API container by instance ID and stops it.
No tokens, session cookies, private keys or message payloads are included.
+27 -2
View File
@@ -4,11 +4,37 @@
{
"Effect": "Allow",
"Action": [
"s3:GetBucketLocation",
"s3:GetBucketLocation"
],
"Resource": [
"arn:aws:s3:::__S3_BUCKET__"
]
},
{
"Effect": "Allow",
"Action": [
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::__S3_BUCKET__"
],
"Condition": {
"StringLike": {
"s3:prefix": [
"attachments/*",
"staging/*"
]
}
}
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::__S3_BUCKET__/attachments/*"
]
},
{
@@ -19,7 +45,6 @@
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::__S3_BUCKET__/attachments/*",
"arn:aws:s3:::__S3_BUCKET__/staging/*"
]
}
+25
View File
@@ -0,0 +1,25 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::__S3_BUCKET__/staging/*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::__S3_BUCKET__/attachments/*"
]
}
]
}
+56 -13
View File
@@ -7,7 +7,26 @@ param(
)
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if(-not (Test-Path (Join-Path $projectRoot 'compose.yaml'))) {
throw "Run the repository copy of this script: $projectRoot does not contain compose.yaml."
}
function Get-OpenSslPath {
$command = Get-Command openssl -ErrorAction SilentlyContinue
if($command){ return $command.Source }
$git = Get-Command git -ErrorAction SilentlyContinue
if($git){
$gitRoot = Split-Path (Split-Path $git.Source -Parent) -Parent
foreach($relative in 'usr\bin\openssl.exe','mingw64\bin\openssl.exe'){
$candidate = Join-Path $gitRoot $relative
if(Test-Path -LiteralPath $candidate){ return $candidate }
}
}
return $null
}
if([string]::IsNullOrWhiteSpace($PkiDirectory)){ $PkiDirectory = 'secrets\pki' }
$pki = (Resolve-Path -LiteralPath $PkiDirectory).Path
$now = [DateTimeOffset]::UtcNow
@@ -29,19 +48,43 @@ foreach($certificateFile in Get-ChildItem -LiteralPath $pki -Recurse -Filter tls
throw "$($certificateFile.Directory.Name) certificate has no SAN"
}
$privateKey = [System.Security.Cryptography.RSA]::Create()
$publicKey = $null
try {
$privateKey.ImportFromPem([System.IO.File]::ReadAllText($keyFile))
$privatePublic = [Convert]::ToBase64String($privateKey.ExportSubjectPublicKeyInfo())
$publicKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPublicKey($certificate)
$certificatePublic = [Convert]::ToBase64String($publicKey.ExportSubjectPublicKeyInfo())
if($privatePublic -ne $certificatePublic){ throw "$($certificateFile.Directory.Name) private key does not match certificate" }
} finally {
if($null -ne $publicKey){ $publicKey.Dispose() }
$privateKey.Dispose()
$certificate.Dispose()
if($PSVersionTable.PSVersion.Major -ge 6) {
$privateKey = [System.Security.Cryptography.RSA]::Create()
$publicKey = $null
try {
$privateKey.ImportFromPem([System.IO.File]::ReadAllText($keyFile))
$privatePublic = [Convert]::ToBase64String($privateKey.ExportSubjectPublicKeyInfo())
$publicKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPublicKey($certificate)
$certificatePublic = [Convert]::ToBase64String($publicKey.ExportSubjectPublicKeyInfo())
if($privatePublic -ne $certificatePublic){ throw "$($certificateFile.Directory.Name) private key does not match certificate" }
} finally {
if($null -ne $publicKey){ $publicKey.Dispose() }
$privateKey.Dispose()
}
} else {
# Windows PowerShell 5.1 has no ImportFromPem; compare public keys via OpenSSL.
$openssl = Get-OpenSslPath
if($null -eq $openssl){
throw "Cannot verify key pair for $($certificateFile.Directory.Name): install PowerShell 7+ or OpenSSL."
}
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$keyPublic = ((& $openssl pkey -in $keyFile -pubout 2>&1 | Out-String).Trim()) -replace "`r",''
$keyExit = $LASTEXITCODE
$certPublic = ((& $openssl x509 -in $certificateFile.FullName -pubkey -noout 2>&1 | Out-String).Trim()) -replace "`r",''
$certExit = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($keyExit -ne 0 -or $certExit -ne 0){
throw "OpenSSL could not read key/certificate for $($certificateFile.Directory.Name)"
}
if($keyPublic -ne $certPublic){
throw "$($certificateFile.Directory.Name) private key does not match certificate"
}
}
$certificate.Dispose()
$leafCount++
}
if($leafCount -eq 0){ throw 'No leaf certificates found' }
+130
View File
@@ -0,0 +1,130 @@
[CmdletBinding()]
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
# Expected denials write to stderr; keep them from becoming terminating errors
# under $ErrorActionPreference = 'Stop'.
function Invoke-InContainer {
param([string]$Service, [string]$Script)
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$output = @($Script | & docker compose --env-file $EnvFile exec -T $Service sh -s 2>&1) -join "`n"
$exitCode = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
[pscustomobject]@{ ExitCode = $exitCode; Output = $output }
}
$probe = @'
set -eu
ca=/run/pki/service-ca/ca.crt
probe_ok() {
label=$1; target=$2; name=$3; shift 3
if ! openssl s_client -brief -verify_return_error -verify_hostname "$name" \
-connect "$target" -servername "$name" -CAfile "$ca" "$@" \
</dev/null >/tmp/tls-probe.log 2>&1; then
echo "FAIL: $label did not pass CA/hostname verification" >&2
sed -n '1,12p' /tmp/tls-probe.log >&2
exit 1
fi
}
probe_rejected() {
label=$1; target=$2; name=$3
set +e
printf '\n' | openssl s_client -tls1_2 -brief -verify_return_error -verify_hostname "$name" \
-connect "$target" -servername "$name" -CAfile "$ca" \
>/tmp/tls-probe.log 2>&1
status=$?
set -e
if [ "$status" -eq 0 ] || ! grep -Eq 'certificate required|handshake failure|certificate unknown|bad certificate' /tmp/tls-probe.log; then
echo "FAIL: $label accepted a connection without its required client certificate" >&2
sed -n '1,12p' /tmp/tls-probe.log >&2
exit 1
fi
}
probe_ok postgres postgres:5432 postgres -starttls postgres
probe_ok minio minio:9000 minio
probe_ok openbao openbao:8200 openbao
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 \
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
probe_rejected rabbitmq rabbitmq:5671 rabbitmq
probe_ok otel-ingest-api otel-collector:4318 otel-collector \
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
probe_ok otel-ingest-worker otel-collector:4318 otel-collector \
-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
probe_rejected otel-metrics otel-collector:8889 otel-collector
probe_ok loki loki:3100 loki \
-cert /run/pki/collector-client/tls.crt -key /run/pki/collector-client/tls.key
probe_rejected loki loki:3100 loki
probe_ok tempo-ingest tempo:4318 tempo \
-cert /run/pki/collector-client/tls.crt -key /run/pki/collector-client/tls.key
probe_rejected tempo-ingest tempo:4318 tempo
probe_ok tempo-query tempo:3200 tempo \
-cert /run/pki/grafana-client/tls.crt -key /run/pki/grafana-client/tls.key
probe_rejected tempo-query tempo:3200 tempo
probe_ok prometheus prometheus:9090 prometheus \
-cert /run/pki/grafana-client/tls.crt -key /run/pki/grafana-client/tls.key
probe_rejected prometheus prometheus:9090 prometheus
echo 'PASS: DB, S3, broker, Redis, Collector, telemetry backends and OpenBao verify server CA/hostname; all declared mTLS endpoints reject no-cert clients.'
'@
$probe | & docker compose --env-file $EnvFile run --rm -T --no-deps --entrypoint /bin/sh nginx -s
if($LASTEXITCODE -ne 0){ throw 'Internal TLS verification failed' }
# Database probes use distinct runtime credentials and verify the server over TLS.
$apiDdl = 'PGPASSWORD="$DATABASE_API_PASSWORD" PGSSLMODE=verify-full PGSSLROOTCERT=/run/pki/service-ca/ca.crt psql -h postgres -U messenger_api -d messenger -v ON_ERROR_STOP=1 -c "CREATE TABLE forbidden_api_probe(id integer)"'
$apiDdlResult = Invoke-InContainer postgres $apiDdl
if($apiDdlResult.ExitCode -eq 0 -or $apiDdlResult.Output -notmatch 'permission denied'){
throw 'Database ACL failure: API role DDL was not denied with a permission error'
}
$workerUsers = 'PGPASSWORD="$DATABASE_WORKER_PASSWORD" PGSSLMODE=verify-full PGSSLROOTCERT=/run/pki/service-ca/ca.crt psql -h postgres -U messenger_worker -d messenger -v ON_ERROR_STOP=1 -c "SELECT password_hash FROM users LIMIT 1"'
$workerUsersResult = Invoke-InContainer postgres $workerUsers
if($workerUsersResult.ExitCode -eq 0 -or $workerUsersResult.Output -notmatch 'permission denied'){
throw 'Database ACL failure: worker password-hash read was not denied with a permission error'
}
# Redis identities have disjoint command/key permissions in addition to mTLS.
$apiOutsideKey = 'redis-cli --tls --cacert /run/pki/service-ca/ca.crt --cert /run/pki/api-client/tls.crt --key /run/pki/api-client/tls.key --user messenger-api --pass "$REDIS_API_PASSWORD" --no-auth-warning SET forbidden:probe value'
$apiOutsideResult = (Invoke-InContainer redis $apiOutsideKey).Output
if($apiOutsideResult -notmatch 'NOPERM'){ throw 'Redis ACL failure: API wrote outside messenger:*' }
$workerRead = 'redis-cli --tls --cacert /run/pki/service-ca/ca.crt --cert /run/pki/worker-client/tls.crt --key /run/pki/worker-client/tls.key --user messenger-worker --pass "$REDIS_WORKER_PASSWORD" --no-auth-warning GET messenger:user:probe'
$workerReadResult = (Invoke-InContainer redis $workerRead).Output
if($workerReadResult -notmatch 'NOPERM'){ throw 'Redis ACL failure: worker read an API cache key' }
$apiAdmin = 'redis-cli --tls --cacert /run/pki/service-ca/ca.crt --cert /run/pki/api-client/tls.crt --key /run/pki/api-client/tls.key --user messenger-api --pass "$REDIS_API_PASSWORD" --no-auth-warning CONFIG GET "*"'
$apiAdminResult = (Invoke-InContainer redis $apiAdmin).Output
if($apiAdminResult -notmatch 'NOPERM'){ throw 'Redis ACL failure: API executed an administrative command' }
$permissions = (& docker compose --env-file $EnvFile exec -T rabbitmq rabbitmqctl list_permissions --formatter table) -join "`n"
if($permissions -notmatch 'messenger-api' -or $permissions -notmatch 'messenger-worker'){
throw 'RabbitMQ ACL failure: separate application identities are missing'
}
if($permissions -match 'messenger-(api|worker)\s+\.\*\s+\.\*\s+\.\*'){
throw 'RabbitMQ ACL failure: an application identity has unrestricted permissions'
}
Write-Host 'PASS: PostgreSQL, Redis and RabbitMQ runtime identities are separate and forbidden operations are denied.'
+29 -9
View File
@@ -2,17 +2,37 @@
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
function Invoke-Probe([string]$Target, [string]$TlsArguments) {
$script = "printf 'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n' | openssl s_client -quiet -connect ${Target}:8443 -servername api -CAfile /run/pki/service-ca/ca.crt $TlsArguments 2>&1"
$output = (& docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $script 2>&1)
return ($output -join "`n")
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if(-not (Test-Path (Join-Path $projectRoot 'compose.yaml'))) {
throw "Run the repository copy of this script: $projectRoot does not contain compose.yaml."
}
$published = (& docker compose --env-file $EnvFile port api 8443 2>$null) -join "`n"
if (-not [string]::IsNullOrWhiteSpace($published)) {
throw "mTLS bypass: API port is published directly at $published"
function Invoke-Probe([string]$Target, [string]$TlsArguments) {
$probeScript = "printf 'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n' | openssl s_client -quiet -connect ${Target}:8443 -servername api -CAfile /run/pki/service-ca/ca.crt $TlsArguments 2>&1"
# Rejected handshakes write to stderr; keep them from becoming terminating errors.
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$output = @(& docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $probeScript 2>&1) -join "`n"
} finally {
$ErrorActionPreference = $previous
}
return $output
}
# A missing published port is expected: compose returns nonzero and writes
# "no port 8443/tcp ..." to stderr.
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$published = @(& docker compose --env-file $EnvFile port api 8443 2>&1) -join "`n"
$portExit = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if ($portExit -eq 0 -and $published.Trim() -and $published -notmatch 'no port') {
throw "mTLS bypass: API port is published directly at $($published.Trim())"
}
$replicas = @(& docker compose --env-file $EnvFile ps -q api)
+31 -6
View File
@@ -2,21 +2,46 @@
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if(-not (Test-Path (Join-Path $projectRoot 'compose.yaml'))) {
throw "Run the repository copy of this script: $projectRoot does not contain compose.yaml."
}
function Get-AppRoleToken([string]$Role) {
$dir = Join-Path 'secrets\openbao' $Role
$dir = Join-Path $projectRoot (Join-Path 'secrets\openbao' $Role)
foreach($name in 'role-id','secret-id') {
$path = Join-Path $dir $name
if(-not (Test-Path -LiteralPath $path)) {
throw "Missing $path. Run .\scripts\bootstrap-openbao.ps1 with BAO_TOKEN first."
}
}
$roleId = [System.IO.File]::ReadAllText((Join-Path $dir 'role-id')).Trim()
$secretId = [System.IO.File]::ReadAllText((Join-Path $dir 'secret-id')).Trim()
$body = @{ role_id = $roleId; secret_id = $secretId } | ConvertTo-Json -Compress
$token = ($body | & docker compose --env-file $EnvFile exec -T openbao bao write -field=token auth/approle/login - | Out-String).Trim()
if($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($token)) { throw "AppRole login failed for $Role" }
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$token = ($body | & docker compose --env-file $EnvFile exec -T openbao bao write -field=token auth/approle/login - 2>&1 | Out-String).Trim()
$loginExit = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($loginExit -ne 0 -or [string]::IsNullOrWhiteSpace($token)) { throw "AppRole login failed for $Role" }
return $token
}
function Bao-WithToken([string]$Token,[Parameter(ValueFromRemainingArguments=$true)][string[]]$Arguments) {
& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$Token" openbao bao @Arguments 2>$null | Out-Null
return $LASTEXITCODE
# Expected denials write to stderr; do not let them become terminating errors.
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$Token" openbao bao @Arguments 2>&1 | Out-Null
$exitCode = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
return $exitCode
}
foreach($role in 'api','worker') {
+24 -5
View File
@@ -6,7 +6,11 @@ param(
)
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if(-not (Test-Path (Join-Path $projectRoot 'compose.yaml'))) {
throw "Run the repository copy of this script: $projectRoot does not contain compose.yaml."
}
$ca = (Resolve-Path 'secrets\pki\public-ca\ca.crt').Path
& "$PSScriptRoot\check-compose-hardening.ps1" -EnvFile $EnvFile
@@ -30,8 +34,16 @@ with urllib.request.urlopen(sys.argv[1].rstrip('/') + '/health/ready', context=c
'@
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
do {
& $Python -c $probe $BaseUrl $ca 2>$null
if($LASTEXITCODE -eq 0){ return }
# Not ready yet is expected during recovery; do not turn it into a terminating error.
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& $Python -c $probe $BaseUrl $ca 2>&1 | Out-Null
$probeExit = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($probeExit -eq 0){ return }
Start-Sleep -Milliseconds 500
} while((Get-Date) -lt $deadline)
throw "HTTPS readiness did not recover within $TimeoutSeconds seconds"
@@ -43,6 +55,13 @@ Run-Test @('tests/smoke.py','--base-url',$BaseUrl,'--ca-file',$ca)
Run-Test @('tests/resilience.py','--mode','persistence','--action-script',(Resolve-Path 'scripts/restart.cmd').Path,'--base-url',$BaseUrl,'--ca-file',$ca)
Run-Test @('tests/resilience.py','--mode','failover','--action-script',(Resolve-Path 'scripts/stop-one.cmd').Path,'--base-url',$BaseUrl,'--ca-file',$ca)
& docker compose --env-file $EnvFile up -d --no-deps --scale api=2 api
if($LASTEXITCODE -ne 0){ throw 'Failed to restore the stopped API replica' }
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& docker compose --env-file $EnvFile up -d --no-deps --scale api=2 api 2>&1 | Out-Null
$restoreExit = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($restoreExit -ne 0){ throw 'Failed to restore the stopped API replica' }
Write-Host 'PASS: HTTPS smoke, persistence restart and one-replica failure completed with CA and hostname verification enabled.'