From 60fa12ce6e41dee7f5b44c6c7ef93702bfd5edbb Mon Sep 17 00:00:00 2001 From: EgorAnti Date: Thu, 26 Nov 2026 17:26:19 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A3=D1=81=D0=B8=D0=BB=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5=D0=B9=D0=BD=D0=B5=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=20=D0=B8=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BE=D1=82=D0=BA=D0=B0=D0=B7=D0=BE=D1=83=D1=81?= =?UTF-8?q?=D1=82=D0=BE=D0=B9=D1=87=D0=B8=D0=B2=D0=BE=D1=81=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 4 +- README.md | 25 +++ REPORT.md | 9 +- compose.yaml | 144 +++++++++++++++--- infra/openbao/README.md | 4 +- infra/openbao/openbao.hcl | 11 +- infra/otel/README.md | 4 +- infra/rabbitmq/rabbitmq.conf | 1 - scripts/bootstrap-openbao.ps1 | 49 ++++-- scripts/bootstrap-pki.ps1 | 9 ++ scripts/check-compose-hardening.ps1 | 44 ++++++ scripts/check-security-lifecycle.ps1 | 68 +++++++++ scripts/check_contract.py | 8 +- scripts/restart.cmd | 8 +- scripts/restart.sh | 8 +- scripts/rotate-openbao-secret-ids.ps1 | 7 +- scripts/test-openbao-policies.ps1 | 2 +- scripts/validate_openapi.py | 6 +- scripts/verify-https-resilience.ps1 | 48 ++++++ .../worker/AttachmentWorker.java | 7 + src/main/resources/application.yml | 4 +- tests/README.md | 8 +- tests/client.py | 4 +- tests/resilience.py | 4 +- 24 files changed, 418 insertions(+), 68 deletions(-) create mode 100644 scripts/check-compose-hardening.ps1 create mode 100644 scripts/check-security-lifecycle.ps1 create mode 100644 scripts/verify-https-resilience.ps1 diff --git a/.env.example b/.env.example index bd3289b..62a0560 100644 --- a/.env.example +++ b/.env.example @@ -99,6 +99,4 @@ OBSERVABILITY_QUEUE_POLL_INTERVAL=5s GRAFANA_PORT=3000 GRAFANA_ADMIN_USER=admin GRAFANA_ADMIN_PASSWORD=replace-with-a-long-random-grafana-password -PROMETHEUS_PORT=9090 -LOKI_PORT=3100 -TEMPO_PORT=3200 +OPENBAO_PORT=8200 diff --git a/README.md b/README.md index 9105eac..504d4ad 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,31 @@ docker compose --env-file .env up -d --build Для 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). +Проверка 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; stateless root filesystems — +read-only. Stateful entrypoints сохраняют только минимальный набор capabilities, +нужный для смены UID и подготовки named volume. + +Полный повторяемый сценарий после запуска и unseal стенда: + +```powershell +.\scripts\verify-https-resilience.ps1 +``` + +Он последовательно выполняет certificate/secret lifecycle check, HTTPS smoke, +перезапуск API/worker и хранилищ с сохранением volumes, отказ одной из двух API +реплик и восстановление масштаба. Во все HTTP-тесты явно передаётся public CA; +режима `--insecure` и `curl -k` в сценарии нет. + Примеры запросов доступны в `examples/requests.http`, примеры JSON — в `contracts/examples.json`. Для полной проверки схемы (по желанию локально; CI делает её автоматически): diff --git a/REPORT.md b/REPORT.md index 9801db4..eb87135 100644 --- a/REPORT.md +++ b/REPORT.md @@ -17,7 +17,11 @@ TODO: схема процессов/хранилищ, источник исти | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | +| Compose hardening | `scripts/check-compose-hardening.ps1` | PASS: только три loopback HTTPS-порта; limits/capability/read-only policy проверены | `compose.yaml`, самопроверка скрипта | +| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 20 cert/key bundles валидны; expiry, SAN, пары ключей, Git ignore и возраст SecretID проверены | вывод команды без secret values | +| Публичный smoke | `scripts/verify-https-resilience.ps1` | PASS: полный API-сценарий, включая ACL и вложения, выполнен через HTTPS с проверкой CA и hostname | вывод команды | +| Перезапуск с сохранением | тот же сценарий, mode `persistence` | PASS: после остановки и запуска stateful-сервисов, worker, двух API и LB сохранились сессия, сообщение и байты вложения | вывод команды | +| Отказ одной API-реплики | тот же сценарий, mode `failover` | PASS: до отказа наблюдались 2 реплики; после остановки выбранной реплики — 7 успешных записей, 0 ошибок, восстановление за 4.842 с; подтверждённые данные не потеряны | вывод команды | | Остальные пункты уровня 3 | TODO | TODO | TODO | | Все пункты уровня 4, если заявлен | TODO | TODO | TODO | | Выбранный трек 5, если заявлен | TODO | TODO | TODO | @@ -30,7 +34,8 @@ TODO: гипотеза, hardware/лимиты, версии, объём данн | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Перезапуск PostgreSQL, Redis, MinIO, RabbitMQ, worker, двух API и LB без удаления volumes | Существующая сессия и подтверждённые данные доступны после готовности | Сессия повторно не создавалась; сообщение и вложение совпали с исходными | в пределах 120 с / потерь не обнаружено | +| Остановка API-реплики, обслужившей контрольный запрос | LB продолжает направлять запросы на вторую реплику | 7 успешных записей, 0 неуспешных попыток; остановленная реплика отсутствует среди последних ответов | 4.842 с / потерь и дублей не обнаружено | ## Ограничения и следующие шаги diff --git a/compose.yaml b/compose.yaml index b1c40a8..1c4d3b7 100644 --- a/compose.yaml +++ b/compose.yaml @@ -31,8 +31,8 @@ x-api-environment: &api-environment REDIS_HOST: redis REDIS_PORT: 6379 REDIS_SSL_ENABLED: "true" - REDIS_CONNECT_TIMEOUT: ${REDIS_CONNECT_TIMEOUT:-1s} - REDIS_COMMAND_TIMEOUT: ${REDIS_COMMAND_TIMEOUT:-500ms} + 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} @@ -82,22 +82,34 @@ x-api-environment: &api-environment 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 - command: ["server", "-config=/openbao/config/openbao.hcl"] + 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/data - - ./infra/openbao:/openbao/config:ro + - 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] - security_opt: ["no-new-privileges:true"] + 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 @@ -106,9 +118,13 @@ services: 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 @@ -118,14 +134,21 @@ services: - ./secrets/openbao/api:/run/bootstrap:ro - api-runtime-secrets:/run/rendered cap_drop: [ALL] - security_opt: ["no-new-privileges:true"] + 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 @@ -135,11 +158,15 @@ services: - ./secrets/openbao/worker:/run/bootstrap:ro - worker-runtime-secrets:/run/rendered cap_drop: [ALL] - security_opt: ["no-new-privileges:true"] + 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} @@ -161,11 +188,13 @@ services: timeout: 2s retries: 30 restart: unless-stopped + cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT] 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} @@ -186,11 +215,13 @@ services: timeout: 2s retries: 30 restart: unless-stopped + cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT] 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} @@ -208,11 +239,13 @@ services: start_period: 60s retries: 12 restart: unless-stopped + cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT] cpus: 0.5 mem_limit: 1024m networks: [backend] rabbitmq-init: + <<: *runtime-hardening image: curlimages/curl:8.12.1 depends_on: rabbitmq: @@ -232,18 +265,26 @@ services: 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":"^$"}' + 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 @@ -255,16 +296,19 @@ services: timeout: 2s retries: 30 restart: unless-stopped + cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT] 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} @@ -274,19 +318,21 @@ services: S3_WORKER_SECRET_ACCESS_KEY: ${S3_WORKER_SECRET_ACCESS_KEY:?Set S3_WORKER_SECRET_ACCESS_KEY in .env} volumes: - ./infra/minio-api-policy.json:/policy/minio-api-policy.json:ro - - ./secrets/pki/service-ca/ca.crt:/root/.mc/certs/CAs/service-ca.crt: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 attempt=0 - until mc alias set local https://minio:9000 "$$MINIO_ROOT_USER" "$$MINIO_ROOT_PASSWORD" \ + 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 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 add -- local "$$S3_WORKER_ACCESS_KEY_ID" "$$S3_WORKER_SECRET_ACCESS_KEY" \ || mc admin user info local "$$S3_WORKER_ACCESS_KEY_ID") \ && (mc admin policy create local messenger-attachments-rw /tmp/minio-api-policy.json \ || mc admin policy info local messenger-attachments-rw) \ @@ -301,30 +347,39 @@ services: 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} volumes: - - ./secrets/pki/service-ca/ca.crt:/root/.mc/certs/CAs/service-ca.crt:ro + - ./secrets/pki/service-ca/ca.crt:/run/ca.crt:ro entrypoint: ["/bin/sh", "-c"] command: - | set -eu - mc alias set anonymous https://minio:9000 + 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 alias set -- restricted https://minio:9000 "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY" mc ls "restricted/$$S3_BUCKET" >/dev/null if mc admin info restricted >/dev/null 2>&1; then echo "FAIL: API credentials have administrative access" >&2 @@ -332,10 +387,16 @@ services: fi echo "PASS: bucket is private and API credentials are non-admin" 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: . @@ -360,11 +421,15 @@ services: 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: . @@ -411,11 +476,15 @@ services: 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 @@ -423,7 +492,7 @@ services: MESSENGER_ROLE: worker OTEL_SERVICE_NAME: messenger-worker SPRING_MAIN_WEB_APPLICATION_TYPE: none - JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=70 + 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 @@ -455,11 +524,18 @@ services: 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" @@ -476,11 +552,20 @@ services: 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: @@ -494,14 +579,16 @@ services: 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] prometheus: + <<: *runtime-hardening image: prom/prometheus:v3.14.0 - ports: - - "127.0.0.1:${PROMETHEUS_PORT:-9090}:9090" command: - --config.file=/etc/prometheus/prometheus.yml - --storage.tsdb.path=/prometheus @@ -515,39 +602,47 @@ services: - ./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"] - ports: - - "127.0.0.1:${LOKI_PORT:-3100}:3100" 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"] - ports: - - "127.0.0.1:${TEMPO_PORT:-3200}:3200" 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" @@ -576,6 +671,9 @@ services: 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] diff --git a/infra/openbao/README.md b/infra/openbao/README.md index e901ef9..40bc550 100644 --- a/infra/openbao/README.md +++ b/infra/openbao/README.md @@ -1,6 +1,6 @@ # OpenBao: эксплуатация стенда -OpenBao запускается обычным `server`, а не `dev`: данные хранятся в named volume `openbao-data` через integrated Raft storage. TLS обязателен, порт опубликован только на loopback. После перезапуска данные сохраняются, но сервер снова sealed до ручного unseal. +OpenBao запускается обычным `server`, а не `dev`: данные хранятся в named volume `openbao-data` через integrated Raft storage (`/openbao/file`). TLS обязателен, порт опубликован только на loopback. После перезапуска данные сохраняются, но сервер снова sealed до ручного unseal. ## Первичная инициализация @@ -42,7 +42,7 @@ OpenBao запускается обычным `server`, а не `dev`: данн Remove-Item Env:BAO_TOKEN ``` - Скрипт не печатает secret values. Он загружает их в KV v2 через stdin, включает file audit, создаёт отдельные `messenger-api` и `messenger-worker` policies и кладёт только стартовые AppRole RoleID/SecretID в игнорируемый каталог `secrets/openbao/`. + Скрипт не печатает 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. Запустите весь стенд: diff --git a/infra/openbao/openbao.hcl b/infra/openbao/openbao.hcl index 82203b1..dcfef85 100644 --- a/infra/openbao/openbao.hcl +++ b/infra/openbao/openbao.hcl @@ -6,7 +6,7 @@ api_addr = "https://openbao:8200" cluster_addr = "https://openbao:8201" storage "raft" { - path = "/openbao/data" + path = "/openbao/file" node_id = "openbao-stand" } @@ -22,3 +22,12 @@ listener "tcp" { 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" + } +} diff --git a/infra/otel/README.md b/infra/otel/README.md index 13f1f84..7417441 100644 --- a/infra/otel/README.md +++ b/infra/otel/README.md @@ -16,11 +16,11 @@ - `grafana/dashboards/messenger-overview.json` — импортируемый dashboard; - `runbooks.md` — локальные действия для каждого alert. -Grafana доступна только на `127.0.0.1:3000`, Prometheus — на `127.0.0.1:9090`. Для автоматизированных incident snapshots Loki и Tempo доступны только на loopback-портах 3100 и 3200. OTLP Collector не публикуется на интерфейсы хоста. +Grafana доступна только на `127.0.0.1:3000`. Prometheus, Loki, Tempo и OTLP Collector не публикуются на интерфейсы хоста; доступ к backend выполняется только из внутренней Docker-сети через Grafana или отдельный одноразовый verification-контейнер. ## Проверка корреляции -1. Выполнить `python tests/smoke.py --base-url http://localhost:8080`. +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. diff --git a/infra/rabbitmq/rabbitmq.conf b/infra/rabbitmq/rabbitmq.conf index 666952e..ca7c048 100644 --- a/infra/rabbitmq/rabbitmq.conf +++ b/infra/rabbitmq/rabbitmq.conf @@ -7,7 +7,6 @@ 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.tcp.port = none management.ssl.port = 15671 management.ssl.cacertfile = /run/pki/service-ca/ca.crt management.ssl.certfile = /run/pki/rabbitmq/tls.crt diff --git a/scripts/bootstrap-openbao.ps1 b/scripts/bootstrap-openbao.ps1 index 1b81fd0..7c909f1 100644 --- a/scripts/bootstrap-openbao.ps1 +++ b/scripts/bootstrap-openbao.ps1 @@ -2,7 +2,9 @@ param([string]$EnvFile = '.env') $ErrorActionPreference = 'Stop' -Set-Location (Join-Path $PSScriptRoot '..') +$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.' } @@ -21,14 +23,40 @@ 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 + } + } +} -& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao secrets enable -path=secret -version=2 kv 2>$null -if($LASTEXITCODE -ne 0) { Bao secrets list | Select-String 'secret/' | Out-Null } -& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao auth enable approle 2>$null -if($LASTEXITCODE -ne 0) { Bao auth list | Select-String 'approle/' | 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/config/api-policy.hcl | Out-Null -Bao policy write messenger-worker /openbao/config/worker-policy.hcl | 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 @@ -53,14 +81,15 @@ if($LASTEXITCODE -ne 0){ throw 'Failed to write worker secrets' } foreach($role in 'api','worker') { $roleName = "messenger-$role" - $dir = Join-Path 'secrets\openbao' $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) } -& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao audit enable file file_path=/openbao/data/audit.log 2>$null -if($LASTEXITCODE -ne 0) { Bao audit list | Select-String 'file/' | Out-Null } Write-Host 'OpenBao policies, AppRoles, KV secrets and agent bootstrap files are ready. Secret values were not printed.' diff --git a/scripts/bootstrap-pki.ps1 b/scripts/bootstrap-pki.ps1 index 0f93c09..0ea184e 100644 --- a/scripts/bootstrap-pki.ps1 +++ b/scripts/bootstrap-pki.ps1 @@ -37,6 +37,9 @@ function New-Ca([string]$Name) { [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 @@ -63,6 +66,12 @@ function New-Leaf( [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)) } diff --git a/scripts/check-compose-hardening.ps1 b/scripts/check-compose-hardening.ps1 new file mode 100644 index 0000000..fe1ef1a --- /dev/null +++ b/scripts/check-compose-hardening.ps1 @@ -0,0 +1,44 @@ +[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 } +$statefulWritableRoots = @('postgres','redis','rabbitmq','minio') + +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($name -notin $statefulWritableRoots -and $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: ports, privileges, capabilities, filesystems and resource limits satisfy the local hardening contract.' diff --git a/scripts/check-security-lifecycle.ps1 b/scripts/check-security-lifecycle.ps1 new file mode 100644 index 0000000..977091c --- /dev/null +++ b/scripts/check-security-lifecycle.ps1 @@ -0,0 +1,68 @@ +[CmdletBinding()] +param( + [string]$PkiDirectory, + [int]$MinimumRemainingDays = 7, + [int]$MaximumLeafValidityDays = 31, + [int]$MaximumSecretIdAgeHours = 24 +) + +$ErrorActionPreference = 'Stop' +Set-Location (Join-Path $PSScriptRoot '..') +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" + } + + $privateKey = [System.Security.Cryptography.RSA]::Create() + $publicKey = $null + try { + $privateKey.ImportFromPem([System.IO.File]::ReadAllText($keyFile)) + $privatePublic = [Convert]::ToBase64String($privateKey.ExportSubjectPublicKeyInfo()) + $publicKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPublicKey($certificate) + $certificatePublic = [Convert]::ToBase64String($publicKey.ExportSubjectPublicKeyInfo()) + if($privatePublic -ne $certificatePublic){ throw "$($certificateFile.Directory.Name) private key does not match certificate" } + } finally { + if($null -ne $publicKey){ $publicKey.Dispose() } + $privateKey.Dispose() + $certificate.Dispose() + } + $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." diff --git a/scripts/check_contract.py b/scripts/check_contract.py index dcb34df..0c75274 100644 --- a/scripts/check_contract.py +++ b/scripts/check_contract.py @@ -8,8 +8,8 @@ import re ROOT = Path(__file__).resolve().parents[1] def main(): - lab = json.loads((ROOT/'lab.json').read_text())['number'] - spec = json.loads((ROOT/'contracts/openapi.json').read_text()) + lab = json.loads((ROOT/'lab.json').read_text(encoding='utf-8'))['number'] + spec = json.loads((ROOT/'contracts/openapi.json').read_text(encoding='utf-8')) assert spec['openapi']=='3.1.0' assert spec['info']['version']=='1.%d.0'%lab operation_ids = set() @@ -41,11 +41,11 @@ def main(): assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2) assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4) 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'): if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts): 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'): assert (ROOT/required).is_file(), 'missing '+required print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.') diff --git a/scripts/restart.cmd b/scripts/restart.cmd index ddc596a..8f21b46 100644 --- a/scripts/restart.cmd +++ b/scripts/restart.cmd @@ -3,8 +3,10 @@ setlocal EnableExtensions cd /d "%~dp0\.." if not defined ENV_FILE set "ENV_FILE=.env" -docker compose --env-file "%ENV_FILE%" stop nginx api redis postgres minio || exit /b 1 -docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 postgres redis minio || exit /b 1 +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%" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api || 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 diff --git a/scripts/restart.sh b/scripts/restart.sh index d8a5cec..029a61c 100644 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -8,8 +8,10 @@ cd "$PROJECT_DIR" # 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 redis postgres minio -docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 postgres redis minio +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" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api +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 diff --git a/scripts/rotate-openbao-secret-ids.ps1 b/scripts/rotate-openbao-secret-ids.ps1 index 1c4c00a..95c59ff 100644 --- a/scripts/rotate-openbao-secret-ids.ps1 +++ b/scripts/rotate-openbao-secret-ids.ps1 @@ -2,12 +2,15 @@ param([string]$EnvFile = '.env') $ErrorActionPreference = 'Stop' -Set-Location (Join-Path $PSScriptRoot '..') +$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 "secrets\openbao\$role" 'secret-id'),$secretId,[System.Text.Encoding]::ASCII) + [System.IO.File]::WriteAllText((Join-Path $directory 'secret-id'),$secretId,[System.Text.Encoding]::ASCII) } Write-Host 'AppRole SecretIDs rotated without printing their values.' diff --git a/scripts/test-openbao-policies.ps1 b/scripts/test-openbao-policies.ps1 index 0e07dad..1d508bf 100644 --- a/scripts/test-openbao-policies.ps1 +++ b/scripts/test-openbao-policies.ps1 @@ -24,7 +24,7 @@ foreach($role in 'api','worker') { $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/config/api-policy.hcl) -eq 0) { throw "$role unexpectedly changed an OpenBao policy" } + 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.' diff --git a/scripts/validate_openapi.py b/scripts/validate_openapi.py index 1dfe4a9..1542dc6 100644 --- a/scripts/validate_openapi.py +++ b/scripts/validate_openapi.py @@ -6,17 +6,17 @@ from openapi_spec_validator import validate from jsonschema import Draft202012Validator 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) from referencing import Registry, Resource # The base URI resolves local #/components references inside examples. resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'}) 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} Draft202012Validator(schema, registry=registry).validate(example) 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) for example in schema.get('examples',[]): Draft202012Validator(schema).validate(example) diff --git a/scripts/verify-https-resilience.ps1 b/scripts/verify-https-resilience.ps1 new file mode 100644 index 0000000..49670fa --- /dev/null +++ b/scripts/verify-https-resilience.ps1 @@ -0,0 +1,48 @@ +[CmdletBinding()] +param( + [string]$EnvFile = '.env', + [string]$Python = 'python', + [string]$BaseUrl = 'https://localhost:8443' +) + +$ErrorActionPreference = 'Stop' +Set-Location (Join-Path $PSScriptRoot '..') +$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 = 120) { + $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 { + & $Python -c $probe $BaseUrl $ca 2>$null + if($LASTEXITCODE -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) + +& docker compose --env-file $EnvFile up -d --no-deps --scale api=2 api +if($LASTEXITCODE -ne 0){ throw 'Failed to restore the stopped API replica' } +Write-Host 'PASS: HTTPS smoke, persistence restart and one-replica failure completed with CA and hostname verification enabled.' diff --git a/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java b/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java index e3d42d8..37e578f 100644 --- a/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java +++ b/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java @@ -154,6 +154,13 @@ public class AttachmentWorker { outcome = "interrupted"; } catch (ExecutionException execution) { Throwable cause = execution.getCause(); + log.atWarn() + .addKeyValue("event", "attachment_processing_attempt_failed") + .addKeyValue("job.type", AttachmentJob.TYPE) + .addKeyValue("attempt", attempt) + .addKeyValue("error.type", cause.getClass().getName()) + .setCause(cause) + .log("Attachment processing attempt failed"); if (cause instanceof ImageVariantProcessor.ProcessingException imageFailure && imageFailure.permanent()) { failPermanent(job, leaseToken, imageFailure.errorCode(), deliveryTag, channel); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 6553b6a..374a2bc 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -34,8 +34,8 @@ spring: redis: host: ${REDIS_HOST:localhost} port: ${REDIS_PORT:6379} - connect-timeout: ${REDIS_CONNECT_TIMEOUT:1s} - timeout: ${REDIS_COMMAND_TIMEOUT:500ms} + connect-timeout: ${REDIS_CONNECT_TIMEOUT:5s} + timeout: ${REDIS_COMMAND_TIMEOUT:2s} username: ${REDIS_USER:messenger-api} password: ${REDIS_PASSWORD:} ssl: diff --git a/tests/README.md b/tests/README.md index c061bba..02e49d8 100644 --- a/tests/README.md +++ b/tests/README.md @@ -4,9 +4,9 @@ Python **3.9+**, стандартная библиотека. Сервер уж ```sh make check -make test BASE_URL=http://localhost:8080 +make test BASE_URL=https://localhost:8443 CA_FILE=secrets/pki/public-ca/ca.crt # без make: -python3 tests/smoke.py --base-url http://localhost:8080 +python3 tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt ``` `smoke.py` выполняет **один сквозной сценарий**, автоматически выбирая профиль из `lab.json`: health → три пользователя → вход с lab2 → чат → сообщения → пагинация → ошибки доступа → идемпотентность с lab3 → файл с lab4 → thumbnail с lab5 → logout. Он проверяет JSON по используемому подмножеству схемы, коды/headers, Unicode, SHA-256 оригинала и фактические JPEG-размеры thumbnail. Это публичный минимум, не полный fuzz/security/load suite. @@ -35,6 +35,10 @@ make test-failover ACTION_SCRIPT=scripts/stop-one.sh Перед отказом тест наблюдает ≥2 API-реплики; 15 секунд отправляет сообщения параллельно выполнению hook, повторяет неопределённый POST с тем же ключом, проверяет восстановление записи за ≤10 секунд, отсутствие остановленной реплики в последних ответах, сохранность подтверждённых сообщений и отсутствие дублей. Ошибки переходного периода учитываются. Затем восстановите реплику и повторите для другой. Скрипт — проверка одного отказа API, не гарантия HA БД/LB/host. Вывод hook скрыт, чтобы не утекли секреты; отлаживайте его отдельно с безопасным выводом. +Для Windows готовый orchestration выполняет все три проверки с одним CA и затем +восстанавливает две реплики: `scripts/verify-https-resilience.ps1`. Скрипт сначала +проверяет published ports/privileges/limits и certificate/secret lifecycle. + ## Нагрузка ```sh diff --git a/tests/client.py b/tests/client.py index f0499a2..8fdeea8 100644 --- a/tests/client.py +++ b/tests/client.py @@ -13,8 +13,8 @@ import urllib.request import uuid ROOT = Path(__file__).resolve().parents[1] -LAB = json.loads((ROOT / 'lab.json').read_text())['number'] -SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text()) +LAB = json.loads((ROOT / 'lab.json').read_text(encoding='utf-8'))['number'] +SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text(encoding='utf-8')) class Failure(AssertionError): pass diff --git a/tests/resilience.py b/tests/resilience.py index f3fa700..b1374e2 100644 --- a/tests/resilience.py +++ b/tests/resilience.py @@ -65,14 +65,14 @@ def main(): except subprocess.TimeoutExpired: raise Failure('restart hook exceeded 90 seconds') from None check(code==0,'restart hook failed (inspect your script locally)') - deadline = time.monotonic()+90 + deadline = time.monotonic()+120 while True: try: c.call('GET','/health/ready',schema='Health') c.call('GET','/api/v1/users/me',actor=alice,schema='User') break except Failure: - check(time.monotonic()