ЛР 7 — БПИ2301 — Антипин — на 4 #51

Closed
Egor_Antipin wants to merge 15 commits from Egor_Antipin/mtusi2026lab7:solution/bpi2301-antipin into main
207 changed files with 13531 additions and 115 deletions
+95 -34
View File
@@ -1,41 +1,102 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. # Copy to .env for a local synthetic environment. Never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0 APP_HOST=0.0.0.0
APP_PORT=8080 APP_PORT=8080
APP_ENV=lab APP_ENV=lab
SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values. # Public traffic terminates as HTTPS at nginx. Generate the certificate and
DATABASE_URL_FILE=/run/secrets/database_url # private key locally with scripts/bootstrap-tls.*; never add secrets/ to Git.
# Optional on 3, required use on 4 in lab2; Redis OR Valkey: PUBLIC_BIND_ADDRESS=127.0.0.1
SESSION_STORE=postgres PUBLIC_HTTPS_PORT=8443
CACHE_URL_FILE=/run/secrets/cache_url PUBLIC_BASE_URL=https://localhost:8443
API_REPLICAS=2
IDEMPOTENCY_TTL_SECONDS=86400 DATABASE_NAME=messenger
S3_ENDPOINT=https://s3:9000 DATABASE_USER=messenger
DATABASE_PASSWORD=replace-with-a-long-random-database-password
DATABASE_API_PASSWORD=replace-with-a-different-api-database-password
DATABASE_WORKER_PASSWORD=replace-with-a-different-worker-database-password
DATABASE_MIGRATION_PASSWORD=replace-with-a-different-migration-database-password
RABBITMQ_USER=messenger
RABBITMQ_PASSWORD=replace-with-a-long-random-rabbitmq-password
RABBITMQ_ADMIN_USER=operator
RABBITMQ_ADMIN_PASSWORD=replace-with-a-long-random-rabbitmq-admin-password
RABBITMQ_API_PASSWORD=replace-with-a-different-rabbitmq-api-password
RABBITMQ_WORKER_PASSWORD=replace-with-a-different-rabbitmq-worker-password
RABBITMQ_VHOST=/
ATTACHMENT_JOB_EXCHANGE=attachments.v1
ATTACHMENT_JOB_QUEUE=attachments.process.level4.v1
ATTACHMENT_JOB_ROUTING_KEY=attachment.process.v1
ATTACHMENT_DLQ_EXCHANGE=attachments.dlx.v1
ATTACHMENT_DLQ_QUEUE=attachments.failed.v1
ATTACHMENT_DLQ_ROUTING_KEY=attachment.failed.v1
ATTACHMENT_PIPELINE_VERSION=2
WORKER_CONCURRENCY=2
WORKER_PREFETCH=1
JOB_MAX_ATTEMPTS=5
JOB_RETRY_BASE_DELAY=1s
JOB_RETRY_MAX_DELAY=30s
JOB_TIMEOUT=60s
JOB_LEASE_DURATION=90s
JOB_LEASE_REAPER_INTERVAL=5s
WORKER_MAX_IMAGE_PIXELS=40000000
WORKER_MEMORY_BUDGET_BYTES=536870912
WORKER_MEMORY_WAIT=2s
# Fault injection is opt-in and intended only for an isolated test stand.
FAULT_CRASH_AFTER_OUTBOX_COMMIT=false
FAULT_CRASH_BEFORE_SIDE_EFFECT=false
FAULT_CRASH_AFTER_SIDE_EFFECT=false
FAULT_CRASH_AFTER_RESULT_COMMIT=false
S3_REGION=us-east-1 S3_REGION=us-east-1
S3_BUCKET=messenger-attachments S3_BUCKET=messenger-attachments
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id S3_ACCESS_KEY_ID=messenger-api
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key S3_SECRET_ACCESS_KEY=replace-with-a-long-random-api-secret
MAX_UPLOAD_BYTES=10485760 S3_WORKER_ACCESS_KEY_ID=messenger-worker
MAX_IMAGE_PIXELS=40000000 S3_WORKER_SECRET_ACCESS_KEY=replace-with-a-different-long-random-worker-secret
BROKER_URL_FILE=/run/secrets/broker_url MINIO_ROOT_USER=minio-root
WORKER_CONCURRENCY=2 MINIO_ROOT_PASSWORD=replace-with-a-different-long-random-root-secret
JOB_MAX_ATTEMPTS=5 REDIS_API_PASSWORD=replace-with-a-long-random-redis-api-password
JOB_TIMEOUT_SECONDS=60 REDIS_WORKER_PASSWORD=replace-with-a-different-random-redis-worker-password
STAGING_RETENTION_SECONDS=86400
OTEL_SERVICE_NAME=messenger-api SESSION_TTL_SECONDS=3600
# Worker must set a distinct service.name. SESSION_MAXIMUM_ACTIVE=3
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318 # Shared Redis-backed login guard across all API replicas.
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf LOGIN_ATTEMPTS_PER_USERNAME=5
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab LOGIN_ATTEMPTS_PER_SOURCE=100
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix. LOGIN_RATE_WINDOW_SECONDS=60
PUBLIC_BASE_URL=https://localhost:8443 ARGON2_MEMORY_KIB=32768
TLS_CA_FILE=/run/secrets/ca.crt
TLS_CERT_FILE=/run/secrets/service.crt
TLS_KEY_FILE=/run/secrets/service.key
BAO_ADDR=https://openbao:8200
BAO_CACERT=/run/secrets/bao-ca.crt
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
ARGON2_MEMORY_KIB=19456
ARGON2_ITERATIONS=2 ARGON2_ITERATIONS=2
ARGON2_PARALLELISM=1 ARGON2_PARALLELISM=1
IDEMPOTENCY_TTL_SECONDS=86400
MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000
MAX_CONCURRENT_UPLOADS=3
UPLOAD_PERMIT_WAIT_MILLIS=10000
# Staging objects are deleted only after the final result is committed.
# A separate lifecycle/cleanup policy may remove abandoned staging objects
# after this retention interval; it must never remove active jobs.
STAGING_RETENTION_SECONDS=86400
ATTACHMENT_CLEANUP_GRACE_SECONDS=3600
ATTACHMENT_CLEANUP_DRY_RUN=false
ATTACHMENT_RECONCILE_INTERVAL_MILLIS=600000
ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS=60000
# Observability (lab6). The worker must set a distinct OTEL_SERVICE_NAME.
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_TRACES_SAMPLER=parentbased_traceidratio
# Balanced lab profile: keep 25% of complete parent-based traces; keep all logs/metrics.
OTEL_TRACES_SAMPLER_ARG=0.25
OTEL_METRIC_EXPORT_INTERVAL=30000
OTEL_BSP_MAX_QUEUE_SIZE=2048
OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512
OTEL_BSP_EXPORT_TIMEOUT=5000
OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT=256
OBSERVABILITY_QUEUE_POLL_INTERVAL=5s
GRAFANA_PORT=3000
GRAFANA_ADMIN_USER=admin
GRAFANA_ADMIN_PASSWORD=replace-with-a-long-random-grafana-password
OPENBAO_PORT=8200
+1
View File
@@ -14,6 +14,7 @@ volumes/
data/ data/
backups/ backups/
# Runtime/build artifacts # Runtime/build artifacts
.gradle/
.venv/ .venv/
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
+44
View File
@@ -0,0 +1,44 @@
# Stage 1: Build
FROM eclipse-temurin:23-jdk AS build
WORKDIR /app
COPY gradlew .
COPY gradle gradle
COPY build.gradle settings.gradle ./
COPY src src
RUN --mount=type=cache,target=/root/.gradle \
chmod +x gradlew && ./gradlew bootJar --no-daemon
# Stage 2: Runtime
FROM eclipse-temurin:23-jre
WORKDIR /app
COPY --from=build /app/build/libs/*.jar app.jar
ARG OTEL_JAVA_AGENT_VERSION=2.33.1
RUN apt-get update \
&& apt-get install --yes --no-install-recommends curl \
&& curl --fail --location --silent --show-error \
--connect-timeout 15 --max-time 180 --retry 3 --retry-all-errors \
"https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/download/v${OTEL_JAVA_AGENT_VERSION}/opentelemetry-javaagent.jar" \
--output /opt/opentelemetry-javaagent.jar \
&& rm -rf /var/lib/apt/lists/* \
&& useradd --system --create-home messenger
COPY --chmod=0755 infra/otel/docker-entrypoint.sh /usr/local/bin/messenger-entrypoint
USER messenger
EXPOSE 8080
STOPSIGNAL SIGTERM
HEALTHCHECK NONE
ENTRYPOINT ["messenger-entrypoint"]
+14 -1
View File
@@ -4,7 +4,7 @@ CA_FILE ?=
ACTION_SCRIPT ?= ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence test-failover test-security .PHONY: help check validate test load test-persistence test-failover test-security test-session-expiry test-mtls test-login-dos test-credential-storage
help: help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@@ -31,3 +31,16 @@ test-failover:
test-security: test-security:
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-session-expiry:
$(PYTHON) tests/session_expiry.py --base-url "$(BASE_URL)" $(TLS_ARGS)
LOGIN_DOS_ARGS ?= --source-budget
test-login-dos:
$(PYTHON) tests/login_dos.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(LOGIN_DOS_ARGS)
test-credential-storage:
$(PYTHON) tests/credential_storage.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-mtls:
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/test-mtls.ps1
+143 -1
View File
@@ -49,6 +49,47 @@
## Как начать и проверить ## Как начать и проверить
Перенесённое приложение lab6 собирается из `src/` и доступно только через
HTTPS-ingress. Перед первым запуском создайте локальные ключи (каталог
`secrets/` игнорируется Git):
```powershell
.\scripts\bootstrap-secrets.ps1
.\scripts\bootstrap-pki.ps1
docker compose --env-file .env up -d openbao
# Один раз: operator init; при каждом старте: ручной unseal двумя долями.
# Затем временно задайте BAO_TOKEN и выполните bootstrap политик/AppRole:
.\scripts\bootstrap-openbao.ps1
docker compose --env-file .env up -d --build --scale api=2
make test CA_FILE=$PWD/secrets/pki/public-ca/ca.crt
```
`bootstrap-pki.ps1` создаёт отдельные public/service/client CA и leaf identities
для ingress, LB, API, workload-клиентов и зависимостей. Приватные ключи и
готовые credentials в репозиторий не поставляются. LB→API, API/worker→Collector,
RabbitMQ, Redis и telemetry backends используют mTLS с раздельными identities;
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 задаётся только
в окружении текущего процесса оператора на время bootstrap и сразу удаляется.
```sh ```sh
# Работает прямо в skeleton, Python 3.9+; приложение не запускается: # Работает прямо в skeleton, Python 3.9+; приложение не запускается:
make check make check
@@ -68,7 +109,108 @@ docker compose --env-file .env up -d --build
# Для Swarm укажите эквивалентные build/push/deploy-команды в REPORT.md. # Для Swarm укажите эквивалентные build/push/deploy-команды в REPORT.md.
``` ```
Для HTTPS передайте публичный CA: `make test CA_FILE=/absolute/path/to/ca.crt`. CA certificate можно распространять; private keys создаются локально. `make test-security` проверяет только внешний TLS trust; внутренние отрицательные тесты реализуйте по [trust matrix](contracts/trust-matrix.md). Для HTTPS передайте публичный CA: `make test CA_FILE=/absolute/path/to/ca.crt`. CA certificate можно распространять; private keys создаются локально. `make test-security` проверяет внешний TLS trust, ACL, upload/session/login limits и logout; `make test-session-expiry` управляемо истекает одну синтетическую сессию локального Compose-стенда и подтверждает `401`. `make test-login-dos` измеряет общий Redis-бюджет login DoS и распределение попыток по репликам; `make test-credential-storage` проверяет, что пароль и session token хранятся только как hashes и не попадают в логи. Внутренние отрицательные тесты реализованы отдельно по [trust matrix](contracts/trust-matrix.md).
Проверка hardening и lifecycle не требует запущенного приложения:
```powershell
.\scripts\check-compose-hardening.ps1
.\scripts\check-security-lifecycle.ps1
```
В локальном профиле опубликованы только HTTPS ingress и loopback-интерфейсы
оператора OpenBao/Grafana. Prometheus, Loki, Tempo, data stores, API и worker
доступны только во внутренней сети. Каждый контейнер имеет CPU/RAM/PID limits,
`no-new-privileges`, capability drop policy и отдельный tmpfs для временных файлов;
stateless root filesystems — read-only с `cap_drop: ALL`. Исключения сделаны только
для postgres, redis, rabbitmq и minio: их stock entrypoints подготавливают persistent
named volume до смены UID, поэтому root filesystem остаётся writable при том же
`no-new-privileges` и drop шести опасных capabilities. Причины каждого исключения
печатает `scripts/check-compose-hardening.ps1`.
Dependency-сканирование выполняет OSV по фактически разрешённому Gradle
`runtimeClasspath`; image-сканирование — Trivy по собранному образу приложения.
Каждый High/Critical finding разбирается по reachability, наличию fix и временному
контролю; подробности и результаты — `evidence/dependency-image-scan.txt`.
```powershell
.\scripts\scan-dependencies.ps1 -FailOnHigh
docker run --rm -v //var/run/docker.sock:/var/run/docker.sock -v trivy-cache:/root/.cache/trivy aquasec/trivy:0.62.1 image --scanners vuln --timeout 20m --severity HIGH,CRITICAL hla-lab7-app:local
```
После запуска стенда отдельная runtime-проверка подтверждает фактический non-root
UID API/worker, отсутствие privileged/host network/Docker socket, реальные
лимиты и port bindings. Она также сравнивает значения secret-переменных из
локального `.env` с Git-файлами, metadata образа и последними логами, не печатая
сами значения, и проверяет обязательный redaction processor во всех telemetry
pipelines:
```powershell
.\scripts\test-container-secret-boundaries.ps1
```
Полный повторяемый сценарий после запуска и unseal стенда:
```powershell
.\scripts\verify-https-resilience.ps1
```
Он последовательно выполняет certificate/secret lifecycle check, HTTPS smoke,
перезапуск API/worker и хранилищ с сохранением volumes, отказ одной из двух API
реплик и восстановление масштаба. Во все HTTP-тесты явно передаётся public CA;
режима `--insecure` и `curl -k` в сценарии нет.
### Калибровка Argon2id
Пароль хранится одной PHC-строкой `$argon2id$v=19$m=...,t=...,p=...$salt$digest`:
случайный 16-байтовый salt и все параметры находятся рядом с digest. Код не
принимает runtime-конфигурацию ниже `19456 KiB`, `t=2`, `p=1`. Итоговый профиль
стенда — `32768 KiB`, `t=2`, `p=1`; более слабая допустимая строка обновляется
после успешного входа.
Воспроизводимое измерение запускается без application secrets в одноразовом
контейнере с теми же лимитами, что у API (`0.75 CPU`, `768 MiB`):
```powershell
.\scripts\benchmark-argon2.ps1
```
На этом стенде (5 прогревов, 21 encode+verify на профиль) получены следующие
значения, мс:
| Профиль | encode p50 / p95 | verify p50 / p95 |
| --- | ---: | ---: |
| 19456 KiB, t=2, p=1 | 62,1 / 103,9 | 63,7 / 97,5 |
| 32768 KiB, t=2, p=1 | 101,3 / 150,3 | 102,6 / 142,7 |
| 19456 KiB, t=3, p=1 | 97,0 / 113,3 | 94,8 / 123,6 |
`32 MiB, t=2, p=1` выбран как более высокий memory cost при p95 около 150 мс;
он укладывается в локальный 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
.\scripts\test-openbao-runtime-boundaries.ps1
```
Единый аудит уровня 4 дополнительно проверяет всю заявленную TLS/mTLS-матрицу,
same-CA wrong-role/foreign-CA/no-cert отказы, DB/Redis/RabbitMQ/MinIO ACL,
фактические CPU/RAM/PID limits worker, 40M pixel и 512 MiB processing budget,
60 s job timeout и отсутствие уникального Authorization/body canary в
stdout/stderr, Loki, Tempo и Prometheus:
```powershell
.\scripts\test-level4-security-audit.ps1
```
Scoped OpenBao allow/deny probe требует неистёкший AppRole SecretID (TTL 24 h).
После его документированного обновления добавьте
`-IncludeFreshOpenBaoPolicy`; аудит намеренно не использует root token как fallback.
Примеры запросов доступны в `examples/requests.http`, примеры JSON — в `contracts/examples.json`. Для полной проверки схемы (по желанию локально; CI делает её автоматически): Примеры запросов доступны в `examples/requests.http`, примеры JSON — в `contracts/examples.json`. Для полной проверки схемы (по желанию локально; CI делает её автоматически):
+285 -15
View File
@@ -1,37 +1,307 @@
# Отчёт — лабораторная 7 # Отчёт — лабораторная 7
- Автор, группа: TODO - Автор, группа: Егор Антипин, БПИ2301
- Целевая оценка; выбранный трек 5, если нужен: TODO - Целевая оценка: **4**; трек уровня 5 не заявляется
- Commit/PR: TODO после публикации - Ветка: `solution/bpi2301-antipin`; точный сдаваемый commit определяется
- Использованные источники, библиотеки и помощь ИИ: TODO `git rev-parse HEAD`; законченные security-этапы — `16760f4`…`567d568`;
отдельный PR не создавался
- Использованные источники и помощь: официальная документация Spring
Security/Boot, Docker Compose, PostgreSQL, Redis, RabbitMQ, MinIO, OpenBao,
OpenTelemetry, Prometheus/Loki/Tempo/Grafana, OSV и Trivy; OWASP Password
Storage Cheat Sheet. Для анализа кода, подготовки проверочных скриптов и
редактирования документации использовался OpenAI GPT-5.6 Sol через OpenCode.
Все заявленные результаты получены локальным запуском команд из таблицы
доказательств, а не приняты из ответа ИИ.
## Запуск из чистого clone ## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. ### Предварительные требования
- Docker Desktop с Docker Compose v2 и доступным Linux engine; стенду нужно
ориентировочно 8 GiB RAM и свободные loopback-порты 8443, 8200 и 3000.
- Windows PowerShell 5.1+ или PowerShell 7 для bootstrap/audit scripts.
- Python 3.9+; GNU Make необязателен — команды из Makefile можно запускать
напрямую через Python.
- JDK 23 для host-side unit/benchmark задач. Gradle устанавливать не нужно:
используется `gradlew.bat`.
Основные закреплённые runtime-образы: OpenBao 2.7.3, PostgreSQL 16.4,
Redis 7.4, RabbitMQ 4.1.4, nginx 1.27.4, MinIO 2025.4.22 (digest pinned),
OTel Collector 0.165.0, Prometheus 3.14.0, Loki 3.7.8, Tempo 3.1.1 и
Grafana 13.3.0. Application image собирается как `hla-lab7-app:local` на
Eclipse Temurin 23 JRE.
### Первичный bootstrap и запуск
Из корня чистого clone:
```powershell
.\scripts\bootstrap-secrets.ps1
.\scripts\bootstrap-pki.ps1
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d openbao
docker compose --env-file .env exec openbao bao status
```
`bootstrap-secrets.ps1` создаёт игнорируемый `.env` со случайными отдельными
credentials и не печатает значения. `bootstrap-pki.ps1` создаёт private CA/leaf
material только в игнорируемом `secrets/`.
OpenBao требует ручного действия оператора. Один раз выполняется init:
```powershell
docker compose --env-file .env exec openbao bao operator init -key-shares=3 -key-threshold=2
```
Три unseal share и initial root token сразу переносятся во внешнее защищённое
хранилище и не сохраняются в проекте, shell history или отчёте. Любые две доли
вводятся интерактивно:
```powershell
docker compose --env-file .env exec openbao bao operator unseal
docker compose --env-file .env exec openbao bao operator unseal
docker compose --env-file .env exec openbao bao status
```
Затем root token задаётся только в окружении текущего процесса на время
создания KV/policies/AppRole и немедленно удаляется:
```powershell
$env:BAO_TOKEN = Read-Host 'OpenBao root token'
.\scripts\bootstrap-openbao.ps1
Remove-Item Env:BAO_TOKEN
docker compose --env-file .env up -d --build --scale api=2
```
One-shot `migrate` применяет Flyway V1–V9 отдельной migration identity;
`rabbitmq-init` и `minio-init` создают минимальные runtime users/policies.
API не запускает миграции самостоятельно. После restart persistent OpenBao
остаётся sealed и требует повторного ввода двух долей, но повторный init не
выполняется.
Ожидание readiness с явной проверкой CA и hostname:
```powershell
python -c "import ssl,urllib.request; c=ssl.create_default_context(cafile='secrets/pki/public-ca/ca.crt'); print(urllib.request.urlopen('https://localhost:8443/health/ready',context=c,timeout=10).status)"
docker compose --env-file .env ps
```
### Проверка
```powershell
python scripts/check_contract.py
python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
python tests/security.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
.\scripts\test-level4-security-audit.ps1
.\scripts\verify-https-resilience.ps1
```
Для live OpenBao policy probe нужен свежий SecretID с TTL 24 часа:
```powershell
.\scripts\test-level4-security-audit.ps1 -IncludeFreshOpenBaoPolicy
```
Истёкший SecretID обновляется документированным operator bootstrap; root token
никогда не используется приложением или как fallback проверки.
### Остановка и удаление данных
Безопасная остановка с сохранением named volumes:
```powershell
docker compose --env-file .env down
```
Следующий запуск выполняется `up -d`; OpenBao нужно вручную unseal. Только для
намеренного удаления всех синтетических данных:
```powershell
docker compose --env-file .env down -v --remove-orphans
Remove-Item -Recurse -Force secrets
Remove-Item -Force .env
```
Последние команды необратимо удаляют БД, объекты, telemetry, OpenBao storage,
локальные credentials и PKI; применять их к нужному стенду нельзя.
## Архитектура и решения ## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. ```text
verified HTTPS client
│
▼
nginx ingress ── exact-identity mTLS ──► API ×2
│ │
│ ├─ TLS + role ─► PostgreSQL
│ ├─ mTLS + ACL ─► Redis
│ ├─ TLS + policy ► MinIO
│ └─ role gateway/mTLS ─► RabbitMQ
│ │
│ ▼
└───────────────────────────────────────────────────── worker
API/worker ── exact-role mTLS gateway ─► OTel Collector
OpenBao Agents ── TLS/AppRole ─► OpenBao ── read-only files ─► API/worker
Collector ── mTLS ─► Loki/Tempo; Prometheus scrape; Grafana query identity
```
**Источники истины.** PostgreSQL хранит users, Argon2id hashes, session token
hashes, membership, сообщения, attachment metadata, job lease/state, idempotency
и transactional outbox. MinIO хранит staging/original/variant bytes. RabbitMQ —
at-least-once transport, но не источник истины: потерянная публикация
восстанавливается из DB outbox, зависший consumer — из lease. Redis содержит
восстанавливаемый cache и общий login rate-limit state. OpenBao/Raft — источник
runtime service credentials. Loki/Tempo/Prometheus являются telemetry, а не
business storage.
**Транзакционные границы.**
- Регистрация, session lifecycle, membership/message writes и idempotency
выполняются в PostgreSQL с repository predicates; session plaintext выдаётся
один раз, в БД остаётся SHA-256.
- Upload сначала проверяется по bytes/MIME/pixels и пишется под opaque staging
key. DB-транзакция фиксирует attachment, job и outbox; при неуспехе staging
очищается. `202` возвращается только после durable handoff.
- Publisher отправляет outbox job с confirm; повтор безопасен. Worker атомарно
получает DB lease, обрабатывает immutable input, пишет детерминированные
versioned keys и отдельной транзакцией фиксирует `ready`/variants. Staging
удаляется только после commit. Timeout/retry и lease reaper не подтверждают
недолговечный результат как готовый.
- Flyway V1–V9 выполняется one-shot контейнером с отдельной DDL role. API и
worker используют разные роли без DDL и без взаимного доступа к sensitive
tables/operations.
**Изменения относительно lab6.** Сохранены REST contract, PostgreSQL/Redis,
асинхронный attachment pipeline, MinIO/RabbitMQ и OTel observability. В lab7
добавлены public TLS, внутренний TLS/mTLS и role gateways, отдельные service
identities/ACL, Argon2id + rehash, hash-only sessions, общий Redis login limit,
OpenBao Agents/policies/rotation, hardened containers, dependency/image scan,
threat model и воспроизводимые negative tests.
**Конфигурация.** Все строки `replace-with-*` из `.env.example` заменяет
`bootstrap-secrets.ps1`; `.env` игнорируется Git. Имена DB/RabbitMQ/S3 и worker
bounds напрямую используются `compose.yaml`. Общие `DATABASE_USER`,
`RABBITMQ_USER/PASSWORD` оставлены для bootstrap/совместимости, тогда как API,
worker и migration получают отдельные identities. Значение
`OTEL_EXPORTER_OTLP_ENDPOINT=http://...` из общего template намеренно
переопределяется Compose на `https://otel-gateway:4318`; API получает внутренний
HTTPS port 8443, worker запускается без web server. Rendered
`docker compose config` проверяется hardening/audit scripts.
## Доказательства критериев ## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO | | Argon2id storage и калибровка | `scripts/benchmark-argon2.ps1`, `PasswordConfigTest` | PASS: итоговый профиль 32768 KiB/t=2/p=1; p95 encode 134.8 мс, verify 165.5 мс при 0.75 CPU/768 MiB (предыдущий прогон: 150.3/142.7 мс); PHC хранит параметры и уникальный 16-byte salt | `evidence/login-dos.txt`, `README.md`, unit test |
| Остальные пункты уровня 3 | TODO | TODO | TODO | | LB → каждая API-реплика | `scripts/test-mtls.ps1`, `TrustedClientCertificateFilterTest` | PASS: обе реплики отдельно отклоняют no-cert, foreign CA и доверенный cert с чужим URI SAN; LB identity принята; API port не опубликован; добавлен fail-closed deny-list отозванных DER SHA-256 leaf | `compose.yaml`, runtime test, unit test |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | | Внутренние TLS-связи и service ACL | `scripts/test-internal-tls.ps1`; `docker compose --env-file .env --profile verification run --rm private-bucket-check` | PASS: PostgreSQL, MinIO, OpenBao, Grafana, Redis, RabbitMQ, Collector, Loki, Tempo и Prometheus проверяют service CA и hostname; mTLS endpoints отвергают no-cert/foreign-CA; PostgreSQL/Redis/RabbitMQ и MinIO API/worker identities разделены, запрещённые DDL/keys/commands/prefixes denied | `evidence/internal-tls.txt`, `evidence/level4-security-audit.txt`, `contracts/trust-matrix.md` |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO | | 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` |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. | 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, `no-new-privileges`, capability drop, private tmpfs и read-only root у всех stateless сервисов; четыре stateful исключения с объяснением | `compose.yaml`, `evidence/dependency-image-scan.txt` |
| 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` |
| Rehash старого password hash | `DatabaseAuthenticationProviderTest` (5 тестов) | PASS: legacy Argon2id 19456 KiB/t=2/p=1 после успешного login заменяется на 32768 KiB/t=2/p=1 через CAS `replacePasswordHash(userId, expectedHash, newHash)`; неверный пароль, unknown user и уже актуальный hash не переписываются; unknown/non-Argon2 значение проверяется по dummy hash | `evidence/password-rehash.txt` |
| Login DoS budget и общий rate limit | `scripts/measure-login-dos.ps1 -SourceBudget`, `scripts/benchmark-argon2.ps1`, `LoginRateLimiterTest` | PASS: 5 попыток/username/60 s и 100/source/60 s в общем Redis; 6-я и 101-я попытки → `429` + `Retry-After`; 429 ≈ 19 мс против 401 p50 287 мс (Argon2 не запускается); обе реплики наблюдались; Redis outage fail-closed; ключи — SHA-256 digests | `evidence/login-dos.txt` |
| Credential non-disclosure | `tests/credential_storage.py`, `tests/login_dos.py` | PASS: `password_hash` — Argon2id PHC, `token_hash` — 32-byte SHA-256; plaintext password/token/hash отсутствуют в API/LB logs; known и unknown user дают одинаковый `401` code/message; тела ошибок не содержат credentials | `evidence/credential-storage.txt`, `evidence/login-dos.txt` |
| Ротация leaf certificate и отзыв identity | `scripts/rotate-pki-leaf.ps1`, `scripts/test-rotated-leaf.ps1`, `scripts/test-mtls.ps1` | PASS: LB leaf перевыпущен без rebuild, старый DER SHA-256 `8b3f0a8d…` добавлен в deny-list; обе API-реплики отвечают `403` на старый leaf и `200` на новый; image ID nginx/API не изменился | `evidence/rotation-renewal.txt` |
| Ротация рабочего secret | `scripts/rotate-grafana-admin-password.ps1` | PASS: Grafana admin password изменён через API, `.env` обновлён, старый пароль отклонён, новый принят, image ID не изменился, значения не печатаются | `evidence/rotation-renewal.txt` |
| Sealed/expiry OpenBao, bootstrap trust и renewal | `scripts/test-openbao-rotation-boundaries.ps1`, `scripts/check-security-lifecycle.ps1`, `scripts/test-openbao-policies.ps1` | PASS: при sealed OpenBao агенты и API продолжают работать на кэшированном rendered env, fresh startup без файла падает за 2.8 c при лимите 2 c; TTL 15m/1h, template 5m, root/unseal/secret «для получения секретов» в образе и репозитории отсутствуют | `evidence/rotation-renewal.txt`, `infra/openbao/README.md` |
| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 28 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 целиком: TLS data plane, persistence/failover, private attachments, sessions и observability | `tests/smoke.py`, `tests/security.py`, `scripts/test-internal-tls.ps1`, `scripts/verify-https-resilience.ps1`, `scripts/test-container-secret-boundaries.ps1` | PASS: публичный HTTPS contract, user/attachment ACL, private bucket, отдельные runtime roles, TLS connections, persistence и one-replica failover проверены; telemetry redaction и отсутствие secret values подтверждены | `evidence/public-security.txt`, `evidence/internal-tls.txt`, `evidence/verify-https-resilience.txt`, `evidence/container-secret-boundaries.txt` |
| Контейнерные исключения и dependency/image scan | `scripts/check-compose-hardening.ps1`, `scripts/scan-dependencies.ps1`, Trivy image scan | PASS: OSV 139 resolved deps → 0 findings после обновлений; Trivy Java HIGH/CRITICAL → 0; оставшиеся OS-находки разобраны по reachability/fix/временным контролям, stateful writable root объяснён | `evidence/dependency-image-scan.txt` |
| Threat model, worker bounds и полный TLS/telemetry audit | `scripts/test-level4-security-audit.ps1`; worker unit tests | PASS: 13 конкретных угроз связаны с контролями/negative tests; вся заявленная TLS-матрица проверена на CA/hostname и no-cert/foreign-CA, role gateways — на same-CA wrong role; data-plane ACL denied; worker ограничен 1 CPU/1 GiB/256 PID, concurrency 2, 40M pixels, 512 MiB processing budget и 60 s; Authorization/body canary отсутствует в logs/Loki/Tempo/Prometheus | `security/THREAT_MODEL.md`, `evidence/level4-security-audit.txt` |
| Выбранный трек 5 | Не заявляется | N/A: целевая оценка 4 | — |
## Эксперименты и отказы ## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. ### Login DoS budget
Гипотеза: общий Redis fixed-window лимит не даёт одному username или одному
ingress-адресу бесконечно запускать дорогой Argon2id, а отказ Redis не
открывает дорогой путь.
Стенд: Docker Desktop, две API-реплики по 0.75 CPU / 768 MiB, nginx HTTPS
ingress, Redis 7.4 по mTLS. Argon2id: 32768 KiB, t=2, p=1; 5 warmup и 21
измерение с уникальной солью. Калибровка: encode p50 100.2 мс / p95 134.8 мс,
verify p50 115.5 мс / p95 165.5 мс. Предыдущий прогон того же скрипта дал
encode p95 150.3 мс и verify p95 142.7 мс, поэтому в расчёте используется
худший из наблюдавшихся p95 verify 165.5 мс.
Black-box через nginx: 5 неверных попыток одного username прошли с `401`
(обе реплики видны в `X-Instance-Id`), 6-я вернула `429` + `Retry-After`.
После окна 60 с 100 попыток с разными username прошли с `401`, 101-я вернула
`429`. В последовательном режиме 401 p50 287.5 мс / p95 490.4 мс, а 429 —
18.7–19.7 мс, то есть лимитер срабатывает до Argon2. Пять одновременных
Argon2-проверок дали p50 1547 мс: это очередь на CPU-лимите 0.75, а не
латентность одной проверки. Расчёт бюджета: 5 × 165.5 мс ≈ 0.83 с Argon2 CPU
на username за окно; 100 × 165.5 мс ≈ 16.55 с, то есть ≈0.276 CPU в среднем
за 60 с при лимите 0.75 CPU. Лимитер ограничивает rate, но не concurrency;
одновременный burst всё ещё может создать очередь. При недоступном Redis
проверка fail-closed, а не пропускает login.
Ограничение: source-ключ сейчас строится по `request.getRemoteAddr()`, то есть
по адресу nginx/LB. Это общий cap для всех клиентов за LB, а не per-client;
основная защита конкретного аккаунта — username-лимит. Trusted-proxy модель
для клиентского адреса остаётся следующим шагом. Fixed window допускает burst
на границе окна; успешные login тоже расходуют бюджет.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | | Перезапуск PostgreSQL, Redis, MinIO, RabbitMQ, worker, двух API и LB без удаления volumes | Существующая сессия и подтверждённые данные доступны после готовности | Сессия повторно не создавалась; сообщение и вложение совпали с исходными | в пределах 180 с / потерь не обнаружено |
| Остановка API-реплики, обслужившей контрольный запрос | LB продолжает направлять запросы на вторую реплику | 7 успешных записей без неуспешных попыток; остановленная реплика отсутствует среди последних ответов | 5.042 с / потерь и дублей не обнаружено |
| 5 неверных login одного username; 100 login с разными username | Argon2 ограничен, следующая попытка — быстрый 429 | 6-я и 101-я попытки → 429 + Retry-After; 429 ≈ 19 мс против 401 p50 287 мс; обе реплики | n/a / budget восстанавливается по TTL окна |
## Ограничения и следующие шаги ## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. - Login source limit использует адрес nginx/LB, поэтому это общий cap для
клиентов за LB, а не per-client. Username-лимит остаётся основной защитой
аккаунта; для per-client нужна trusted-proxy модель с проверкой, что
`X-Forwarded-For` пришёл от доверенного LB.
- Fixed window допускает burst на границе окна и считает успешные login
наравне с неуспешными. Это осознанный компромисс; sliding window или
отдельный счётчик только неуспешных попыток — возможное улучшение.
- Лимитер ограничивает rate, но не concurrency: одновременный burst из
нескольких клиентов может создать очередь на CPU-лимите API. Дополнительный
bulkhead/semaphore вокруг Argon2 остаётся улучшением.
- Argon2id 32768 KiB/t=2/p=1 выбран по измерению на локальном стенде; на
другом hardware профиль нужно перекалибровать и обновить benchmark.
- `MtusiMessengerApplicationTests` — интеграционный тест, которому нужны
доступные PostgreSQL/Redis на localhost; в текущем Compose они не
публикуются. Проверка этого критерия выполнена unit-тестами
`DatabaseAuthenticationProviderTest`/`LoginRateLimiterTest` и black-box
тестами через HTTPS.
- OpenBao использует ручной unseal; bootstrap SecretID имеет TTL 24 часа.
Перед демонстрацией live policy test оператор обновляет SecretID, но не
заменяет его постоянным root credential.
- Loki/Tempo работают в single-tenant режиме: mTLS разделяет ingest/query
identities, но fine-grained query ACL внутри backend остаётся следующим
шагом.
- Trivy после обновления зависимостей показывает 0 Java findings, но Ubuntu
layer сохраняет разобранные OS findings. Их code paths не вызываются
runtime entrypoint; план устранения — регулярная пересборка на обновлённом
digest базового Temurin image.
## Основные источники
- [Spring Security password storage](https://docs.spring.io/spring-security/reference/features/authentication/password-storage.html)
и [OWASP Password Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html)
— выбор Argon2id, rehash и требования к хранению.
- [Docker Compose reference](https://docs.docker.com/reference/compose-file/)
— limits, read-only filesystem, capabilities, tmpfs и security options.
- [PostgreSQL TLS](https://www.postgresql.org/docs/current/ssl-tcp.html),
[Redis TLS](https://redis.io/docs/latest/operate/oss_and_stack/management/security/encryption/)
и [RabbitMQ TLS](https://www.rabbitmq.com/docs/ssl) — transport security.
- [OpenBao AppRole](https://openbao.org/docs/auth/approle/) и
[OpenBao Agent](https://openbao.org/docs/agent-and-proxy/agent/) — bootstrap,
scoped policies, token renewal и file rendering.
- [OpenTelemetry Collector configuration](https://opentelemetry.io/docs/collector/configuration/)
и [W3C Trace Context](https://www.w3.org/TR/trace-context/) — telemetry
pipelines, limits, redaction и propagation.
- [OSV API](https://google.github.io/osv.dev/api/) и
[Trivy vulnerability scanning](https://trivy.dev/latest/docs/scanner/vulnerability/)
— воспроизводимое dependency/image scanning и triage.
+79
View File
@@ -0,0 +1,79 @@
plugins {
id 'java'
id 'org.springframework.boot' version '4.1.1'
id 'io.spring.dependency-management' version '1.1.7'
}
// Override Spring Boot BOM versions only where OSV triage found a fix.
// Each override is re-checked by scripts/scan-dependencies.ps1.
ext['jackson-2-bom.version'] = '2.21.7'
ext['jackson-bom.version'] = '3.1.7'
ext['rabbit-amqp-client.version'] = '5.37.1'
ext['tomcat.version'] = '11.0.25'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(23)
}
}
repositories {
mavenCentral()
}
dependencies {
// implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-amqp'
implementation 'org.springframework.boot:spring-boot-flyway'
implementation 'org.flywaydb:flyway-core'
implementation 'org.flywaydb:flyway-database-postgresql'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.bouncycastle:bcprov-jdk18on:1.85'
// MinIO 8.6.0 pulls older Guava/snappy-java; pin the patched releases.
implementation 'com.google.guava:guava:33.7.2-jre'
implementation 'org.xerial.snappy:snappy-java:1.1.10.9'
implementation 'org.apache.commons:commons-pool2'
implementation 'io.minio:minio:8.6.0'
implementation 'net.coobird:thumbnailator:0.4.20'
implementation 'org.sejda.imageio:webp-imageio:0.1.6'
// The runtime SDK is supplied by the pinned OpenTelemetry Java agent.
// The API dependency keeps custom business metrics vendor-neutral.
implementation 'io.opentelemetry:opentelemetry-api:1.67.0'
runtimeOnly 'org.postgresql:postgresql'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.3'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
// testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test'
// testImplementation 'org.springframework.boot:spring-boot-starter-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
testCompileOnly 'org.projectlombok:lombok'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testAnnotationProcessor 'org.projectlombok:lombok'
implementation("com.github.f4b6a3:uuid-creator:6.1.1")
}
tasks.named('test') {
useJUnitPlatform()
}
tasks.register('argon2Benchmark', JavaExec) {
group = 'verification'
description = 'Measures Argon2id encode/verify latency without printing hashes or passwords.'
dependsOn testClasses
classpath = sourceSets.test.runtimeClasspath
mainClass = 'com.example.mtusi_messenger.config.Argon2Benchmark'
}
+792
View File
@@ -0,0 +1,792 @@
name: hla-lab7
x-api-environment: &api-environment
APP_HOST: 0.0.0.0
APP_PORT: 8080
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-gateway:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_TRACES_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_LOGS_EXPORTER: otlp
OTEL_PROPAGATORS: tracecontext,baggage
OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false}
OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-parentbased_traceidratio}
OTEL_TRACES_SAMPLER_ARG: ${OTEL_TRACES_SAMPLER_ARG:-0.25}
OTEL_METRIC_EXPORT_INTERVAL: ${OTEL_METRIC_EXPORT_INTERVAL:-30000}
OTEL_BSP_MAX_QUEUE_SIZE: ${OTEL_BSP_MAX_QUEUE_SIZE:-2048}
OTEL_BSP_MAX_EXPORT_BATCH_SIZE: ${OTEL_BSP_MAX_EXPORT_BATCH_SIZE:-512}
OTEL_BSP_EXPORT_TIMEOUT: ${OTEL_BSP_EXPORT_TIMEOUT:-5000}
OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: ${OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:-256}
OTEL_RESOURCE_ATTRIBUTES: service.version=0.0.1,deployment.environment.name=${APP_ENV:-lab}
SERVICE_TLS_CA: /run/pki/service-ca/ca.crt
OTEL_INSTRUMENTATION_LOGBACK_APPENDER_EXPERIMENTAL_MDC_ATTRIBUTES_INCLUDED: request_id
OTEL_INSTRUMENTATION_COMMON_LOGGING_STRUCTURED_ATTRIBUTES_INCLUDED: event,job.type,outcome,attempt,error.code,http.request.method,http.route,http.response.status_code
OTEL_INSTRUMENTATION_HTTP_SERVER_CAPTURE_REQUEST_HEADERS: ""
OTEL_INSTRUMENTATION_HTTP_SERVER_CAPTURE_RESPONSE_HEADERS: ""
DATABASE_URL: jdbc:postgresql://postgres:5432/${DATABASE_NAME:-messenger}?sslmode=verify-full&sslrootcert=/run/pki/service-ca/ca.crt
DATABASE_POOL_SIZE: ${DATABASE_POOL_SIZE:-10}
DATABASE_MIN_IDLE: ${DATABASE_MIN_IDLE:-2}
DATABASE_QUERY_TIMEOUT_SECONDS: ${DATABASE_QUERY_TIMEOUT_SECONDS:-5}
DATABASE_TRANSACTION_TIMEOUT_SECONDS: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:-5}
REDIS_HOST: redis
REDIS_PORT: 6379
REDIS_SSL_ENABLED: "true"
REDIS_CONNECT_TIMEOUT: ${REDIS_CONNECT_TIMEOUT:-5s}
REDIS_COMMAND_TIMEOUT: ${REDIS_COMMAND_TIMEOUT:-2s}
REDIS_POOL_MAX_ACTIVE: ${REDIS_POOL_MAX_ACTIVE:-8}
REDIS_POOL_MAX_IDLE: ${REDIS_POOL_MAX_IDLE:-8}
REDIS_POOL_MIN_IDLE: ${REDIS_POOL_MIN_IDLE:-0}
REDIS_POOL_MAX_WAIT: ${REDIS_POOL_MAX_WAIT:-500ms}
USER_CACHE_TTL_SECONDS: ${USER_CACHE_TTL_SECONDS:-300}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
SESSION_MAXIMUM_ACTIVE: ${SESSION_MAXIMUM_ACTIVE:-3}
LOGIN_ATTEMPTS_PER_USERNAME: ${LOGIN_ATTEMPTS_PER_USERNAME:-5}
LOGIN_ATTEMPTS_PER_SOURCE: ${LOGIN_ATTEMPTS_PER_SOURCE:-100}
LOGIN_RATE_WINDOW_SECONDS: ${LOGIN_RATE_WINDOW_SECONDS:-60}
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-32768}
ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2}
ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
S3_ENDPOINT: https://minio:9000
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
MAX_CONCURRENT_UPLOADS: ${MAX_CONCURRENT_UPLOADS:-3}
UPLOAD_PERMIT_WAIT_MILLIS: ${UPLOAD_PERMIT_WAIT_MILLIS:-10000}
RABBITMQ_HOST: rabbitmq
RABBITMQ_PORT: 5671
RABBITMQ_SSL_ENABLED: "true"
RABBITMQ_VHOST: ${RABBITMQ_VHOST:-/}
ATTACHMENT_JOB_EXCHANGE: ${ATTACHMENT_JOB_EXCHANGE:-attachments.v1}
ATTACHMENT_JOB_QUEUE: ${ATTACHMENT_JOB_QUEUE:-attachments.process.level4.v1}
ATTACHMENT_JOB_ROUTING_KEY: ${ATTACHMENT_JOB_ROUTING_KEY:-attachment.process.v1}
ATTACHMENT_DLQ_EXCHANGE: ${ATTACHMENT_DLQ_EXCHANGE:-attachments.dlx.v1}
ATTACHMENT_DLQ_QUEUE: ${ATTACHMENT_DLQ_QUEUE:-attachments.failed.v1}
ATTACHMENT_DLQ_ROUTING_KEY: ${ATTACHMENT_DLQ_ROUTING_KEY:-attachment.failed.v1}
ATTACHMENT_PIPELINE_VERSION: ${ATTACHMENT_PIPELINE_VERSION:-2}
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
WORKER_PREFETCH: ${WORKER_PREFETCH:-1}
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
JOB_RETRY_BASE_DELAY: ${JOB_RETRY_BASE_DELAY:-1s}
JOB_RETRY_MAX_DELAY: ${JOB_RETRY_MAX_DELAY:-30s}
JOB_TIMEOUT: ${JOB_TIMEOUT:-60s}
JOB_LEASE_DURATION: ${JOB_LEASE_DURATION:-90s}
JOB_LEASE_REAPER_INTERVAL: ${JOB_LEASE_REAPER_INTERVAL:-5s}
WORKER_MAX_IMAGE_PIXELS: ${WORKER_MAX_IMAGE_PIXELS:-40000000}
WORKER_MEMORY_BUDGET_BYTES: ${WORKER_MEMORY_BUDGET_BYTES:-536870912}
WORKER_MEMORY_WAIT: ${WORKER_MEMORY_WAIT:-2s}
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
ATTACHMENT_CLEANUP_GRACE_SECONDS: ${ATTACHMENT_CLEANUP_GRACE_SECONDS:-3600}
ATTACHMENT_CLEANUP_DRY_RUN: ${ATTACHMENT_CLEANUP_DRY_RUN:-false}
ATTACHMENT_RECONCILE_INTERVAL_MILLIS: ${ATTACHMENT_RECONCILE_INTERVAL_MILLIS:-600000}
ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS: ${ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS:-60000}
x-runtime-hardening: &runtime-hardening
security_opt: ["no-new-privileges:true"]
pids_limit: 256
services:
openbao:
<<: *runtime-hardening
image: ghcr.io/openbao/openbao:2.7.3
user: "0:0"
command: ["server"]
environment:
BAO_ADDR: https://openbao:8200
BAO_CACERT: /run/pki/service-ca/ca.crt
ports:
- "127.0.0.1:${OPENBAO_PORT:-8200}:8200"
volumes:
- openbao-data:/openbao/file
- ./infra/openbao/openbao.hcl:/openbao/config/openbao.hcl:ro
- ./infra/openbao/api-policy.hcl:/openbao/policies/api-policy.hcl:ro
- ./infra/openbao/worker-policy.hcl:/openbao/policies/worker-policy.hcl:ro
- ./secrets/pki:/run/pki:ro
cap_drop: [ALL]
cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, KILL, SETGID, SETUID]
read_only: true
tmpfs: ["/tmp:size=32m,mode=1777"]
restart: unless-stopped
cpus: 0.5
mem_limit: 512m
healthcheck:
test: ["CMD-SHELL", "bao status >/dev/null 2>&1; code=$$?; test $$code -eq 0 -o $$code -eq 2"]
interval: 5s
timeout: 3s
retries: 30
networks: [backend]
openbao-agent-api:
<<: *runtime-hardening
image: ghcr.io/openbao/openbao:2.7.3
user: "0:0"
command: ["agent", "-config=/openbao/config/agent.hcl"]
environment:
BAO_SKIP_DROP_ROOT: "true"
SKIP_CHOWN: "true"
depends_on:
openbao:
condition: service_started
volumes:
- ./infra/openbao/agent-api.hcl:/openbao/config/agent.hcl:ro
- ./secrets/pki:/run/pki:ro
- ./secrets/openbao/api:/run/bootstrap:ro
- api-runtime-secrets:/run/rendered
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=32m,mode=1777"]
restart: unless-stopped
cpus: 0.25
mem_limit: 128m
networks: [backend]
openbao-agent-worker:
<<: *runtime-hardening
image: ghcr.io/openbao/openbao:2.7.3
user: "0:0"
command: ["agent", "-config=/openbao/config/agent.hcl"]
environment:
BAO_SKIP_DROP_ROOT: "true"
SKIP_CHOWN: "true"
depends_on:
openbao:
condition: service_started
volumes:
- ./infra/openbao/agent-worker.hcl:/openbao/config/agent.hcl:ro
- ./secrets/pki:/run/pki:ro
- ./secrets/openbao/worker:/run/bootstrap:ro
- worker-runtime-secrets:/run/rendered
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=32m,mode=1777"]
restart: unless-stopped
cpus: 0.25
mem_limit: 128m
networks: [backend]
postgres:
<<: *runtime-hardening
image: postgres:16.4-bookworm
environment:
POSTGRES_DB: ${DATABASE_NAME:-messenger}
POSTGRES_USER: ${DATABASE_USER:-messenger}
POSTGRES_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env}
DATABASE_API_PASSWORD: ${DATABASE_API_PASSWORD:?Set DATABASE_API_PASSWORD in .env}
DATABASE_WORKER_PASSWORD: ${DATABASE_WORKER_PASSWORD:?Set DATABASE_WORKER_PASSWORD in .env}
DATABASE_MIGRATION_PASSWORD: ${DATABASE_MIGRATION_PASSWORD:?Set DATABASE_MIGRATION_PASSWORD in .env}
volumes:
- postgres-data:/var/lib/postgresql/data
- ./secrets/pki:/run/pki:ro
- ./infra/postgres/entrypoint-tls.sh:/usr/local/bin/entrypoint-tls:ro
- ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
- ./infra/postgres/01-roles.sh:/docker-entrypoint-initdb.d/01-roles.sh:ro
entrypoint: ["/bin/sh", "/usr/local/bin/entrypoint-tls"]
healthcheck:
test: ["CMD-SHELL", "PGSSLMODE=verify-full PGSSLROOTCERT=/run/pki/service-ca/ca.crt pg_isready -h postgres -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 2s
timeout: 2s
retries: 30
restart: unless-stopped
cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT]
tmpfs: ["/tmp:size=64m,mode=1777"]
cpus: 1.0
mem_limit: 768m
networks: [backend]
redis:
<<: *runtime-hardening
image: redis:7.4-bookworm
environment:
REDIS_API_PASSWORD: ${REDIS_API_PASSWORD:?Set REDIS_API_PASSWORD in .env}
REDIS_WORKER_PASSWORD: ${REDIS_WORKER_PASSWORD:?Set REDIS_WORKER_PASSWORD in .env}
entrypoint: ["/bin/sh", "-c"]
command:
- |
set -eu
umask 077
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
- ./secrets/pki:/run/pki:ro
healthcheck:
test: ["CMD-SHELL", "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\" ping | grep PONG"]
interval: 2s
timeout: 2s
retries: 30
restart: unless-stopped
cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT]
tmpfs: ["/tmp:size=16m,mode=1777"]
cpus: 0.25
mem_limit: 256m
networks: [backend]
rabbitmq:
<<: *runtime-hardening
image: rabbitmq:4.1.4-management-alpine
environment:
RABBITMQ_DEFAULT_USER: ${RABBITMQ_ADMIN_USER:-operator}
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_ADMIN_PASSWORD:?Set RABBITMQ_ADMIN_PASSWORD in .env}
RABBITMQ_DEFAULT_VHOST: ${RABBITMQ_VHOST:-/}
RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: "+S 2:2"
volumes:
- rabbitmq-data:/var/lib/rabbitmq
- ./secrets/pki:/run/pki:ro
- ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 10s
timeout: 10s
start_period: 60s
retries: 12
restart: unless-stopped
cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT]
tmpfs: ["/tmp:size=64m,mode=1777"]
cpus: 0.5
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
depends_on:
rabbitmq:
condition: service_healthy
environment:
ADMIN_USER: ${RABBITMQ_ADMIN_USER:-operator}
ADMIN_PASSWORD: ${RABBITMQ_ADMIN_PASSWORD:?Set RABBITMQ_ADMIN_PASSWORD in .env}
API_PASSWORD: ${RABBITMQ_API_PASSWORD:?Set RABBITMQ_API_PASSWORD in .env}
WORKER_PASSWORD: ${RABBITMQ_WORKER_PASSWORD:?Set RABBITMQ_WORKER_PASSWORD in .env}
volumes:
- ./secrets/pki/service-ca/ca.crt:/run/ca.crt:ro
entrypoint: ["/bin/sh", "-c"]
command:
- |
set -eu
base=https://rabbitmq:15671/api
auth="$$ADMIN_USER:$$ADMIN_PASSWORD"
curl --fail --silent --show-error --cacert /run/ca.crt -u "$$auth" -H content-type:application/json -X PUT "$$base/users/messenger-api" -d "{\"password\":\"$$API_PASSWORD\",\"tags\":\"\"}"
curl --fail --silent --show-error --cacert /run/ca.crt -u "$$auth" -H content-type:application/json -X PUT "$$base/users/messenger-worker" -d "{\"password\":\"$$WORKER_PASSWORD\",\"tags\":\"\"}"
curl --fail --silent --show-error --cacert /run/ca.crt -u "$$auth" -H content-type:application/json -X PUT "$$base/permissions/%2F/messenger-api" -d '{"configure":"^attachments\\..*","write":"^attachments\\..*","read":"^attachments\\.(v1|dlx\\.v1)$"}'
curl --fail --silent --show-error --cacert /run/ca.crt -u "$$auth" -H content-type:application/json -X PUT "$$base/permissions/%2F/messenger-worker" -d '{"configure":"^attachments\\..*","write":"^attachments\\..*","read":"^attachments\\..*"}'
restart: "no"
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=16m,mode=1777"]
cpus: 0.25
mem_limit: 128m
networks: [backend]
minio:
<<: *runtime-hardening
image: bitnamilegacy/minio:2025.4.22-debian-12-r1@sha256:d7cd0e172c4cc0870f4bdc3142018e2a37be9acf04d68f386600daad427e0cab
environment:
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
MINIO_SCHEME: https
MINIO_CERTS_DIR: /certs
# The dedicated minio-init service owns bucket/user/policy bootstrap.
MINIO_SKIP_CLIENT: "yes"
volumes:
- minio-data:/bitnami/minio/data
- ./secrets/pki/minio/tls.crt:/certs/public.crt:ro
- ./secrets/pki/minio/tls.key:/certs/private.key:ro
- ./secrets/pki/service-ca/ca.crt:/certs/CAs/ca.crt:ro
healthcheck:
test: ["CMD", "curl", "--fail", "--silent", "--cacert", "/certs/CAs/ca.crt", "https://minio:9000/minio/health/live"]
interval: 2s
timeout: 2s
retries: 30
restart: unless-stopped
cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT]
tmpfs: ["/tmp:size=32m,mode=1777"]
cpus: 0.75
mem_limit: 512m
networks: [backend]
minio-init:
<<: *runtime-hardening
image: bitnamilegacy/minio-client:2025.4.16-debian-12-r0@sha256:28e38f52642c06a2344fa974cf55786b4c52601b6b9b0676c68d40ee0876a5bc
depends_on:
minio:
condition: service_healthy
environment:
MC_CONFIG_DIR: /tmp/mc
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
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:
- ./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:
- |
set -eu
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" \
&& mc anonymous set none "local/$$S3_BUCKET" \
&& (mc admin user add -- local "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY" \
|| 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-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
echo "MinIO bootstrap did not complete after 30 attempts" >&2
exit 1
fi
sleep 2
done
restart: "no"
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=32m,mode=1777"]
cpus: 0.25
mem_limit: 128m
networks: [backend]
private-bucket-check:
<<: *runtime-hardening
profiles: ["verification"]
image: bitnamilegacy/minio-client:2025.4.16-debian-12-r0@sha256:28e38f52642c06a2344fa974cf55786b4c52601b6b9b0676c68d40ee0876a5bc
depends_on:
minio-init:
condition: service_completed_successfully
environment:
MC_CONFIG_DIR: /tmp/mc
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"]
command:
- |
set -eu
mkdir -p "$$MC_CONFIG_DIR/certs/CAs"
cp /run/ca.crt "$$MC_CONFIG_DIR/certs/CAs/service-ca.crt"
mc alias set -- anonymous https://minio:9000
if mc ls "anonymous/$$S3_BUCKET" >/dev/null 2>&1; then
echo "FAIL: anonymous bucket listing succeeded" >&2
exit 1
fi
mc alias set -- restricted https://minio:9000 "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY"
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
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
tmpfs: ["/tmp:size=16m,mode=1777"]
cpus: 0.25
mem_limit: 128m
networks: [backend]
# One-shot Flyway runner. It is invoked explicitly before API replicas.
migrate:
<<: *runtime-hardening
image: hla-lab7-app:local
build:
context: .
environment:
<<: *api-environment
FLYWAY_ENABLED: "true"
MIGRATE_ONLY: "true"
MESSENGER_ROLE: migration
SPRING_MAIN_WEB_APPLICATION_TYPE: none
OTEL_SDK_DISABLED: "true"
DATABASE_USER: messenger_migration
DATABASE_PASSWORD: ${DATABASE_MIGRATION_PASSWORD:?Set DATABASE_MIGRATION_PASSWORD in .env}
CLIENT_TLS_CERTIFICATE: /run/pki/migration-client/tls.crt
CLIENT_TLS_PRIVATE_KEY: /run/pki/migration-client/tls.key
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
rabbitmq:
condition: service_healthy
volumes:
- ./secrets/pki:/run/pki:ro
restart: "no"
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=128m,mode=1777"]
cpus: 0.75
mem_limit: 768m
networks: [backend]
api:
<<: *runtime-hardening
image: hla-lab7-app:local
build:
context: .
environment:
<<: *api-environment
FLYWAY_ENABLED: "false"
MESSENGER_ROLE: api
OTEL_SERVICE_NAME: messenger-api
APP_PORT: 8443
SERVER_SSL_ENABLED: "true"
SERVER_SSL_CERTIFICATE: /run/pki/api/tls.crt
SERVER_SSL_PRIVATE_KEY: /run/pki/api/tls.key
SERVER_SSL_TRUST_CERTIFICATE: /run/pki/lb-client-ca/ca.crt
SERVER_SSL_CLIENT_AUTH: need
MTLS_ALLOWED_CLIENT_URI: spiffe://hla-lab7/lb
MTLS_REVOKED_CERTIFICATES_FILE: /run/pki/revoked-client-sha256.txt
DATABASE_USER: messenger_api
CLIENT_TLS_CERTIFICATE: /run/pki/api-client/tls.crt
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
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/pki/api-client/tls.key
FAULT_CRASH_AFTER_OUTBOX_COMMIT: ${FAULT_CRASH_AFTER_OUTBOX_COMMIT:-false}
depends_on:
migrate:
condition: service_completed_successfully
redis:
condition: service_healthy
minio-init:
condition: service_completed_successfully
rabbitmq-init:
condition: service_completed_successfully
rabbit-api-gateway:
condition: service_started
otel-gateway:
condition: service_started
openbao-agent-api:
condition: service_started
volumes:
- ./secrets/pki:/run/pki:ro
- api-runtime-secrets:/run/openbao:ro
healthcheck:
disable: true
init: true
stop_grace_period: 12s
restart: unless-stopped
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=128m,mode=1777"]
cpus: 0.75
mem_limit: 768m
networks: [backend]
worker:
<<: *runtime-hardening
image: hla-lab7-app:local
environment:
<<: *api-environment
FLYWAY_ENABLED: "false"
MESSENGER_ROLE: worker
OTEL_SERVICE_NAME: messenger-worker
SPRING_MAIN_WEB_APPLICATION_TYPE: none
JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=70 -Djava.io.tmpdir=/tmp/native
DATABASE_USER: messenger_worker
CLIENT_TLS_CERTIFICATE: /run/pki/worker-client/tls.crt
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
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/pki/worker-client/tls.key
FAULT_CRASH_BEFORE_SIDE_EFFECT: ${FAULT_CRASH_BEFORE_SIDE_EFFECT:-false}
FAULT_CRASH_AFTER_SIDE_EFFECT: ${FAULT_CRASH_AFTER_SIDE_EFFECT:-false}
FAULT_CRASH_AFTER_RESULT_COMMIT: ${FAULT_CRASH_AFTER_RESULT_COMMIT:-false}
depends_on:
migrate:
condition: service_completed_successfully
minio-init:
condition: service_completed_successfully
rabbitmq-init:
condition: service_completed_successfully
rabbit-worker-gateway:
condition: service_started
otel-gateway:
condition: service_started
openbao-agent-worker:
condition: service_started
healthcheck:
disable: true
volumes:
- ./secrets/pki:/run/pki:ro
- worker-runtime-secrets:/run/openbao:ro
init: true
stop_grace_period: 20s
restart: unless-stopped
cap_drop: [ALL]
read_only: true
tmpfs:
- /tmp:size=192m,mode=1777
# webp-imageio extracts its native codec here; keep executable temp scoped to the worker.
- /tmp/native:size=64m,mode=1777,exec
cpus: 1.0
mem_limit: 1024m
networks: [backend]
nginx:
<<: *runtime-hardening
image: nginx:1.27.4-bookworm
ports:
- "${PUBLIC_BIND_ADDRESS:-127.0.0.1}:${PUBLIC_HTTPS_PORT:-8443}:8443"
volumes:
- ./infra/nginx.conf:/etc/nginx/nginx.conf:ro
- ./secrets/pki:/run/pki:ro
depends_on:
api:
condition: service_started
healthcheck:
test: ["CMD", "nginx", "-t"]
interval: 2s
timeout: 2s
retries: 15
stop_grace_period: 10s
restart: unless-stopped
user: "101:101"
cap_drop: [ALL]
read_only: true
tmpfs:
- /var/cache/nginx:size=32m,mode=1777
- /var/log/nginx:size=16m,mode=1777
- /var/run:size=4m,mode=1777
- /tmp:size=16m,mode=1777
cpus: 0.25
mem_limit: 128m
networks: [backend]
otel-collector:
<<: *runtime-hardening
image: otel/opentelemetry-collector-contrib:0.165.0
command: ["--config=/etc/otelcol-contrib/collector.yaml"]
volumes:
- ./infra/otel/collector.yaml:/etc/otelcol-contrib/collector.yaml:ro
- ./secrets/pki:/run/pki:ro
depends_on:
prometheus:
condition: service_started
loki:
condition: service_started
tempo:
condition: service_started
restart: unless-stopped
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=32m,mode=1777"]
cpus: 0.5
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
command:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=3d
- --web.enable-lifecycle
- --web.config.file=/etc/prometheus/web.yaml
volumes:
- ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yml:ro
- ./infra/otel/prometheus-alerts.yaml:/etc/prometheus/prometheus-alerts.yaml:ro
- ./infra/otel/prometheus-web.yaml:/etc/prometheus/web.yaml:ro
- ./secrets/pki:/run/pki:ro
- prometheus-data:/prometheus
restart: unless-stopped
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=32m,mode=1777"]
cpus: 0.5
mem_limit: 512m
networks: [backend]
loki:
<<: *runtime-hardening
image: grafana/loki:3.7.8
command: ["-config.file=/etc/loki/local-config.yaml"]
volumes:
- ./infra/otel/loki.yaml:/etc/loki/local-config.yaml:ro
- ./secrets/pki:/run/pki:ro
- loki-data:/loki
restart: unless-stopped
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=32m,mode=1777"]
cpus: 0.5
mem_limit: 512m
networks: [backend]
tempo:
<<: *runtime-hardening
image: grafana/tempo:3.1.1
command: ["-config.file=/etc/tempo/tempo.yaml"]
volumes:
- ./infra/otel/tempo.yaml:/etc/tempo/tempo.yaml:ro
- ./secrets/pki:/run/pki:ro
- tempo-data:/var/tempo
restart: unless-stopped
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=32m,mode=1777"]
cpus: 0.5
mem_limit: 512m
networks: [backend]
grafana:
<<: *runtime-hardening
image: grafana/grafana:13.3.0
ports:
- "127.0.0.1:${GRAFANA_PORT:-3000}:3000"
environment:
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:-admin}
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD in .env}
GF_USERS_ALLOW_SIGN_UP: "false"
GF_AUTH_ANONYMOUS_ENABLED: "false"
GF_UNIFIED_ALERTING_ENABLED: "true"
GF_SERVER_PROTOCOL: https
GF_SERVER_CERT_FILE: /run/pki/grafana/tls.crt
GF_SERVER_CERT_KEY: /run/pki/grafana/tls.key
SSL_CERT_FILE: /run/pki/service-ca/ca.crt
entrypoint: ["/bin/sh", "/etc/grafana/grafana-entrypoint.sh"]
volumes:
- ./infra/otel/grafana/provisioning:/etc/grafana/provisioning:ro
- ./infra/otel/grafana/dashboards:/var/lib/grafana/dashboards:ro
- ./infra/otel/grafana-entrypoint.sh:/etc/grafana/grafana-entrypoint.sh:ro
- grafana-data:/var/lib/grafana
- ./secrets/pki:/run/pki:ro
depends_on:
prometheus:
condition: service_started
loki:
condition: service_started
tempo:
condition: service_started
restart: unless-stopped
cap_drop: [ALL]
read_only: true
tmpfs: ["/tmp:size=64m,mode=1777"]
cpus: 0.5
mem_limit: 512m
networks: [backend]
networks:
backend:
driver: bridge
volumes:
openbao-data:
api-runtime-secrets:
worker-runtime-secrets:
postgres-data:
redis-data:
minio-data:
rabbitmq-data:
prometheus-data:
loki-data:
tempo-data:
grafana-data:
+106 -27
View File
@@ -1,37 +1,116 @@
# Матрица доверия — заполнить в решении lab7 # Матрица доверия HLA Lab 7
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. Матрица фиксирует целевую архитектуру и текущее покрытие. **PASS** — контроль реализован; **PARTIAL** — реализована часть; **GAP** — связь пока не удовлетворяет минимуму lab7. Docker-сеть сама по себе не является аутентификацией.
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | Имена 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.
Все перечисленные продукты поддерживают 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 с отрицательным тестом.
## Основные связи
| Связь | Endpoint / порт | Протокол и server trust | Client identity и минимальные права | Lifecycle | Проверяемый отказ / доказательство | Статус |
| --- | --- | --- | --- | --- | --- | --- |
| Клиент → nginx | `https://localhost:8443` | TLS 1.2/1.3; `secrets/pki/public-ca/ca.crt`; SAN `localhost`; hostname verification | Public registration/health, Basic login, Bearer business API; `X-User-Id` не identity | Session 3600 s, максимум 3 активных; logout/replacement/expiry revoke access; leaf 30 d | `make test-security`, `make test-session-expiry`, `scripts/measure-login-dos.ps1 -SourceBudget`; пустой trust store → certificate error; revoked/expired token → 401; login burst → 429 + Retry-After; rehash и dummy hash — unit tests | **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 и deny-list DER SHA-256 до auth проверяет `TrustedClientCertificateFilter`; API port не публикуется | Leaf 30 d, rotation/revocation без rebuild; unreadable deny-list fail-closed | `scripts/test-mtls.ps1` проверяет каждую реплику: no cert и foreign CA отклоняются handshake; trusted cert SAN `.../worker` получает 403; `scripts/test-rotated-leaf.ps1`: старый LB leaf → 403, новый → 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-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 | `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-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** |
| 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`: 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; bootstrap и rendered volumes не общие между ролями | Agent рендерит только 5 allowlisted credential keys; app mount read-only; root/unseal/BAO token отсутствуют | Render interval 5 min; приложение перечитывает при restart | `test-openbao-runtime-boundaries.ps1`: общий volume, writable mount, operator env/material или неожиданный key → FAIL | **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** |
### Ротация, отзыв и обновление доверия
| Контроль | Реализация | Проверка | Статус |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | | Leaf rotation без rebuild | `scripts/rotate-pki-leaf.ps1` выпускает новый leaf тем же service CA, архивирует старый комплект и записывает только его DER SHA-256 в `/run/pki/revoked-client-sha256.txt`; image ID не меняется | `scripts/test-rotated-leaf.ps1`: 2 реплики → old 403 / new 200; `scripts/test-mtls.ps1` остаётся PASS | **PASS** |
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | | Отзыв старой identity | `TrustedClientCertificateFilter` сверяет отпечаток client leaf с deny-list при каждом запросе; отсутствие/нечитаемость файла при явной конфигурации отзывает все identity | unit test на revoked fingerprint; runtime probe старого LB leaf → 403 | **PASS** |
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | | Ротация рабочего secret | `scripts/rotate-grafana-admin-password.ps1` меняет пароль через Grafana API, обновляет `.env`, пересоздаёт только контейнер, проверяет old/new и не печатает значения | `evidence/rotation-renewal.txt`: old rejected, new accepted, image unchanged | **PASS** |
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | | Bootstrap trust | Operator init создаёт 3 Shamir shares (порог 2) и root token вне репозитория; `bootstrap-openbao.ps1` создаёт scoped policies/AppRoles/KV и записывает RoleID/SecretID только в `secrets/` | `scripts/test-openbao-policies.ps1`, `scripts/test-openbao-runtime-boundaries.ps1`, `scripts/check-security-lifecycle.ps1` | **PASS** |
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | | Renewal и sealed/expiry | Service token 15 min/max 1 h, Agent auto-auth и template 5 min, `exit_on_retry_failure=false`; sealed OpenBao не снимает уже выданные runtime credentials; fresh startup без rendered file завершается по таймауту | `scripts/test-openbao-rotation-boundaries.ps1`: agents Up, health 200, fail-closed за 2.8 c при лимите 2 c | **PASS** |
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. ### Пароли, сессии и login DoS
## Обязательные отрицательные проверки | Контроль | Реализация | Проверка | Статус |
| --- | --- | --- | --- |
| Password storage | Argon2id PHC 32768 KiB/t=2/p=1, уникальная 16-byte salt; параметры проверяются при старте | `PasswordConfigTest`; `benchmark-argon2.ps1`; `credential_storage.py` проверяет префикс PHC и отсутствие plaintext | **PASS** |
| Rehash при успешном login | `upgradeEncoding` + CAS `replacePasswordHash(userId, expectedHash, newHash)`; неверный пароль/unknown/current hash не переписываются | `DatabaseAuthenticationProviderTest` (5 тестов) | **PASS** |
| Session token storage | 32 random bytes, base64url; в БД только 32-byte SHA-256 `token_hash`; TTL и максимум 3 активных сессии | `AuthenticationServiceTest`; `credential_storage.py` сверяет SHA-256 и отсутствие token в БД/логах | **PASS** |
| Error non-disclosure | Единые `401 unauthorized`, `429 rate_limited`, `503 unavailable`; known/unknown user не различаются; тела ошибок без credentials | `login_dos.py`; `credential_storage.py`; redaction `authorization`/body в telemetry | **PASS** |
| Shared login limit | Redis Lua atomic fixed window: 5/username/60 s и 100/source/60 s; ключи — SHA-256 digests; обе реплики используют один Redis | `LoginRateLimiterTest`; `measure-login-dos.ps1 -SourceBudget` (обе реплики в `X-Instance-Id`) | **PASS** |
| Redis outage | Fail-closed `AuthenticationServiceException` → `503`, дорогой Argon2 не запускается | `LoginRateLimiterTest`; runtime можно проверить остановкой Redis | **PASS** |
| Measured DoS budget | p95 verify 165.5 мс при 0.75 CPU/768 MiB; 5 × p95 ≈ 0.83 s CPU на username/окно; 100 × p95 ≈ 16.55 s CPU на source/окно (≈0.276 CPU в среднем); 429 ≈ 19 мс без Argon2 | `benchmark-argon2.ps1`; `measure-login-dos.ps1 -SourceBudget`; `evidence/login-dos.txt` | **PASS** |
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». Ограничение: source-ключ строится по `request.getRemoteAddr()`, то есть по
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. адресу nginx/LB. Это общий cap для всех клиентов за LB, не per-client;
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. username-лимит остаётся основной защитой аккаунта. Fixed window допускает
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. burst на границе окна; лимитер ограничивает rate, но не concurrency.
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
## Bootstrap и эксплуатация ### Контейнерная изоляция и supply chain
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. | Контроль | Реализация | Проверка | Статус |
| --- | --- | --- | --- |
| Read-only root и capability drop | Stateless-сервисы используют `read_only: true` и `cap_drop: ALL`; везде `no-new-privileges:true`, CPU/RAM/PID limits и отдельный tmpfs | `scripts/check-compose-hardening.ps1` проверяет каждый сервис из `docker compose config`; `scripts/test-container-secret-boundaries.ps1` сверяет runtime | **PASS** |
| Stateful writable-root исключения | Только postgres, redis, rabbitmq и minio сохраняют writable root: их entrypoints перед сменой UID подготавливают persistent named volume. Drop шести опасных capabilities и `no-new-privileges` сохранены; tmpfs выделен отдельно | Скрипт печатает причину каждого исключения и требует ожидаемый data volume; вывод в `evidence/dependency-image-scan.txt` | **PASS (4 объяснённых исключения)** |
| Dependency/image scan | OSV по Gradle `runtimeClasspath`; Trivy по собранному `hla-lab7-app:local`. Для каждого HIGH/CRITICAL указаны package/version, reachability, fix и временный контроль | `scripts/scan-dependencies.ps1 -FailOnHigh`; Trivy command и разбор в `evidence/dependency-image-scan.txt` | **PASS** |
| Upload-worker resource bounds | Container: 1 CPU, 1 GiB, 256 PID; process: concurrency 2/prefetch 1, 40M pixels, 512 MiB fair semaphore, 2 s permit wait, 60 s job timeout и lease 90 s | `scripts/test-worker-resource-bounds.ps1`; `ImageVariantProcessorTest`; `AttachmentWorkerLimitsTest` | **PASS** |
| Telemetry non-disclosure canary | Header/body capture выключен; Collector удаляет Authorization, request/response/message bodies, DB parameters и query во всех pipelines | `scripts/test-telemetry-redaction.ps1`: canary отсутствует в container logs, Loki, Tempo sensitive tags и Prometheus labels | **PASS** |
OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии. ## Health, scrape и bootstrap
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым 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 | 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 ещё ручная |
## Обязательные отрицательные сценарии
Каждый тест сохраняет команду, 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.
- `scripts/test-container-secret-boundaries.ps1` проверяет rendered Compose и runtime: нет privileged/host network/Docker socket, API/worker имеют UID != 0, `cap_drop: ALL`, read-only rootfs, private tmpfs и CPU/RAM/PID limits. Единственные host bindings — TLS ingress и loopback OpenBao/Grafana. Stateful writable-root исключения и их причины перечислены выше.
- Та же проверка без печати значений сопоставляет локальные secret values с tracked text, metadata/filesystem application image и последними container logs. Collector удаляет Authorization, bodies, query и DB parameters во всех трёх pipelines; HTTP header capture у API/worker выключен.
- Владелец 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. Автоматизировать rotation runtime credentials MinIO с overlap/reconnect.
3. Добавить отдельную узкую operator policy для ротации AppRole вместо root token после первичного bootstrap.
4. Добавить backend query-level ACL поверх уже включённого telemetry mTLS.
5. Расширить rotation tests; TLS/no-cert и runtime ACL для внутренних сервисов проверяет `scripts/test-internal-tls.ps1`.
+21
View File
@@ -0,0 +1,21 @@
Container and secret boundary verification
Date: 2026-11-27 (Europe/Moscow)
Command:
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/test-container-secret-boundaries.ps1
Observed:
PASS: runtime isolation, non-root app/worker, resource and port boundaries,
Git/image/log secret isolation, and telemetry redaction are enforced.
Checked 14 local secret values without printing them.
Scope:
- rendered Compose and all running project containers;
- actual UID of API and worker;
- privileged, host network, Docker socket, capabilities, read-only rootfs,
CPU, memory and PID limits;
- runtime host port bindings;
- tracked text, application image metadata/filesystem and last 2000 log lines;
- OpenTelemetry redaction in traces, metrics and logs pipelines.
No secret value, private key, root token or unseal key is included in this file.
+30
View File
@@ -0,0 +1,30 @@
# Credential storage and log non-disclosure
Date: 2026-11-27
Stand: local Docker Desktop, compose project hla-lab7
Command:
python tests/credential_storage.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
Observed result:
PASS: password and session token are stored only as hashes and are absent from API/LB logs.
What the check does:
- creates one synthetic user and one session over verified HTTPS;
- reads the user's password_hash and the session token_hash from
PostgreSQL using the operator connection;
- requires password_hash to start with the measured
$argon2id$v=19$m=32768,t=2,p=1$ profile and to differ from the password;
- requires token_hash to be exactly the SHA-256 of the issued token
(64 hex characters / 32 bytes) and not the token itself;
- scans the API and nginx logs for the synthetic password, the synthetic
token, the stored password hash and the stored token hash;
- fails if any of those values appear in the logs.
Related black-box check:
tests/login_dos.py asserts that 401/429 bodies and headers do not contain
the tested username, password, hash or token. Known and unknown usernames
return the same 401 code and message.
The synthetic password and token exist only in process memory; this file
contains no credential values.
+174
View File
@@ -0,0 +1,174 @@
# Container hardening and dependency/image scan evidence
Date: 2026-11-27
Stand: local Docker Desktop, compose project hla-lab7, Windows host, Java 23 toolchain
Scope: README level 4 hardening/scan criterion. No secret values are recorded.
## 1. Reproducible commands
Compose hardening:
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\check-compose-hardening.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-container-secret-boundaries.ps1
Dependency scan (OSV querybatch + per-advisory detail over resolved Gradle runtimeClasspath):
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\scan-dependencies.ps1 -JsonPath "%TEMP%\osv-findings-before.json"
# after applying the fixes below
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\scan-dependencies.ps1 -FailOnHigh -JsonPath "%TEMP%\osv-findings-after.json"
Image build and scan (Docker Scout needs a Docker account login and was not used):
docker compose --env-file .env build api
mkdir "%TEMP%\trivy-out"
docker run --rm -v //var/run/docker.sock:/var/run/docker.sock -v "%TEMP%\trivy-out:/out" aquasec/trivy:0.62.1 image --scanners vuln --no-progress --timeout 20m --format json --output /out/trivy-app-before.json hla-lab7-app:local
docker run --rm -v //var/run/docker.sock:/var/run/docker.sock -v "%TEMP%\trivy-out:/out" aquasec/trivy:0.62.1 image --scanners vuln --no-progress --timeout 20m --format json --output /out/trivy-app-after.json hla-lab7-app:local
Runtime verification and application check after recreating containers:
docker compose --env-file .env up -d --no-deps --force-recreate --scale api=2 api worker
docker compose --env-file .env up -d --no-deps --force-recreate postgres redis rabbitmq minio
docker compose --env-file .env run --rm rabbitmq-init
python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
No curl -k / --insecure is used; the Python check loads the explicit public CA file.
OSV/Trivy outputs contain advisory data only, not credentials.
## 2. Container hardening and explained exceptions
Observed check output:
PASS: every service has no-new-privileges, a capability drop policy, private tmpfs and resource limits.
PASS: non-stateful services use a read-only root and drop ALL capabilities.
EXCEPTION minio writable root: Bitnami entrypoint prepares /bitnami/minio/data and the /certs links
EXCEPTION postgres writable root: entrypoint chown/chmod of /var/lib/postgresql/data before dropping to the postgres user
EXCEPTION rabbitmq writable root: entrypoint prepares /var/lib/rabbitmq and the Erlang cookie
EXCEPTION redis writable root: entrypoint writes /tmp/users.acl and persists RDB snapshots to the /data volume
PASS: runtime isolation, non-root app/worker, resource and port boundaries, Git/image/log secret isolation, and telemetry redaction are enforced. Checked 14 local secret values without printing them.
Runtime `docker inspect` for the app and four stateful exceptions (ReadonlyRootfs | Tmpfs | SecurityOpt | CapDrop):
hla-lab7-api-2 true | {"/tmp":"size=128m,mode=1777"} | no-new-privileges:true | ALL
hla-lab7-worker-1 true | {"/tmp":"size=192m,mode=1777","/tmp/native":"size=64m,mode=1777,exec"} | no-new-privileges:true | ALL
hla-lab7-postgres-1 false | {"/tmp":"size=64m,mode=1777"} | no-new-privileges:true | AUDIT_WRITE,MKNOD,NET_RAW,SETFCAP,SETPCAP,SYS_CHROOT
hla-lab7-redis-1 false | {"/tmp":"size=16m,mode=1777"} | no-new-privileges:true | AUDIT_WRITE,MKNOD,NET_RAW,SETFCAP,SETPCAP,SYS_CHROOT
hla-lab7-rabbitmq-1 false | {"/tmp":"size=64m,mode=1777"} | no-new-privileges:true | AUDIT_WRITE,MKNOD,NET_RAW,SETFCAP,SETPCAP,SYS_CHROOT
hla-lab7-minio-1 false | {"/tmp":"size=32m,mode=1777"} | no-new-privileges:true | AUDIT_WRITE,MKNOD,NET_RAW,SETFCAP,SETPCAP,SYS_CHROOT
Why only these four keep a writable root: each stock entrypoint must create/chown a
persistent named volume before it drops to its unprivileged runtime user. Setting
`read_only: true` there breaks first startup/permission setup. The exceptions are
not generic: the check requires the exact data volume and exact six-capability drop
profile, and still requires `no-new-privileges`, tmpfs and resource limits. All other
services have `read_only: true` and `cap_drop: ALL`.
Post-recreate smoke: `PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.`
RabbitMQ users are created by the `rabbitmq-init` one-shot; this was rerun after the
broker container was recreated so the mTLS role identities continued to work.
## 3. OSV dependency scan and applicability triage
Baseline command on the pre-fix `build.gradle`:
Resolved OSV Maven dependencies: 139
Packages with findings: 9
Findings by severity: CRITICAL=5 HIGH=18 MODERATE=10 LOW=1
Grouped baseline findings (package@installed version, findings, severities, fixed versions from advisory data):
com.fasterxml.jackson.core:jackson-core@2.21.5 2 HIGH2 2.18.11, 2.21.7, 2.22.3, 3.1.7, 3.2.2, 3.2.3
com.fasterxml.jackson.core:jackson-databind@2.21.5 5 HIGH3/MODERATE2 up to 2.21.7 / 2.22.3 / 3.1.7 / 3.2.3
tools.jackson.core:jackson-core@3.1.5 2 HIGH2 2.18.11, 2.21.7, 2.22.3, 3.1.7, 3.2.2, 3.2.3
tools.jackson.core:jackson-databind@3.1.5 5 HIGH3/MODERATE2 up to 2.21.7 / 2.22.3 / 3.1.7 / 3.2.3
com.google.guava:guava@33.4.8-jre 1 HIGH1 33.7.2
com.rabbitmq:amqp-client@5.30.0 10 HIGH4/MODERATE5/LOW1 5.31.0, 5.33.0, 5.33.1, 5.34.0, 5.35.0, 5.36.0, 5.36.1
org.apache.tomcat.embed:tomcat-embed-core@11.0.24 4 CRITICAL4 10.1.58, 10.1.59, 11.0.25, 9.0.121
org.bouncycastle:bcprov-jdk18on@1.84 2 CRITICAL1/HIGH1 1.85 (and other incompatible lines)
org.xerial.snappy:snappy-java@1.1.10.7 3 HIGH2/MODERATE1 1.1.10.9
Representative HIGH/CRITICAL advisory IDs:
jackson-core/databind 2.x and 3.x: GHSA-7hhh-6rmp-j9qf / CVE-2026-89425,
GHSA-p6pp-m3f8-5c89 / CVE-2026-89407, GHSA-cxp5-3px4-pw24 / CVE-2026-91777,
GHSA-q4xh-88c3-wmh7 / CVE-2026-68497, GHSA-wv8q-qhhj-9h54 / CVE-2026-91776
amqp-client: GHSA-6g32-pxv4-2wfj / CVE-2026-63337,
GHSA-68mj-5wr7-6fgg / CVE-2026-69219, GHSA-93j5-89vc-pph4 / CVE-2026-69220,
GHSA-jh4v-gfqj-7rhx / CVE-2026-75516
tomcat-embed-core: GHSA-gcx9-497g-6cp6 / CVE-2026-65182,
GHSA-f525-44xv-f2qj / CVE-2026-65637, GHSA-9xv2-5v5q-p794 / CVE-2026-65905,
GHSA-h3x4-894j-xpx5 / CVE-2026-68525
bcprov: GHSA-9pwp-9qqc-pr26 / CVE-2026-8763, GHSA-qp49-qgx5-5m26 / CVE-2026-13506
guava: GHSA-xxph-c9ww-hj94 / CVE-2026-102554
snappy-java: GHSA-gwq9-9ffj-mvrv / CVE-2026-93451,
GHSA-q233-g92q-qxp6 / CVE-2026-108106
Applicability, fix and control per package:
Package / version | Reachability in this configuration | Fix availability | Temporary control before fix / final state
Jackson 2.x and 3.x | Reachable: Spring Boot MVC uses Jackson for public JSON request/response binding; malformed input reaches the parser. Both the 2.x and 3.x coordinate sets were on the runtime classpath. | Fixed in 2.21.7 and 3.1.7; BOM overrides applied. | Before fix: 10 MiB request-body limit and mTLS at ingress, but not a substitute for parser limits. After fix: upgraded; OSV reports no finding.
tomcat-embed-core 11.0.24 | Reachable: embedded Tomcat serves the public HTTPS API through nginx; DIGEST/FORM paths are not enabled here, but the core parser/host handling is on the request path. | Fixed in 11.0.25; BOM override applied. | Before fix: mTLS identity check, body/rate limits and no exposed admin endpoints. After fix: upgraded; startup log shows Apache Tomcat/11.0.25.
amqp-client 5.30.0 | Reachable: API publishes attachment jobs and worker consumes them through mTLS broker gateways. Broker is trusted and role ACLs are narrow, but untrusted frame content would still be parsed by the client. | OSV lists 5.33.0/5.33.1/5.34.0/5.36.1; Maven Central has no 5.36.1 artifact, so 5.37.1 was selected. BOM override applied. | Before fix: mTLS gateways, exact role CN, ACLs and backend bypass denial. After fix: upgraded; OSV query for 5.37.1 returns no findings.
bcprov-jdk18on 1.84 | Transitive from MinIO; no direct BouncyCastle API use in application code. Reachable only through MinIO client TLS/signature internals against a fixed internal endpoint. | Fixed in 1.85; direct pin applied. | Before fix: internal-only MinIO endpoint, verify-full TLS and scoped credentials. After fix: upgraded; no direct ASN.1 parsing from untrusted input in app code.
guava 33.4.8-jre | Transitive from MinIO 8.6.0; reachable through its client internals, especially attachment I/O. | Fixed in 33.7.2; direct pin applied. | Before fix: 10 MiB attachment limit, staging prefix restrictions and mTLS. After fix: upgraded.
snappy-java 1.1.10.7 | Transitive from MinIO 8.6.0; only relevant if compressed object data is decoded. | Fixed in 1.1.10.9; direct pin applied. | Before fix: size/pixel bounds and internal endpoint. After fix: upgraded.
Result after the fixes:
Resolved OSV Maven dependencies: 139
Packages with findings: 0
Findings by severity:
osv_final_exit=0
The fix is `jackson-2-bom.version=2.21.7`, `jackson-bom.version=3.1.7`,
`rabbit-amqp-client.version=5.37.1`, `tomcat.version=11.0.25`, plus direct pins
`bcprov-jdk18on:1.85`, `guava:33.7.2-jre`, `snappy-java:1.1.10.9` in `build.gradle`.
## 4. Trivy image scan and applicability triage
Both scans used `aquasec/trivy:0.62.1`, `--scanners vuln`, Docker socket access and a
persistent `trivy-cache` volume. The Java DB was refreshed during the runs; each
scan completed with exit 0.
Image before dependency fix: sha256:56362acf75313be92f91ffd8735bd8683c882402139b25d4298dbc85e3c7d095
Image after dependency fix: sha256:73470b278aa115dabe8ba84f5202feeab41859744e929f73790f285200a1c1eb
Before: ubuntu 24.04 os-pkgs 442 findings (HIGH=16, MEDIUM=329, LOW=97)
Java jar 34 findings (CRITICAL=5, HIGH=18, MODERATE=10, LOW=1)
After: ubuntu 24.04 os-pkgs 442 findings (HIGH=16, MEDIUM=329, LOW=97)
Java jar 0 findings
The Java result independently confirms the OSV result: all HIGH/CRITICAL library
findings were removed by the version upgrades. The rebuilt image ID changed because
of this dependency work; the earlier rotation evidence recorded the previous image
ID at rotation time and is not contradicted by that later rebuild.
OS HIGH findings are base-image packages, not application libraries. All have fixed
versions in the Ubuntu tracker; applicability at runtime:
Package(s) / installed -> fixed | Reachability | Temporary control
apt 2.7.14build2 -> 2.8.4ubuntu0.1 | Package-manager code. The final entrypoint never invokes apt; there is no install/upgrade step in the running container. | Runtime user is non-root, rootfs is read-only, capabilities are ALL-dropped, and no shell/package-manager step exists in the entrypoint. Fix is available via base-image refresh.
libapt-pkg6.0t64 2.7.14build2 -> 2.8.4ubuntu0.1 | Library used by apt only; not linked into the JVM path used by the app. | Same runtime controls; base-image refresh tracked separately.
gnupg suite 2.4.4-2ubuntu17 -> 2.4.4-2ubuntu17.4 | dirmngr/gpg/gpg-agent/keyboxd etc. No key import, signing or verification is invoked by the final image entrypoint. | Same runtime controls; no untrusted key material is processed at runtime. Fix available in Ubuntu updates.
libbrotli1 1.1.0-2build2 -> 1.1.0-2ubuntu0.1 | Decoder library that could be loaded by the installed curl; curl is used only during image build to fetch the OTel agent, not by the runtime entrypoint. | Java TLS does not load this decoder for the app request path; non-root/read-only/no-new-privileges/cap-drop ALL remain in force. Fix available via base-image refresh.
openssl/libssl3t64 3.0.13-0ubuntu3.4 -> ...3.11/...3.16 | Used by system tools such as curl; the Java app uses the JDK TLS stack, not the system OpenSSL library. No runtime process in the entrypoint invokes openssl/curl. | Same runtime controls; base-image refresh tracked separately.
This is applicability analysis rather than dismissal by port state: the conclusion is
based on the actual final-stage entrypoint (`infra/otel/docker-entrypoint.sh`: wait
for rendered env, import service CA with `keytool`, then `exec java ...`) and on the
runtime user/filesystem/capability settings. The OS findings are still recorded with
fixed versions; patching the base image is the remaining supply-chain follow-up.
## 5. Regression checks after upgrades
.\gradlew.bat test --tests com.example.mtusi_messenger.security.DatabaseAuthenticationProviderTest --tests com.example.mtusi_messenger.security.LoginRateLimiterTest --tests com.example.mtusi_messenger.config.PasswordConfigTest --tests com.example.mtusi_messenger.cache.UserCacheTest --tests com.example.mtusi_messenger.queue.RetryPolicyTest --no-daemon --console=plain
BUILD SUCCESSFUL
python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
The full `gradlew test` run also includes `MtusiMessengerApplicationTests`, which
requires PostgreSQL/Redis on localhost; those ports are deliberately not published
by this Compose profile, so that integration class returns 503 in this host setup.
This limitation is already documented in `REPORT.md`; the relevant unit tests and
black-box HTTPS checks above pass.
+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.
+145
View File
@@ -0,0 +1,145 @@
# Level-4 threat model, worker bounds, TLS/ACL and telemetry audit
Date: 2026-11-27
Stand: local Docker Desktop, compose project hla-lab7
Scope: README level-4 final security criterion. No credential, token, canary value
or private key is recorded.
## Reproducible commands
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-level4-security-audit.ps1
The aggregate command invokes:
.\scripts\test-mtls.ps1
python tests/security.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
.\scripts\test-internal-tls.ps1
docker compose --env-file .env --profile verification run --rm private-bucket-check
.\scripts\test-openbao-runtime-boundaries.ps1 -SkipLivePolicy
.\scripts\test-worker-resource-bounds.ps1
.\scripts\test-telemetry-redaction.ps1
For a freshly bootstrapped AppRole SecretID (TTL 24 h), include the live OpenBao
allow/deny probe:
.\scripts\test-level4-security-audit.ps1 -IncludeFreshOpenBaoPolicy
The audit deliberately does not use an operator/root token as a fallback for an
expired SecretID. The scoped OpenBao policy result is also recorded independently
in evidence/openbao-policies.txt.
## Threat-to-control-to-negative-test traceability
The table in security/THREAT_MODEL.md contains 13 concrete threat paths. At least
the following independently reproducible paths cover the required six:
1. Ingress MITM/wrong hostname -> public CA + SAN verification -> empty/foreign
trust and wrong hostname fail in tests/security.py.
2. Direct API bypass -> client-auth=need + exact LB URI SAN -> no cert, foreign CA
and same-CA wrong SAN fail on each API replica in test-mtls.ps1.
3. Cross-user UUID/header abuse -> Bearer identity + membership predicates ->
forged X-User-Id and outsider chat/message/attachment requests return 401/404
in tests/security.py.
4. Compromised worker -> separate DB/Redis/RabbitMQ/MinIO/OpenBao identities ->
password_hash SELECT, cache key/admin commands, cross-role broker identity,
MinIO admin/final delete and foreign KV access are denied by the referenced
ACL/policy tests.
5. False telemetry ingest/backend access -> mTLS gateways and telemetry client CA
-> no cert/foreign CA, same-CA migration role and direct backend bypass fail.
6. Authorization/body leakage -> capture disabled + Collector redaction in all
pipelines -> a unique canary is absent from stdout/stderr, Loki, Tempo sensitive
tag values and Prometheus label sets.
7. Image bomb/slow decoder -> byte/pixel/memory/concurrency/time/container bounds
-> 10 MiB upload gets 413; 50M-pixel header and over-budget image are rejected;
a slow worker job is cancelled and scheduled with processing_timeout.
8. Sealed OpenBao fallback -> scoped Agent files and startup deadline -> no
operator material/fallback in app, fresh start without rendered env fails.
## Observed aggregate output
PASS: 2 API replicas require a client certificate and LB CA; forbidden URI SAN
is rejected; only the LB identity succeeds; no API port is published.
PASS: trusted HTTPS, ACL/attachment isolation, session cap, upload and login limits.
PASS: DB, S3, broker, Redis, Collector, telemetry backends and OpenBao verify
server CA/hostname; all declared mTLS endpoints reject no-cert and
foreign-CA clients.
PASS: API/worker use distinct broker identities; trusted-CA wrong roles receive
no AMQP access or OTel ingest; direct backend bypass is rejected.
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
PASS: OpenBao uses persistent raft storage outside dev mode; API/worker use
separate AppRoles and read-only rendered files; operator material is absent.
INFO: live scoped-policy probe skipped because the local 24 h AppRole SecretID
had expired; no elevated fallback was used.
PASS: image memory/pixel rejection and processing-timeout retry passed as
executable unit tests.
PASS: worker CPU=1, RAM=1073741824 bytes, pids=256, concurrency=2, prefetch=1,
pixels=40000000, image budget=536870912 bytes, job timeout=60000 ms and
memory wait=2000 ms are bounded.
PASS: unique Authorization/body canary was absent from container logs, Loki
records, Tempo sensitive tag values and Prometheus label sets.
PASS: telemetry backends were queried over CA-verified mTLS with the dedicated
Grafana identity.
PASS: level-4 audit covered the declared TLS matrix, same/foreign/no-cert
identity failures, data-plane ACLs, bounded upload worker and end-to-end
telemetry non-disclosure.
## Worker hard bounds and executable failure paths
Rendered Compose and runtime docker inspect agree:
CPU 1.0 core
memory 1 GiB
PID limit 256
JVM MaxRAM 70% of container
listener concurrency 2
broker prefetch 1
decoded pixels 40,000,000
processing budget 512 MiB (fair semaphore)
memory permit wait 2 s
per-job timeout 60 s
DB lease 90 s (must outlive timeout)
Unit command:
.\gradlew.bat test `
--tests com.example.mtusi_messenger.worker.ImageVariantProcessorTest `
--tests com.example.mtusi_messenger.worker.AttachmentWorkerLimitsTest `
--no-daemon --console=plain
Observed: BUILD SUCCESSFUL. ImageVariantProcessorTest verifies normal transforms,
determinism, rejection above the memory estimate and rejection of a 50M-pixel PNG
header before decoded allocation. AttachmentWorkerLimitsTest rejects invalid
timeout/lease/concurrency settings and proves that a slow operation is cancelled,
acknowledged only after durable retry scheduling, and marked processing_timeout.
## TLS matrix coverage
The audit verifies CA and hostname for ingress, PostgreSQL, MinIO, OpenBao, Grafana, Redis, both
RabbitMQ gateways, OTel gateway/Collector, Loki, both Tempo ports and Prometheus.
Every declared mTLS backend is tested with no certificate and a certificate from
the wrong CA. Exact-role gateways additionally test a certificate signed by the
trusted workload CA but assigned to migration/cross-role identity. Valid API,
worker, Collector, Prometheus and Grafana identities pass their respective links.
Runtime ACL checks execute forbidden operations rather than relying only on config:
API DDL and worker users/password_hash SELECT fail; Redis outside-prefix GET/SET
and CONFIG fail; RabbitMQ application permissions are separate and non-wildcard;
MinIO anonymous/admin/cross-prefix/final-write-or-delete operations fail.
## Telemetry non-disclosure method
test-telemetry-redaction.ps1 generates a random in-memory canary and sends it once
as an invalid Bearer value and once inside a malformed JSON body. Expected 401/400
responses prove the requests reached the protected/error paths. After the export
delay the script, without printing the canary:
- searches recent Compose stdout/stderr;
- queries Loki records;
- queries Tempo values for authorization, request/response/message bodies,
DB statement parameters and URL query;
- searches all returned Prometheus series label sets.
All searches returned zero matches. Backend queries themselves use the dedicated
Grafana client certificate with CA and hostname verification.
+62
View File
@@ -0,0 +1,62 @@
# Measured login DoS budget and shared rate limit
Date: 2026-11-27
Stand: local Docker Desktop, compose project hla-lab7, two API replicas
(0.75 CPU / 768 MiB each), nginx HTTPS ingress, Redis 7.4 over mTLS.
Commands:
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\benchmark-argon2.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\measure-login-dos.ps1 -SourceBudget
Argon2id calibration (0.75 CPU / 768 MiB, 5 warmups, 21 samples, unique salt):
32768 KiB, t=2, p=1:
encode p50 100.182 ms, p95 134.817 ms
verify p50 115.483 ms, p95 165.503 ms
Previous run of the same script: encode p95 150.3 ms, verify p95 142.7 ms.
Observed login budget (black-box through nginx):
Per username: 5 attempts / 60 s, shared by both replicas.
- 5 concurrent failed logins returned 401 and were served by two
distinct X-Instance-Id values.
- The 6th attempt returned 429 rate_limited with Retry-After 58 s.
- 5 concurrent Argon2 verifications: p50 1547.045 ms, p95 1662.582 ms.
This is queueing on the 0.75-CPU limit, not a single-request latency.
- The 429 response took 19.682 ms, i.e. it did not run Argon2.
Per source: 100 attempts / 60 s, shared by both replicas.
- After the 60 s window was allowed to expire, 100 failed logins with
distinct usernames returned 401; both replicas were observed.
- The 101st attempt returned 429 rate_limited with Retry-After 60 s.
- Sequential 401 path: p50 287.473 ms, p95 490.411 ms (includes
TLS, Redis, PostgreSQL and Argon2id).
- The 429 response took 18.654 ms, i.e. it did not run Argon2.
Known and unknown usernames:
- Both returned 401 with code "unauthorized" and the same message.
- Known-user request 510.424 ms; unknown-user request 309.891 ms in
that run. The difference is not a stable user-existence oracle; both
paths run one Argon2id verification (the unknown path uses the dummy
hash).
Budget calculation using the p95 verify time:
- Per username: 5 * 165.503 ms = 0.83 s of Argon2 CPU per 60 s window.
- Per source: 100 * 165.503 ms = 16.55 s of Argon2 CPU per 60 s window,
i.e. about 0.276 CPU averaged over the window on the 0.75-CPU API limit.
- The limiter is a rate cap, not a concurrency cap: a simultaneous burst
can still queue on the CPU limit, as the 5-way burst above shows.
- A Redis outage fails closed (503), so the expensive path is not exposed.
Shared-state and key handling:
- The fixed-window counters live in Redis under
messenger:login:user:<sha256> and messenger:login:source:<sha256>.
- The Lua script increments both counters and sets the TTL atomically.
- Both API replicas use the same Redis keys, so the budget is global for
the deployment, not per process.
- Raw usernames and source addresses are not used as Redis key material.
Known limitation:
- The source key currently uses request.getRemoteAddr(), which is the
nginx/LB address. It is therefore a global source cap shared by all
clients behind the LB, not a per-client cap. The per-username limit is
the primary per-account control. A trusted-proxy client-address model
remains the next step.
No passwords, session tokens or password hashes 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.
+15
View File
@@ -0,0 +1,15 @@
# OpenBao runtime boundary verification
Date: 2026-11-27
Stand: local Docker Desktop, compose project hla-lab7, OpenBao initialized and unsealed
Command:
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-openbao-runtime-boundaries.ps1
Observed output:
OpenBao policy checks passed: own path allowed; foreign path and policy changes denied.
PASS: OpenBao uses persistent raft storage outside dev mode; API/worker use separate AppRoles, scoped policies and read-only rendered files; operator material is absent.
Scope: server mode, initialized/unsealed Raft state, writable named volume at `/openbao/file`, separate AppRole bootstrap and rendered volumes, read-only application mounts, exact allowlisted runtime key names, and absence of root/unseal material from workload environments and project secrets.
No root token, unseal key, SecretID, service token or secret value is included.
+36
View File
@@ -0,0 +1,36 @@
# Password rehash and shared login-rate-limit unit checks
Date: 2026-11-27
Stand: Windows host, Gradle 9.7.1, Java 23 toolchain
Command:
.\gradlew.bat test --tests com.example.mtusi_messenger.security.DatabaseAuthenticationProviderTest --tests com.example.mtusi_messenger.security.LoginRateLimiterTest --no-daemon --console=plain
Observed result:
BUILD SUCCESSFUL
DatabaseAuthenticationProviderTest: 5 tests, 0 failures, 0 errors
LoginRateLimiterTest: 5 tests, 0 failures, 0 errors
DatabaseAuthenticationProviderTest proves:
- a valid legacy Argon2id hash (19456 KiB, t=2, p=1) is replaced after a
successful login by a hash with the measured runtime profile
(32768 KiB, t=2, p=1);
- the replacement uses the compare-and-swap contract
replacePasswordHash(userId, expectedHash, newHash);
- a wrong password, an unknown user and an already-current hash do not
rewrite the stored hash;
- an unknown user and a non-Argon2 stored value are checked against the
dummy hash, not against attacker-controlled stored text;
- authentication failures do not echo the password or the stored hash.
LoginRateLimiterTest proves:
- two limiter instances (simulated replicas) share the same username and
source budgets through the same Redis template;
- username matching is case-insensitive;
- Redis keys are SHA-256 digests and do not contain the raw username or
source address;
- a Redis outage fails closed with AuthenticationServiceException instead
of allowing expensive password verification;
- invalid limit/window configuration is rejected.
No passwords, session tokens or password hashes are printed by these tests.
+23
View File
@@ -0,0 +1,23 @@
Public HTTPS security verification
Date: 2026-11-27 (Europe/Moscow)
Commands:
python tests/security.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
python tests/session_expiry.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
Observed:
PASS: trusted HTTPS, ACL/attachment isolation, session cap, upload and login limits.
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
PASS: an expired server-side session is rejected over verified HTTPS.
Verified failures and boundaries:
- empty trust store rejects the ingress certificate with a certificate verification error;
- outsider and cross-chat access return 404 without object disclosure;
- attachment body above 10 MiB returns 413;
- the fifth failed login in the configured window returns 429 with positive Retry-After;
- session replacement, logout and expiry make the old Bearer token return 401;
- all positive and negative HTTP probes use HTTPS with CA and hostname verification.
Certificates and credentials were created locally. No token, password, private key
or secret value is included in this file.
+81
View File
@@ -0,0 +1,81 @@
# Rotation, revocation and OpenBao boundary evidence
Date: 2026-11-27
Stand: local Docker Desktop, compose project hla-lab7
Scope: README level 4, rotation/revocation/renewal criterion. No secret values are recorded.
## 1. LB leaf rotation and old identity revocation
Commands:
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\rotate-pki-leaf.ps1 `
-Leaf lb -CaName lb-client-ca -UriSan spiffe://hla-lab7/lb -RevokeOld
docker compose --env-file .env up -d --no-deps --force-recreate --scale api=2 api
docker compose --env-file .env up -d --no-deps --force-recreate nginx
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-rotated-leaf.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-mtls.ps1
Observed:
ROTATED lb (CA lb-client-ca) without rebuilding images.
old_leaf_sha256=8b3f0a8d2fb055dff0bb6fd2bf8409942c8f60de1c6306ecaff43f8cd100f6c2
new_leaf_sha256=d411b42909f0186d8c9b3514e27c6fd3921dd7a6ec5d316546f2dc13c5cf29af
revoked_old_leaf=8b3f0a8d2fb055dff0bb6fd2bf8409942c8f60de1c6306ecaff43f8cd100f6c2
api image before/after reload: sha256:56362acf75313be92f91ffd8735bd8683c882402139b25d4298dbc85e3c7d095
nginx image before/after reload: sha256:4cad75abc83d5ca6ee22053d85850676eaef657ee9d723d7bef61179e1e1e485
PASS: 2 API replicas reject the revoked LB leaf with 403 and accept the rotated LB leaf with 200.
PASS: 2 API replicas require a client certificate and LB CA; forbidden URI SAN is rejected; only the LB identity succeeds; no API port is published.
The old leaf/key are archived under secrets/pki/revoked/lb/ (ignored by Git). Only its
SHA-256 DER fingerprint is appended to the runtime deny-list mounted at
/run/pki/revoked-client-sha256.txt. An unreadable deny-list fails closed.
## 2. Working secret rotation without image rebuild
Command:
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\rotate-grafana-admin-password.ps1
Observed:
PASS: Grafana admin password rotated through the API and .env without rebuilding images.
old_password_accepted_after=false
new_password_accepted_after=true
grafana_image=sha256:6afa1ab7f6e662c739a45a1d458598d7eb6ab70fc7c0ab45af64864e1503d4b6
The script generates the new password locally, calls Grafana PUT /api/user/password,
updates .env, recreates only the Grafana container, verifies old/new credentials and
never prints or commits either value. Image ID was unchanged.
## 3. Sealed/unavailable OpenBao and bounded expiry behavior
Command:
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-openbao-rotation-boundaries.ps1
Observed:
bao status: Sealed true, Initialized true, Shamir 3 shares / threshold 2.
openbao-agent-api and openbao-agent-worker: Running=true.
Rendered runtime env keys still present: DATABASE_PASSWORD, RABBITMQ_PASSWORD, REDIS_PASSWORD, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY.
Public HTTPS /health/ready: 200.
Fresh startup with OPENBAO_RENDERED_ENV=/run/missing/runtime.env and a 2 s deadline:
exit 1, "OpenBao did not render runtime credentials before startup deadline", 2.8 s.
PASS: AppRole token TTL is 15m/1h, templates renew every 5m, and no permanent operator secret is embedded in the image.
PASS: application image has no BAO_TOKEN/UNSEAL/ROOT_TOKEN/SECRET_ID env entry and no .env/secrets/runtime.env/key artifact.
After the sealed-state evidence was captured, the lab OpenBao instance was reinitialized
and re-bootstrapped from local .env because unseal shares are intentionally held offline.
No unseal share or root token was written to the repository.
## 4. Bootstrap trust and lifecycle checks
Commands:
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\check-security-lifecycle.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-openbao-policies.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-openbao-runtime-boundaries.ps1
Observed:
PASS: 28 certificate/key bundles are valid; private/operator secrets are untracked; present SecretIDs are within TTL.
OpenBao policy checks passed: own path allowed; foreign path and policy changes denied.
PASS: OpenBao uses persistent raft storage outside dev mode; API/worker use separate AppRoles, scoped policies and read-only rendered files; operator material is absent.
Trust bootstrap: operator init creates 3 Shamir shares with threshold 2 offline; root token
is used only for bootstrap and removed from the environment; AppRole role-id/secret-id are
stored in ignored local files; agents auto-auth to OpenBao over verified TLS and render only
five allowlisted keys into per-role named volumes. The app enters controlled-unready when
the rendered file is missing and does not fall back to plaintext credentials.
+13
View File
@@ -0,0 +1,13 @@
# Certificate and secret lifecycle verification
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: 28 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.
+27
View File
@@ -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.
+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.
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+82
View File
@@ -0,0 +1,82 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+52
View File
@@ -0,0 +1,52 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"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/*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject"
],
"Resource": [
"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/*"
]
}
]
}
+146
View File
@@ -0,0 +1,146 @@
worker_processes auto;
worker_shutdown_timeout 10s;
events {
worker_connections 1024;
}
http {
# Let the application enforce the exact 10 MiB contract and return JSON.
client_max_body_size 11m;
client_body_timeout 10s;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log warn;
# Docker embedded DNS returns current Compose replicas. Nginx OSS 1.27.3+
# refreshes these addresses without a configuration reload.
resolver 127.0.0.11 valid=2s ipv6=off;
resolver_timeout 1s;
upstream api_backend {
zone api_backend 64k;
least_conn;
server api:8443 resolve max_fails=1 fail_timeout=2s;
keepalive 32;
}
server {
listen 8443 ssl;
server_name localhost;
ssl_certificate /run/pki/ingress/tls.crt;
ssl_certificate_key /run/pki/ingress/tls.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_tickets off;
add_header Strict-Transport-Security "max-age=31536000" always;
proxy_ssl_certificate /run/pki/lb/tls.crt;
proxy_ssl_certificate_key /run/pki/lb/tls.key;
proxy_ssl_trusted_certificate /run/pki/service-ca/ca.crt;
proxy_ssl_verify on;
proxy_ssl_verify_depth 2;
proxy_ssl_server_name on;
proxy_ssl_name api;
proxy_intercept_errors on;
error_page 502 503 504 = @no_ready_api;
location = /nginx-health {
access_log off;
default_type application/json;
return 200 '{"status":"ok"}';
}
# After both peers have refused traffic or become unreachable, Nginx
# would normally emit its own HTML 502. Keep the public API contract:
# no ready backend is a JSON 503 with the required tracing headers.
location @no_ready_api {
internal;
default_type application/json;
add_header X-Request-Id $request_id always;
add_header X-Instance-Id nginx always;
add_header Cache-Control "no-store" always;
return 503 '{"error":{"code":"unavailable","message":"No ready API backend","request_id":"$request_id"}}';
}
# Message POST is the only non-idempotent HTTP method that is safe to
# replay here: the API requires Idempotency-Key and commits the message
# together with its shared PostgreSQL idempotency record.
location ~ ^/api/v1/chats/[0-9a-fA-F-]+/messages$ {
proxy_pass https://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_request_buffering on;
proxy_connect_timeout 500ms;
proxy_send_timeout 15s;
proxy_read_timeout 15s;
proxy_next_upstream error timeout http_502 http_503 http_504 non_idempotent;
proxy_next_upstream_tries 2;
}
location ~ ^/api/v1/chats/[0-9a-fA-F-]+/attachments$ {
proxy_pass https://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_request_buffering on;
proxy_connect_timeout 500ms;
proxy_send_timeout 20s;
proxy_read_timeout 20s;
# Upload is not replayed: it has no idempotency key. The client may retry explicitly.
proxy_next_upstream off;
}
# Argon2id is intentionally CPU/memory expensive and may exceed the
# general four-second budget on a CPU-limited cold replica. These POSTs
# are never replayed by the LB because both create durable state.
location = /api/v1/users {
proxy_pass https://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 500ms;
proxy_send_timeout 15s;
proxy_read_timeout 15s;
proxy_next_upstream off;
}
location = /api/v1/auth/sessions {
proxy_pass https://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 500ms;
proxy_send_timeout 15s;
proxy_read_timeout 15s;
proxy_next_upstream off;
}
location / {
proxy_pass https://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 500ms;
proxy_send_timeout 15s;
proxy_read_timeout 15s;
# No sticky sessions. Failed/unready peers are retried elsewhere.
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
}
}
+139 -4
View File
@@ -1,7 +1,142 @@
# OpenBao — реализовать конфигурацию и политики # OpenBao: эксплуатация стенда
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key. OpenBao запускается обычным `server`, а не `dev`: данные хранятся в named volume `openbao-data` через integrated Raft storage (`/openbao/file`). TLS обязателен, порт опубликован только на loopback. После перезапуска данные сохраняются, но сервер снова sealed до ручного unseal.
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения. ## Первичная инициализация
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md. 1. Создайте локальные credentials и PKI:
```powershell
.\scripts\bootstrap-secrets.ps1
.\scripts\bootstrap-pki.ps1
```
2. Запустите только OpenBao и проверьте состояние `uninitialized`:
```powershell
docker compose --env-file .env up -d openbao
docker compose --env-file .env exec openbao bao status
```
3. Один раз выполните init из интерактивного терминала оператора:
```powershell
docker compose --env-file .env exec openbao bao operator init -key-shares=3 -key-threshold=2
```
Команда выводит три unseal share и initial root token. Оператор немедленно переносит их в защищённое внешнее хранилище; доли передаются разным хранителям. Их запрещено сохранять в `.env`, `secrets/`, shell history, отчёт, скриншот или Git. Скрипты проекта намеренно не автоматизируют и не перехватывают init.
4. Введите любые две разные доли вручную. Значения вместо маркеров в команду не вставляйте: команда запросит их скрыто интерактивно.
```powershell
docker compose --env-file .env exec openbao bao operator unseal
docker compose --env-file .env exec openbao bao operator unseal
docker compose --env-file .env exec openbao bao status
```
5. Только на время bootstrap задайте root token в окружении текущего PowerShell-процесса и создайте KV, политики и AppRole:
```powershell
$env:BAO_TOKEN = Read-Host 'OpenBao root token'
.\scripts\bootstrap-openbao.ps1
Remove-Item Env:BAO_TOKEN
```
Скрипт не печатает secret values. Он загружает их в KV v2 через stdin, создаёт отдельные `messenger-api` и `messenger-worker` policies и кладёт только стартовые AppRole RoleID/SecretID в игнорируемый каталог `secrets/openbao/`. File audit задаётся декларативно в `openbao.hcl`, поскольку OpenBao 2.7 по умолчанию запрещает создание audit devices через API.
6. Запустите весь стенд:
```powershell
docker compose --env-file .env up -d
```
OpenBao Agent у API и worker аутентифицируется своим AppRole, получает renewable token с TTL 15 минут и max TTL 1 час и рендерит только разрешённый набор runtime credentials в отдельный named volume. Root token и unseal shares в контейнеры приложений не передаются.
## Политики и проверяемые отказы
- `messenger-api` читает только `secret/data/messenger/api` и его metadata.
- `messenger-worker` читает только `secret/data/messenger/worker` и его metadata.
- У ролей нет доступа к чужому KV, `sys/policies/*`, auth configuration, init или unseal.
- AppRole SecretID действует 24 часа; token TTL — 15 минут, max TTL — 1 час. `token_num_uses=0` необходим для renewal и повторного чтения Agent, но область доступа ограничивает named policy.
После bootstrap выполните:
```powershell
.\scripts\test-openbao-policies.ps1
```
Тест требует существующие игнорируемые AppRole-файлы и доказывает allow для собственного пути, deny для чужого пути и deny изменения policy. Токены и SecretID не выводятся.
## Перезапуск, seal и восстановление
После перезапуска `openbao-data` сохраняется. Оператор снова выполняет две интерактивные команды `bao operator unseal`. Пока OpenBao sealed, agents не получают и не обновляют token; hardcoded или `.env` fallback у приложений отсутствует. После unseal agents повторяют authentication. Если приложение ещё не запущено, entrypoint ждёт rendered file до `OPENBAO_STARTUP_TIMEOUT_SECONDS` (по умолчанию 120 с) и завершает работу при его отсутствии. Значение можно уменьшить для быстрого fail-closed; это не влияет на уже работающие контейнеры.
Статические DB/Redis/RabbitMQ/S3 credentials читаются приложением при старте. После создания новой KV version следует последовательно перезапустить API/worker, проверить новые соединения, затем отозвать старые credentials в зависимости. OpenBao token rotation выполняется Agent автоматически.
## Ротация и отзыв без пересборки образов
Три сценария ротации выполняются на работающем стенде и не меняют image ID контейнеров. Полный санитизированный протокол — `evidence/rotation-renewal.txt`.
### Leaf certificate и отзыв старой identity
```powershell
.\scripts\rotate-pki-leaf.ps1 -Leaf lb -CaName lb-client-ca -UriSan spiffe://hla-lab7/lb -RevokeOld
docker compose --env-file .env up -d --no-deps --force-recreate --scale api=2 api
docker compose --env-file .env up -d --no-deps --force-recreate nginx
.\scripts\test-rotated-leaf.ps1
.\scripts\test-mtls.ps1
```
Скрипт выпускает новый leaf тем же CA, архивирует старый комплект в игнорируемый каталог `secrets/pki/revoked/<leaf>/` и добавляет в deny-list только DER SHA-256 отпечаток старого сертификата. Файл монтируется как `/run/pki/revoked-client-sha256.txt`; `TrustedClientCertificateFilter` сверяет отпечаток каждого client leaf до auth. Явно сконфигурированный, но нечитаемый deny-list отзывает все client identity (fail-closed). Перезапуск контейнеров сохраняет image ID: PKI смонтирован из volume, а не зашит в образ. Измерено: обе API-реплики отвечают `403` на старый leaf и `200` на новый; image ID API и nginx до/после одинаковы.
### Рабочий secret
```powershell
.\scripts\rotate-grafana-admin-password.ps1
```
Скрипт генерирует новый пароль локально, меняет его через `PUT /api/user/password`, обновляет игнорируемый `.env`, пересоздаёт только Grafana и проверяет, что старый пароль отклонён, а новый принят. Значения не печатаются и не попадают в Git или образ; image ID Grafana не меняется.
### Sealed/expiry и ограниченное поведение
```powershell
# Оператор seals OpenBao или останавливает сервер; share хранятся offline.
.\scripts\test-openbao-rotation-boundaries.ps1
```
Скрипт намеренно не выполняет unseal: он проверяет уже наступившее состояние `Sealed true`. Измерено: оба Agent остаются Running, кэшированные rendered keys доступны, public HTTPS `/health/ready` → `200`. Свежий контейнер с отсутствующим rendered env завершился за 2.8 с при configured deadline 2 с. После снятия показаний лабораторный OpenBao был переинициализирован и заново bootstrapped из локального `.env`; новые share/root token в репозиторий или окружение не записывались.
Renewal задан конфигурацией: AppRole token TTL 15 min / max 1 h, `static_secret_render_interval = "5m"`, `exit_on_retry_failure = false`. В образе приложения нет `BAO_TOKEN`, UNSEAL/ROOT_TOKEN, SecretID, `.env`, `secrets/` или key-артефактов — постоянного секрета «для получения секретов» не существует.
## Ротация AppRole bootstrap credential
SecretID нужно менять до истечения 24 часов:
```powershell
$env:BAO_TOKEN = Read-Host 'OpenBao operator token'
.\scripts\rotate-openbao-secret-ids.ps1
Remove-Item Env:BAO_TOKEN
docker compose --env-file .env restart openbao-agent-api openbao-agent-worker
```
Скрипт заменяет локальные SecretID-файлы и не печатает их. В production вместо root token для этой операции создаётся отдельная узкая operator policy; root token после первичного bootstrap хранится offline.
## Эксплуатационные ограничения
`disable_mlock=true` выбран для локального Docker Desktop стенда: контейнеру не выдаётся `IPC_LOCK`. Это осознанный компромисс лабораторного окружения; swap/дампы хоста остаются в зоне доверия оператора. Agents запускаются как root только для записи в выделенные named volumes, при этом имеют `cap_drop: ALL`, `no-new-privileges`, read-only mounts конфигурации/PKI/bootstrap и не получают Docker socket.
Удаление volume уничтожает OpenBao storage и требует нового init. Выполнять следующую команду можно только при намеренном полном сбросе стенда и наличии решения оператора о судьбе старых shares:
```powershell
docker compose --env-file .env down --volumes
```
## Что не хранится в репозитории
- initial root token;
- unseal shares;
- AppRole SecretID и RoleID стенда;
- private keys и рабочие service credentials;
- содержимое Raft storage и audit log.
Справка: [operator init](https://openbao.org/docs/commands/operator/init/), [AppRole](https://openbao.org/docs/auth/approle/), [Agent auto-auth](https://openbao.org/docs/agent-and-proxy/autoauth/), [Raft storage](https://openbao.org/docs/configuration/storage/raft/), [KV CLI stdin](https://openbao.org/docs/commands/).
+31
View File
@@ -0,0 +1,31 @@
vault {
address = "https://openbao:8200"
ca_cert = "/run/pki/service-ca/ca.crt"
}
auto_auth {
method "approle" {
mount_path = "auth/approle"
config = {
role_id_file_path = "/run/bootstrap/role-id"
secret_id_file_path = "/run/bootstrap/secret-id"
remove_secret_id_file_after_reading = false
}
}
}
template_config {
static_secret_render_interval = "5m"
exit_on_retry_failure = false
}
template {
contents = <<EOT
{{ with secret "secret/data/messenger/api" -}}
DATABASE_PASSWORD={{ .Data.data.database_password }}
REDIS_PASSWORD={{ .Data.data.redis_password }}
RABBITMQ_PASSWORD={{ .Data.data.rabbitmq_password }}
S3_ACCESS_KEY_ID={{ .Data.data.s3_access_key_id }}
S3_SECRET_ACCESS_KEY={{ .Data.data.s3_secret_access_key }}
{{- end }}
EOT
destination = "/run/rendered/runtime.env"
perms = "0644"
}
+31
View File
@@ -0,0 +1,31 @@
vault {
address = "https://openbao:8200"
ca_cert = "/run/pki/service-ca/ca.crt"
}
auto_auth {
method "approle" {
mount_path = "auth/approle"
config = {
role_id_file_path = "/run/bootstrap/role-id"
secret_id_file_path = "/run/bootstrap/secret-id"
remove_secret_id_file_after_reading = false
}
}
}
template_config {
static_secret_render_interval = "5m"
exit_on_retry_failure = false
}
template {
contents = <<EOT
{{ with secret "secret/data/messenger/worker" -}}
DATABASE_PASSWORD={{ .Data.data.database_password }}
REDIS_PASSWORD={{ .Data.data.redis_password }}
RABBITMQ_PASSWORD={{ .Data.data.rabbitmq_password }}
S3_ACCESS_KEY_ID={{ .Data.data.s3_access_key_id }}
S3_SECRET_ACCESS_KEY={{ .Data.data.s3_secret_access_key }}
{{- end }}
EOT
destination = "/run/rendered/runtime.env"
perms = "0644"
}
+6
View File
@@ -0,0 +1,6 @@
path "secret/data/messenger/api" {
capabilities = ["read"]
}
path "secret/metadata/messenger/api" {
capabilities = ["read"]
}
+33
View File
@@ -0,0 +1,33 @@
ui = false
disable_mlock = true
default_lease_ttl = "15m"
max_lease_ttl = "1h"
api_addr = "https://openbao:8200"
cluster_addr = "https://openbao:8201"
storage "raft" {
path = "/openbao/file"
node_id = "openbao-stand"
}
listener "tcp" {
address = "0.0.0.0:8200"
cluster_address = "0.0.0.0:8201"
tls_cert_file = "/run/pki/openbao/tls.crt"
tls_key_file = "/run/pki/openbao/tls.key"
tls_min_version = "tls12"
tls_disable_client_certs = true
}
telemetry {
disable_hostname = true
}
audit "file" "file" {
description = "Persistent HMAC-protected operator audit log"
options {
file_path = "/openbao/file/audit.log"
mode = "0600"
log_raw = "false"
}
}
+6
View File
@@ -0,0 +1,6 @@
path "secret/data/messenger/worker" {
capabilities = ["read"]
}
path "secret/metadata/messenger/worker" {
capabilities = ["read"]
}
+27 -4
View File
@@ -1,7 +1,30 @@
# Конфигурация наблюдаемости — реализовать # Стек наблюдаемости
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend. Поток данных:
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`. `messenger-api / messenger-worker -> OTLP/HTTP -> otel-collector -> Prometheus / Loki / Tempo -> Grafana`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён. Версии закреплены в `compose.yaml`: Java agent 2.33.1 (SDK 1.67.0), Collector Contrib 0.165.0, Prometheus 3.14.0, Loki 3.7.8, Tempo 3.1.1 и Grafana 13.3.0.
## Файлы
- `collector.yaml` — OTLP receivers, memory limiter, redaction, batch и bounded retry queues;
- `prometheus.yaml` и `prometheus-alerts.yaml` — scrape, SLO/queue/worker/export alerts;
- `loki.yaml` — локальное хранилище структурных OTLP logs;
- `tempo.yaml` — локальное хранилище traces;
- `grafana/provisioning` — три datasources и dashboard provisioning;
- `grafana/dashboards/messenger-overview.json` — импортируемый dashboard;
- `runbooks.md` — локальные действия для каждого alert.
Grafana доступна только на `127.0.0.1:3000`. Prometheus, Loki, Tempo и OTLP Collector не публикуются на интерфейсы хоста; доступ к backend выполняется только из внутренней Docker-сети через Grafana или отдельный одноразовый verification-контейнер.
## Проверка корреляции
1. Выполнить `python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt`.
2. В Tempo найти server span upload и перейти к RabbitMQ producer/consumer span.
3. Скопировать `trace_id` и выполнить в Loki `{service_name=~"messenger-(api|worker)"} | json | trace_id="..."`.
4. Убедиться, что у API и worker разные `service.name`, но общий trace context.
Для durable retry `traceparent/tracestate` сохраняются рядом с job в PostgreSQL и восстанавливаются перед outbox republish. Проверяемый сценарий: `scripts/incident-retry-trace.ps1`; он требует минимум два producer/consumer span в одной trace и сохраняет их parent IDs.
Collector удаляет потенциально чувствительные HTTP/message/body/DB parameter attributes. Java agent не настроен на захват request/response headers или bodies. Метрики используют только route template, status/method, job type/outcome и queue name.
+104
View File
@@ -0,0 +1,104 @@
extensions:
health_check:
endpoint: 0.0.0.0:13133
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
tls:
cert_file: /run/pki/otel-collector/tls.crt
key_file: /run/pki/otel-collector/tls.key
client_ca_file: /run/pki/service-ca/ca.crt
min_version: "1.2"
processors:
memory_limiter:
check_interval: 1s
limit_mib: 384
spike_limit_mib: 96
attributes/redact:
actions:
- key: http.request.header.authorization
action: delete
- key: http.request.body
action: delete
- key: http.response.body
action: delete
- key: messaging.message.body
action: delete
- key: db.statement.parameters
action: delete
- key: url.query
action: delete
batch:
send_batch_size: 512
timeout: 5s
exporters:
prometheus:
endpoint: 0.0.0.0:8889
tls:
cert_file: /run/pki/otel-collector/tls.crt
key_file: /run/pki/otel-collector/tls.key
client_ca_file: /run/pki/telemetry-client-ca/ca.crt
send_timestamps: true
resource_constant_labels:
included: ["service.*", "deployment.environment.name"]
otlp_http/tempo:
endpoint: https://tempo:4318
tls:
ca_file: /run/pki/service-ca/ca.crt
cert_file: /run/pki/collector-client/tls.crt
key_file: /run/pki/collector-client/tls.key
sending_queue:
enabled: true
queue_size: 2048
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 60s
otlp_http/loki:
endpoint: https://loki:3100/otlp
tls:
ca_file: /run/pki/service-ca/ca.crt
cert_file: /run/pki/collector-client/tls.crt
key_file: /run/pki/collector-client/tls.key
sending_queue:
enabled: true
queue_size: 2048
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 60s
service:
extensions: [health_check]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
without_type_suffix: false
without_units: false
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [otlp_http/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [otlp_http/loki]
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
set -eu
if [ -n "${OPENBAO_RENDERED_ENV:-}" ]; then
deadline=$(( $(date +%s) + ${OPENBAO_STARTUP_TIMEOUT_SECONDS:-120} ))
while [ ! -s "$OPENBAO_RENDERED_ENV" ]; do
if [ "$(date +%s)" -ge "$deadline" ]; then
echo "OpenBao did not render runtime credentials before startup deadline" >&2
exit 1
fi
sleep 1
done
while IFS='=' read -r name value; do
case "$name" in
DATABASE_PASSWORD|REDIS_PASSWORD|RABBITMQ_PASSWORD|S3_ACCESS_KEY_ID|S3_SECRET_ACCESS_KEY)
export "$name=$value" ;;
'') ;;
*) echo "Unexpected key in OpenBao rendered environment: $name" >&2; exit 1 ;;
esac
done < "$OPENBAO_RENDERED_ENV"
fi
if [ -f /run/pki/service-ca/ca.crt ]; then
keytool -importcert -noprompt -alias hla-lab7-service-ca \
-file /run/pki/service-ca/ca.crt -keystore /tmp/service-truststore.p12 \
-storetype PKCS12 -storepass changeit >/dev/null 2>&1
export JAVA_TOOL_OPTIONS="${JAVA_TOOL_OPTIONS:-} -Djavax.net.ssl.trustStore=/tmp/service-truststore.p12 -Djavax.net.ssl.trustStorePassword=changeit"
fi
if [ "${OTEL_SDK_DISABLED:-false}" = "true" ]; then
exec java -jar /app/app.jar "$@"
fi
exec java -javaagent:/opt/opentelemetry-javaagent.jar -jar /app/app.jar "$@"
+35
View File
@@ -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;
}
}
}
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
export SERVICE_CA_PEM="$(cat /run/pki/service-ca/ca.crt)"
export GRAFANA_CLIENT_CERT_PEM="$(cat /run/pki/grafana-client/tls.crt)"
export GRAFANA_CLIENT_KEY_PEM="$(cat /run/pki/grafana-client/tls.key)"
exec /run.sh
@@ -0,0 +1,141 @@
{
"annotations": {"list": []},
"editable": false,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [],
"liveNow": false,
"panels": [
{
"id": 1,
"title": "API requests / second",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "sum by (http_request_method) (rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m]))", "legendFormat": "{{http_request_method}}"}],
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 0}
},
{
"id": 2,
"title": "API 5xx ratio",
"description": "5xx business responses divided by all business responses over 5 minutes; health routes are excluded. Displayed as percent (0..100%).",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "(sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_code=~\"5..\",http_route!~\"/health/.*\"}[5m])) or vector(0)) / clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])), 0.001)", "legendFormat": "5xx / all"}],
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 0}
},
{
"id": 3,
"title": "API duration p50 / p95 / p99",
"description": "Seconds. histogram_quantile is calculated from the summed Prometheus histogram buckets of all API replicas; replica percentiles are never averaged.",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p99"}
],
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 0}
},
{
"id": 4,
"title": "Job outcomes / second",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "sum by (outcome) (rate(messenger_jobs_processed_total{service_name=\"messenger-worker\"}[5m]))", "legendFormat": "{{outcome}}"}],
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 8}
},
{
"id": 5,
"title": "Job duration p95",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_job_processing_duration_seconds_bucket{service_name=\"messenger-worker\"}[5m])))", "legendFormat": "{{outcome}}"}],
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 8}
},
{
"id": 6,
"title": "Time to ready p95",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{service_name=\"messenger-worker\"}[10m])))", "legendFormat": "p95"}],
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 8}
},
{
"id": 7,
"title": "Queue depth and oldest age",
"description": "Left axis: durable queued jobs (count). Right axis: age of the oldest unfinished job (seconds). Backlog age is not processing latency.",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [
{"refId": "A", "expr": "max(messenger_queue_depth{service_name=\"messenger-api\"})", "legendFormat": "depth"},
{"refId": "B", "expr": "max(messenger_queue_oldest_job_age_seconds{service_name=\"messenger-api\"})", "legendFormat": "oldest age (s)"}
],
"fieldConfig": {
"defaults": {},
"overrides": [
{"matcher": {"id": "byName", "options": "depth"}, "properties": [{"id": "unit", "value": "short"}, {"id": "custom.axisPlacement", "value": "left"}]},
{"matcher": {"id": "byName", "options": "oldest age (s)"}, "properties": [{"id": "unit", "value": "s"}, {"id": "custom.axisPlacement", "value": "right"}]}
]
},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 16}
},
{
"id": 8,
"title": "Worker saturation",
"description": "busy workers / configured worker capacity. Dimensionless ratio displayed as percent.",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "messenger_worker_busy{service_name=\"messenger-worker\"} / clamp_min(messenger_worker_capacity{service_name=\"messenger-worker\"}, 1)", "legendFormat": "{{service_instance_id}}"}],
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 16}
},
{
"id": 9,
"title": "DB pool used / waiting",
"description": "Number of HikariCP connections by state plus pending acquisition requests. Unit: connections/requests (count).",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [
{"refId": "A", "expr": "sum by (service_name, state) (db_client_connections_usage{service_name=~\"messenger-(api|worker)\"})", "legendFormat": "{{service_name}} {{state}}"},
{"refId": "B", "expr": "sum by (service_name) (db_client_connections_pending_requests{service_name=~\"messenger-(api|worker)\"})", "legendFormat": "{{service_name}} waiting"}
],
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 16}
},
{
"id": 10,
"title": "Correlated application logs",
"type": "logs",
"datasource": {"type": "loki", "uid": "loki"},
"targets": [{"refId": "A", "expr": "{service_name=~\"messenger-(api|worker)\"} | json", "queryType": "range"}],
"options": {"showTime": true, "showLabels": false, "wrapLogMessage": true, "prettifyLogMessage": true, "enableLogDetails": true, "sortOrder": "Descending", "dedupStrategy": "none"},
"gridPos": {"h": 10, "w": 16, "x": 0, "y": 24}
},
{
"id": 11,
"title": "Recent traces",
"type": "traces",
"datasource": {"type": "tempo", "uid": "tempo"},
"targets": [{"refId": "A", "queryType": "search", "serviceName": "messenger-api", "limit": 20}],
"gridPos": {"h": 10, "w": 8, "x": 16, "y": 24}
}
],
"refresh": "10s",
"schemaVersion": 41,
"tags": ["hla", "lab6", "opentelemetry"],
"templating": {"list": []},
"time": {"from": "now-30m", "to": "now"},
"timepicker": {},
"timezone": "browser",
"title": "Messenger observability",
"uid": "messenger-observability",
"version": 3,
"weekStart": ""
}
@@ -0,0 +1,13 @@
apiVersion: 1
providers:
- name: Messenger Lab 6
orgId: 1
folder: HLA Lab 6
type: file
disableDeletion: true
updateIntervalSeconds: 30
allowUiUpdates: false
options:
path: /var/lib/grafana/dashboards
foldersFromFilesStructure: false
@@ -0,0 +1,77 @@
apiVersion: 1
deleteDatasources:
- name: Prometheus
orgId: 1
- name: Loki
orgId: 1
- name: Tempo
orgId: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
timeInterval: 10s
exemplarTraceIdDestinations:
- name: trace_id
datasourceUid: tempo
secureJsonData:
tlsCACert: ${SERVICE_CA_PEM}
tlsClientCert: ${GRAFANA_CLIENT_CERT_PEM}
tlsClientKey: ${GRAFANA_CLIENT_KEY_PEM}
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
derivedFields:
- name: TraceID
matcherRegex: '"trace_id":"([a-f0-9]{32})"'
datasourceUid: tempo
url: '$${__value.raw}'
secureJsonData:
tlsCACert: ${SERVICE_CA_PEM}
tlsClientCert: ${GRAFANA_CLIENT_CERT_PEM}
tlsClientKey: ${GRAFANA_CLIENT_KEY_PEM}
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
httpMethod: GET
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: -1m
spanEndTimeShift: 1m
filterByTraceID: true
filterBySpanID: false
customQuery: true
query: '{$${__tags}} | json | trace_id="$${__trace.traceId}"'
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
search:
hide: false
secureJsonData:
tlsCACert: ${SERVICE_CA_PEM}
tlsClientCert: ${GRAFANA_CLIENT_CERT_PEM}
tlsClientKey: ${GRAFANA_CLIENT_KEY_PEM}
+42
View File
@@ -0,0 +1,42 @@
auth_enabled: false
server:
http_listen_port: 3100
http_tls_config:
cert_file: /run/pki/loki/tls.crt
key_file: /run/pki/loki/tls.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/pki/telemetry-client-ca/ca.crt
common:
path_prefix: /loki
replication_factor: 1
ring:
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 72h
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+51
View File
@@ -0,0 +1,51 @@
groups:
- name: messenger-slo
rules:
- alert: MessengerApiHighErrorRate
expr: |
(
(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5..",http_route!~"/health/.*"}[5m])) or vector(0))
/
clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*"}[5m])), 0.001)
) > 0.05
for: 2m
labels:
severity: warning
slo: api-availability
annotations:
summary: Messenger API 5xx ratio exceeds 5%
description: Five-minute 5xx ratio is above 5% for two minutes.
runbook: infra/otel/runbooks.md#api-high-error-rate
- alert: AttachmentQueueLagHigh
expr: messenger_queue_oldest_job_age_seconds{service_name="messenger-api"} > 60
for: 1m
labels:
severity: warning
slo: attachment-time-to-ready
annotations:
summary: Oldest attachment job is over 60 seconds old
description: The durable worker queue has not drained within the SLO threshold.
runbook: infra/otel/runbooks.md#queue-lag
- alert: AttachmentWorkerSaturated
expr: |
messenger_worker_busy{service_name="messenger-worker"}
/ clamp_min(messenger_worker_capacity{service_name="messenger-worker"}, 1) >= 1
for: 2m
labels:
severity: warning
annotations:
summary: All attachment workers are busy
description: Worker busy/capacity has remained at 100% for two minutes.
runbook: infra/otel/runbooks.md#worker-saturation
- alert: TelemetryExportFailures
expr: sum(rate(otelcol_exporter_send_failed_spans_total[5m])) + sum(rate(otelcol_exporter_send_failed_log_records_total[5m])) > 0
for: 1m
labels:
severity: info
annotations:
summary: Collector is dropping traces or logs
description: A telemetry backend is unavailable or rejecting data.
runbook: infra/otel/runbooks.md#telemetry-backend
+8
View File
@@ -0,0 +1,8 @@
tls_server_config:
cert_file: /run/pki/prometheus/tls.crt
key_file: /run/pki/prometheus/tls.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/pki/telemetry-client-ca/ca.crt
client_allowed_sans:
- spiffe://hla-lab7/grafana
min_version: TLS12
+17
View File
@@ -0,0 +1,17 @@
global:
scrape_interval: 10s
evaluation_interval: 10s
rule_files:
- /etc/prometheus/prometheus-alerts.yaml
scrape_configs:
- job_name: otel-collector-exported-metrics
scheme: https
tls_config:
ca_file: /run/pki/service-ca/ca.crt
server_name: otel-collector
cert_file: /run/pki/prometheus-client/tls.crt
key_file: /run/pki/prometheus-client/tls.key
static_configs:
- targets: ["otel-collector:8889"]
+27
View File
@@ -0,0 +1,27 @@
# Runbooks
## API high error rate
1. In Grafana, compare the 5xx ratio with `db_client_*` pool metrics.
2. Open a failed server span in Tempo and inspect child JDBC/Redis/S3 spans.
3. Search Loki by the trace ID. Do not search by a user, chat or message ID.
4. Restore the failing dependency and confirm the alert resolves after the five-minute window.
## Queue lag
1. Check `messenger_queue_depth` and `messenger_queue_oldest_job_age_seconds`.
2. Check worker busy/capacity and the rate of `messenger_jobs_processed_total` by outcome.
3. Search worker errors in Loki, then open the linked consumer trace in Tempo.
4. Restore or scale the worker and confirm depth and age return to zero.
## Worker saturation
1. Compare busy/capacity with job duration p95 and container CPU/RAM.
2. Inspect slow consumer spans and their S3/JDBC children.
3. Remove the bottleneck before increasing concurrency; memory is explicitly bounded.
## Telemetry backend
1. Inspect Collector exporter failure and queue metrics on port 8888 through Prometheus.
2. Restore Loki or Tempo. Collector retries for at most 60 seconds with a 2048-item queue.
3. Confirm the application remained available; telemetry loss is allowed and bounded.
+40
View File
@@ -0,0 +1,40 @@
server:
http_listen_port: 3200
http_tls_config:
cert_file: /run/pki/tempo/tls.crt
key_file: /run/pki/tempo/tls.key
client_auth_type: RequireAndVerifyClientCert
client_ca_file: /run/pki/telemetry-client-ca/ca.crt
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
tls:
cert_file: /run/pki/tempo/tls.crt
key_file: /run/pki/tempo/tls.key
client_ca_file: /run/pki/telemetry-client-ca/ca.crt
live_store:
max_trace_idle: 10s
max_block_duration: 5m
wal:
path: /var/tempo/live-store/traces
storage:
trace:
backend: local
local:
path: /var/tempo/blocks
overrides:
defaults:
compaction:
block_retention: 72h
usage_report:
reporting_enabled: false
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
psql --set=ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" \
--set=api_password="$DATABASE_API_PASSWORD" \
--set=worker_password="$DATABASE_WORKER_PASSWORD" \
--set=migration_password="$DATABASE_MIGRATION_PASSWORD" <<'SQL'
CREATE ROLE messenger_api LOGIN PASSWORD :'api_password';
CREATE ROLE messenger_worker LOGIN PASSWORD :'worker_password';
CREATE ROLE messenger_migration LOGIN PASSWORD :'migration_password';
GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker, messenger_migration;
GRANT USAGE, CREATE ON SCHEMA public TO messenger_migration;
SQL
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
install -d -m 0700 -o postgres -g postgres /var/lib/postgresql/tls
install -m 0600 -o postgres -g postgres /run/pki/postgres/tls.key /var/lib/postgresql/tls/server.key
install -m 0644 -o postgres -g postgres /run/pki/postgres/tls.crt /var/lib/postgresql/tls/server.crt
exec docker-entrypoint.sh postgres \
-c ssl=on \
-c ssl_min_protocol_version=TLSv1.2 \
-c ssl_cert_file=/var/lib/postgresql/tls/server.crt \
-c ssl_key_file=/var/lib/postgresql/tls/server.key \
-c hba_file=/etc/postgresql/pg_hba.conf
+5
View File
@@ -0,0 +1,5 @@
local all all trust
hostnossl all all 0.0.0.0/0 reject
hostnossl all all ::0/0 reject
hostssl all all 0.0.0.0/0 scram-sha-256
hostssl all all ::0/0 scram-sha-256
+32
View File
@@ -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;
}
}
+13
View File
@@ -0,0 +1,13 @@
listeners.tcp = none
listeners.ssl.default = 5671
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
ssl_options.fail_if_no_peer_cert = true
ssl_options.versions.1 = tlsv1.3
ssl_options.versions.2 = tlsv1.2
management.ssl.port = 15671
management.ssl.cacertfile = /run/pki/service-ca/ca.crt
management.ssl.certfile = /run/pki/rabbitmq/tls.crt
management.ssl.keyfile = /run/pki/rabbitmq/tls.key
+32
View File
@@ -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;
}
}
+21
View File
@@ -0,0 +1,21 @@
[CmdletBinding()]
param(
[string]$Image = 'eclipse-temurin:23-jdk'
)
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
$arguments = @(
'run', '--rm',
'--cpus', '0.75',
'--memory', '768m',
'--mount', "type=bind,source=$root,target=/workspace",
'--mount', 'type=volume,source=hla-lab7-gradle-benchmark,target=/root/.gradle',
'--workdir', '/workspace',
'--entrypoint', '/bin/bash',
$Image,
'-c', 'bash ./gradlew argon2Benchmark --no-daemon --quiet'
)
& docker @arguments
if($LASTEXITCODE -ne 0){ throw 'Argon2id benchmark failed' }
+88
View File
@@ -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."
+95
View File
@@ -0,0 +1,95 @@
[CmdletBinding()]
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $false
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if ([string]::IsNullOrWhiteSpace($env:BAO_TOKEN)) {
throw 'Set BAO_TOKEN to the operator root token only for this bootstrap process.'
}
$values = @{}
foreach($line in [System.IO.File]::ReadAllLines((Resolve-Path $EnvFile))) {
if($line -match '^(?<name>[A-Z][A-Z0-9_]*)=(?<value>.*)$') { $values[$Matches.name]=$Matches.value }
}
function Require-Value([string]$Name) {
if(-not $values.ContainsKey($Name) -or [string]::IsNullOrWhiteSpace($values[$Name])) {
throw "Missing $Name in $EnvFile"
}
return $values[$Name]
}
function Bao([Parameter(ValueFromRemainingArguments=$true)][string[]]$Arguments) {
& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao @Arguments
if($LASTEXITCODE -ne 0){ throw "OpenBao command failed: bao $($Arguments -join ' ')" }
}
function Revoke-AppRoleSecretIds([string]$RoleName) {
# Windows PowerShell 5 wraps native stderr as NativeCommandError. OpenBao
# legitimately returns exit code 2 when this LIST collection is empty, so
# suppress only that invocation and inspect its exit code explicitly.
$previousErrorAction = $ErrorActionPreference
try {
$ErrorActionPreference = 'SilentlyContinue'
$json = (& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao list -format=json "auth/approle/role/$RoleName/secret-id" 2>$null | Out-String).Trim()
$code = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previousErrorAction
}
if($code -eq 2){ return } # OpenBao returns 2 when the collection is empty.
if($code -ne 0){ throw "Failed to list existing SecretID accessors for $RoleName" }
$parsed = $json | ConvertFrom-Json
$accessors = if($parsed.PSObject.Properties.Name -contains 'keys'){ @($parsed.keys) } else { @($parsed) }
foreach($accessor in $accessors) {
if(-not [string]::IsNullOrWhiteSpace($accessor)) {
Bao write "auth/approle/role/$RoleName/secret-id-accessor/destroy" "secret_id_accessor=$accessor" | Out-Null
}
}
}
$secretMounts = (Bao secrets list -format=json | Out-String) | ConvertFrom-Json
if($secretMounts.PSObject.Properties.Name -notcontains 'secret/') {
Bao secrets enable -path=secret -version=2 kv | Out-Null
}
$authMounts = (Bao auth list -format=json | Out-String) | ConvertFrom-Json
if($authMounts.PSObject.Properties.Name -notcontains 'approle/') {
Bao auth enable approle | Out-Null
}
Bao policy write messenger-api /openbao/policies/api-policy.hcl | Out-Null
Bao policy write messenger-worker /openbao/policies/worker-policy.hcl | Out-Null
Bao write auth/approle/role/messenger-api token_policies=messenger-api token_ttl=15m token_max_ttl=1h token_num_uses=0 secret_id_ttl=24h secret_id_num_uses=0 | Out-Null
Bao write auth/approle/role/messenger-worker token_policies=messenger-worker token_ttl=15m token_max_ttl=1h token_num_uses=0 secret_id_ttl=24h secret_id_num_uses=0 | Out-Null
$api = @{
database_password = Require-Value DATABASE_API_PASSWORD
redis_password = Require-Value REDIS_API_PASSWORD
rabbitmq_password = Require-Value RABBITMQ_API_PASSWORD
s3_access_key_id = Require-Value S3_ACCESS_KEY_ID
s3_secret_access_key = Require-Value S3_SECRET_ACCESS_KEY
} | ConvertTo-Json -Compress
$worker = @{
database_password = Require-Value DATABASE_WORKER_PASSWORD
redis_password = Require-Value REDIS_WORKER_PASSWORD
rabbitmq_password = Require-Value RABBITMQ_WORKER_PASSWORD
s3_access_key_id = Require-Value S3_WORKER_ACCESS_KEY_ID
s3_secret_access_key = Require-Value S3_WORKER_SECRET_ACCESS_KEY
} | ConvertTo-Json -Compress
$api | & docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao kv put -mount=secret messenger/api - | Out-Null
if($LASTEXITCODE -ne 0){ throw 'Failed to write API secrets' }
$worker | & docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao kv put -mount=secret messenger/worker - | Out-Null
if($LASTEXITCODE -ne 0){ throw 'Failed to write worker secrets' }
foreach($role in 'api','worker') {
$roleName = "messenger-$role"
$dir = Join-Path $projectRoot "secrets\openbao\$role"
New-Item -ItemType Directory -Path $dir -Force | Out-Null
# A previous interrupted bootstrap may have issued a SecretID without
# persisting it. Revoke each old credential by its non-secret accessor.
Revoke-AppRoleSecretIds $roleName
$roleId = (Bao read -field=role_id "auth/approle/role/$roleName/role-id" | Out-String).Trim()
$secretId = (Bao write -field=secret_id -f "auth/approle/role/$roleName/secret-id" | Out-String).Trim()
[System.IO.File]::WriteAllText((Join-Path $dir 'role-id'),$roleId,[System.Text.Encoding]::ASCII)
[System.IO.File]::WriteAllText((Join-Path $dir 'secret-id'),$secretId,[System.Text.Encoding]::ASCII)
}
Write-Host 'OpenBao policies, AppRoles, KV secrets and agent bootstrap files are ready. Secret values were not printed.'
+119
View File
@@ -0,0 +1,119 @@
[CmdletBinding()]
param([string]$OutputDirectory, [int]$LeafValidityDays = 30)
$ErrorActionPreference = 'Stop'
if ([string]::IsNullOrWhiteSpace($OutputDirectory)) {
$OutputDirectory = Join-Path $PSScriptRoot '..\secrets\pki'
}
New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null
$OutputDirectory = (Resolve-Path -LiteralPath $OutputDirectory).Path
$script:Cas = @{}
function Write-Pem([string]$Path, [string]$Label, [byte[]]$Value) {
$base64 = [Convert]::ToBase64String($Value)
$lines = for($offset=0; $offset -lt $base64.Length; $offset+=64){
$base64.Substring($offset,[Math]::Min(64,$base64.Length-$offset))
}
$pem = "-----BEGIN $Label-----`n" + ($lines -join "`n") + "`n-----END $Label-----`n"
[System.IO.File]::WriteAllText($Path, $pem, [System.Text.Encoding]::ASCII)
}
function Export-PrivateKey($Rsa) {
if ($null -ne $Rsa.PSObject.Methods['ExportPkcs8PrivateKey']) {
return $Rsa.ExportPkcs8PrivateKey()
}
return $Rsa.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob)
}
function New-Ca([string]$Name) {
$rsa = [System.Security.Cryptography.RSA]::Create(3072)
$request = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new(
"CN=HLA Lab 7 $Name", $rsa,
[System.Security.Cryptography.HashAlgorithmName]::SHA256,
[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($true,$false,0,$true))
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new(
[System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyCertSign -bor
[System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::CrlSign,$true))
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension]::new(
$request.PublicKey,$false))
$certificate = $request.CreateSelfSigned([DateTimeOffset]::UtcNow.AddMinutes(-5),[DateTimeOffset]::UtcNow.AddDays(365))
$dir = Join-Path $OutputDirectory $Name
New-Item -ItemType Directory -Path $dir -Force | Out-Null
Write-Pem (Join-Path $dir 'ca.crt') 'CERTIFICATE' $certificate.Export(
[System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
Write-Pem (Join-Path $dir 'ca.key') 'PRIVATE KEY' (Export-PrivateKey $rsa)
$script:Cas[$Name] = $certificate
}
function New-Leaf(
[string]$Name, [string]$CaName, [bool]$ServerAuth,
[string[]]$DnsNames, [string[]]$IpAddresses, [string[]]$Uris) {
$rsa = [System.Security.Cryptography.RSA]::Create(3072)
$request = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new(
"CN=$Name",$rsa,[System.Security.Cryptography.HashAlgorithmName]::SHA256,
[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($false,$false,0,$true))
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new(
[System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::DigitalSignature -bor
[System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyEncipherment,$true))
$eku = [System.Security.Cryptography.OidCollection]::new()
[void]$eku.Add([System.Security.Cryptography.Oid]::new($(if($ServerAuth){'1.3.6.1.5.5.7.3.1'}else{'1.3.6.1.5.5.7.3.2'})))
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension]::new($eku,$false))
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension]::new(
$request.PublicKey,$false))
$request.CertificateExtensions.Add(
[System.Security.Cryptography.X509Certificates.X509AuthorityKeyIdentifierExtension]::CreateFromCertificate(
$script:Cas[$CaName],$true,$false))
$san = [System.Security.Cryptography.X509Certificates.SubjectAlternativeNameBuilder]::new()
foreach($dns in $DnsNames){ $san.AddDnsName($dns) }
foreach($ip in $IpAddresses){ $san.AddIpAddress([System.Net.IPAddress]::Parse($ip)) }
foreach($uri in $Uris){ $san.AddUri([Uri]::new($uri)) }
$request.CertificateExtensions.Add($san.Build($true))
$serial = [byte[]]::new(16)
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($serial)
$rng.Dispose()
$serial[0] = $serial[0] -band 0x7f
$signed = $request.Create($script:Cas[$CaName],[DateTimeOffset]::UtcNow.AddMinutes(-5),
[DateTimeOffset]::UtcNow.AddDays($LeafValidityDays),$serial)
$certificate = $signed
$dir = Join-Path $OutputDirectory $Name
New-Item -ItemType Directory -Path $dir -Force | Out-Null
Write-Pem (Join-Path $dir 'tls.crt') 'CERTIFICATE' $certificate.Export(
[System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
Write-Pem (Join-Path $dir 'tls.key') 'PRIVATE KEY' (Export-PrivateKey $rsa)
Copy-Item (Join-Path $OutputDirectory "$CaName\ca.crt") (Join-Path $dir 'ca.crt') -Force
}
foreach($name in 'public-ca','service-ca','lb-client-ca','workload-client-ca','telemetry-client-ca'){ New-Ca $name }
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')
New-Leaf 'wrong-lb-client' 'lb-client-ca' $false @() @() @('spiffe://hla-lab7/worker')
New-Leaf 'api-client' 'workload-client-ca' $false @() @() @('spiffe://hla-lab7/api')
New-Leaf 'worker-client' 'workload-client-ca' $false @() @() @('spiffe://hla-lab7/worker')
New-Leaf 'migration-client' 'workload-client-ca' $false @() @() @('spiffe://hla-lab7/migration')
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')"
+28
View File
@@ -0,0 +1,28 @@
[CmdletBinding()]
param([string]$Destination, [switch]$Force)
$ErrorActionPreference = 'Stop'
if ([string]::IsNullOrWhiteSpace($Destination)) {
$Destination = Join-Path $PSScriptRoot '..\.env'
}
if ((Test-Path -LiteralPath $Destination) -and -not $Force) {
throw "$Destination already exists; use -Force only for an intentional full credential rotation"
}
$template = Join-Path $PSScriptRoot '..\.env.example'
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
try {
$lines = foreach($line in [System.IO.File]::ReadAllLines($template)) {
if ($line -match '^(?<name>[A-Z][A-Z0-9_]*)=replace-with-') {
$bytes = [byte[]]::new(32)
$rng.GetBytes($bytes)
$secret = [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+','-').Replace('/','_')
"$($Matches.name)=$secret"
} else {
$line
}
}
} finally {
$rng.Dispose()
}
[System.IO.File]::WriteAllLines($Destination,$lines,[System.Text.UTF8Encoding]::new($false))
Write-Host "Created local stand credentials in $Destination; values were not printed."
+40
View File
@@ -0,0 +1,40 @@
[CmdletBinding()]
param(
[string]$OutputDirectory = (Join-Path $PSScriptRoot '..\secrets\tls'),
[int]$ValidityDays = 30
)
$ErrorActionPreference = 'Stop'
if (-not (Get-Command openssl -ErrorAction SilentlyContinue)) {
throw 'openssl is required and was not found in PATH'
}
New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null
$OutputDirectory = (Resolve-Path -LiteralPath $OutputDirectory).Path
$caKey = Join-Path $OutputDirectory 'ca.key'
$caCert = Join-Path $OutputDirectory 'ca.crt'
$serverKey = Join-Path $OutputDirectory 'server.key'
$serverCsr = Join-Path $OutputDirectory 'server.csr'
$serverCert = Join-Path $OutputDirectory 'server.crt'
$extensions = Join-Path $OutputDirectory 'server.ext'
@'
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth
subjectAltName=DNS:localhost,IP:127.0.0.1
'@ | Set-Content -LiteralPath $extensions -Encoding ascii
& openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out $caKey
& openssl req -x509 -new -sha256 -key $caKey -days $ValidityDays `
-subj '/CN=HLA Lab 7 Local CA' -out $caCert
& openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out $serverKey
& openssl req -new -sha256 -key $serverKey -subj '/CN=localhost' -out $serverCsr
& openssl x509 -req -sha256 -in $serverCsr -CA $caCert -CAkey $caKey `
-CAcreateserial -days $ValidityDays -extfile $extensions -out $serverCert
Remove-Item -LiteralPath $serverCsr, $extensions, (Join-Path $OutputDirectory 'ca.srl') -Force -ErrorAction SilentlyContinue
Write-Host "Created local TLS material in $OutputDirectory"
Write-Host "Trust this CA only for the lab: $caCert"
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env sh
set -eu
repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
out_dir=${1:-"$repo_dir/secrets/tls"}
days=${TLS_VALIDITY_DAYS:-30}
command -v openssl >/dev/null 2>&1 || {
echo 'openssl is required and was not found in PATH' >&2
exit 1
}
mkdir -p "$out_dir"
umask 077
cat >"$out_dir/server.ext" <<'EOF'
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth
subjectAltName=DNS:localhost,IP:127.0.0.1
EOF
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out "$out_dir/ca.key"
openssl req -x509 -new -sha256 -key "$out_dir/ca.key" -days "$days" \
-subj '/CN=HLA Lab 7 Local CA' -out "$out_dir/ca.crt"
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out "$out_dir/server.key"
openssl req -new -sha256 -key "$out_dir/server.key" -subj '/CN=localhost' -out "$out_dir/server.csr"
openssl x509 -req -sha256 -in "$out_dir/server.csr" -CA "$out_dir/ca.crt" \
-CAkey "$out_dir/ca.key" -CAcreateserial -days "$days" \
-extfile "$out_dir/server.ext" -out "$out_dir/server.crt"
rm -f "$out_dir/server.csr" "$out_dir/server.ext" "$out_dir/ca.srl"
printf 'Created local TLS material in %s\n' "$out_dir"
printf 'Trust this CA only for the lab: %s/ca.crt\n' "$out_dir"
+74
View File
@@ -0,0 +1,74 @@
[CmdletBinding()]
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
$json = & docker compose --profile verification --env-file $EnvFile config --format json
if($LASTEXITCODE -ne 0){ throw 'docker compose config failed' }
$config = $json | ConvertFrom-Json
$allowedPublished = @{ nginx = 8443; openbao = 8200; grafana = 3000 }
# The only four services with a writable root filesystem. Their stock entrypoints
# prepare a persistent named volume before dropping privileges, so read_only would
# break startup. They still drop the six capabilities listed below.
$statefulWritableRoots = @{
postgres = @{ reason = 'entrypoint chown/chmod of /var/lib/postgresql/data before dropping to the postgres user'; data = '/var/lib/postgresql/data' }
redis = @{ reason = 'entrypoint writes /tmp/users.acl and persists RDB snapshots to the /data volume'; data = '/data' }
rabbitmq = @{ reason = 'entrypoint prepares /var/lib/rabbitmq and the Erlang cookie'; data = '/var/lib/rabbitmq' }
minio = @{ reason = 'Bitnami entrypoint prepares /bitnami/minio/data and the /certs links'; data = '/bitnami/minio/data' }
}
$statefulDroppedCapabilities = @('AUDIT_WRITE','MKNOD','NET_RAW','SETFCAP','SETPCAP','SYS_CHROOT')
foreach($property in $config.services.PSObject.Properties) {
$name = $property.Name
$service = $property.Value
if($service.privileged -eq $true){ throw "$name is privileged" }
if($service.network_mode -eq 'host'){ throw "$name uses host networking" }
if(-not $service.pids_limit -or -not $service.cpus -or -not $service.mem_limit){
throw "$name is missing pids/cpu/memory limits"
}
if(-not ($service.security_opt -contains 'no-new-privileges:true')){
throw "$name is missing no-new-privileges"
}
if(-not $service.cap_drop -or $service.cap_drop.Count -eq 0){ throw "$name has no capability drop policy" }
if(-not @($service.tmpfs) -or @($service.tmpfs).Count -eq 0){
throw "$name has no private tmpfs for runtime scratch data"
}
if($name -in $statefulWritableRoots.Keys) {
if($service.read_only -eq $true){ throw "$name is declared as a stateful writable-root exception but is read_only" }
foreach($capability in $statefulDroppedCapabilities) {
if($service.cap_drop -notcontains $capability){
throw "$name does not drop $capability from its stateful exception profile"
}
}
$expectedData = $statefulWritableRoots[$name].data
$dataVolume = @($service.volumes) | Where-Object { $_.target -eq $expectedData }
if(-not $dataVolume){ throw "$name has no $expectedData persistent volume justifying the writable root" }
} else {
if($service.cap_drop -notcontains 'ALL'){ throw "$name must drop ALL capabilities" }
if($service.read_only -ne $true){ throw "$name must use a read-only root filesystem" }
}
foreach($volume in @($service.volumes) | Where-Object { $null -ne $_ }) {
if($volume.source -match 'docker\.sock' -or $volume.target -match 'docker\.sock'){
throw "$name mounts the Docker socket"
}
}
foreach($port in @($service.ports) | Where-Object { $null -ne $_ }) {
if(-not $allowedPublished.ContainsKey($name) -or [int]$port.target -ne $allowedPublished[$name]){
throw "$name publishes unexpected port $($port.published):$($port.target)"
}
if($port.host_ip -notin @('127.0.0.1','::1')){ throw "$name port is not loopback-bound" }
}
}
foreach($expected in $allowedPublished.Keys){
if(-not $config.services.$expected.ports){ throw "$expected operator/public port is missing" }
}
Write-Host 'PASS: every service has no-new-privileges, a capability drop policy, private tmpfs and resource limits.'
Write-Host 'PASS: non-stateful services use a read-only root and drop ALL capabilities.'
foreach($name in ($statefulWritableRoots.Keys | Sort-Object)){
Write-Host "EXCEPTION $name writable root: $($statefulWritableRoots[$name].reason)"
}
+111
View File
@@ -0,0 +1,111 @@
[CmdletBinding()]
param(
[string]$PkiDirectory,
[int]$MinimumRemainingDays = 7,
[int]$MaximumLeafValidityDays = 31,
[int]$MaximumSecretIdAgeHours = 24
)
$ErrorActionPreference = 'Stop'
$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
$leafCount = 0
foreach($certificateFile in Get-ChildItem -LiteralPath $pki -Recurse -Filter tls.crt) {
$keyFile = Join-Path $certificateFile.DirectoryName 'tls.key'
$caFile = Join-Path $certificateFile.DirectoryName 'ca.crt'
if(-not (Test-Path -LiteralPath $keyFile) -or -not (Test-Path -LiteralPath $caFile)){
throw "Incomplete certificate bundle: $($certificateFile.Directory.Name)"
}
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certificateFile.FullName)
if([DateTimeOffset]$certificate.NotBefore -gt $now.AddMinutes(1)){ throw "$($certificateFile.Directory.Name) certificate is not valid yet" }
if([DateTimeOffset]$certificate.NotAfter -le $now.AddDays($MinimumRemainingDays)){ throw "$($certificateFile.Directory.Name) certificate expires too soon" }
if(($certificate.NotAfter.ToUniversalTime() - $certificate.NotBefore.ToUniversalTime()).TotalDays -gt ($MaximumLeafValidityDays + 1)){
throw "$($certificateFile.Directory.Name) leaf validity exceeds the contract"
}
if(-not ($certificate.Extensions | Where-Object { $_.Oid.Value -eq '2.5.29.17' })){
throw "$($certificateFile.Directory.Name) certificate has no SAN"
}
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' }
$trackedPrivate = & git ls-files -- .env secrets '*.key' '*.p12' '*.pfx' '*.jks' '*.pem'
if($LASTEXITCODE -ne 0){ throw 'git ls-files failed' }
if($trackedPrivate){ throw 'Private material is tracked by Git' }
foreach($path in '.env','secrets/pki/openbao/tls.key'){
& git check-ignore --quiet -- $path
if($LASTEXITCODE -ne 0){ throw "$path is not ignored by Git" }
}
$operatorArtifacts = Get-ChildItem -LiteralPath secrets -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match '(?i)unseal|root[-_.]?token|\.vault-token' }
if($operatorArtifacts){ throw 'Root token or unseal-named operator artifact exists inside the project secrets directory' }
foreach($role in 'api','worker'){
$secretId = Join-Path "secrets\openbao\$role" 'secret-id'
if(Test-Path -LiteralPath $secretId){
$age = $now - [DateTimeOffset](Get-Item -LiteralPath $secretId).LastWriteTimeUtc
if($age.TotalHours -ge $MaximumSecretIdAgeHours){ throw "$role AppRole SecretID reached its rotation deadline" }
}
}
Write-Host "PASS: $leafCount certificate/key bundles are valid; private/operator secrets are untracked; present SecretIDs are within TTL."
+4 -4
View File
@@ -8,8 +8,8 @@ import re
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
def main(): def main():
lab = json.loads((ROOT/'lab.json').read_text())['number'] lab = json.loads((ROOT/'lab.json').read_text(encoding='utf-8'))['number']
spec = json.loads((ROOT/'contracts/openapi.json').read_text()) spec = json.loads((ROOT/'contracts/openapi.json').read_text(encoding='utf-8'))
assert spec['openapi']=='3.1.0' assert spec['openapi']=='3.1.0'
assert spec['info']['version']=='1.%d.0'%lab assert spec['info']['version']=='1.%d.0'%lab
operation_ids = set() operation_ids = set()
@@ -41,11 +41,11 @@ def main():
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2) assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4) assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')): for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
ast.parse(file.read_text(),filename=str(file)) ast.parse(file.read_text(encoding='utf-8'),filename=str(file))
for file in ROOT.rglob('*.json'): for file in ROOT.rglob('*.json'):
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts): if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
continue continue
json.loads(file.read_text()) json.loads(file.read_text(encoding='utf-8'))
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'): for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
assert (ROOT/required).is_file(), 'missing '+required assert (ROOT/required).is_file(), 'missing '+required
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.') print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
+42
View File
@@ -0,0 +1,42 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$Python = 'python',
[string]$BaseUrl = 'https://localhost:8443',
[int]$MinimumInstances = 2,
[switch]$SourceBudget,
[switch]$IncludeArgon2
)
$ErrorActionPreference = 'Stop'
$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
$replicas = @(& docker compose --env-file $EnvFile ps -q api)
if($replicas.Count -lt $MinimumInstances){
throw "At least $MinimumInstances running API replicas are required"
}
# Check storage/logs before the DoS phase consumes the source budget.
& $Python 'tests/credential_storage.py' --base-url $BaseUrl --ca-file $ca --env-file $EnvFile
if($LASTEXITCODE -ne 0){ throw 'Credential storage/log check failed' }
if($IncludeArgon2){
& "$PSScriptRoot\benchmark-argon2.ps1"
if($LASTEXITCODE -ne 0){ throw 'Argon2id benchmark failed' }
}
$testArguments = @(
'tests/login_dos.py',
'--base-url', $BaseUrl,
'--ca-file', $ca,
'--minimum-instances', "$MinimumInstances"
)
if($SourceBudget){ $testArguments += '--source-budget' }
& $Python @testArguments
if($LASTEXITCODE -ne 0){ throw 'Login DoS budget test failed' }
Write-Host 'PASS: shared login budget, fast rate-limit rejection and credential non-disclosure verified.'
+12
View File
@@ -0,0 +1,12 @@
@echo off
setlocal EnableExtensions
cd /d "%~dp0\.."
if not defined ENV_FILE set "ENV_FILE=.env"
docker compose --env-file "%ENV_FILE%" stop nginx api worker redis postgres minio rabbitmq || exit /b 1
docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 postgres redis minio rabbitmq || exit /b 1
docker compose --env-file "%ENV_FILE%" run --rm minio-init || exit /b 1
docker compose --env-file "%ENV_FILE%" run --rm rabbitmq-init || exit /b 1
docker compose --env-file "%ENV_FILE%" up -d --no-deps worker || exit /b 1
docker compose --env-file "%ENV_FILE%" up -d --no-deps --scale api=2 api || exit /b 1
docker compose --env-file "%ENV_FILE%" up -d --no-deps nginx || exit /b 1
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
set -eu
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PROJECT_DIR=$(dirname -- "$SCRIPT_DIR")
cd "$PROJECT_DIR"
: "${ENV_FILE:=.env}"
# Preserve named volumes and the network. The migration job is intentionally
# not re-run during a same-version restart.
docker compose --env-file "$ENV_FILE" stop nginx api worker redis postgres minio rabbitmq
docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 postgres redis minio rabbitmq
docker compose --env-file "$ENV_FILE" run --rm minio-init
docker compose --env-file "$ENV_FILE" run --rm rabbitmq-init
docker compose --env-file "$ENV_FILE" up -d --no-deps worker
docker compose --env-file "$ENV_FILE" up -d --no-deps --scale api=2 api
docker compose --env-file "$ENV_FILE" up -d --no-deps nginx
+132
View File
@@ -0,0 +1,132 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[int]$Port = 3000
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
$envPath = Join-Path $projectRoot $EnvFile
$caCertificate = Join-Path $projectRoot 'secrets\pki\service-ca\ca.crt'
if (-not (Test-Path -LiteralPath $envPath)) { throw "Missing env file: $EnvFile" }
if (-not (Test-Path -LiteralPath $caCertificate)) { throw "Missing service CA: $caCertificate" }
function Get-EnvValue([string]$Name) {
foreach ($line in [System.IO.File]::ReadAllLines($envPath)) {
if ($line -match "^\s*$([regex]::Escape($Name))=(.*)$") {
return $Matches[1].Trim().Trim('"')
}
}
return $null
}
function Set-EnvValue([string]$Name, [string]$Value) {
$lines = [System.IO.File]::ReadAllLines($envPath)
$updated = $false
for ($index = 0; $index -lt $lines.Count; $index++) {
if ($lines[$index] -match "^\s*$([regex]::Escape($Name))=") {
$lines[$index] = "$Name=$Value"
$updated = $true
break
}
}
if (-not $updated) { throw "$Name is missing from $EnvFile" }
[System.IO.File]::WriteAllLines($envPath, $lines, [System.Text.UTF8Encoding]::new($false))
}
function Invoke-Grafana([string]$User, [string]$Password, [string]$Path,
[string]$Method = 'GET', [string]$Body = '') {
$arguments = @('-sS','-o','NUL','-w','%{http_code}','--cacert',$caCertificate,
'--ssl-no-revoke','--connect-timeout','5','--max-time','15','-u',"$User`:$Password")
if ($Method -ne 'GET') { $arguments += @('-X',$Method) }
$bodyFile = $null
if ($Body) {
# curl.exe on Windows must receive JSON from a file: inline arguments
# are quote-stripped, and PowerShell's default UTF-8 writer adds a BOM.
$bodyFile = Join-Path ([System.IO.Path]::GetTempPath()) ("grafana-rotation-" + [guid]::NewGuid().ToString('N') + '.json')
[System.IO.File]::WriteAllText($bodyFile, $Body, [System.Text.UTF8Encoding]::new($false))
$arguments += @('-H','Content-Type: application/json','--data-binary',"@$bodyFile")
}
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$code = (& curl.exe @arguments "https://localhost:$Port$Path" 2>$null | Out-String).Trim()
} finally {
$ErrorActionPreference = $previous
if ($bodyFile) { Remove-Item -LiteralPath $bodyFile -Force -ErrorAction SilentlyContinue }
}
return $code
}
function Invoke-ComposeQuiet([string[]]$Arguments) {
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& docker compose @Arguments 2>&1 | Out-Null
$code = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if ($code -ne 0) { throw "docker compose failed with exit code $code" }
}
function New-RotationPassword {
$bytes = New-Object byte[] 24
$generator = [System.Security.Cryptography.RandomNumberGenerator]::Create()
try { $generator.GetBytes($bytes) } finally { $generator.Dispose() }
return [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=')
}
$user = Get-EnvValue 'GRAFANA_ADMIN_USER'
if ([string]::IsNullOrWhiteSpace($user)) { $user = 'admin' }
$oldPassword = Get-EnvValue 'GRAFANA_ADMIN_PASSWORD'
if ([string]::IsNullOrWhiteSpace($oldPassword)) { throw 'GRAFANA_ADMIN_PASSWORD is missing from the env file' }
$newPassword = New-RotationPassword
$imageBefore = (& docker inspect --format '{{.Image}}' hla-lab7-grafana-1 2>$null | Out-String).Trim()
if ((Invoke-Grafana $user $oldPassword '/api/user') -ne '200') {
throw 'Current Grafana admin credentials were not accepted before rotation'
}
$body = @{
oldPassword = $oldPassword
newPassword = $newPassword
confirmNew = $newPassword
} | ConvertTo-Json -Compress
$rotationStatus = Invoke-Grafana $user $oldPassword '/api/user/password' 'PUT' $body
if ($rotationStatus -ne '200' -and $rotationStatus -ne '204') {
throw "Grafana password API returned an unexpected status: $rotationStatus"
}
$envBackup = [System.IO.File]::ReadAllBytes($envPath)
try {
Set-EnvValue 'GRAFANA_ADMIN_PASSWORD' $newPassword
Invoke-ComposeQuiet @('--env-file',$EnvFile,'up','-d','--no-deps','--force-recreate','grafana')
$ready = $false
for ($attempt = 0; $attempt -lt 30; $attempt++) {
if ((Invoke-Grafana $user $newPassword '/api/user') -eq '200') { $ready = $true; break }
Start-Sleep -Seconds 2
}
if (-not $ready) { throw 'Rotated Grafana credentials were not accepted after container recreate' }
if ((Invoke-Grafana $user $oldPassword '/api/user') -eq '200') {
throw 'Old Grafana password is still accepted after rotation'
}
} catch {
[System.IO.File]::WriteAllBytes($envPath, $envBackup)
$rollbackBody = @{
oldPassword = $newPassword
newPassword = $oldPassword
confirmNew = $oldPassword
} | ConvertTo-Json -Compress
Invoke-Grafana $user $newPassword '/api/user/password' 'PUT' $rollbackBody | Out-Null
throw
}
$imageAfter = (& docker inspect --format '{{.Image}}' hla-lab7-grafana-1 2>$null | Out-String).Trim()
if ($imageBefore -ne $imageAfter) { throw 'Grafana image changed during rotation' }
Write-Host 'PASS: Grafana admin password rotated through the API and .env without rebuilding images.'
Write-Host "old_password_accepted_after=false"
Write-Host "new_password_accepted_after=true"
Write-Host "grafana_image=$imageAfter"
+16
View File
@@ -0,0 +1,16 @@
[CmdletBinding()]
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if ([string]::IsNullOrWhiteSpace($env:BAO_TOKEN)) { throw 'Set BAO_TOKEN for this operator action.' }
foreach($role in 'api','worker') {
$roleName = "messenger-$role"
$directory = Join-Path $projectRoot "secrets\openbao\$role"
New-Item -ItemType Directory -Path $directory -Force | Out-Null
$secretId = (& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao write -field=secret_id -f "auth/approle/role/$roleName/secret-id" | Out-String).Trim()
if($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($secretId)){ throw "Failed to rotate $roleName SecretID" }
[System.IO.File]::WriteAllText((Join-Path $directory 'secret-id'),$secretId,[System.Text.Encoding]::ASCII)
}
Write-Host 'AppRole SecretIDs rotated without printing their values.'
+136
View File
@@ -0,0 +1,136 @@
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][string]$Leaf,
[Parameter(Mandatory=$true)][string]$CaName,
[string[]]$UriSan = @(),
[string[]]$DnsName = @(),
[string[]]$IpAddress = @(),
[switch]$ServerAuth,
[switch]$RevokeOld,
[string]$Image = 'nginx:1.27.4-bookworm'
)
$ErrorActionPreference = 'Stop'
$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."
}
$pki = Join-Path $projectRoot 'secrets\pki'
$leafDir = Join-Path $pki $Leaf
$caCertificate = Join-Path $pki "$CaName\ca.crt"
$caKey = Join-Path $pki "$CaName\ca.key"
foreach ($path in @($leafDir, $caCertificate, $caKey)) {
if (-not (Test-Path $path)) { throw "Missing PKI input: $path" }
}
$sanLines = @()
$index = 1
foreach ($value in $UriSan) { $sanLines += "URI.$index = $value"; $index++ }
$index = 1
foreach ($value in $DnsName) { $sanLines += "DNS.$index = $value"; $index++ }
$index = 1
foreach ($value in $IpAddress) { $sanLines += "IP.$index = $value"; $index++ }
if ($sanLines.Count -eq 0) { throw 'At least one SAN value is required for a rotated leaf.' }
$eku = if ($ServerAuth) { 'serverAuth' } else { 'clientAuth' }
$config = @"
[req]
distinguished_name = dn
prompt = no
[dn]
CN = $Leaf
[v3_leaf]
basicConstraints = critical,CA:FALSE
keyUsage = critical,digitalSignature,keyEncipherment
extendedKeyUsage = $eku
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
subjectAltName = @san
[san]
$($sanLines -join "`n")
"@
$configDir = Join-Path ([System.IO.Path]::GetTempPath()) ("pki-rotate-" + [guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $configDir -Force | Out-Null
[System.IO.File]::WriteAllText((Join-Path $configDir 'leaf.cnf'), $config, [System.Text.Encoding]::ASCII)
function Invoke-Docker([string[]]$Arguments, [switch]$Capture) {
# Windows PowerShell 5 wraps native stderr as terminating errors when
# ErrorActionPreference is Stop; openssl writes progress there.
$previous = $ErrorActionPreference
try {
$ErrorActionPreference = 'Continue'
if ($Capture) {
$output = (& docker @Arguments 2>&1 | Out-String)
} else {
& docker @Arguments 2>&1 | Out-Null
$output = ''
}
$code = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if ($code -ne 0) { throw "Docker command failed with exit code $code" }
return $output
}
function Get-CertificateFingerprint([string]$CertificatePath) {
$relative = $CertificatePath.Substring($pki.Length).TrimStart('\','/').Replace('\','/')
$output = Invoke-Docker @('run','--rm', `
"--mount=type=bind,source=$pki,target=/pki,readonly", `
'--entrypoint','sh',$Image,'-c', `
"openssl x509 -in /pki/$relative -outform DER | sha256sum | cut -d' ' -f1") -Capture
return ($output.Trim() -split "`n")[-1].Trim().ToLowerInvariant()
}
try {
$revokedDir = Join-Path $pki "revoked\$Leaf"
New-Item -ItemType Directory -Path $revokedDir -Force | Out-Null
Copy-Item (Join-Path $leafDir 'tls.crt') (Join-Path $revokedDir 'tls.crt') -Force
Copy-Item (Join-Path $leafDir 'tls.key') (Join-Path $revokedDir 'tls.key') -Force
Copy-Item (Join-Path $leafDir 'ca.crt') (Join-Path $revokedDir 'ca.crt') -Force
Invoke-Docker @('run','--rm', `
"--mount=type=bind,source=$pki,target=/pki", `
'--entrypoint','chmod',$Image,'0644', `
"/pki/revoked/$Leaf/tls.crt","/pki/revoked/$Leaf/tls.key","/pki/revoked/$Leaf/ca.crt") | Out-Null
$oldFingerprint = Get-CertificateFingerprint (Join-Path $revokedDir 'tls.crt')
$script = @"
openssl req -new -newkey rsa:3072 -nodes -keyout /pki/$Leaf/tls.key.next -out /pki/$Leaf/tls.csr -config /config/leaf.cnf &&
openssl x509 -req -in /pki/$Leaf/tls.csr -CA /pki/$CaName/ca.crt -CAkey /pki/$CaName/ca.key -CAserial /config/ca.srl -CAcreateserial -out /pki/$Leaf/tls.crt.next -days 30 -sha256 -extfile /config/leaf.cnf -extensions v3_leaf &&
chmod 0644 /pki/$Leaf/tls.key.next /pki/$Leaf/tls.crt.next &&
rm -f /pki/$Leaf/tls.csr
"@
Invoke-Docker @('run','--rm', `
"--mount=type=bind,source=$pki,target=/pki", `
"--mount=type=bind,source=$configDir,target=/config", `
'--entrypoint','sh',$Image,'-c',$script) | Out-Null
foreach ($name in 'tls.key.next', 'tls.crt.next') {
if (-not (Test-Path (Join-Path $leafDir $name))) { throw "OpenSSL did not produce $name" }
}
Move-Item -Force (Join-Path $leafDir 'tls.key.next') (Join-Path $leafDir 'tls.key')
Move-Item -Force (Join-Path $leafDir 'tls.crt.next') (Join-Path $leafDir 'tls.crt')
$newFingerprint = Get-CertificateFingerprint (Join-Path $leafDir 'tls.crt')
if ($newFingerprint -eq $oldFingerprint) { throw 'Rotation did not change the leaf certificate' }
if ($RevokeOld) {
$revocationFile = Join-Path $pki 'revoked-client-sha256.txt'
$lines = if (Test-Path $revocationFile) {
@([System.IO.File]::ReadAllLines($revocationFile))
} else { @() }
if ($lines -notcontains $oldFingerprint) {
Add-Content -Path $revocationFile -Value $oldFingerprint -Encoding ASCII
}
}
Write-Host "ROTATED $Leaf (CA $CaName) without rebuilding images."
Write-Host "old_leaf_sha256=$oldFingerprint"
Write-Host "new_leaf_sha256=$newFingerprint"
if ($RevokeOld) { Write-Host "revoked_old_leaf=$oldFingerprint" }
}
finally {
Remove-Item -Recurse -Force $configDir -ErrorAction SilentlyContinue
}
+123
View File
@@ -0,0 +1,123 @@
[CmdletBinding()]
param(
[string]$Gradlew = '.\gradlew.bat',
[string]$Configuration = 'runtimeClasspath',
[string]$OsvEndpoint = 'https://api.osv.dev/v1/querybatch',
[string]$JsonPath = '',
[switch]$FailOnHigh
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if (-not (Test-Path -LiteralPath $Gradlew)) { throw "Missing Gradle wrapper: $Gradlew" }
function Get-ResolvedCoordinates([string]$Text) {
$resolved = @{}
foreach ($line in ($Text -split "`r?`n")) {
if ($line -match '^\s*[|+\\ -]*[+\\]---\s+([A-Za-z0-9_.-]+):([A-Za-z0-9_.-]+)(?::([0-9][A-Za-z0-9_.+-]*))?') {
$group = $Matches[1]
$artifact = $Matches[2]
$version = $Matches[3]
$remainder = $line.Substring($Matches[0].Length)
if ($remainder -match '->\s*([A-Za-z0-9_.+-]+)') { $version = $Matches[1] }
if ($version) { $resolved["$group`:$artifact"] = $version }
}
}
return $resolved
}
function Invoke-OsvBatch([array]$Queries) {
$body = @{ queries = $Queries } | ConvertTo-Json -Depth 8 -Compress
$response = Invoke-RestMethod -Method Post -Uri $OsvEndpoint -Body $body `
-ContentType 'application/json' -TimeoutSec 90
if ($null -eq $response.results) { throw 'OSV batch response has no results' }
return $response.results
}
function Get-Severity($Vulnerability) {
if ($Vulnerability.database_specific -and $Vulnerability.database_specific.severity) {
return ([string]$Vulnerability.database_specific.severity).ToUpperInvariant()
}
return 'UNKNOWN'
}
function Get-FixedVersions($Vulnerability) {
$fixed = @()
foreach ($affected in @($Vulnerability.affected)) {
foreach ($range in @($affected.ranges)) {
foreach ($event in @($range.events)) {
if ($event.fixed) { $fixed += [string]$event.fixed }
}
}
}
return @($fixed | Sort-Object -Unique)
}
$dependencyOutput = & $Gradlew dependencies "--configuration=$Configuration" --no-daemon --console=plain 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) { throw 'Gradle dependency resolution failed' }
$coordinates = Get-ResolvedCoordinates $dependencyOutput
$names = @($coordinates.Keys | Sort-Object)
if ($names.Count -eq 0) { throw 'No resolved dependencies were found' }
$queries = @($names | ForEach-Object {
@{ package = @{ name = $_; ecosystem = 'Maven' }; version = $coordinates[$_] }
})
$results = @()
for ($offset = 0; $offset -lt $queries.Count; $offset += 100) {
$slice = @($queries | Select-Object -Skip $offset -First 100)
$results += @(Invoke-OsvBatch $slice)
}
if ($results.Count -ne $queries.Count) { throw 'OSV returned an incomplete batch result' }
# querybatch returns only IDs; fetch each advisory once for severity/fix metadata.
$vulnerabilityIds = @()
foreach ($result in $results) {
if ($result.vulns) { $vulnerabilityIds += @($result.vulns | ForEach-Object { $_.id }) }
}
$vulnerabilityIds = @($vulnerabilityIds | Sort-Object -Unique)
$advisories = @{}
foreach ($id in $vulnerabilityIds) {
$advisories[$id] = Invoke-RestMethod -Uri "https://api.osv.dev/v1/vulns/$id" -TimeoutSec 60
}
$findings = @()
for ($index = 0; $index -lt $results.Count; $index++) {
if (-not $results[$index].vulns) { continue }
foreach ($reference in $results[$index].vulns) {
$vulnerability = $advisories[$reference.id]
if (-not $vulnerability) { throw "OSV advisory detail is missing for $($reference.id)" }
$aliases = @($vulnerability.aliases | Where-Object { $_ -like 'CVE-*' })
$findings += [pscustomobject]@{
package = $names[$index]
version = $coordinates[$names[$index]]
id = $vulnerability.id
cve = if ($aliases.Count) { $aliases[0] } else { '' }
severity = Get-Severity $vulnerability
fixed = @(Get-FixedVersions $vulnerability) -join ','
summary = [string]$vulnerability.summary
}
}
}
if ($JsonPath) {
[System.IO.File]::WriteAllText($JsonPath, ($findings | ConvertTo-Json -Depth 6),
[System.Text.UTF8Encoding]::new($false))
}
$severityCounts = @{}
foreach ($finding in $findings) {
$key = $finding.severity
if (-not $severityCounts.ContainsKey($key)) { $severityCounts[$key] = 0 }
$severityCounts[$key]++
}
Write-Host "Resolved OSV Maven dependencies: $($names.Count)"
Write-Host "Packages with findings: $(@($findings | Select-Object -ExpandProperty package -Unique).Count)"
Write-Host "Findings by severity: $(($severityCounts.GetEnumerator() | Sort-Object Name | ForEach-Object { "$($_.Name)=$($_.Value)" }) -join ' ')"
foreach ($finding in @($findings | Where-Object { $_.severity -in @('HIGH','CRITICAL') } | Sort-Object package, id)) {
Write-Host "HIGH_OR_CRITICAL $($finding.id) $($finding.cve) $($finding.package)@$($finding.version) fixed=$($finding.fixed)"
Write-Host " $($finding.summary)"
}
if ($FailOnHigh -and @($findings | Where-Object { $_.severity -in @('HIGH','CRITICAL') }).Count -gt 0) {
throw 'High or critical dependency findings require triage before this check can pass'
}
+26
View File
@@ -0,0 +1,26 @@
@echo off
setlocal EnableExtensions EnableDelayedExpansion
if "%TARGET_INSTANCE_ID%"=="" exit /b 2
cd /d "%~dp0\.."
if not defined ENV_FILE set "ENV_FILE=.env"
set "TARGET_CONTAINER="
set /a MATCHES=0
for /f "usebackq delims=" %%C in (`docker compose --env-file "%ENV_FILE%" ps -q api`) do (
set "CONTAINER_ID=%%C"
set "SHORT_ID=!CONTAINER_ID:~0,12!"
set "HOSTNAME_VALUE="
for /f "usebackq delims=" %%H in (`docker inspect --format "{{.Config.Hostname}}" %%C`) do set "HOSTNAME_VALUE=%%H"
if "!HOSTNAME_VALUE!"=="%TARGET_INSTANCE_ID%" (
set "TARGET_CONTAINER=%%C"
set /a MATCHES+=1
) else if "!SHORT_ID!"=="%TARGET_INSTANCE_ID%" (
set "TARGET_CONTAINER=%%C"
set /a MATCHES+=1
)
)
if not "!MATCHES!"=="1" exit /b 2
docker stop --time 5 "!TARGET_CONTAINER!" >nul
exit /b %ERRORLEVEL%
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PROJECT_DIR=$(dirname -- "$SCRIPT_DIR")
cd "$PROJECT_DIR"
: "${ENV_FILE:=.env}"
target=""
matches=0
for container_id in $(docker compose --env-file "$ENV_FILE" ps -q api); do
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id")
short_id=$(printf '%s' "$container_id" | cut -c1-12)
if [ "$TARGET_INSTANCE_ID" = "$hostname" ] || [ "$TARGET_INSTANCE_ID" = "$short_id" ]; then
target=$container_id
matches=$((matches + 1))
fi
done
if [ "$matches" -ne 1 ]; then
printf '%s\n' "Expected one API replica for X-Instance-Id, found $matches" >&2
exit 2
fi
# Five seconds keeps the operator hook below the test's ten-second budget while
# still delivering SIGTERM and allowing Spring's graceful shutdown phase.
docker stop --time 5 "$target" >/dev/null
@@ -0,0 +1,163 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$ApplicationImage = 'hla-lab7-app:local'
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
function Invoke-CheckedDocker {
param([Parameter(Mandatory=$true)][string[]]$Arguments, [string]$Failure = 'Docker command failed')
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$output = & docker @Arguments 2>&1
$exitCode = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($exitCode -ne 0){ throw "$Failure (exit $exitCode)" }
return $output
}
function Get-ComposeArguments {
param([string[]]$Tail)
return @('compose','--env-file',$EnvFile) + $Tail
}
function Get-SecretCandidates {
if(-not (Test-Path -LiteralPath $EnvFile)){ return @() }
$result = @()
foreach($line in Get-Content -LiteralPath $EnvFile) {
if($line -notmatch '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$'){ continue }
$name = $Matches[1]
$value = $Matches[2].Trim()
if($value.Length -ge 8 -and $name -match '(?i)(PASSWORD|TOKEN|SECRET|PRIVATE_KEY|UNSEAL|CREDENTIAL)') {
$result += [pscustomobject]@{ Name = $name; Value = $value }
}
}
return $result
}
$configText = Invoke-CheckedDocker (Get-ComposeArguments @('--profile','verification','config','--format','json')) 'docker compose config failed'
$config = ($configText -join "`n") | ConvertFrom-Json
$allowedPorts = @{
nginx = @{ ContainerPort = '8443/tcp'; PublishedPort = '8443' }
openbao = @{ ContainerPort = '8200/tcp'; PublishedPort = '8200' }
grafana = @{ ContainerPort = '3000/tcp'; PublishedPort = '3000' }
}
foreach($property in $config.services.PSObject.Properties) {
$name = $property.Name
$service = $property.Value
if($service.privileged -eq $true){ throw "$name is privileged" }
if($service.network_mode -eq 'host'){ throw "$name uses host networking" }
foreach($volume in @($service.volumes) | Where-Object { $null -ne $_ }) {
if("$($volume.source) $($volume.target)" -match '(?i)docker\.sock') { throw "$name mounts the Docker socket" }
}
}
foreach($serviceName in 'api','worker') {
$service = $config.services.$serviceName
if(-not ($service.cap_drop -contains 'ALL')){ throw "$serviceName does not drop all capabilities" }
if(@($service.cap_add | Where-Object { $null -ne $_ }).Count -gt 0){ throw "$serviceName adds capabilities" }
if(-not $service.cpus -or -not $service.mem_limit -or -not $service.pids_limit){ throw "$serviceName has incomplete resource limits" }
if($service.read_only -ne $true){ throw "$serviceName root filesystem is writable" }
if(-not ($service.security_opt -contains 'no-new-privileges:true')){ throw "$serviceName lacks no-new-privileges" }
}
$runningServices = @(Invoke-CheckedDocker (Get-ComposeArguments @('ps','--services','--status','running')) 'Cannot list running services')
foreach($required in 'api','worker') {
if($runningServices -notcontains $required){ throw "$required must be running for the runtime boundary check" }
$uid = ((Invoke-CheckedDocker (Get-ComposeArguments @('exec','-T',$required,'id','-u')) "Cannot read $required runtime UID") -join '').Trim()
if($uid -notmatch '^\d+$' -or [int]$uid -eq 0){ throw "$required runs as root" }
}
$containerIds = @(Invoke-CheckedDocker (Get-ComposeArguments @('ps','-q')) 'Cannot list Compose containers') | Where-Object { $_ }
if($containerIds.Count -eq 0){ throw 'No running Compose containers found' }
foreach($containerId in $containerIds) {
$inspect = ((Invoke-CheckedDocker @('inspect',$containerId) 'Container inspect failed') -join "`n") | ConvertFrom-Json
$container = $inspect[0]
$serviceName = $container.Config.Labels.'com.docker.compose.service'
if($container.HostConfig.Privileged){ throw "$serviceName runtime container is privileged" }
if($container.HostConfig.NetworkMode -eq 'host'){ throw "$serviceName runtime container uses host networking" }
if(-not $container.HostConfig.PidsLimit -or -not $container.HostConfig.Memory -or -not $container.HostConfig.NanoCpus){
throw "$serviceName runtime container is missing resource limits"
}
if($serviceName -in @('api','worker')) {
if(-not ($container.HostConfig.CapDrop -contains 'ALL')){ throw "$serviceName runtime container does not drop all capabilities" }
if(@($container.HostConfig.CapAdd | Where-Object { $null -ne $_ }).Count -gt 0){ throw "$serviceName runtime container adds capabilities" }
if(-not $container.HostConfig.ReadonlyRootfs){ throw "$serviceName runtime root filesystem is writable" }
if(-not ($container.HostConfig.SecurityOpt -contains 'no-new-privileges:true')){ throw "$serviceName runtime container lacks no-new-privileges" }
}
foreach($mount in @($container.Mounts)) {
if("$($mount.Source) $($mount.Destination)" -match '(?i)docker\.sock'){ throw "$serviceName runtime container mounts the Docker socket" }
}
foreach($portProperty in $container.NetworkSettings.Ports.PSObject.Properties) {
foreach($binding in @($portProperty.Value) | Where-Object { $null -ne $_ }) {
if(-not $allowedPorts.ContainsKey($serviceName)){ throw "$serviceName publishes unexpected port $($portProperty.Name)" }
$expected = $allowedPorts[$serviceName]
if($portProperty.Name -ne $expected.ContainerPort -or $binding.HostPort -ne $expected.PublishedPort){
throw "$serviceName publishes unexpected binding $($binding.HostPort):$($portProperty.Name)"
}
if($binding.HostIp -notin @('127.0.0.1','::1')){ throw "$serviceName is not loopback-bound" }
}
}
}
$trackedPrivate = @(& git ls-files -- .env 'secrets/*' '*.key' '*.pem' '*.p12' '*.pfx' '*.jks')
if($LASTEXITCODE -ne 0){ throw 'git ls-files failed' }
if($trackedPrivate.Count -gt 0){ throw 'Git tracks private material' }
$dockerIgnore = Get-Content -LiteralPath '.dockerignore' -Raw
foreach($requiredRule in '(?m)^\.env\r?$','(?m)^secrets\r?$','(?m)^\*\.key\r?$') {
if($dockerIgnore -notmatch $requiredRule){ throw ".dockerignore is missing required rule $requiredRule" }
}
$secretCandidates = @(Get-SecretCandidates)
$trackedFiles = @(& git ls-files)
if($LASTEXITCODE -ne 0){ throw 'git ls-files failed' }
$textExtensions = @('.md','.txt','.yaml','.yml','.json','.xml','.properties','.conf','.hcl','.ps1','.sh','.java','.gradle','.example')
foreach($path in $trackedFiles) {
if(-not (Test-Path -LiteralPath $path -PathType Leaf)){ continue }
$item = Get-Item -LiteralPath $path
if($item.Length -gt 5MB -or $textExtensions -notcontains $item.Extension){ continue }
$content = [System.IO.File]::ReadAllText($item.FullName)
foreach($candidate in $secretCandidates) {
if($content.Contains($candidate.Value)){ throw "Git-tracked file contains value from $($candidate.Name)" }
}
}
$imageInspectText = Invoke-CheckedDocker @('image','inspect',$ApplicationImage) "Application image $ApplicationImage is unavailable"
$imageInspect = (($imageInspectText -join "`n") | ConvertFrom-Json)[0]
$imageMetadata = (($imageInspect.Config.Env -join "`n") + "`n" + ((Invoke-CheckedDocker @('history','--no-trunc','--format','{{.CreatedBy}}',$ApplicationImage) 'Image history failed') -join "`n"))
foreach($candidate in $secretCandidates) {
if($imageMetadata.Contains($candidate.Value)){ throw "Application image metadata contains value from $($candidate.Name)" }
}
Invoke-CheckedDocker @('run','--rm','--entrypoint','sh',$ApplicationImage,'-c','test ! -e /app/.env && test ! -e /app/secrets && test ! -e /app/runtime.env && ! find /app -type f \( -name "*.key" -o -name "*.p12" -o -name "*.jks" \) -print -quit | grep -q .') 'Application image contains a forbidden secret artifact' | Out-Null
$composeLogs = (Invoke-CheckedDocker (Get-ComposeArguments @('logs','--no-color','--tail','2000')) 'Cannot read Compose logs') -join "`n"
foreach($candidate in $secretCandidates) {
if($composeLogs.Contains($candidate.Value)){ throw "Container logs contain value from $($candidate.Name)" }
}
$collector = Get-Content -LiteralPath 'infra/otel/collector.yaml' -Raw
foreach($attribute in 'http.request.header.authorization','http.request.body','http.response.body','messaging.message.body','db.statement.parameters','url.query') {
if($collector -notmatch "(?m)^\s*- key: $([regex]::Escape($attribute))\s*$"){ throw "Telemetry redaction is missing $attribute" }
}
foreach($pipeline in 'traces','metrics','logs') {
if($collector -notmatch "(?ms)^\s{4}${pipeline}:\s+.*?processors:\s*\[[^\]]*attributes/redact[^\]]*\]"){
throw "Telemetry $pipeline pipeline does not use attributes/redact"
}
}
foreach($serviceName in 'api','worker') {
$environment = $config.services.$serviceName.environment
if($environment.OTEL_INSTRUMENTATION_HTTP_SERVER_CAPTURE_REQUEST_HEADERS -ne '' -or
$environment.OTEL_INSTRUMENTATION_HTTP_SERVER_CAPTURE_RESPONSE_HEADERS -ne '') {
throw "$serviceName enables HTTP header capture"
}
}
Write-Host "PASS: runtime isolation, non-root app/worker, resource and port boundaries, Git/image/log secret isolation, and telemetry redaction are enforced. Checked $($secretCandidates.Count) local secret values without printing them."
+157
View File
@@ -0,0 +1,157 @@
[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_foreign_ca_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" \
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key \
>/tmp/tls-probe.log 2>&1
status=$?
set -e
if [ "$status" -eq 0 ] || ! grep -Eq 'unknown ca|certificate unknown|bad certificate' /tmp/tls-probe.log; then
echo "FAIL: $label accepted a client certificate from a foreign CA" >&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 grafana grafana:3000 grafana
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-api rabbit-api-gateway:5671 rabbit-api-gateway \
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
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-gateway:4318 otel-gateway \
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
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_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_foreign_ca_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_ok loki-query loki:3100 loki \
-cert /run/pki/grafana-client/tls.crt -key /run/pki/grafana-client/tls.key
probe_rejected loki loki:3100 loki
probe_foreign_ca_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_foreign_ca_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_foreign_ca_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
probe_foreign_ca_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 and foreign-CA 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'
}
& (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.'
+49
View File
@@ -0,0 +1,49 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$BaseUrl = 'https://localhost:8443',
[string]$Python = 'python',
[switch]$SkipWorkerUnitTests,
[switch]$SkipPublicSecurity,
[switch]$IncludeFreshOpenBaoPolicy
)
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
& "$PSScriptRoot\test-mtls.ps1" -EnvFile $EnvFile
if($LASTEXITCODE -ne 0){ throw 'LB-to-API mTLS audit failed' }
if(-not $SkipPublicSecurity) {
$ca = (Resolve-Path 'secrets\pki\public-ca\ca.crt').Path
& $Python tests/security.py --base-url $BaseUrl --ca-file $ca
if($LASTEXITCODE -ne 0){ throw 'Public TLS/ACL negative audit failed' }
}
# Includes server CA/hostname checks for every declared internal TLS endpoint,
# no-cert/foreign-CA checks, DB/Redis/RabbitMQ ACLs and exact role gateways.
& "$PSScriptRoot\test-internal-tls.ps1" -EnvFile $EnvFile
if($LASTEXITCODE -ne 0){ throw 'Internal TLS/ACL audit failed' }
& docker compose --env-file $EnvFile --profile verification run --rm private-bucket-check
if($LASTEXITCODE -ne 0){ throw 'MinIO private-bucket/API-worker ACL audit failed' }
& "$PSScriptRoot\test-openbao-runtime-boundaries.ps1" -EnvFile $EnvFile -SkipLivePolicy
if($LASTEXITCODE -ne 0){ throw 'OpenBao runtime-boundary audit failed' }
if($IncludeFreshOpenBaoPolicy) {
# SecretID deliberately has a 24 h TTL. Never substitute an operator/root
# token when it expires: refresh it through the documented bootstrap first.
& "$PSScriptRoot\test-openbao-policies.ps1" -EnvFile $EnvFile
if($LASTEXITCODE -ne 0){ throw 'OpenBao policy audit failed; refresh the scoped AppRole SecretID' }
} else {
Write-Host 'INFO: scoped OpenBao allow/deny test skipped; pass -IncludeFreshOpenBaoPolicy after refreshing the 24 h AppRole SecretID.'
}
& "$PSScriptRoot\test-worker-resource-bounds.ps1" -EnvFile $EnvFile `
-SkipUnitTests:$SkipWorkerUnitTests
if($LASTEXITCODE -ne 0){ throw 'Upload worker resource-bound audit failed' }
& "$PSScriptRoot\test-telemetry-redaction.ps1" -EnvFile $EnvFile -BaseUrl $BaseUrl
if($LASTEXITCODE -ne 0){ throw 'Telemetry redaction audit failed' }
Write-Host 'PASS: level-4 audit covered the declared TLS matrix, same/foreign/no-cert identity failures, data-plane ACLs, bounded upload worker and end-to-end telemetry non-disclosure.'
+66
View File
@@ -0,0 +1,66 @@
[CmdletBinding()]
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
$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 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)
if ($replicas.Count -lt 2) { throw 'At least two running API replicas are required for the mTLS test' }
foreach($replica in $replicas) {
$target = (& docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $replica).Trim()
if ([string]::IsNullOrWhiteSpace($target)) { throw "No internal address found for API replica $replica" }
$noCertificate = Invoke-Probe $target ''
if ($noCertificate -match 'HTTP/1.1' -or $noCertificate -notmatch 'certificate required|handshake failure') {
throw "mTLS failure: API replica $replica did not reject a missing client certificate during TLS handshake"
}
$foreignCa = Invoke-Probe $target '-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key'
if ($foreignCa -match 'HTTP/1.1' -or $foreignCa -notmatch 'certificate unknown|unknown ca|bad certificate') {
throw "mTLS failure: API replica $replica did not reject a foreign client CA during TLS handshake"
}
$wrongIdentity = Invoke-Probe $target '-cert /run/pki/wrong-lb-client/tls.crt -key /run/pki/wrong-lb-client/tls.key'
if ($wrongIdentity -notmatch 'HTTP/1.1 403') {
throw "mTLS failure: API replica $replica accepted or mishandled a trusted certificate with forbidden URI SAN"
}
$allowed = Invoke-Probe $target '-cert /run/pki/lb/tls.crt -key /run/pki/lb/tls.key'
if ($allowed -notmatch 'HTTP/1.1 200') {
throw "mTLS failure: allowed LB identity did not reach API replica $replica"
}
}
Write-Host "PASS: $($replicas.Count) API replicas require a client certificate and LB CA; forbidden URI SAN is rejected; only the LB identity succeeds; no API port is published."
+55
View File
@@ -0,0 +1,55 @@
[CmdletBinding()]
param([string]$EnvFile = '.env')
$ErrorActionPreference = 'Stop'
$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 $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
$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) {
# 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') {
$other = if($role -eq 'api'){'worker'}else{'api'}
$token = Get-AppRoleToken $role
if((Bao-WithToken $token kv get -mount=secret "messenger/$role") -ne 0) { throw "$role cannot read its own KV path" }
if((Bao-WithToken $token kv get -mount=secret "messenger/$other") -eq 0) { throw "$role unexpectedly read the $other KV path" }
if((Bao-WithToken $token policy write forbidden /openbao/policies/api-policy.hcl) -eq 0) { throw "$role unexpectedly changed an OpenBao policy" }
}
Write-Host 'OpenBao policy checks passed: own path allowed; foreign path and policy changes denied.'
@@ -0,0 +1,80 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$ApplicationImage = 'hla-lab7-app:local',
[int]$Port = 8443
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
$publicCa = Join-Path $projectRoot 'secrets\pki\public-ca\ca.crt'
if (-not (Test-Path -LiteralPath $publicCa)) { throw "Missing public CA: $publicCa" }
function Invoke-Quiet([scriptblock]$Command) {
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$output = & $Command 2>&1 | Out-String
$code = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
return [pscustomobject]@{ Code = $code; Output = $output }
}
foreach ($name in 'agent-api.hcl','agent-worker.hcl') {
$config = [System.IO.File]::ReadAllText((Join-Path $projectRoot "infra\openbao\$name"))
if ($config -notmatch 'static_secret_render_interval\s*=\s*"5m"') { throw "$name does not renew rendered secrets every 5 minutes" }
if ($config -notmatch 'exit_on_retry_failure\s*=\s*false') { throw "$name exits when OpenBao retries fail" }
}
$serverConfig = [System.IO.File]::ReadAllText((Join-Path $projectRoot 'infra\openbao\openbao.hcl'))
if ($serverConfig -notmatch 'default_lease_ttl\s*=\s*"15m"' -or
$serverConfig -notmatch 'max_lease_ttl\s*=\s*"1h"') {
throw 'OpenBao lease TTLs are not bounded'
}
$imageConfig = (Invoke-Quiet { docker image inspect --format '{{range .Config.Env}}{{println .}}{{end}}' $ApplicationImage }).Output
if ($imageConfig -match '(?i)BAO_TOKEN|UNSEAL|ROOT_TOKEN|SECRET_ID') {
throw 'Application image environment contains an operator credential name'
}
Invoke-Quiet { docker run --rm --entrypoint sh $ApplicationImage -c 'test ! -e /app/.env && test ! -e /app/secrets && test ! -e /app/runtime.env && ! find /app -type f \( -name "*.key" -o -name "*.p12" -o -name "*.jks" \) -print -quit | grep -q .' } | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Application image contains forbidden secret artifacts' }
# The operator seals OpenBao (or stops the server) with the unseal shares held
# offline. This script verifies the resulting boundary; it never handles the
# shares itself and never tries to unseal.
$statusDuringSeal = (Invoke-Quiet { docker compose --env-file $EnvFile exec -T openbao bao status }).Output
if ($statusDuringSeal -notmatch 'Sealed\s+true') {
throw 'Run this check while OpenBao is sealed so the boundary is actually exercised'
}
foreach ($service in 'openbao-agent-api','openbao-agent-worker') {
$running = (Invoke-Quiet { docker inspect --format '{{.State.Running}}' "hla-lab7-$($service)-1" }).Output.Trim()
if ($running -ne 'true') { throw "$service stopped while OpenBao was unavailable" }
}
$agentId = (Invoke-Quiet { docker compose --env-file $EnvFile ps -q openbao-agent-api }).Output.Trim()
$keys = (Invoke-Quiet { docker exec $agentId sh -c 'test -s /run/rendered/runtime.env && cut -d= -f1 /run/rendered/runtime.env | sort | tr "\n" ","' }).Output.Trim()
if ($keys -notmatch 'DATABASE_PASSWORD' -or $keys -notmatch 'REDIS_PASSWORD') {
throw 'Cached rendered runtime secrets are unavailable during the seal test'
}
$health = Invoke-Quiet { curl.exe -sS -o NUL -w '%{http_code}' --cacert $publicCa --ssl-no-revoke --connect-timeout 5 --max-time 10 "https://localhost:$Port/health/ready" }
if ($health.Output.Trim() -ne '200') { throw 'Application readiness failed while OpenBao was unavailable' }
$watch = [Diagnostics.Stopwatch]::StartNew()
$fresh = Invoke-Quiet {
docker run --rm --entrypoint messenger-entrypoint `
-e OPENBAO_RENDERED_ENV=/run/missing/runtime.env `
-e OPENBAO_STARTUP_TIMEOUT_SECONDS=2 $ApplicationImage
}
$watch.Stop()
if ($fresh.Code -eq 0 -or $fresh.Output -notmatch 'did not render runtime credentials') {
throw 'Fresh startup did not fail closed on a missing rendered secret file'
}
if ($watch.Elapsed.TotalSeconds -gt 10) { throw 'Fresh startup exceeded the bounded fail-closed deadline' }
$elapsed = [math]::Round($watch.Elapsed.TotalSeconds, 1)
Write-Host 'PASS: OpenBao seal/unavailability does not stop agents or running API; cached runtime secrets keep readiness at 200.'
Write-Host "PASS: fresh startup with no rendered env failed closed in ${elapsed}s (configured deadline 2s)."
Write-Host 'PASS: AppRole token TTL is 15m/1h, templates renew every 5m, and no permanent operator secret is embedded in the image.'
@@ -0,0 +1,91 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[switch]$SkipLivePolicy
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
function Inspect-One([string]$Service) {
$ids = @(& docker compose --env-file $EnvFile ps -q $Service)
if($ids.Count -ne 1){ throw "Expected one running $Service container, found $($ids.Count)" }
return ((& docker inspect $ids[0] | Out-String) | ConvertFrom-Json)[0]
}
function Environment-Names($Inspection) {
return @($Inspection.Config.Env | ForEach-Object { ($_ -split '=',2)[0] })
}
function Assert-NoOperatorMaterial($Inspection,[string]$Service) {
$forbidden = @('BAO_TOKEN','VAULT_TOKEN','OPENBAO_ROOT_TOKEN','ROOT_TOKEN','UNSEAL_KEY','UNSEAL_KEYS')
$present = @(Environment-Names $Inspection | Where-Object { $forbidden -contains $_ })
if($present.Count -gt 0){ throw "$Service contains operator-only environment variables: $($present -join ', ')" }
}
function Assert-RuntimeKeys([string]$ContainerId,[string]$Role) {
$expected = @('DATABASE_PASSWORD','RABBITMQ_PASSWORD','REDIS_PASSWORD','S3_ACCESS_KEY_ID','S3_SECRET_ACCESS_KEY') | Sort-Object
$actual = @(& docker exec $ContainerId sh -c "cut -d= -f1 /run/openbao/runtime.env" 2>$null | Where-Object { $_ } | Sort-Object)
if($LASTEXITCODE -ne 0){ throw "$Role cannot read its rendered runtime secret file" }
if(($actual -join ',') -ne ($expected -join ',')){
throw "$Role runtime secret file contains unexpected key names"
}
}
$status = ((& docker compose --env-file $EnvFile exec -T openbao bao status -format=json | Out-String) | ConvertFrom-Json)
if(-not $status.initialized -or $status.sealed){ throw 'OpenBao must be initialized and unsealed for this test' }
if($status.storage_type -ne 'raft'){ throw "OpenBao storage is $($status.storage_type), expected raft" }
$openbao = Inspect-One 'openbao'
$commandLine = (@($openbao.Config.Entrypoint) + @($openbao.Config.Cmd)) -join ' '
if($commandLine -match '(^|\s)(dev|server\s+-dev)(\s|$)') { throw 'OpenBao is running in dev mode' }
$storageMount = @($openbao.Mounts | Where-Object { $_.Destination -eq '/openbao/file' })
if($storageMount.Count -ne 1 -or $storageMount[0].Type -ne 'volume' -or -not $storageMount[0].RW){
throw 'OpenBao raft storage is not backed by one writable named volume at /openbao/file'
}
Assert-NoOperatorMaterial $openbao 'openbao'
$agents = @{}
foreach($role in 'api','worker'){
$agent = Inspect-One "openbao-agent-$role"
Assert-NoOperatorMaterial $agent "openbao-agent-$role"
$bootstrap = @($agent.Mounts | Where-Object { $_.Destination -eq '/run/bootstrap' })
$rendered = @($agent.Mounts | Where-Object { $_.Destination -eq '/run/rendered' })
if($bootstrap.Count -ne 1 -or $bootstrap[0].RW){ throw "$role agent bootstrap mount is missing or writable" }
if($rendered.Count -ne 1 -or $rendered[0].Type -ne 'volume'){ throw "$role agent has no dedicated rendered volume" }
$agents[$role] = @{ bootstrap = $bootstrap[0].Source; rendered = $rendered[0].Name }
}
if($agents.api.bootstrap -eq $agents.worker.bootstrap -or $agents.api.rendered -eq $agents.worker.rendered){
throw 'API and worker OpenBao agents share bootstrap or rendered-secret storage'
}
foreach($service in 'api','worker'){
$ids = @(& docker compose --env-file $EnvFile ps -q $service)
if($ids.Count -lt 1){ throw "No running $service container" }
foreach($id in $ids){
$inspection = ((& docker inspect $id | Out-String) | ConvertFrom-Json)[0]
Assert-NoOperatorMaterial $inspection $service
$runtime = @($inspection.Mounts | Where-Object { $_.Destination -eq '/run/openbao' })
if($runtime.Count -ne 1 -or $runtime[0].RW){ throw "$service runtime secret mount is missing or writable" }
if(@($inspection.Mounts | Where-Object { $_.Destination -in '/run/bootstrap','/openbao/file' }).Count -gt 0){
throw "$service can access AppRole bootstrap or OpenBao raft storage"
}
Assert-RuntimeKeys $id $service
}
}
$operatorArtifacts = @(Get-ChildItem -LiteralPath (Join-Path $projectRoot 'secrets') -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match '(?i)(root.*token|unseal)' })
if($operatorArtifacts.Count -gt 0){ throw 'Root token or unseal material exists inside the project secrets tree' }
if(-not $SkipLivePolicy) {
& "$PSScriptRoot\test-openbao-policies.ps1" -EnvFile $EnvFile
}
Write-Host 'PASS: OpenBao uses persistent raft storage outside dev mode; API/worker use separate AppRoles and read-only rendered files; operator material is absent.'
if($SkipLivePolicy) {
Write-Host 'INFO: live scoped-policy probe skipped; it requires a non-expired 24 h AppRole SecretID.'
} else {
Write-Host 'PASS: scoped OpenBao allow/deny policies were verified with fresh AppRole credentials.'
}
+56
View File
@@ -0,0 +1,56 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$OldCertificate = 'secrets/pki/revoked/lb/tls.crt',
[string]$OldKey = 'secrets/pki/revoked/lb/tls.key',
[string]$NewCertificate = 'secrets/pki/lb/tls.crt',
[string]$NewKey = 'secrets/pki/lb/tls.key'
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
foreach ($path in @($OldCertificate, $OldKey, $NewCertificate, $NewKey)) {
if (-not (Test-Path -LiteralPath $path)) { throw "Missing certificate material: $path" }
}
function Convert-ToContainerPath([string]$Path) {
if ($Path -match '^(secrets[\\/])pki[\\/](.+)$') { return '/run/pki/' + $Matches[2].Replace('\','/') }
return $Path.Replace('\','/')
}
$OldCertificate = Convert-ToContainerPath $OldCertificate
$OldKey = Convert-ToContainerPath $OldKey
$NewCertificate = Convert-ToContainerPath $NewCertificate
$NewKey = Convert-ToContainerPath $NewKey
foreach ($path in @($OldCertificate, $OldKey, $NewCertificate, $NewKey)) {
if ($path -notlike '/run/pki/*') { throw "Certificate path must be under secrets/pki: $path" }
}
function Invoke-Probe([string]$Target, [string]$Certificate, [string]$Key) {
$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 -cert ${Certificate} -key ${Key} 2>&1"
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
return @(& docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $probeScript 2>&1) -join "`n"
} finally {
$ErrorActionPreference = $previous
}
}
$replicas = @(& docker compose --env-file $EnvFile ps -q api)
if ($replicas.Count -lt 2) { throw 'At least two running API replicas are required for rotation evidence' }
foreach ($replica in $replicas) {
$target = (& docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $replica).Trim()
if ([string]::IsNullOrWhiteSpace($target)) { throw "No internal address found for API replica $replica" }
$oldResult = Invoke-Probe $target $OldCertificate $OldKey
if ($oldResult -notmatch 'HTTP/1.1 403') {
throw "Revoked leaf was accepted by API replica $replica"
}
$newResult = Invoke-Probe $target $NewCertificate $NewKey
if ($newResult -notmatch 'HTTP/1.1 200') {
throw "Rotated leaf was rejected by API replica $replica"
}
}
Write-Host "PASS: $($replicas.Count) API replicas reject the revoked LB leaf with 403 and accept the rotated LB leaf with 200."
+108
View File
@@ -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
+106
View File
@@ -0,0 +1,106 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$BaseUrl = 'https://localhost:8443',
[int]$ExportWaitSeconds = 15
)
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $root
$ca = (Resolve-Path 'secrets\pki\public-ca\ca.crt').Path
$canary = 'otel-canary-' + [guid]::NewGuid().ToString('N')
$bodyPath = Join-Path $env:TEMP ('otel-body-' + [guid]::NewGuid().ToString('N') + '.json')
function Invoke-ExpectedHttp([string[]]$Arguments, [string]$ExpectedStatus) {
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$status = (& curl.exe --silent --show-error --output NUL --write-out '%{http_code}' `
--cacert $ca --ssl-no-revoke --connect-timeout 5 --max-time 15 @Arguments 2>$null) -join ''
$exitCode = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($exitCode -ne 0 -or $status -ne $ExpectedStatus){
throw "Telemetry canary request expected HTTP $ExpectedStatus but received $status"
}
}
function Invoke-GrafanaProbe([string]$Script) {
$Script = $Script.Replace("`r", '')
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Script))
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$command = "echo '$encoded' | base64 -d | sh -s -- '$canary'"
$output = @(& docker compose --env-file $EnvFile exec -T grafana sh -c $command 2>&1) -join "`n"
$exitCode = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($exitCode -ne 0){ throw "Telemetry backend probe failed without exposing the canary: $output" }
return $output
}
try {
# Exercise both sensitive carriers. The first value is an invalid Bearer token;
# the second is inside a deliberately malformed JSON body and is never stored.
Invoke-ExpectedHttp @('-H', "Authorization: Bearer $canary",
"$($BaseUrl.TrimEnd('/'))/api/v1/users/me") '401'
[System.IO.File]::WriteAllText($bodyPath,
'{"username":"telemetry_probe","display_name":"' + $canary + '"',
[System.Text.UTF8Encoding]::new($false))
Invoke-ExpectedHttp @('-H','Content-Type: application/json','--data-binary',"@$bodyPath",
"$($BaseUrl.TrimEnd('/'))/api/v1/users") '400'
Start-Sleep -Seconds $ExportWaitSeconds
$logs = (& docker compose --env-file $EnvFile logs --no-color --tail 3000 2>&1) -join "`n"
if($LASTEXITCODE -ne 0){ throw 'Cannot read Compose logs for telemetry canary check' }
if($logs.Contains($canary)){ throw 'Telemetry canary appeared in container stdout/stderr logs' }
$backendProbe = @'
set -eu
canary=$1
ca=/run/pki/service-ca/ca.crt
cert=/run/pki/grafana-client/tls.crt
key=/run/pki/grafana-client/tls.key
tmp=/tmp/telemetry-redaction-$$
trap 'rm -f "$tmp".*' EXIT
curl -fsS --cacert "$ca" --cert "$cert" --key "$key" --get \
--data-urlencode 'query={service_name=~".+"}' \
--data-urlencode "limit=5000" \
https://loki:3100/loki/api/v1/query_range >"$tmp.loki"
if grep -Fq "$canary" "$tmp.loki"; then
echo 'Loki contains the telemetry canary' >&2
exit 20
fi
for tag in http.request.header.authorization http.request.body http.response.body \
messaging.message.body db.statement.parameters url.query; do
curl -fsS --cacert "$ca" --cert "$cert" --key "$key" \
"https://tempo:3200/api/search/tag/$tag/values" >"$tmp.tempo"
if grep -Fq "$canary" "$tmp.tempo"; then
echo "Tempo tag $tag contains the telemetry canary" >&2
exit 21
fi
done
curl -fsS --cacert "$ca" --cert "$cert" --key "$key" \
'https://prometheus:9090/api/v1/series?match%5B%5D=%7B__name__%3D~%22.%2B%22%7D' \
>"$tmp.prometheus"
if grep -Fq "$canary" "$tmp.prometheus"; then
echo 'Prometheus label set contains the telemetry canary' >&2
exit 22
fi
'@
Invoke-GrafanaProbe $backendProbe | Out-Null
Write-Host 'PASS: unique Authorization/body canary was absent from container logs, Loki records, Tempo sensitive tag values and Prometheus label sets.'
Write-Host 'PASS: telemetry backends were queried over CA-verified mTLS with the dedicated Grafana identity.'
} finally {
Remove-Item -LiteralPath $bodyPath -Force -ErrorAction SilentlyContinue
$canary = $null
}
+74
View File
@@ -0,0 +1,74 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[switch]$SkipUnitTests
)
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
function Convert-DurationToMilliseconds([string]$Value) {
if($Value -notmatch '^([0-9]+)(ms|s|m)$'){ throw "Unsupported duration format: $Value" }
$number = [long]$Matches[1]
switch($Matches[2]) {
'ms' { return $number }
's' { return $number * 1000 }
'm' { return $number * 60000 }
}
}
$configText = & docker compose --env-file $EnvFile config --format json
if($LASTEXITCODE -ne 0){ throw 'docker compose config failed' }
$config = ($configText -join "`n") | ConvertFrom-Json
$worker = $config.services.worker
if($null -eq $worker){ throw 'worker service is missing' }
$cpu = [double]$worker.cpus
$memory = [long]$worker.mem_limit
$pids = [long]$worker.pids_limit
$environment = $worker.environment
$concurrency = [int]$environment.WORKER_CONCURRENCY
$prefetch = [int]$environment.WORKER_PREFETCH
$pixelLimit = [long]$environment.WORKER_MAX_IMAGE_PIXELS
$memoryBudget = [long]$environment.WORKER_MEMORY_BUDGET_BYTES
$jobTimeoutMs = Convert-DurationToMilliseconds ([string]$environment.JOB_TIMEOUT)
$leaseMs = Convert-DurationToMilliseconds ([string]$environment.JOB_LEASE_DURATION)
$memoryWaitMs = Convert-DurationToMilliseconds ([string]$environment.WORKER_MEMORY_WAIT)
if($cpu -le 0 -or $cpu -gt 1.0){ throw "worker CPU limit must be in (0,1], found $cpu" }
if($memory -ne 1GB){ throw "worker memory limit must be 1 GiB, found $memory bytes" }
if($pids -le 0 -or $pids -gt 256){ throw "worker PID limit is missing or excessive: $pids" }
if($concurrency -lt 1 -or $concurrency -gt 2){ throw "worker concurrency must be 1..2, found $concurrency" }
if($prefetch -lt 1 -or $prefetch -gt $concurrency){ throw "worker prefetch exceeds bounded concurrency" }
if($pixelLimit -ne 40000000){ throw "worker decoded-pixel limit must be 40,000,000" }
if($memoryBudget -le 0 -or $memoryBudget -gt 512MB -or $memoryBudget -ge $memory){
throw "worker in-process memory budget is not bounded below the container limit"
}
if($jobTimeoutMs -le 0 -or $jobTimeoutMs -gt 60000){ throw "worker job timeout exceeds 60 seconds" }
if($leaseMs -le $jobTimeoutMs){ throw "worker lease must outlive the processing timeout" }
if($memoryWaitMs -lt 0 -or $memoryWaitMs -gt 2000){ throw "worker memory permit wait exceeds 2 seconds" }
if($worker.read_only -ne $true -or $worker.cap_drop -notcontains 'ALL'){
throw 'worker must use read-only root and drop ALL capabilities'
}
$containerId = (& docker compose --env-file $EnvFile ps -q worker | Select-Object -First 1).Trim()
if(-not $containerId){ throw 'running worker container is required for runtime limit verification' }
$inspect = (& docker inspect $containerId | ConvertFrom-Json)[0]
if([long]$inspect.HostConfig.Memory -ne $memory){ throw 'runtime worker memory limit differs from rendered Compose' }
if([long]$inspect.HostConfig.NanoCpus -ne [long]($cpu * 1000000000)){ throw 'runtime worker CPU limit differs from rendered Compose' }
if(-not $inspect.HostConfig.ReadonlyRootfs -or $inspect.HostConfig.CapDrop -notcontains 'ALL'){
throw 'runtime worker filesystem/capability bounds differ from rendered Compose'
}
if(-not $SkipUnitTests) {
& .\gradlew.bat test `
--tests com.example.mtusi_messenger.worker.ImageVariantProcessorTest `
--tests com.example.mtusi_messenger.worker.AttachmentWorkerLimitsTest `
--no-daemon --console=plain
if($LASTEXITCODE -ne 0){ throw 'worker resource-bound unit tests failed' }
Write-Host 'PASS: image memory/pixel rejection and processing-timeout retry passed as executable unit tests.'
} else {
Write-Host 'INFO: worker unit tests skipped; only rendered/runtime bounds were verified.'
}
Write-Host "PASS: worker CPU=$cpu, RAM=$memory bytes, pids=$pids, concurrency=$concurrency, prefetch=$prefetch, pixels=$pixelLimit, image budget=$memoryBudget bytes, job timeout=$jobTimeoutMs ms and memory wait=$memoryWaitMs ms are bounded."
+3 -3
View File
@@ -6,17 +6,17 @@ from openapi_spec_validator import validate
from jsonschema import Draft202012Validator from jsonschema import Draft202012Validator
root = Path(__file__).resolve().parents[1] root = Path(__file__).resolve().parents[1]
spec = json.loads((root/'contracts/openapi.json').read_text()) spec = json.loads((root/'contracts/openapi.json').read_text(encoding='utf-8'))
validate(spec) validate(spec)
from referencing import Registry, Resource from referencing import Registry, Resource
# The base URI resolves local #/components references inside examples. # The base URI resolves local #/components references inside examples.
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'}) resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource)) registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
for name, example in json.loads((root/'contracts/examples.json').read_text()).items(): for name, example in json.loads((root/'contracts/examples.json').read_text(encoding='utf-8')).items():
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name} schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
Draft202012Validator(schema, registry=registry).validate(example) Draft202012Validator(schema, registry=registry).validate(example)
for path in (root/'contracts').glob('*.schema.json'): for path in (root/'contracts').glob('*.schema.json'):
schema = json.loads(path.read_text()) schema = json.loads(path.read_text(encoding='utf-8'))
Draft202012Validator.check_schema(schema) Draft202012Validator.check_schema(schema)
for example in schema.get('examples',[]): for example in schema.get('examples',[]):
Draft202012Validator(schema).validate(example) Draft202012Validator(schema).validate(example)
+67
View File
@@ -0,0 +1,67 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$Python = 'python',
[string]$BaseUrl = 'https://localhost:8443'
)
$ErrorActionPreference = 'Stop'
$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
& "$PSScriptRoot\check-security-lifecycle.ps1"
& docker info --format '{{.ServerVersion}}' | Out-Null
if($LASTEXITCODE -ne 0){ throw 'Docker engine is unavailable' }
$replicas = @(& docker compose --env-file $EnvFile ps -q api)
if($replicas.Count -lt 2){ throw 'At least two running API replicas are required' }
function Run-Test([string[]]$Arguments) {
& $Python @Arguments
if($LASTEXITCODE -ne 0){ throw "HTTPS test failed: $($Arguments[0])" }
}
function Wait-HttpsReady([int]$TimeoutSeconds = 180) {
$probe = @'
import ssl, sys, urllib.request
context = ssl.create_default_context(cafile=sys.argv[2])
with urllib.request.urlopen(sys.argv[1].rstrip('/') + '/health/ready', context=context, timeout=2) as response:
raise SystemExit(0 if response.status == 200 else 1)
'@
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
do {
# 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"
}
# All clients receive an explicit CA file. This workflow has no insecure mode and never uses -k.
Wait-HttpsReady
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)
$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.'
+107 -9
View File
@@ -1,19 +1,117 @@
# Модель угроз — заполнить # Модель угроз HLA Lab 7
## Активы и акторы ## Область и допущения
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. Модель относится к локальному учебному стенду из `compose.yaml`: клиент, nginx ingress, две и более реплики API, worker, PostgreSQL, Redis, RabbitMQ, MinIO, OpenTelemetry Collector, Prometheus/Loki/Tempo, Grafana и OpenBao. Хост Docker и рабочее место оператора считаются доверенной административной зоной. Компрометация ядра хоста, Docker daemon или учётной записи оператора находится за границей модели, но последствия ограничиваются раздельными credentials, непривилегированными контейнерами, отсутствием Docker socket и возможностью ротации.
## Границы доверия Документ различает фактическое состояние и целевой контракт. Контроль с пометкой **GAP** ещё не реализован и не считается доказательством защищённости. Полное описание соединений и отрицательных проверок находится в [`contracts/trust-matrix.md`](../contracts/trust-matrix.md).
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. ## Активы
| Актив | Требование защиты | Источник истины / владелец |
| --- | --- | --- |
| Пароли пользователей | Конфиденциальность; Argon2id hash с уникальной солью и параметрами | PostgreSQL; API |
| Bearer-сессии | Непредсказуемость, ограниченный TTL, отзыв; plaintext выдаётся один раз | SHA-256 token hash в PostgreSQL; API |
| Чаты, сообщения и metadata вложений | Доступ только участникам соответствующего чата; целостность и порядок | PostgreSQL |
| Оригиналы и варианты вложений | Конфиденциальность bucket, целостность объекта, запрет cross-chat доступа | MinIO; API/worker |
| Очередь заданий и lease/outbox | Нельзя подделать задание или подтвердить чужой lease; at-least-once без потери | PostgreSQL + RabbitMQ |
| Service identities и credentials | Минимальные права, раздельность API/worker/operator, отзыв и ротация | OpenBao/локальный bootstrap; оператор |
| CA private keys, leaf keys, root token, unseal shares | Не попадают в Git, image, env/logs/telemetry; доступны только оператору | Вне Git; оператор |
| Telemetry | Не содержит Authorization, tokens, пароли, тела сообщений/файлов; write/read разделены | Collector и telemetry backends |
| Доступность | Деградации не приводят к обходу auth/TLS или повреждению данных | Весь стенд; оператор |
## Акторы и возможности
| Актор | Разрешённые действия | Потенциально враждебные возможности |
| --- | --- | --- |
| Участник чата | Работает со своими сессиями и чатами, загружает допустимые изображения | Меняет UUID, заголовки, cursor/idempotency key, MIME/размер файла, повторяет запросы |
| Аутентифицированный посторонний | Создаёт собственные чаты и сообщения | Пытается читать/изменять чужой чат и вложение, прикрепить чужой attachment |
| Внешний клиент без сессии | Регистрация, login и health через HTTPS | MITM, credential stuffing, malformed/oversized requests, недоверенный CA/hostname |
| Скомпрометированный API/worker | Действует с identity и сетевым доступом одного сервиса | Читает чужие secret paths, bucket prefixes, очереди или БД; шлёт ложную telemetry |
| Скомпрометированный внутренний контейнер | Имеет адрес в Docker-сети, но не service credential | Сканирует порты, пытается обойти ingress и подключиться без mTLS |
| Оператор | Init/unseal, bootstrap, выдача/отзыв identities, резервирование и аудит | Ошибка конфигурации или утечка bootstrap material — максимальный риск стенда |
## Границы доверия и потоки
```text
Internet/local client
│ HTTPS :8443, public CA + hostname, Bearer
▼
nginx ingress (DMZ)
│ target: mTLS, client SAN spiffe://hla-lab7/lb
▼
API replicas ── TLS/ACL ── PostgreSQL / Redis / MinIO / RabbitMQ
│ ▲ │
└──── TLS/mTLS ── Collector │ ▼
│ └────────────── worker
└── TLS ── Prometheus/Loki/Tempo ── TLS ── Grafana
API / worker ── TLS + service auth ── OpenBao
Operator ── loopback/protected channel ── admin planes
```
1. **Публичная:** клиент → nginx. Единственный публикуемый business endpoint — `127.0.0.1:8443` в локальном профиле. Проверяются CA и SAN `localhost`.
2. **DMZ → application:** nginx → API использует обязательный mTLS, отдельный LB client CA и allowlist URI SAN `spiffe://hla-lab7/lb`; API port не публикуется.
3. **Application → data plane:** PostgreSQL, Redis, MinIO и RabbitMQ принимают TLS; API/worker имеют раздельные DB/cache/broker/S3 identities и разные prefix/action S3 policies.
4. **Application → telemetry:** API/worker пишут в Collector по mTLS с раздельными leaf identities; Collector, Prometheus и Grafana также используют отдельные mTLS identities для backend-связей. Redaction processor удаляет известные чувствительные поля.
5. **Secrets control plane:** отдельные API/worker Agents → OpenBao по TLS с разными AppRole и scoped policy; credentials передаются приложениям через разные read-only runtime volumes.
6. **Administrative:** operator → OpenBao/Grafana/MinIO admin. Интерфейсы не публикуются наружу; локальные Grafana/telemetry ports bound к loopback.
## Инварианты безопасности и угрозы
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | | Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | TODO | | MITM подменяет ingress certificate или используется неверный hostname | Basic/Bearer передаются только аутентифицированному ingress | TLS 1.2/1.3, локальный CA, SAN `localhost`, hostname verification, без `-k` | `make test-security CA_FILE=secrets/pki/public-ca/ca.crt`; пустой/чужой CA и wrong hostname → certificate error | Ручная установка CA — bootstrap trust; компрометация CA требует ротации |
| Внутренний контейнер обращается к API, минуя nginx | Business API доступен только доверенному LB | API TLS `client-auth=need`, отдельный LB CA и точный allowlist SAN `spiffe://hla-lab7/lb`; порт не публикуется | `scripts/test-mtls.ps1`: no cert/foreign CA/wrong SAN rejected; LB accepted | Компрометация LB key требует немедленного отзыва/ротации |
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. | Пользователь меняет `X-User-Id` или UUID и читает чужой чат/attachment | Identity определяется Bearer; membership проверяется сервером | Stateless auth filter, token hash lookup, repository membership predicates и FK | Bob + Alice UUID → 404/401; forged `X-User-Id` не меняет результат | Ошибки намеренно не различают отсутствие объекта и отсутствие прав |
| Пользователь прикрепляет чужой attachment или читает object key напрямую | Attachment принадлежит тому же чату; bucket private | Membership/ownership/chat validation, private bucket, opaque keys | Загрузить в чат A, попытаться attach/read из B; anonymous `mc ls/cp` → denied | Компрометация S3 credential даёт доступ в пределах его policy |
| Credential stuffing на login истощает CPU Argon2id | Login bounded; ответ не раскрывает существование user | Argon2id 32768 KiB/t=2/p=1, dummy hash; общий Redis fixed-window limit 5/username/60 s и 100/source/60 s, fail-closed, 429/Retry-After | `measure-login-dos.ps1 -SourceBudget`: 6-я/101-я попытки → 429; обе реплики; 429 ≈19 мс против 401 p50 287 мс; `LoginRateLimiterTest` — shared state и fail-closed; existing/unknown user имеют одинаковый 401 | Fixed window допускает burst на границе окна; source limit видит адрес ingress (общий cap за LB), trusted-proxy модель не завершена; лимитер не ограничивает concurrency |
| Кража БД раскрывает пароль или активный bearer token | В БД нет plaintext password/session token | Argon2id password hash с rehash при успешном login через CAS; SHA-256 session token hash; TTL/logout | `credential_storage.py`: PHC-префикс, SHA-256 token hash, plaintext password/token/hash отсутствуют в API/LB logs; `DatabaseAuthenticationProviderTest` — rehash и dummy hash; после logout/expiry token → 401 | Offline guessing зависит от качества пароля и измеренных Argon2 параметров |
| Скомпрометированный worker читает users/sessions или admin bucket/queue | Worker видит только jobs и нужные storage operations | Отдельные DB role, S3 key и prefix/action policy, RabbitMQ/Redis cert+user+ACL; отдельная OpenBao AppRole читает только worker KV | Worker: `SELECT password_hash`, MinIO admin/final delete, cross-role broker gateway и API KV → denied | MinIO остаётся single-tenant; компрометация worker key даёт разрешённые операции над attachment prefix |
| Поддельный RabbitMQ job или подтверждение чужой работы | Producer/consumer identities и ACL различаются | mTLS `5671`, отдельные cert/users/regex permissions; plaintext listener disabled; DB lease fencing | No cert/foreign CA → TLS отказ; запрещённая broker operation → access refused | Точная проверка URI SAN выполняется ACL user mapping, не самим Rabbit TLS listener |
| Внутренний контейнер шлёт фальшивую telemetry или читает backends | Только заявленные workload identities могут ingest/query | mTLS на workload→Collector, Collector→Loki/Tempo, Prometheus→Collector и Grafana→backends; отдельные certs; redaction | `test-level4-security-audit.ps1`: no-cert/foreign CA rejected; same-CA migration role получает 403 на ingest; workload cert не обходит gateway | Single-tenant Loki/Tempo не дают fine-grained query ACL сверх mTLS role |
| Authorization/password/body попадает в signals | Telemetry не содержит credentials/payload | OTel capture headers/bodies выключен; Collector удаляет auth, bodies, DB parameters/query | `test-telemetry-redaction.ps1`: уникальный Authorization + malformed-body canary; поиск в stdout/stderr, Loki, Tempo sensitive tag values и Prometheus labels → 0 | Новые instrumentation attributes требуют повторного canary-теста |
| Image bomb или concurrent uploads исчерпывают worker | Файл и суммарная обработка имеют bounds | 10 MiB limit, 40M pixel limit до decode, fair memory semaphore с 512 MiB budget/2 s wait, concurrency 2/prefetch 1, 60 s job timeout; container 1 CPU/1 GiB/256 PID | `test-worker-resource-bounds.ps1`; `ImageVariantProcessorTest` отвергает 50M-pixel header и memory over-budget; `AttachmentWorkerLimitsTest` отменяет slow job и ставит bounded retry с `processing_timeout` | Native decoder может не сразу реагировать на interrupt; container CPU/RAM/PID и lease reaper остаются внешним hard bound |
| Private key/secret попадает в Git, image или app env | Operator secrets не поставляются со skeleton | `.gitignore`, `.dockerignore`, local bootstrap в `secrets/`, OpenBao Agent и отдельные runtime files | Secret scanner, `docker history`, inspect app env не содержат root/unseal/runtime password | Dependency bootstrap passwords пока поступают их контейнерам через Compose env; это остаточный локальный риск |
| OpenBao sealed, приложение использует hardcoded fallback/plaintext | Отказ secret plane не ослабляет auth/TLS | Agent retry, отсутствие app fallback, controlled startup failure без rendered file; TLS не отключается | `test-openbao-rotation-boundaries.ps1`: при `Sealed true` агенты Running, render keys сохранены, public health 200; fresh startup без rendered env → exit 1 за 2.8 c при лимите 2 c | Уже запущенное приложение продолжает работать со статическими dependency credentials до restart/их отзыва |
## Lifecycle и инциденты ## Lifecycle и инциденты
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. ### Bootstrap
1. Оператор на доверенном хосте создаёт CA/leaf keys и initial OpenBao material. Private keys, root token, unseal shares и SecretID находятся вне Git; `secrets/` имеет минимальные filesystem permissions.
2. OpenBao запускается не в dev-mode с persistent storage. Init выполняется один раз. Unseal shares разделяются между владельцами; root token используется только для bootstrap/recovery.
3. Оператор включает KV v2, создаёт отдельные policies/auth roles `messenger-api` и `messenger-worker`. SecretID имеет TTL 24 h и хранится только в игнорируемом локальном bootstrap mount; постоянного `BAO_TOKEN` в Compose нет.
4. Сервисы получают короткоживущие tokens, читают только свои paths и запускаются после проверки TLS/server identity. Миграции используют отдельную `migration` role.
Шаги реализованы конфигурацией Compose, policy/bootstrap scripts и Agents. Init/unseal намеренно остаются ручной обязанностью оператора; runtime доказательство выполняется на initialized стенде скриптом `test-openbao-policies.ps1`.
### Сроки и ротация
- User session: `SESSION_TTL_SECONDS`, по умолчанию 3600 s; logout немедленно помечает token hash revoked.
- TLS leaf: целевой TTL 30 дней; renewal начинается не позднее 2/3 TTL. CA ротируется overlap-набором trust anchors.
- OpenBao service token: целевой TTL 15 min, renewable до max TTL 1 h, затем повторная service authentication.
- Static service credential на уровне 3: новая KV version, последовательный reload/restart клиентов, проверка новых соединений, отзыв старой версии.
- Реализованная ротация leaf: `rotate-pki-leaf.ps1` выпускает новый leaf тем же CA без rebuild, архивирует старый комплект, добавляет только его SHA-256 в deny-list; `test-rotated-leaf.ps1` доказывает old 403/new 200 на обеих репликах. Нечитаемый deny-list при явной конфигурации отзывает все client identity.
- Реализованная ротация рабочего secret: `rotate-grafana-admin-password.ps1` меняет пароль через API и `.env`, пересоздаёт только Grafana и проверяет old rejected/new accepted; значения не попадают в логи, Git или образ.
### Компрометация identity
1. Изолировать сервис и зафиксировать время/serial/accessor без публикации secret value.
2. Отозвать leaf/OpenBao token и связанные DB/S3/broker credentials; закрыть pooled connections или дождаться измеренного TTL.
3. Выдать новую identity, перезапустить только затронутые replicas, выполнить allow/deny и integrity checks.
4. Проверить audit/telemetry на чужие paths/prefixes; при компрометации CA выполнить staged rollover.
### Sealed OpenBao и восстановление
Обычный restart сохраняет storage, но требует operator unseal в принятой ручной модели. Пока sealed, сервисы не получают новые leases, не используют root token и не переходят на `.env` fallback. После unseal agents повторяют auth с backoff, обновляют file-rendered secrets атомарно, приложения пересоздают соединения. Эксперимент зафиксировал: при `Sealed true` оба Agent остаются Running, кэшированные ключи доступны, public `/health/ready` → 200, а новый контейнер без rendered env завершается за 2.8 c при configured deadline 2 c. TTL токена 15 min/max 1 h и interval шаблона 5 min заданы в конфигурации; `exit_on_retry_failure=false` предотвращает выход Agent из-за временного отказа OpenBao.
### Dependency/image scan
Для каждого High/Critical finding фиксируются package/version, достижимость кода в данной конфигурации, наличие fix, срок обновления и временный контроль. Одно количество CVE не является доказательством. Неприменимость подтверждается отсутствием component/code path или выключенной feature, а не только закрытым портом.
OSV по разрешённому Gradle `runtimeClasspath` до обновлений показал 139 зависимостей и 9 пакетов с finding-ами (`CRITICAL=5 HIGH=18 MODERATE=10 LOW=1`). Jackson 2.x/3.x и Tomcat реально участвуют в разборе публичных HTTP-запросов; `amqp-client` участвует в обмене с брокером через mTLS gateway; Guava, snappy-java и BouncyCastle приходят транзитивно через MinIO. Fix-версии существовали для всех High/Critical позиций: BOM-оверрайды `jackson-2-bom=2.21.7`, `jackson-bom=3.1.7`, `rabbit-amqp-client=5.37.1`, `tomcat=11.0.25` и прямые pin'ы `bcprov=1.85`, `guava=33.7.2-jre`, `snappy-java=1.1.10.9`. Для `amqp-client` OSV указывал 5.36.1, но этого артефакта нет в Maven Central, поэтому выбран доступный 5.37.1. После обновлений OSV (`-FailOnHigh`) сообщает `Packages with findings: 0`.
Trivy по образу приложения до обновлений дал 34 Java-finding (`CRITICAL=5 HIGH=18`), после пересборки — 0. Оставшиеся 16 HIGH в Ubuntu-слое относятся к apt/GnuPG/curl-библиотекам и OpenSSL; они не вызываются финальным entrypoint, который только ждёт rendered env, импортирует service CA через `keytool` и запускает Java. Fix-версии зафиксированы, временный контроль — non-root, read-only root, `cap_drop: ALL`, `no-new-privileges`, отсутствие package-manager шагов в runtime; обновление базового образа остаётся отдельным squeeze-out шагом. Полный разбор с командами и наблюдениями — `evidence/dependency-image-scan.txt`.
Контейнерный контроль не сводится к отсутствию привилегий: check-скрипт требует `no-new-privileges`, capability drop, private tmpfs и resource limits у каждого сервиса. Read-only root и `cap_drop: ALL` обязательны для stateless; writable root разрешён только postgres, redis, rabbitmq и minio, потому что их entrypoints подготавливают persistent volume до смены UID. Для каждого исключения проверяется конкретный data volume и шесть запрещённых capabilities; причины печатаются в выводе скрипта.
+1
View File
@@ -0,0 +1 @@
rootProject.name = 'mtusi-messenger'
@@ -0,0 +1,20 @@
package com.example.mtusi_messenger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class MtusiMessengerApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(
MtusiMessengerApplication.class, args);
if (Boolean.parseBoolean(System.getenv("MIGRATE_ONLY"))) {
System.exit(SpringApplication.exit(context));
}
}
}
@@ -0,0 +1,83 @@
package com.example.mtusi_messenger.cache;
import com.example.mtusi_messenger.model.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
@Component
public class UserCache {
private static final Logger log = LoggerFactory.getLogger(UserCache.class);
private static final String KEY_PREFIX = "messenger:user:";
private final StringRedisTemplate redis;
private final ObjectMapper mapper;
private final Duration ttl;
public UserCache(
StringRedisTemplate redis,
ObjectMapper mapper,
@Value("${messenger.cache.user-ttl-seconds:300}") long ttlSeconds
) {
if (ttlSeconds <= 0) {
throw new IllegalArgumentException("User cache TTL must be positive");
}
this.redis = redis;
this.mapper = mapper;
this.ttl = Duration.ofSeconds(ttlSeconds);
}
public Optional<User> find(UUID userId) {
try {
String value = redis.opsForValue().get(key(userId));
if (value == null) {
return Optional.empty();
}
User cachedUser = mapper.readValue(value, User.class);
if (cachedUser == null) {
log.warn("Ignoring null Redis user cache entry for {}", userId);
evict(userId);
return Optional.empty();
}
return Optional.of(cachedUser);
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; using PostgreSQL fallback");
return Optional.empty();
} catch (JsonProcessingException e) {
log.warn("Ignoring malformed Redis user cache entry for {}", userId);
evict(userId);
return Optional.empty();
}
}
public void put(User user) {
try {
redis.opsForValue().set(key(user.id()), mapper.writeValueAsString(user), ttl);
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; user was not cached");
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize user cache entry", e);
}
}
public void evict(UUID userId) {
try {
redis.delete(key(userId));
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; cache eviction was skipped");
}
}
private String key(UUID userId) {
return KEY_PREFIX + userId;
}
}
@@ -0,0 +1,28 @@
package com.example.mtusi_messenger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
import tools.jackson.databind.cfg.CoercionAction;
import tools.jackson.databind.cfg.CoercionInputShape;
import tools.jackson.databind.type.LogicalType;
@Configuration
public class JacksonConfig {
@Bean
JsonMapperBuilderCustomizer strictStringTypes() {
return builder -> builder.withCoercionConfig(
LogicalType.Textual,
config -> {
config.setCoercion(
CoercionInputShape.Integer, CoercionAction.Fail);
config.setCoercion(
CoercionInputShape.Float, CoercionAction.Fail);
config.setCoercion(
CoercionInputShape.Boolean, CoercionAction.Fail);
}
);
}
}
@@ -0,0 +1,21 @@
package com.example.mtusi_messenger.config;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.context.annotation.Configuration;
@SecurityScheme(
name = "basicAuth",
type = SecuritySchemeType.HTTP,
scheme = "basic"
)
@SecurityScheme(
name = "bearerAuth",
type = SecuritySchemeType.HTTP,
scheme = "bearer",
bearerFormat = "opaque session token"
)
@Configuration
public class OpenApiConfig {
}
@@ -0,0 +1,22 @@
package com.example.mtusi_messenger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordConfig {
@Bean
PasswordEncoder passwordEncoder(
@Value("${messenger.password.argon2.memory-kib:32768}") int memoryKiB,
@Value("${messenger.password.argon2.iterations:2}") int iterations,
@Value("${messenger.password.argon2.parallelism:1}") int parallelism
) {
if (memoryKiB < 19456 || iterations < 2 || parallelism < 1) {
throw new IllegalArgumentException("Argon2id parameters are below the lab7 baseline");
}
return new Argon2PasswordEncoder(16, 32, parallelism, memoryKiB, iterations);
}
}
@@ -0,0 +1,57 @@
package com.example.mtusi_messenger.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitJobConfig {
@Bean
DirectExchange attachmentExchange(@Value("${messenger.jobs.exchange}") String name) {
return new DirectExchange(name, true, false);
}
@Bean
Queue attachmentQueue(
@Value("${messenger.jobs.queue}") String name,
@Value("${messenger.jobs.dead-letter-exchange}") String deadLetterExchange,
@Value("${messenger.jobs.dead-letter-routing-key}") String deadLetterRoutingKey) {
return QueueBuilder.durable(name)
.withArgument("x-dead-letter-exchange", deadLetterExchange)
.withArgument("x-dead-letter-routing-key", deadLetterRoutingKey)
.build();
}
@Bean
DirectExchange attachmentDeadLetterExchange(
@Value("${messenger.jobs.dead-letter-exchange}") String name) {
return new DirectExchange(name, true, false);
}
@Bean
Queue attachmentDeadLetterQueue(@Value("${messenger.jobs.dead-letter-queue}") String name) {
return QueueBuilder.durable(name).build();
}
@Bean
Binding attachmentBinding(
@Qualifier("attachmentQueue") Queue attachmentQueue,
@Qualifier("attachmentExchange") DirectExchange attachmentExchange,
@Value("${messenger.jobs.routing-key}") String routingKey) {
return BindingBuilder.bind(attachmentQueue).to(attachmentExchange).with(routingKey);
}
@Bean
Binding attachmentDeadLetterBinding(
@Qualifier("attachmentDeadLetterQueue") Queue queue,
@Qualifier("attachmentDeadLetterExchange") DirectExchange exchange,
@Value("${messenger.jobs.dead-letter-routing-key}") String routingKey) {
return BindingBuilder.bind(queue).to(exchange).with(routingKey);
}
}
@@ -0,0 +1,122 @@
package com.example.mtusi_messenger.config;
import com.example.mtusi_messenger.security.ApiAuthenticationFilter;
import com.example.mtusi_messenger.security.DatabaseAuthenticationProvider;
import com.example.mtusi_messenger.security.RestAuthenticationEntryPoint;
import com.example.mtusi_messenger.security.LoginRateLimiter;
import com.example.mtusi_messenger.security.TrustedClientCertificateFilter;
import com.example.mtusi_messenger.service.AuthenticationService;
import com.example.mtusi_messenger.web.ReadinessGuardFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class SecurityConfig {
@Bean
AuthenticationManager authenticationManager(DatabaseAuthenticationProvider provider) {
return new ProviderManager(provider);
}
@Bean
RestAuthenticationEntryPoint basicAuthenticationEntryPoint(ObjectMapper mapper) {
return new RestAuthenticationEntryPoint(
mapper,
"Basic realm=\"messenger\", charset=\"UTF-8\"");
}
@Bean
RestAuthenticationEntryPoint bearerAuthenticationEntryPoint(ObjectMapper mapper) {
return new RestAuthenticationEntryPoint(mapper, "Bearer realm=\"messenger\"");
}
@Bean
ApiAuthenticationFilter apiAuthenticationFilter(
AuthenticationManager authenticationManager,
AuthenticationService authenticationService,
LoginRateLimiter loginRateLimiter,
@Qualifier("basicAuthenticationEntryPoint") RestAuthenticationEntryPoint basicAuthenticationEntryPoint,
@Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint
) {
return new ApiAuthenticationFilter(
authenticationManager,
authenticationService,
loginRateLimiter,
basicAuthenticationEntryPoint,
bearerAuthenticationEntryPoint);
}
@Bean
FilterRegistrationBean<ApiAuthenticationFilter> disableServletFilterRegistration(
ApiAuthenticationFilter filter
) {
var registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
@Bean
FilterRegistrationBean<ReadinessGuardFilter> disableReadinessGuardServletRegistration(
ReadinessGuardFilter filter
) {
var registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
@Bean
FilterRegistrationBean<TrustedClientCertificateFilter> disableTrustedClientCertificateServletRegistration(
TrustedClientCertificateFilter filter
) {
var registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
@Bean
SecurityFilterChain securityFilterChain(
HttpSecurity http,
ApiAuthenticationFilter apiAuthenticationFilter,
ReadinessGuardFilter readinessGuardFilter,
TrustedClientCertificateFilter trustedClientCertificateFilter,
@Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint
) throws Exception {
http
.csrf(csrf -> csrf.disable())
.formLogin(form -> form.disable())
.httpBasic(basic -> basic.disable())
.logout(logout -> logout.disable())
.requestCache(cache -> cache.disable())
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(errors -> errors
.authenticationEntryPoint(bearerAuthenticationEntryPoint))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(HttpMethod.GET, "/health/**").permitAll()
.requestMatchers(
"/swagger-ui.html",
"/swagger-ui/**",
"/v3/api-docs/**"
).permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll()
.anyRequest().authenticated())
// Refuse business traffic before authentication touches storage.
// Nginx retries this 503 on another peer and passively excludes
// the refusing replica according to max_fails/fail_timeout.
.addFilterBefore(trustedClientCertificateFilter, AnonymousAuthenticationFilter.class)
.addFilterAfter(readinessGuardFilter, TrustedClientCertificateFilter.class)
.addFilterAfter(apiAuthenticationFilter, ReadinessGuardFilter.class);
return http.build();
}
}
@@ -0,0 +1,19 @@
package com.example.mtusi_messenger.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfig {
@Bean
ObjectMapper objectMapper() {
return JsonMapper.builder().findAndAddModules()
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
.build();
}
}
@@ -0,0 +1,75 @@
package com.example.mtusi_messenger.controller;
import com.example.mtusi_messenger.dto.AttachmentResponse;
import com.example.mtusi_messenger.model.Attachment;
import com.example.mtusi_messenger.security.SessionPrincipal;
import com.example.mtusi_messenger.service.AttachmentService;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import static com.example.mtusi_messenger.service.UuidValidator.parse;
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1")
@SecurityRequirement(name = "bearerAuth")
public class AttachmentController {
private final AttachmentService attachments;
@PostMapping(value = "/chats/{chatId}/attachments",
consumes = {"image/png", "image/jpeg"},
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<AttachmentResponse> upload(
@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String chatId,
@RequestParam String filename,
@RequestHeader(HttpHeaders.CONTENT_TYPE) String contentType,
HttpServletRequest request
) throws IOException {
Attachment attachment = attachments.upload(parse(chatId), principal.user().id(), filename,
contentType, request.getContentLengthLong(), request.getInputStream());
return ResponseEntity.status(HttpStatus.ACCEPTED).body(AttachmentResponse.from(attachment));
}
@GetMapping("/attachments/{attachmentId}")
public AttachmentResponse metadata(
@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String attachmentId
) {
return AttachmentResponse.from(attachments.getAccessible(parse(attachmentId), principal.user().id()));
}
@GetMapping("/attachments/{attachmentId}/content")
public ResponseEntity<byte[]> download(
@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String attachmentId,
@RequestParam(defaultValue = "original") String variant
) {
AttachmentService.Download download = attachments.download(
parse(attachmentId), principal.user().id(), variant);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(download.contentType()))
.contentLength(download.bytes().length)
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline()
.filename(download.filename(), StandardCharsets.UTF_8).build().toString())
.body(download.bytes());
}
}
@@ -0,0 +1,83 @@
package com.example.mtusi_messenger.controller;
import com.example.mtusi_messenger.exception.ApiExceptions;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import com.example.mtusi_messenger.dto.*;
import com.example.mtusi_messenger.model.Chat;
import com.example.mtusi_messenger.service.ChatService;
import com.example.mtusi_messenger.security.SessionPrincipal;
import java.util.List;
import java.util.UUID;
import static com.example.mtusi_messenger.service.UuidValidator.parse;
@RestController
@RequestMapping("/api/v1/chats")
@SecurityRequirement(name = "bearerAuth")
@RequiredArgsConstructor
public class ChatController {
private final ChatService chats;
@PostMapping
public ResponseEntity<ChatResponse> create(@AuthenticationPrincipal SessionPrincipal principal,
@Valid @RequestBody CreateChatRequest body
) {
UUID userId = principal.user().id();
Chat c = chats.create(body, userId);
return ResponseEntity.status(HttpStatus.CREATED).body(ChatResponse.from(c));
}
@GetMapping
public ChatPageResponse list(@AuthenticationPrincipal SessionPrincipal principal,
@RequestParam(required = false) String limit,
@RequestParam(required = false) String cursor
) {
UUID userId = principal.user().id();
int parsedLimit = validateLimit(limit);
validateCursorPresence(cursor);
List<Chat> page = chats.page(userId, parsedLimit, cursor);
boolean hasNext = page.size() > parsedLimit;
if (hasNext) page = page.subList(0, parsedLimit);
return new ChatPageResponse(page.stream().map(ChatResponse::from).toList(), page.isEmpty() ? null :
chats.nextCursor(userId, page.get(page.size() - 1), hasNext));
}
@GetMapping("/{chatId}")
public ChatResponse get(@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String chatId
) {
UUID userId = principal.user().id();
return ChatResponse.from(chats.getAccessible(parse(chatId), userId));
}
private static int validateLimit(String limit) {
if (limit == null) {
return 50;
}
if (!limit.matches("[0-9]+")) {
throw ApiExceptions.invalid("Invalid limit");
}
try {
int value = Integer.parseInt(limit);
if (value < 1 || value > 100) {
throw ApiExceptions.invalid("Invalid limit");
}
return value;
} catch (NumberFormatException ex) {
throw ApiExceptions.invalid("Invalid limit");
}
}
private static void validateCursorPresence(String c) {
if (c != null && c.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
}
}

Some files were not shown because too many files have changed in this diff Show More