From d8ecd2aad99a0d8baa2b0fcafead2e39844262b3 Mon Sep 17 00:00:00 2001 From: badradine Date: Sat, 5 Dec 2026 23:43:41 +0300 Subject: [PATCH] Complete Lab 7 security and PKI track --- .env.example | 43 +- .github/pull_request_template.md | 30 +- .gitignore | 1 + .trivyignore.yaml | 158 +++ Dockerfile | 35 + REPORT.md | 121 ++- compose.yaml | 828 ++++++++++++++++ contracts/trust-matrix.md | 53 +- evidence/track2-crl-run1.json | 17 + evidence/track2-crl-run2.json | 17 + evidence/track2-crl-run3.json | 17 + evidence/track2-final-run1.json | 19 + evidence/track2-final-run2.json | 19 + evidence/track2-final-run3.json | 19 + evidence/track2-lb-rotation-run2.json | 17 + evidence/track2-lb-rotation-run3.json | 17 + evidence/track2-lb-rotation-run4.json | 25 + evidence/track2-lb-rotation-run5.json | 25 + evidence/track2-lb-rotation.json | 17 + evidence/track2-post-upgrade-run1.json | 19 + evidence/track2-post-upgrade-run2.json | 19 + evidence/track2-post-upgrade-run3.json | 19 + evidence/track2-run1.json | 17 + evidence/track2-run2.json | 17 + evidence/track2-run3.json | 17 + evidence/trivy-summary-20261205.md | 17 + infra/README.md | 26 +- infra/api-nginx.conf | 40 + .../dashboards/messenger-overview.json | 23 + .../provisioning/dashboards/dashboards.yaml | 10 + .../provisioning/datasources/datasources.yaml | 52 + infra/images/Dockerfile.alpine-upgrade | 7 + infra/loki/config.yaml | 46 + infra/nginx.conf | 47 + infra/openbao/Dockerfile.renew | 12 + infra/openbao/README.md | 101 +- infra/openbao/server.hcl | 25 + infra/otel/collector.yaml | 85 ++ infra/otel/nginx.conf | 44 + infra/postgres/Dockerfile | 9 + infra/postgres/pg_hba.conf | 13 + infra/postgres/pg_ident.conf | 4 + infra/postgres/postgresql.conf | 6 + infra/prometheus/alerts.yml | 19 + infra/prometheus/prometheus.yml | 5 + infra/prometheus/web.yml | 6 + infra/proxy-mtls.conf | 18 + infra/runbooks/high-errors.md | 7 + infra/runbooks/queue-lag.md | 7 + infra/runbooks/telemetry-backend.md | 23 + infra/supervisord.conf | 32 + infra/tempo/config.yaml | 45 + migrations/001_initial.sql | 36 + migrations/002_idempotency.sql | 16 + migrations/003_attachments.sql | 48 + migrations/004_attachment_schema_compat.sql | 32 + migrations/005_async_attachment_jobs.sql | 45 + migrations/006_telemetry_context.sql | 2 + migrations/007_workload_roles.sql | 13 + migrations/008_dispatcher_outbox_read.sql | 1 + requirements.txt | 18 + scripts/bao_bootstrap.py | 311 ++++++ scripts/bao_policy_probe.py | 52 + scripts/bootstrap-local.ps1 | 152 +++ scripts/issue_expiry_probe.py | 48 + scripts/postgres-init.sh | 32 + scripts/renew_leaf.py | 222 +++++ scripts/restart.sh | 36 + scripts/rollover_intermediate.py | 215 ++++ scripts/scan-images.ps1 | 39 + scripts/security_negative.py | 138 +++ scripts/stop-one.sh | 16 + security/THREAT_MODEL.md | 39 +- src/__init__.py | 1 + src/app/__init__.py | 1 + src/app/db.py | 73 ++ src/app/dispatcher.py | 162 +++ src/app/errors.py | 23 + src/app/explain_history.py | 71 ++ src/app/image_pipeline.py | 76 ++ src/app/main.py | 937 ++++++++++++++++++ src/app/migrate.py | 36 + src/app/models.py | 211 ++++ src/app/reconcile_s3_orphans.py | 97 ++ src/app/replay_job.py | 53 + src/app/s3_bootstrap.py | 251 +++++ src/app/schemas.py | 123 +++ src/app/secrets_bootstrap.py | 96 ++ src/app/settings.py | 116 +++ src/app/storage.py | 23 + src/app/telemetry.py | 186 ++++ src/app/worker.py | 441 +++++++++ tests/load.py | 44 +- 93 files changed, 6714 insertions(+), 133 deletions(-) create mode 100644 .trivyignore.yaml create mode 100644 Dockerfile create mode 100644 compose.yaml create mode 100644 evidence/track2-crl-run1.json create mode 100644 evidence/track2-crl-run2.json create mode 100644 evidence/track2-crl-run3.json create mode 100644 evidence/track2-final-run1.json create mode 100644 evidence/track2-final-run2.json create mode 100644 evidence/track2-final-run3.json create mode 100644 evidence/track2-lb-rotation-run2.json create mode 100644 evidence/track2-lb-rotation-run3.json create mode 100644 evidence/track2-lb-rotation-run4.json create mode 100644 evidence/track2-lb-rotation-run5.json create mode 100644 evidence/track2-lb-rotation.json create mode 100644 evidence/track2-post-upgrade-run1.json create mode 100644 evidence/track2-post-upgrade-run2.json create mode 100644 evidence/track2-post-upgrade-run3.json create mode 100644 evidence/track2-run1.json create mode 100644 evidence/track2-run2.json create mode 100644 evidence/track2-run3.json create mode 100644 evidence/trivy-summary-20261205.md create mode 100644 infra/api-nginx.conf create mode 100644 infra/grafana/dashboards/messenger-overview.json create mode 100644 infra/grafana/provisioning/dashboards/dashboards.yaml create mode 100644 infra/grafana/provisioning/datasources/datasources.yaml create mode 100644 infra/images/Dockerfile.alpine-upgrade create mode 100644 infra/loki/config.yaml create mode 100644 infra/nginx.conf create mode 100644 infra/openbao/Dockerfile.renew create mode 100644 infra/openbao/server.hcl create mode 100644 infra/otel/collector.yaml create mode 100644 infra/otel/nginx.conf create mode 100644 infra/postgres/Dockerfile create mode 100644 infra/postgres/pg_hba.conf create mode 100644 infra/postgres/pg_ident.conf create mode 100644 infra/postgres/postgresql.conf create mode 100644 infra/prometheus/alerts.yml create mode 100644 infra/prometheus/prometheus.yml create mode 100644 infra/prometheus/web.yml create mode 100644 infra/proxy-mtls.conf create mode 100644 infra/runbooks/high-errors.md create mode 100644 infra/runbooks/queue-lag.md create mode 100644 infra/runbooks/telemetry-backend.md create mode 100644 infra/supervisord.conf create mode 100644 infra/tempo/config.yaml create mode 100644 migrations/001_initial.sql create mode 100644 migrations/002_idempotency.sql create mode 100644 migrations/003_attachments.sql create mode 100644 migrations/004_attachment_schema_compat.sql create mode 100644 migrations/005_async_attachment_jobs.sql create mode 100644 migrations/006_telemetry_context.sql create mode 100644 migrations/007_workload_roles.sql create mode 100644 migrations/008_dispatcher_outbox_read.sql create mode 100644 requirements.txt create mode 100644 scripts/bao_bootstrap.py create mode 100644 scripts/bao_policy_probe.py create mode 100644 scripts/bootstrap-local.ps1 create mode 100644 scripts/issue_expiry_probe.py create mode 100644 scripts/postgres-init.sh create mode 100644 scripts/renew_leaf.py create mode 100644 scripts/restart.sh create mode 100644 scripts/rollover_intermediate.py create mode 100644 scripts/scan-images.ps1 create mode 100644 scripts/security_negative.py create mode 100644 scripts/stop-one.sh create mode 100644 src/__init__.py create mode 100644 src/app/__init__.py create mode 100644 src/app/db.py create mode 100644 src/app/dispatcher.py create mode 100644 src/app/errors.py create mode 100644 src/app/explain_history.py create mode 100644 src/app/image_pipeline.py create mode 100644 src/app/main.py create mode 100644 src/app/migrate.py create mode 100644 src/app/models.py create mode 100644 src/app/reconcile_s3_orphans.py create mode 100644 src/app/replay_job.py create mode 100644 src/app/s3_bootstrap.py create mode 100644 src/app/schemas.py create mode 100644 src/app/secrets_bootstrap.py create mode 100644 src/app/settings.py create mode 100644 src/app/storage.py create mode 100644 src/app/telemetry.py create mode 100644 src/app/worker.py diff --git a/.env.example b/.env.example index 2e9f0541..9038492a 100644 --- a/.env.example +++ b/.env.example @@ -1,41 +1,12 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. -APP_HOST=0.0.0.0 -APP_PORT=8080 -APP_ENV=lab +# Optional Compose tuning values. Copy to .env only if you need to change them. +# No credentials belong here; scripts/bootstrap-local.ps1 creates ignored secret files. SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url -API_REPLICAS=2 -IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=https://s3:9000 -S3_REGION=us-east-1 -S3_BUCKET=messenger-attachments -S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id -S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key +LOGIN_RATE_LIMIT_PER_MINUTE=10 MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 -BROKER_URL_FILE=/run/secrets/broker_url -WORKER_CONCURRENCY=2 +WORKER_CONCURRENCY=1 JOB_MAX_ATTEMPTS=5 JOB_TIMEOUT_SECONDS=60 -STAGING_RETENTION_SECONDS=86400 -OTEL_SERVICE_NAME=messenger-api -# Worker must set a distinct service.name. -OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318 -OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf -OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab -# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix. -PUBLIC_BASE_URL=https://localhost:8443 -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_PARALLELISM=1 +JOB_LEASE_SECONDS=180 +OTEL_TRACES_SAMPLER_ARG=0.1 +OTEL_METRIC_EXPORT_INTERVAL=5000 diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8aef0ffd..cadeea6f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,20 @@ ## Лабораторная 7 -Автор / группа: TODO -Целевая оценка (3/4/5): TODO -Трек 5, если заявлен: TODO +Автор / группа: Бадрадин Али / БВТ2302 +Целевой уровень: 5 +Трек: 2 — жизненный цикл PKI и секретов -Что реализовано и что перенесено: TODO -Команды запуска из чистого clone: TODO -Результаты проверок и ссылка на REPORT.md: TODO -Ограничения / известные ошибки: TODO -Источники и использование ИИ: TODO +Что реализовано: HTTPS/mTLS ingress, OpenBao PKI и scoped policies, CRL/revocation, expiry и intermediate rollover, двухрепличный API, Redis broker, persistence/failover hooks, telemetry и hardening. Подробности и остаточные риски — в REPORT.md. -- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. -- [ ] Контракт и публичные тесты не ослаблены. -- [ ] make check и make test выполнены; приложен реальный вывод. -- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. -- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. -- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. +Команды проверки, выполненные на Docker Desktop: `tests/smoke.py`, профиль `bao-policy-probe`, профиль `security-probe`, три финальных запуска `tests/load.py` по 60 секунд. Результаты и метрики — в REPORT.md и `evidence/track2-final-run*.json`. + +Ограничения: последний Trivy scan — 0 CRITICAL и 118 HIGH; 93 findings без доступного исправления, 23 Go module findings и 2 deferred. Два HIGH filesystem misconfigurations остаются в Dockerfile PostgreSQL и одноразовом операторском Dockerfile. Краткое окно HTTP 502 во время замены сертификата API измерено и описано в отчёте. Raw Trivy JSON исключён из Git; сокращённая сводка — в `evidence/trivy-summary-20261205.md`. + +Использование ИИ: Codex использовался для помощи при реализации, отладке и подготовке отчёта. Автор должен проверить и уметь объяснить решения на защите. + +- [ ] Все требования уровней 3 и 4 подтверждены; REPORT.md пока отмечает ограничения проверок DB/Redis. +- [x] Контракт и публичные тесты не ослаблены. +- [ ] Команды `make check` и `make test` выполнены именно через Makefile; smoke и контрактные проверки выполнялись напрямую. +- [x] Сценарии безопасности и уровня 5 воспроизведены; реальные результаты приведены в REPORT.md. +- [x] Секреты и приватные ключи исключены из Git; staged diff необходимо проверить перед отправкой. +- [x] README задания сохранён; REPORT.md описывает запуск этого решения. diff --git a/.gitignore b/.gitignore index b5a71896..fa71a4f7 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,4 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. +evidence/trivy-*.json diff --git a/.trivyignore.yaml b/.trivyignore.yaml new file mode 100644 index 00000000..65d610a0 --- /dev/null +++ b/.trivyignore.yaml @@ -0,0 +1,158 @@ +vulnerabilities: + - id: CVE-2025-61726 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2025-61729 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-111943 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-25679 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-27145 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-32280 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-32281 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-32283 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-33811 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-33814 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-33818 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-39820 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-39821 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-39822 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-39836 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-42499 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-42504 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-56853 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-56858 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-56859 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-56860 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-56862 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-78667 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-78669 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2026-97031 + paths: [usr/local/bin/gosu] + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this inherited Go binary with a symlink to + /sbin/su-exec. Runtime verification confirmed the target and successful user switch. + - id: CVE-2025-68121 + paths: + - usr/local/bin/gosu + expired_at: 2027-01-31 + statement: >- + The final PostgreSQL image replaces this path with /sbin/su-exec; the finding + comes from the inherited image layer. Verified with docker run and readlink. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..582bfc78 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,35 @@ +FROM python:3.12.16-slim-trixie + +ARG BUILD_REVISION=local +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PYTHONUTF8=1 \ + APP_HOST=127.0.0.1 \ + APP_PORT=8080 \ + APP_BUILD_REVISION=${BUILD_REVISION} + +WORKDIR /app + +RUN apt-get update \ + && apt-get upgrade -y --no-install-recommends \ + && apt-get install -y --no-install-recommends nginx \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt ./ +RUN pip install --no-cache-dir --requirement requirements.txt + +COPY src/ ./src/ +COPY migrations/ ./migrations/ +COPY infra/api-nginx.conf /etc/nginx/conf.d/default.conf +COPY infra/supervisord.conf /etc/supervisor/supervisord.conf + +RUN useradd --create-home --uid 10001 appuser \ + && rm -f /etc/nginx/sites-enabled/default +USER appuser + +EXPOSE 8443 + +HEALTHCHECK --interval=3s --timeout=2s --start-period=20s --retries=3 \ + CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status==200 else 1)" + +CMD ["supervisord", "-n", "-c", "/etc/supervisor/supervisord.conf"] diff --git a/REPORT.md b/REPORT.md index 9801db45..be084508 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,114 @@ -# Отчёт — лабораторная 7 +# Лабораторная 7 — безопасность, mTLS и OpenBao -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор / группа: Бадрадин Али, БВТ2302 +- Целевая оценка: 5; выбран трек 2 — жизненный цикл PKI и секретов +- Ветка решения: `solution/БВТ2302-Бадрадин-Али` (публикуется в Gitea) +- Использование ИИ: при разработке использовалась помощь ИИ; перед защитой проверьте и объясните каждое решение ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Требования: Windows 11 с PowerShell 7 или Windows PowerShell, Docker Desktop с Linux Engine, Git for Windows (OpenSSL), Python 3.12. Виртуальное окружение из lab6 не требуется. Команды запускаются из корня репозитория lab7. + +~~~powershell +.\scripts\bootstrap-local.ps1 +docker compose up -d openbao +docker compose exec openbao bao operator init -key-shares=3 -key-threshold=2 -format=json +~~~ + +Сохраните shares для unseal и root token вне репозитория. Два shares вводятся интерактивно: + +~~~powershell +docker compose exec openbao bao operator unseal +docker compose exec openbao bao operator unseal +~~~ + +Затем создайте виртуальное окружение и выполните bootstrap OpenBao: + +~~~powershell +python -m venv .venv +.\.venv\Scripts\python.exe -m pip install -r requirements.txt +python scripts/bao_bootstrap.py +docker compose up -d --build --scale api=2 +docker compose ps +~~~ + +bao_bootstrap.py запросит root token скрытым вводом и не сохранит его. Не сохраняйте JSON с результатом operator init, shares или root token в репозитории, журнале терминала или переписке. Файлы секретов находятся в игнорируемом Git каталоге secrets/; не добавляйте его в Git. + +## Проверки + +~~~powershell +python scripts/check_contract.py +python scripts/validate_openapi.py +python -m compileall -q src scripts +docker compose config --quiet +python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/internal-ca.crt +python tests/security.py --base-url https://localhost:8443 --ca-file secrets/pki/internal-ca.crt +docker compose --profile security-test run --rm security-probe +docker compose --profile security-test run --rm bao-policy-probe +~~~ + +Профиль security-test монтирует ключ клиента LB только для проверки политики в отдельном контейнере. Не используйте его в общей или рабочей среде. Нагрузочный тест запускайте после smoke и негативных проверок. Сохранность данных проверяется командой make test-persistence ACTION_SCRIPT=scripts/restart.sh, отказ одной API-реплики — make test-failover ACTION_SCRIPT=scripts/stop-one.sh; после проверки снова запустите остановленную реплику. Hooks не удаляют volumes. Обычная остановка без удаления данных — docker compose down. Для полного сброса удалите named volumes и локальный secrets/ только после сохранения нужных доказательств. + +Сканирование образов и исходного кода запускается после настройки Docker командой .\scripts\scan-images.ps1. Разберите каждую находку уровня HIGH/CRITICAL: применимость к этой схеме, исправление либо остаточный риск, результат повторной проверки. Для обновления одного leaf-сертификата используйте python scripts/renew_leaf.py api-client (или другую роль из списка) и пересоздайте потребителей. Скрипт не выполняет отзыв через CRL и rollover CA; одной выдачи нового сертификата недостаточно, чтобы считать трек 2 выполненным. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +В lab7 перенесены бизнес-API и схема PostgreSQL из lab6, сессии, outbox, хранилище вложений, Redis Streams, dispatcher, image worker, миграции, telemetry и dashboards. Источник истины для API — OpenAPI-контракт и публичные тесты этого репозитория. Стенд работает через Compose: две API-реплики за одним Nginx ingress. -## Доказательства критериев +Внешний ingress принимает только TLS. LB проверяет CA и SAN API, а API-прокси требует mTLS и разрешает точное имя клиента LB. Порт API не опубликован на хост. API, dispatcher и worker подключаются к PostgreSQL с разными клиентскими сертификатами и SQL-ролями. API Redis и Redis Streams используют TLS, клиентские сертификаты, разные ACL-пользователи и постоянный AOF. API и worker используют разные учетные данные RustFS и политики префиксов объектов. Сертификаты API/worker/dispatcher проходят cert-аутентификацию в OpenBao и читают только собственный KV v2 путь. Telemetry проходит через изолированный mTLS gateway с allowlist CN, затем Collector отправляет данные в TLS/mTLS-защищенные хранилища. Административные порты привязаны к loopback. -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Пароли приложения хешируются Argon2id (m=19456 KiB, t=2, p=1). Общий для API-реплик Redis-счетчик входа возвращает 429 с Retry-After; на ingress также включен лимит по адресу клиента. API/worker/dispatcher работают не от root, с read-only root filesystem, ограниченным tmpfs, no-new-privileges, сброшенными capabilities и лимитами CPU/RAM. Сервисы не используют privileged, host network или Docker socket. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +## Состояние доказательств -## Эксперименты и отказы +| Критерий | Команда / сценарий | Состояние в этом checkout | +| --- | --- | --- | +| Контракт и синтаксис Python | check_contract.py; validate_openapi.py; compileall | Выполнено: все команды завершились успешно | +| Модель Compose | docker compose config --quiet | Успешная проверка модели; не проверяет реальные entrypoint образов и TLS запущенных контейнеров | +| YAML и PowerShell | Проверка YAML; синтаксический разбор bootstrap-local.ps1 и scan-images.ps1 | Выполнено: parsing прошел успешно | +| HTTPS smoke | tests/smoke.py | Выполнено на стенде: `PASS: lab7 public API scenario` | +| Внешний TLS trust | tests/security.py | Выполнено на стенде: trusted HTTPS passed; untrusted CA rejected | +| mTLS LB → API | Compose профиль security-test | Выполнено на стенде: отсутствие client cert, foreign CA, неверная identity и отозванный предыдущий сертификат LB отклонены; текущая LB identity принята; login rate limit returned 429 with Retry-After. Проверка отзыва/CRL подтверждена 2026-12-05 после публикации CRL root + intermediate и пересоздания API | +| Ограниченные политики OpenBao | bao-policy-probe через Compose profile security-test | Выполнено на стенде: каждый workload читает только свой KV v2 path; cross-read и policy write запрещены | +| Ограничения S3/DB/Redis | S3 bootstrap и негативные проверки identity/ACL | Код S3 проверяет анонимный доступ и запрещенные операции вне префикса; проверки DB/Redis требуют наблюдения на стенде | +| Сохранность данных и сессии | `tests/resilience.py --mode persistence --action-script scripts/restart.sh` | Выполнено на стенде: `PASS: persistence preserved confirmed data and existing session`; hook output подавлялся тестом | +| Отказ одной API-реплики | `tests/resilience.py --mode failover --action-script scripts/stop-one.sh` | Выполнено на стенде: 2 реплики до отказа, 122 успешные записи, 0 ошибок, первое восстановление за 1.022 с; `PASS: failover preserved confirmed data and existing session` | +| Окружение и ссылка на код | PowerShell: Get-CimInstance, docker version/info, git rev-parse/status | CPU: 13th Gen Intel Core i5-13420H; RAM хоста: 15.7 GB; Docker Engine 29.9.3; Docker resources: 12 CPUs и 8,185,982,976 bytes RAM (~7.63 GiB). HEAD: `20afc2c`. `git status --short` показал измененные и неотслеживаемые файлы; указанный commit не включает финальное состояние рабочей копии. | +| Trivy: images и filesystem, 2026-12-05 15:12 MSK | `scripts/scan-images.ps1`, Trivy 0.77.0; JSON `evidence/trivy-20261205-151201-*.json` | Повторный scan 12 образов: 0 CRITICAL и 164 HIGH (30 уникальных ID; повторы пакетов/образов включены). Статусы: 93 `affected` без исправленной версии, 69 `fixed` (исправленная версия доступна, но уязвимый пакет ещё найден) и 2 `fix_deferred` — CVE-2026-9538 в `perl-base` API/bao-renew. PostgreSQL по-прежнему без findings при path-specific исключении унаследованного `/usr/local/bin/gosu`; это не исправление базового слоя. После обновления Supervisor/setuptools в API исчезли две Python HIGH находки, а filesystem scan больше не показывает уязвимостей зависимостей. Остались 4 misconfigurations: два HIGH `DS-0002` (root в Dockerfile PostgreSQL и bao-renew) и два LOW `DS-0026` (нет Dockerfile HEALTHCHECK). Секретов не найдено. Smoke, `bao-policy-probe` и `security-probe` после пересборки прошли. | +| Trivy: images + filesystem, 2026-12-05 22:29 MSK | `scripts/scan-images.ps1`, JSON `evidence/trivy-20261205-222959-*.json` | Повторный scan подтвердил именно `grafana/grafana:13.3.2`: всего 0 CRITICAL и 159 HIGH (30 уникальных ID), из них 93 `affected` без исправленной версии, 64 `fixed` и 2 `fix_deferred`. Для Grafana количество HIGH снизилось с 28 на версии 13.3.1 до 23 на 13.3.2. Filesystem scan: 0 dependency vulnerabilities и 4 misconfigurations (2 HIGH `DS-0002` root, 2 LOW `DS-0026` без HEALTHCHECK); секретов нет. | +| Trivy: производные Alpine images + filesystem, 2026-12-05 22:42 MSK | `scripts/scan-images.ps1`, JSON `evidence/trivy-20261205-224145-*.json` | Build 8 локальных images и scan 12 images завершились. HIGH снизились с 159 до 118 (21 уникальный ID), CRITICAL — 0. Исчезли 41 Alpine package findings: Nginx 13, Redis 7, RustFS 7, OpenBao 7, Grafana 7. Осталось 93 `affected`, 23 `fixed` (Go modules) и 2 `fix_deferred`. Filesystem scan: 0 dependency vulnerabilities, 5 misconfigurations (2 HIGH `DS-0002`, 3 LOW `DS-0026` — добавилась проверка нового Dockerfile без встроенного HEALTHCHECK; Compose healthchecks у сервисов остаются настроенными), secret findings отсутствуют. Docker build вывел предупреждение об ARG без default; значения по умолчанию внесены в Dockerfile после этого запуска, Compose передает оба build args. После обновления Compose runtime-проверки завершены: smoke, bao-policy-probe и security-probe прошли; последняя security-probe подтвердила отказ expired/revoked leaf и принятие identities двух intermediates. | +| Уровни 3 и 4 | Smoke, rate limit, ACL, worker вложений, persistence, failover, сканирование образов | Частично проверены на стенде; не заявлены завершенными до проверки ограничений DB/Redis и разбора сканирования образов | +| Уровень 5, трек 2 — базовая нагрузка | `tests/load.py --duration 60 --concurrency 4` три раза через доверенный HTTPS | Выполнено по выводу стенда: 116 успешных записей в каждом запуске, 0 ошибок; успешный RPS 1.923 / 1.926 / 1.923 (медиана 1.923; диапазон 1.923–1.926); p50 2078 ms во всех запусках, p95 2109 / 2109 / 2110 ms, p99 2110 ms. Closed-loop результат включает накладные расходы клиента и не является оценкой максимальной емкости. | +| Уровень 5, трек 2 — нагрузка с CRL | `tests/load.py --duration 60 --concurrency 4` три раза после активации CRL | Выполнено по выводу стенда: 116 успешных записей в каждом запуске, 0 ошибок; успешный RPS 1.916 / 1.919 / 1.921 (медиана 1.919; диапазон 1.916–1.921); p50 2093 / 2078 / 2078 ms (медиана 2078), p95 2110 ms во всех запусках, p99 2125 / 2156 / 2125 ms (медиана 2125). Smoke после CRL прошел. Closed-loop не является оценкой максимальной емкости. | +| Уровень 5, трек 2 — нагрузка после обновления образов и leaf certificates | `tests/load.py --duration 60 --concurrency 4` три раза через доверенный HTTPS; JSON `evidence/track2-post-upgrade-run1.json`–`run3.json` | Выполнено после обновления OpenBao, Grafana/Loki/Tempo и renewal 19 leaf certificates: 116 успешных запросов на каждый прогон, 0 ошибок; успешный RPS 1.883 / 1.880 / 1.890 (медиана 1.883); p50 2094 / 2109 / 2094 ms (медиана 2094); p95 2297 / 2219 / 2250 ms (медиана 2250); p99 2313 / 2234 / 2250 ms (медиана 2250). Closed-loop включает накладные расходы клиента и не является оценкой максимальной емкости. | +| Уровень 5, трек 2 — итоговая нагрузка после обновления Alpine и сертификатов | `tests/load.py --duration 60 --concurrency 4` три раза через доверенный HTTPS; JSON `evidence/track2-final-run1.json`–`run3.json` | Три запуска: 116 успешных записей и 0 ошибок каждый; RPS 1.922 / 1.927 / 1.922 (медиана 1.922); p50 2078 ms во всех запусках; p95 2094 / 2109 / 2110 ms (медиана 2109); p99 2141 / 2125 / 2125 ms (медиана 2125). Closed-loop включает накладные расходы клиента и не является оценкой максимальной емкости. | +| Уровень 5, трек 2 — обновление LB во время нагрузки | `tests/load.py --duration 240 --concurrency 4` с одновременным выпуском нового LB leaf, отзывом предыдущего leaf и пересозданием API/LB | Три прогона: run3 — 446 успехов, 14 ошибок из 460 (3.0435%), успешный RPS 1.857, p50/p95/p99 2078/2110/2188 ms; run4 — 445 успехов, 19 ошибок из 464 (4.0948%), успешный RPS 1.843, p50/p95/p99 2078/2110/2156 ms; run5 с безопасным порядком — 449 успехов, 13 HTTP 502 из 462 (2.8139%), успешный RPS 1.859, p50/p95/p99 2078/2125/2359 ms. Ошибки run5 пришлись на 29.921–36.046 s (6.125 s), во время пересоздания API для применения CRL; LB уже предъявлял новый leaf. API/LB стали healthy; security-probe после ротации прошел. | +| Уровень 5, трек 2 — проба истечения | `scripts/issue_expiry_probe.py` и два запуска security-probe | Выполнено на стенде: отдельный LB leaf с TTL 2 минуты принят до `notAfter`; после ожидания 150 секунд сертификат отклонен, а текущая LB identity осталась принятой. | +| Уровень 5, трек 2 — rollover intermediate CA | `scripts/rollover_intermediate.py prepare/activate` + revoke previous leaf | Выполнено на стенде: overlap probe принял leaf старого и нового intermediate; после активации новый LB leaf принят, old leaf отозван, итоговые smoke и security-probe прошли. Root CA остается offline и не менялся. Повторный запуск activate/revoke дал ожидаемый отказ на уже активном/не найденном serial; скрипты усилены защитой от повторного отзыва текущего leaf и выбором правильного issuer mount. | +| Уровень 5, трек 2 — отсутствие plaintext fallback | `compose.yaml`, `infra/nginx.conf`, `docker compose ps api lb` | Подтверждено конфигурацией и runtime: LB слушает TLS на `127.0.0.1:8443->8443/tcp`; API показывают только внутренний `8443/tcp` и не публикуются на хосте. Monitoring/admin порты привязаны к loopback. | +| Уровень 5, трек 2 — полный жизненный цикл PKI | Обновление/rollover под нагрузкой, expiry/revocation, восстановление, отсутствие plaintext fallback | Функциональные проверки PKI/CRL, expiry, отзыва, intermediate rollover и TLS-only ingress пройдены. Нагрузочные ротации ранее показывали кратковременные HTTP 502 при пересоздании API; это измеренный перерыв, а не нулевая деградация. После обновления версий и всех 19 leaf certificates smoke, `bao-policy-probe` и `security-probe` прошли. Финальные три нагрузочных запуска: 116/116 успешных запросов каждый, 0 ошибок; RPS 1.922, 1.927, 1.922; p95 2094, 2109, 2110 ms; p99 2141, 2125, 2125 ms. Доказательства: `evidence/track2-final-run1.json`–`run3.json`. Scan Trivy от 2026-12-05 22:42: 118 HIGH (21 уникальный ID), 0 CRITICAL; осталось 93 affected без исправленной версии, 23 Go-module findings и 2 fix_deferred. Filesystem scan: 0 dependency vulnerabilities и 5 misconfigurations. Перед обновлением OpenBao 2.6.6→2.7.3 оператор сохранил Raft snapshot вне репозитория (`Documents/lab7-backups/lab7-before-openbao-2.7.3.snap`, 191526 байт). OpenBao 2.7.3 active после unseal двумя Shamir shares (Raft applied index 1460). Все leafs были renewed после истечения 6-часового TTL; consumers пересозданы, включая `s3-tls-init` для обновления TLS volume. Перед сдачей остаётся разобрать остаточные HIGH findings и две HIGH misconfiguration с root-пользователем, а также внести commit/сведения о ресурсах хоста. | -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +### Triage Trivy по scan от 2026-12-05 22:42 -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Категория | Количество | Затронутые компоненты | Решение / остаточный риск | +| --- | ---: | --- | --- | +| `fixed` — Alpine packages | 41 | Grafana 13.3.2 (7), Nginx (13), OpenBao (7), Redis (7), RustFS (7) | Устранены в scan новых локальных образов после `apk upgrade --no-cache`: всего HIGH снизились с 159 до 118, а эти 41 findings исчезли. Нужно ещё пересоздать сервисы из образов и пройти smoke/security probes. | +| `fixed` — Go modules | 23 | Grafana (16), Tempo (4), Prometheus (2), OpenBao (1) | Требуется upstream image, включающий исправленные Go dependencies, либо собственная пересборка соответствующего проекта. Наличие `FixedVersion` в Trivy само по себе не означает, что текущий бинарный файл исправлен. | +| `affected` — Debian packages | 92 | API (46) и bao-renew (46), на Python/Debian 13 | У текущей Trivy DB нет исправленной версии; оба Dockerfile уже выполняют `apt-get update` и `apt-get upgrade`. Это остаточный риск базовых Debian packages, ожидающий исправления в репозитории Debian/обновлении базового образа. | +| `affected` — Go module | 1 | OpenBao: `github.com/go-jose/go-jose/v3` | Trivy не сообщает исправленную версию; findings остаётся, пока upstream не обновит/удалит эту зависимость. | +| `fix_deferred` | 2 | `perl-base` в API и bao-renew | В базе Trivy нет доступного исправления. | +| Misconfiguration | 2 HIGH + 2 LOW | `DS-0002` root у PostgreSQL и bao-renew; `DS-0026` без HEALTHCHECK в тех же Dockerfiles | PostgreSQL запускает официальный entrypoint как root для владения volume/key и затем понижает привилегии до postgres. bao-renew — операторская одноразовая команда с записью в bind-mounted `secrets/`. Compose healthchecks настроены для постоянно работающих сервисов; bao-renew — run-on-demand job. Эти объяснения не делают Trivy findings исчезнувшими. | -## Ограничения и следующие шаги +Итог категории по scan 22:42: 41 Alpine package finding исчезли после обновления пакетов в производных образах. Осталось 118 HIGH: 93 `affected` без исправленной версии, 23 Go module findings с известной исправленной версией, но старым upstream-бинарником, и 2 deferred Perl findings. | -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +## Исследовательский трек 2 и ограничения + +Гипотеза: обновление короткоживущего leaf при сохранении проверок имени сервера и identity клиента вызывает только ограниченный сбой при пересоздании процесса. Просроченный, отозванный или подписанный неизвестным CA сертификат должен блокировать соединение; восстановление должно требовать нового сертификата. + +Повторяемый эксперимент: (1) записать версии образов, CPU/RAM хоста, лимиты стека и commit; (2) базовый прогон и три прогона после включения CRL выполнены: четыре клиента, HTTPS, 60 секунд; см. метрики выше и файлы `evidence/track2-run1.json`–`evidence/track2-run3.json`, `evidence/track2-crl-run1.json`–`evidence/track2-crl-run3.json` на стенде; (3) обновление/отзыв LB leaf подтверждены: предыдущий serial отозван в OpenBao, CRL root + intermediate опубликованы, `security-probe` подтвердил отказ старому leaf; (4) истечение проверено на отдельном двухминутном leaf: принят до срока, отклонен после, действующая identity сохранила доступ; (5) несколько прогонов ротации под нагрузкой завершены; безопасный run5 имел 13 HTTP 502 в 6.125-секундном окне пересоздания API; (6) intermediate rollover завершен: overlap probe принял обе CA identities, затем LB переключен на новый intermediate, старый leaf отозван и финальный smoke/security-probe прошли; (7) runtime mapping подтвердил TLS-only ingress на 8443 и внутренний API; (8) Trivy 0.77.0 проверил 12 образов 2026-12-05 22:42: 118 HIGH (21 уникальный ID), из них 93 `affected`, 23 `fixed` Go-module findings и 2 `fix_deferred`; filesystem scan: 0 dependency vulnerabilities и пять misconfigurations. Удалось убрать две Python findings обновлением Supervisor/setuptools; обновление Grafana 13.3.1→13.3.2 убрало ещё пять HIGH; smoke и security probes после rebuild прошли. Root CA не менялся. + +Финальные три нагрузки после обновления пакетов и сертификатов завершились с 116/116 успешными записями и 0 ошибками; медианный RPS 1.922. Отзыв предыдущего LB leaf и CRL enforcement подтверждены на стенде, как и истечение двухминутного leaf с сохранением доступа действующей identity. Во время 240-секундной нагрузки зафиксированы неудачи при переключении LB/API; безопасный run5 имел 13 HTTP 502 в интервале 6.125 секунд во время пересоздания API. Intermediate rollover завершен на стенде: staged leaf нового CA принят во время overlap, затем LB переключен, предыдущий leaf отозван, и smoke/security-probe прошли. Compose config публикует только loopback ingress на 8443; API не публикует порт, а Nginx использует TLS listener. Trivy 0.77.0 просканировал 12 образов 2026-12-05 22:42: 0 CRITICAL, 118 HIGH (21 уникальный ID; 93 affected, 23 Go modules с доступным исправлением и 2 fix_deferred). Filesystem scan: 0 dependency vulnerabilities, 5 misconfigurations; секретов не найдено. Обновления Python-зависимостей и Grafana отражены отдельными scan; Root CA не менялся. + +## Ограничения + +Это учебный single-host стенд с одним LB и одним экземпляром каждого stateful сервиса. Защита offline root key и unseal shares зависит от оператора. Статические секреты KV загружаются только при старте процесса; автоматическое продление leaf-сертификатов или горячая перезагрузка секретов не реализованы. OpenBao-issued leafs имеют TTL 6 часов; после истечения требуется операторское `bao-renew --all` и пересоздание потребителей. При sealed OpenBao требуется действие оператора. Локальные команды Compose, security probes, нагрузочные проверки и intermediate rollover выполнены пользователем на Docker Desktop; выявленное короткое окно ошибок во время пересоздания API отражено выше. Trivy scan от 2026-12-05 содержит path-specific исключение PostgreSQL для унаследованного пути `usr/local/bin/gosu`: результат не доказывает, что уязвимый файл базового слоя исправлен. Последний scan сообщил 118 HIGH в образах и две HIGH misconfiguration; filesystem scan не выявил уязвимых Python-зависимостей. Отчет не является чистым scan. | diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..3deaa11e --- /dev/null +++ b/compose.yaml @@ -0,0 +1,828 @@ +name: mtusi-messenger-lab7 + +services: + bao-init: + image: mtusi-messenger-lab7-openbao:local + user: "0:0" + entrypoint: ["/bin/sh", "-ec"] + command: ["chown -R openbao:openbao /openbao/data && chmod 0700 /openbao/data"] + volumes: [bao_data:/openbao/data] + restart: "no" + + openbao: + image: mtusi-messenger-lab7-openbao:local + build: + context: . + dockerfile: infra/images/Dockerfile.alpine-upgrade + args: + BASE_IMAGE: openbao/openbao:2.7.3 + RUNTIME_USER: openbao + command: ["server"] + restart: unless-stopped + volumes: + - bao_data:/openbao/data + - ./infra/openbao/server.hcl:/openbao/config/server.hcl:ro + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: openbao_server_crt + target: openbao-server.crt + - source: openbao_server_key + target: openbao-server.key + networks: [backend] + depends_on: + bao-init: {condition: service_completed_successfully} + cap_drop: [ALL] + cap_add: [SETGID, SETUID] + security_opt: [no-new-privileges:true] + healthcheck: + test: ["CMD-SHELL", "bao status -address=https://127.0.0.1:8200 -ca-cert=/run/secrets/internal-ca.crt >/dev/null 2>&1 || [ \"$$?\" -eq 2 ]"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 15s + deploy: + resources: {limits: {cpus: "0.50", memory: 512M}} + + bao-bootstrap: + image: alpine:3.21.3 + profiles: [operator] + entrypoint: ["/bin/sh", "-ec"] + command: ["apk add --no-cache python3 openssl && exec python3 scripts/bao_bootstrap.py"] + working_dir: /lab + environment: + BAO_ADDR: https://openbao:8200 + volumes: + - ./scripts/bao_bootstrap.py:/lab/scripts/bao_bootstrap.py:ro + - ./secrets:/lab/secrets + networks: [backend, default] + depends_on: + openbao: {condition: service_healthy} + stdin_open: true + tty: true + restart: "no" + + bao-renew: + image: mtusi-messenger-lab7-bao-renew:local + build: + context: . + dockerfile: infra/openbao/Dockerfile.renew + profiles: [operator] + working_dir: /lab + entrypoint: ["python3"] + command: ["scripts/renew_leaf.py", "--all"] + environment: + BAO_ADDR: https://openbao:8200 + volumes: + - ./scripts/renew_leaf.py:/lab/scripts/renew_leaf.py:ro + - ./scripts/rollover_intermediate.py:/lab/scripts/rollover_intermediate.py:ro + - ./scripts/issue_expiry_probe.py:/lab/scripts/issue_expiry_probe.py:ro + - ./scripts/bao_bootstrap.py:/lab/scripts/bao_bootstrap.py:ro + - ./secrets:/lab/secrets + networks: [backend] + depends_on: + openbao: {condition: service_healthy} + stdin_open: true + tty: true + restart: "no" + + db: + image: mtusi-messenger-lab7-postgres:local + build: + context: . + dockerfile: infra/postgres/Dockerfile + restart: unless-stopped + entrypoint: ["/bin/sh", "-ec"] + command: + - >- + cp /run/secrets/postgres-server.key /tmp/postgres-server.key; + chown postgres:postgres /tmp/postgres-server.key; + chmod 0600 /tmp/postgres-server.key; + exec docker-entrypoint.sh postgres + -c config_file=/etc/postgresql/postgresql.conf + -c hba_file=/etc/postgresql/pg_hba.conf + -c ident_file=/etc/postgresql/pg_ident.conf + -c ssl_cert_file=/run/secrets/postgres-server.crt + -c ssl_key_file=/tmp/postgres-server.key + -c ssl_ca_file=/run/secrets/internal-ca.crt + environment: + POSTGRES_DB: messenger + POSTGRES_USER: postgres + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + POSTGRES_INITDB_ARGS: --auth-host=scram-sha-256 --auth-local=trust + secrets: + - postgres_password + - source: postgres_server_crt + target: postgres-server.crt + - source: postgres_server_key + target: postgres-server.key + - source: internal_ca_crt + target: internal-ca.crt + volumes: + - postgres_data:/var/lib/postgresql/data + - ./infra/postgres/postgresql.conf:/etc/postgresql/postgresql.conf:ro + - ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro + - ./infra/postgres/pg_ident.conf:/etc/postgresql/pg_ident.conf:ro + - ./scripts/postgres-init.sh:/docker-entrypoint-initdb.d/10-lab7-roles.sh:ro + networks: [backend] + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres -d messenger"] + interval: 3s + timeout: 3s + retries: 20 + start_period: 5s + deploy: + resources: {limits: {cpus: "1.00", memory: 1G}} + + redis-init: + image: mtusi-messenger-lab7-redis:local + user: "0:0" + entrypoint: ["/bin/sh", "-ec"] + command: ["chown -R redis:redis /data"] + volumes: [redis_data:/data] + restart: "no" + + redis: + image: mtusi-messenger-lab7-redis:local + build: + context: . + dockerfile: infra/images/Dockerfile.alpine-upgrade + args: + BASE_IMAGE: redis:7.4.12-alpine3.22 + RUNTIME_USER: redis + restart: unless-stopped + command: + - sh + - -ec + - exec redis-server --port 0 --tls-port 6379 --tls-cert-file /run/secrets/redis-server.crt --tls-key-file /run/secrets/redis-server.key --tls-ca-cert-file /run/secrets/internal-ca.crt --tls-auth-clients yes --aclfile /run/secrets/redis-users.acl --dir /data --appendonly yes --appendfsync everysec --save 60 1 + secrets: + - source: redis_server_crt + target: redis-server.crt + - source: redis_server_key + target: redis-server.key + - source: internal_ca_crt + target: internal-ca.crt + - source: redis_users_acl + target: redis-users.acl + - redis_api_password + - source: api_client_crt + target: api-client.crt + - source: api_client_key + target: api-client.key + volumes: [redis_data:/data] + networks: [backend] + depends_on: + redis-init: {condition: service_completed_successfully} + healthcheck: + test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/redis_api_password)\" redis-cli --tls --cacert /run/secrets/internal-ca.crt --cert /run/secrets/api-client.crt --key /run/secrets/api-client.key --user api ping | grep -q PONG"] + interval: 3s + timeout: 3s + retries: 20 + start_period: 5s + deploy: + resources: {limits: {cpus: "0.25", memory: 256M}} + + broker-init: + image: mtusi-messenger-lab7-redis:local + user: "0:0" + entrypoint: ["/bin/sh", "-ec"] + command: ["chown -R redis:redis /data"] + volumes: [broker_data:/data] + restart: "no" + + broker: + image: mtusi-messenger-lab7-redis:local + restart: unless-stopped + command: + - sh + - -ec + - exec redis-server --port 0 --tls-port 6379 --tls-cert-file /run/secrets/broker-server.crt --tls-key-file /run/secrets/broker-server.key --tls-ca-cert-file /run/secrets/internal-ca.crt --tls-auth-clients yes --aclfile /run/secrets/redis-users.acl --dir /data --appendonly yes --appendfsync everysec --save 60 1 + secrets: + - source: broker_server_crt + target: broker-server.crt + - source: broker_server_key + target: broker-server.key + - source: internal_ca_crt + target: internal-ca.crt + - source: redis_users_acl + target: redis-users.acl + - redis_dispatcher_password + - source: dispatcher_client_crt + target: dispatcher-client.crt + - source: dispatcher_client_key + target: dispatcher-client.key + volumes: [broker_data:/data] + networks: [backend] + depends_on: + broker-init: {condition: service_completed_successfully} + healthcheck: + test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/redis_dispatcher_password)\" redis-cli --tls --cacert /run/secrets/internal-ca.crt --cert /run/secrets/dispatcher-client.crt --key /run/secrets/dispatcher-client.key --user messenger-dispatcher ping | grep -q PONG"] + interval: 3s + timeout: 3s + retries: 20 + start_period: 5s + deploy: + resources: {limits: {cpus: "0.25", memory: 256M}} + + s3-init: + image: alpine:3.21.3 + user: "0:0" + command: ["sh", "-ec", "chown -R 10001:10001 /data && chmod 0750 /data"] + volumes: [s3_data:/data] + restart: "no" + + s3-tls-init: + image: alpine:3.21.3 + user: "0:0" + command: ["sh", "-ec", "cp /run/secrets/rustfs_cert.pem /tls/rustfs_cert.pem && cp /run/secrets/rustfs_key.pem /tls/rustfs_key.pem && chown -R 10001:10001 /tls && chmod 0500 /tls && chmod 0400 /tls/rustfs_cert.pem /tls/rustfs_key.pem"] + secrets: + - source: s3_server_crt + target: rustfs_cert.pem + - source: s3_server_key + target: rustfs_key.pem + volumes: [s3_tls:/tls] + restart: "no" + + s3: + image: mtusi-messenger-lab7-rustfs:local + build: + context: . + dockerfile: infra/images/Dockerfile.alpine-upgrade + args: + BASE_IMAGE: rustfs/rustfs:1.0.7 + RUNTIME_USER: rustfs + restart: unless-stopped + environment: + RUSTFS_VOLUMES: /data + RUSTFS_ADDRESS: 0.0.0.0:9000 + RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001 + RUSTFS_CONSOLE_ENABLE: "false" + RUSTFS_OBS_LOGGER_LEVEL: warn + RUSTFS_CHECK_UPDATE: "false" + RUSTFS_TLS_PATH: /run/tls + RUSTFS_ACCESS_KEY_FILE: /run/secrets/s3_root_access_key_id + RUSTFS_SECRET_KEY_FILE: /run/secrets/s3_root_secret_access_key + secrets: + - s3_root_access_key_id + - s3_root_secret_access_key + - source: internal_ca_crt + target: internal-ca.crt + - source: s3_server_crt + target: rustfs_cert.pem + volumes: [s3_data:/data, s3_tls:/run/tls:ro] + networks: [backend] + depends_on: + s3-init: {condition: service_completed_successfully} + s3-tls-init: {condition: service_completed_successfully} + healthcheck: + test: ["CMD-SHELL", "curl --fail --silent --resolve s3:9000:127.0.0.1 --cacert /run/secrets/internal-ca.crt https://s3:9000/health/ready >/dev/null"] + interval: 3s + timeout: 2s + retries: 20 + start_period: 10s + deploy: + resources: {limits: {cpus: "1.00", memory: 1G}} + + migrate: + image: mtusi-messenger-lab7-api:local + build: {context: ., dockerfile: Dockerfile} + command: ["python", "-m", "src.app.migrate"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + DB_TLS_CA_FILE: /run/secrets/internal-ca.crt + secrets: + - database_url + - source: internal_ca_crt + target: internal-ca.crt + networks: [backend] + depends_on: + db: {condition: service_healthy} + restart: "no" + deploy: + resources: {limits: {cpus: "0.25", memory: 256M}} + + s3-bootstrap: + image: mtusi-messenger-lab7-api:local + build: {context: ., dockerfile: Dockerfile} + command: ["python", "-m", "src.app.s3_bootstrap"] + environment: + S3_ENDPOINT: https://s3:9000 + S3_CA_FILE: /run/secrets/internal-ca.crt + S3_REGION: us-east-1 + S3_BUCKET: messenger-attachments + S3_ROOT_ACCESS_KEY_FILE: /run/secrets/s3_root_access_key_id + S3_ROOT_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_root_secret_access_key + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + S3_WORKER_ACCESS_KEY_ID_FILE: /run/secrets/s3_worker_access_key_id + S3_WORKER_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_worker_secret_access_key + secrets: + - s3_root_access_key_id + - s3_root_secret_access_key + - s3_access_key_id + - s3_secret_access_key + - s3_worker_access_key_id + - s3_worker_secret_access_key + - source: internal_ca_crt + target: internal-ca.crt + networks: [backend] + depends_on: + s3: {condition: service_healthy} + restart: "no" + + api: + image: mtusi-messenger-lab7-api:local + build: {context: ., dockerfile: Dockerfile} + command: + - /bin/sh + - -ec + - cp /run/secrets/api-server.key /tmp/api-server.key; chmod 0600 /tmp/api-server.key; exec supervisord -n -c /etc/supervisor/supervisord.conf + restart: unless-stopped + stop_grace_period: 10s + environment: + APP_HOST: 127.0.0.1 + APP_PORT: 8080 + APP_ENV: lab + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + LOGIN_RATE_LIMIT_PER_MINUTE: ${LOGIN_RATE_LIMIT_PER_MINUTE:-10} + DATABASE_URL: postgresql+psycopg://messenger_api@db:5432/messenger + DB_TLS_CA_FILE: /run/secrets/internal-ca.crt + DB_TLS_CERT_FILE: /run/secrets/api-client.crt + DB_TLS_KEY_FILE: /run/secrets/api-client.key + S3_ENDPOINT: https://s3:9000 + S3_CA_FILE: /run/secrets/internal-ca.crt + S3_REGION: us-east-1 + S3_BUCKET: messenger-attachments + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-180} + BAO_ADDR: https://openbao:8200 + BAO_CA_CERT: /run/secrets/internal-ca.crt + BAO_CLIENT_CERT: /run/secrets/api-client.crt + BAO_CLIENT_KEY: /run/secrets/api-client.key + OTEL_ENABLED: "true" + OTEL_SERVICE_NAME: messenger-api + OTEL_TRACES_SAMPLER_ARG: ${OTEL_TRACES_SAMPLER_ARG:-0.1} + OTEL_METRIC_EXPORT_INTERVAL: ${OTEL_METRIC_EXPORT_INTERVAL:-5000} + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-gateway:4318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/secrets/internal-ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/api-client.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/api-client.key + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: pki_int_crl + target: pki-int.crl.pem + - source: api_server_crt + target: api-server.crt + - source: api_server_key + target: api-server.key + - source: api_client_crt + target: api-client.crt + - source: api_client_key + target: api-client.key + networks: [backend, edge, telemetry_ingress] + depends_on: + db: {condition: service_healthy} + redis: {condition: service_healthy} + s3-bootstrap: {condition: service_completed_successfully} + migrate: {condition: service_completed_successfully} + openbao: {condition: service_started} + otel-gateway: {condition: service_started} + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2)"] + interval: 3s + timeout: 2s + retries: 3 + start_period: 20s + tmpfs: ["/tmp:size=64m,noexec,nosuid", "/run:size=16m,noexec,nosuid,uid=10001,gid=10001", "/var/log/nginx:size=16m,noexec,nosuid,uid=10001,gid=10001"] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + deploy: + replicas: 2 + resources: {limits: {cpus: "0.75", memory: 768M}} + + dispatcher: + image: mtusi-messenger-lab7-api:local + build: {context: ., dockerfile: Dockerfile} + command: ["python", "-m", "src.app.secrets_bootstrap", "dispatcher", "--", "python", "-m", "src.app.dispatcher"] + restart: unless-stopped + environment: + APP_ENV: lab + DATABASE_URL: postgresql+psycopg://messenger_dispatcher@db:5432/messenger + DB_TLS_CA_FILE: /run/secrets/internal-ca.crt + DB_TLS_CERT_FILE: /run/secrets/dispatcher-client.crt + DB_TLS_KEY_FILE: /run/secrets/dispatcher-client.key + BROKER_STREAM: messenger:attachment-jobs:v1 + BAO_ADDR: https://openbao:8200 + BAO_CA_CERT: /run/secrets/internal-ca.crt + BAO_CLIENT_CERT: /run/secrets/dispatcher-client.crt + BAO_CLIENT_KEY: /run/secrets/dispatcher-client.key + OTEL_ENABLED: "true" + OTEL_SERVICE_NAME: messenger-dispatcher + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-gateway:4318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/secrets/internal-ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/dispatcher-client.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/dispatcher-client.key + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: dispatcher_client_crt + target: dispatcher-client.crt + - source: dispatcher_client_key + target: dispatcher-client.key + networks: [backend, telemetry_ingress] + healthcheck: {disable: true} + depends_on: + db: {condition: service_healthy} + broker: {condition: service_healthy} + openbao: {condition: service_started} + migrate: {condition: service_completed_successfully} + tmpfs: ["/tmp:size=32m,noexec,nosuid"] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + deploy: + resources: {limits: {cpus: "0.25", memory: 256M}} + + worker: + image: mtusi-messenger-lab7-api:local + build: {context: ., dockerfile: Dockerfile} + command: ["python", "-m", "src.app.secrets_bootstrap", "worker", "--", "python", "-m", "src.app.worker"] + restart: unless-stopped + stop_grace_period: 15s + environment: + APP_ENV: lab + DATABASE_URL: postgresql+psycopg://messenger_worker@db:5432/messenger + DB_TLS_CA_FILE: /run/secrets/internal-ca.crt + DB_TLS_CERT_FILE: /run/secrets/worker-client.crt + DB_TLS_KEY_FILE: /run/secrets/worker-client.key + S3_ENDPOINT: https://s3:9000 + S3_CA_FILE: /run/secrets/internal-ca.crt + S3_REGION: us-east-1 + S3_BUCKET: messenger-attachments + BROKER_STREAM: messenger:attachment-jobs:v1 + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-1} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-180} + BAO_ADDR: https://openbao:8200 + BAO_CA_CERT: /run/secrets/internal-ca.crt + BAO_CLIENT_CERT: /run/secrets/worker-client.crt + BAO_CLIENT_KEY: /run/secrets/worker-client.key + OTEL_ENABLED: "true" + OTEL_SERVICE_NAME: messenger-worker + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-gateway:4318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/secrets/internal-ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/worker-client.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/worker-client.key + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: worker_client_crt + target: worker-client.crt + - source: worker_client_key + target: worker-client.key + networks: [backend, telemetry_ingress] + healthcheck: {disable: true} + depends_on: + db: {condition: service_healthy} + broker: {condition: service_healthy} + s3-bootstrap: {condition: service_completed_successfully} + openbao: {condition: service_started} + migrate: {condition: service_completed_successfully} + tmpfs: ["/tmp:size=64m,noexec,nosuid"] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + deploy: + replicas: 1 + resources: {limits: {cpus: "0.75", memory: 768M}} + + lb: + image: mtusi-messenger-lab7-nginx:local + build: + context: . + dockerfile: infra/images/Dockerfile.alpine-upgrade + args: + BASE_IMAGE: nginx:1.31.10-alpine3.24 + RUNTIME_USER: "101:101" + user: "101:101" + command: ["nginx", "-g", "daemon off;"] + restart: unless-stopped + ports: ["127.0.0.1:8443:8443"] + volumes: + - ./infra/nginx.conf:/etc/nginx/conf.d/default.conf:ro + - ./infra/proxy-mtls.conf:/etc/nginx/proxy-mtls.conf:ro + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: ingress_crt + target: ingress.crt + - source: ingress_key + target: ingress.key + - source: lb_client_crt + target: lb-client.crt + - source: lb_client_key + target: lb-client.key + networks: [edge, ingress] + tmpfs: ["/tmp:size=32m,noexec,nosuid", "/run:size=16m,noexec,nosuid,uid=101,gid=101", "/var/cache/nginx:size=32m,noexec,nosuid,uid=101,gid=101"] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + depends_on: + api: {condition: service_healthy} + healthcheck: + test: ["CMD", "nginx", "-t"] + interval: 10s + timeout: 3s + retries: 3 + deploy: + resources: {limits: {cpus: "0.25", memory: 128M}} + + security-probe: + image: python:3.12.16-slim-trixie + profiles: [security-test] + user: "10001:10001" + command: ["python", "/probe/security_negative.py"] + volumes: + - ./scripts/security_negative.py:/probe/security_negative.py:ro + - ./secrets/revocation-probe:/revocation:ro + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: lb_client_crt + target: lb-client.crt + - source: lb_client_key + target: lb-client.key + - source: prometheus_client_crt + target: prometheus-client.crt + - source: prometheus_client_key + target: prometheus-client.key + - source: negative_test_client_crt + target: negative-test-client.crt + - source: negative_test_client_key + target: negative-test-client.key + networks: [edge, telemetry_ingress] + depends_on: [lb, api] + read_only: true + tmpfs: ["/tmp:size=16m,noexec,nosuid"] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + + bao-policy-probe: + image: python:3.12.16-slim-trixie + profiles: [security-test] + user: "10001:10001" + working_dir: /lab + command: ["python", "scripts/bao_policy_probe.py"] + environment: + BAO_ADDR: https://openbao:8200 + volumes: + - ./scripts/bao_policy_probe.py:/lab/scripts/bao_policy_probe.py:ro + - ./secrets:/lab/secrets:ro + networks: [backend] + depends_on: + openbao: {condition: service_started} + read_only: true + tmpfs: ["/tmp:size=16m,noexec,nosuid"] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.166.0 + command: ["--config=/etc/otelcol-contrib/config.yaml"] + restart: unless-stopped + volumes: [./infra/otel/collector.yaml:/etc/otelcol-contrib/config.yaml:ro] + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: otel_server_crt + target: otel-server.crt + - source: otel_server_key + target: otel-server.key + - source: otel_client_crt + target: otel-client.crt + - source: otel_client_key + target: otel-client.key + networks: [telemetry] + depends_on: + tempo: {condition: service_started} + loki: {condition: service_started} + deploy: + resources: {limits: {cpus: "0.50", memory: 256M}} + + otel-gateway: + image: mtusi-messenger-lab7-nginx:local + user: "101:101" + command: ["nginx", "-g", "daemon off;"] + restart: unless-stopped + volumes: [./infra/otel/nginx.conf:/etc/nginx/conf.d/default.conf:ro] + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: otel_gateway_server_crt + target: otel-gateway.crt + - source: otel_gateway_server_key + target: otel-gateway.key + - source: otel_client_crt + target: otel-client.crt + - source: otel_client_key + target: otel-client.key + networks: [telemetry_ingress, telemetry] + tmpfs: ["/tmp:size=16m,noexec,nosuid", "/run:size=16m,noexec,nosuid,uid=101,gid=101", "/var/cache/nginx:size=32m,noexec,nosuid,uid=101,gid=101"] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + depends_on: [otel-collector] + deploy: + resources: {limits: {cpus: "0.25", memory: 128M}} + + prometheus: + image: prom/prometheus:v3.16.0 + command: ["--config.file=/etc/prometheus/prometheus.yml", "--storage.tsdb.path=/prometheus", "--storage.tsdb.retention.time=3d", "--web.config.file=/etc/prometheus/web.yml", "--web.enable-remote-write-receiver"] + restart: unless-stopped + volumes: + - ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - ./infra/prometheus/web.yml:/etc/prometheus/web.yml:ro + - prometheus_data:/prometheus + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: prometheus_server_crt + target: prometheus-server.crt + - source: prometheus_server_key + target: prometheus-server.key + - source: prometheus_client_crt + target: prometheus-client.crt + - source: prometheus_client_key + target: prometheus-client.key + networks: [telemetry] + ports: ["127.0.0.1:9091:9090"] + healthcheck: + test: ["CMD", "/bin/prometheus", "--version"] + interval: 10s + timeout: 5s + retries: 3 + + loki: + image: grafana/loki:3.6.23 + command: ["-config.file=/etc/loki/config.yaml"] + restart: unless-stopped + volumes: + - ./infra/loki/config.yaml:/etc/loki/config.yaml:ro + - loki_data:/loki + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: loki_server_crt + target: loki-server.crt + - source: loki_server_key + target: loki-server.key + networks: [telemetry] + healthcheck: + test: ["CMD", "/usr/bin/loki", "-config.file=/etc/loki/config.yaml", "-verify-config"] + interval: 10s + timeout: 5s + retries: 3 + + tempo: + image: grafana/tempo:2.10.10 + command: ["-config.file=/etc/tempo/config.yaml"] + restart: unless-stopped + volumes: + - ./infra/tempo/config.yaml:/etc/tempo/config.yaml:ro + - tempo_data:/var/tempo + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: tempo_server_crt + target: tempo-server.crt + - source: tempo_server_key + target: tempo-server.key + networks: [telemetry] + healthcheck: + test: ["CMD", "/tempo", "-config.file=/etc/tempo/config.yaml", "-version"] + interval: 10s + timeout: 5s + retries: 3 + + grafana: + image: mtusi-messenger-lab7-grafana:local + build: + context: . + dockerfile: infra/images/Dockerfile.alpine-upgrade + args: + BASE_IMAGE: grafana/grafana:13.3.2 + RUNTIME_USER: "472" + restart: unless-stopped + environment: + GF_SERVER_PROTOCOL: https + GF_SERVER_CERT_FILE: /run/secrets/grafana-server.crt + GF_SERVER_CERT_KEY: /run/secrets/grafana-server.key + GF_SECURITY_ADMIN_USER: admin + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + GF_USERS_ALLOW_SIGN_UP: "false" + GF_ANALYTICS_REPORTING_ENABLED: "false" + secrets: + - source: internal_ca_crt + target: internal-ca.crt + - source: grafana_server_crt + target: grafana-server.crt + - source: grafana_server_key + target: grafana-server.key + - source: grafana_client_crt + target: grafana-client.crt + - source: grafana_client_key + target: grafana-client.key + - grafana_admin_password + ports: ["127.0.0.1:3000:3000"] + volumes: + - grafana_data:/var/lib/grafana + - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + networks: [telemetry] + depends_on: [prometheus, loki, tempo] + deploy: + resources: {limits: {cpus: "0.50", memory: 512M}} + +secrets: + internal_ca_crt: {file: ./secrets/pki/internal-ca.crt} + pki_int_crl: {file: ./secrets/pki/pki-int.crl.pem} + openbao_server_crt: {file: ./secrets/pki/openbao-server.crt} + openbao_server_key: {file: ./secrets/pki/openbao-server.key.pem} + postgres_password: {file: ./secrets/postgres_password} + database_url: {file: ./secrets/database_url} + postgres_server_crt: {file: ./secrets/pki/postgres-server.crt} + postgres_server_key: {file: ./secrets/pki/postgres-server.key} + redis_server_crt: {file: ./secrets/pki/redis-server.crt} + redis_server_key: {file: ./secrets/pki/redis-server.key} + broker_server_crt: {file: ./secrets/pki/broker-server.crt} + broker_server_key: {file: ./secrets/pki/broker-server.key} + redis_users_acl: {file: ./secrets/redis-users.acl} + redis_api_password: {file: ./secrets/redis_api_password} + redis_dispatcher_password: {file: ./secrets/redis_dispatcher_password} + redis_worker_password: {file: ./secrets/redis_worker_password} + s3_root_access_key_id: {file: ./secrets/s3_root_access_key_id} + s3_root_secret_access_key: {file: ./secrets/s3_root_secret_access_key} + s3_access_key_id: {file: ./secrets/s3_access_key_id} + s3_secret_access_key: {file: ./secrets/s3_secret_access_key} + s3_worker_access_key_id: {file: ./secrets/s3_worker_access_key_id} + s3_worker_secret_access_key: {file: ./secrets/s3_worker_secret_access_key} + s3_server_crt: {file: ./secrets/pki/s3-server.crt} + s3_server_key: {file: ./secrets/pki/s3-server.key} + api_server_crt: {file: ./secrets/pki/api-server.crt} + api_server_key: {file: ./secrets/pki/api-server.key} + api_client_crt: {file: ./secrets/pki/api-client.crt} + api_client_key: {file: ./secrets/pki/api-client.key} + worker_client_crt: {file: ./secrets/pki/worker-client.crt} + worker_client_key: {file: ./secrets/pki/worker-client.key} + dispatcher_client_crt: {file: ./secrets/pki/dispatcher-client.crt} + dispatcher_client_key: {file: ./secrets/pki/dispatcher-client.key} + ingress_crt: {file: ./secrets/pki/ingress.crt} + ingress_key: {file: ./secrets/pki/ingress.key} + lb_client_crt: {file: ./secrets/pki/lb-client.crt} + lb_client_key: {file: ./secrets/pki/lb-client.key} + otel_server_crt: {file: ./secrets/pki/otel-server.crt} + otel_server_key: {file: ./secrets/pki/otel-server.key} + prometheus_server_crt: {file: ./secrets/pki/prometheus-server.crt} + prometheus_server_key: {file: ./secrets/pki/prometheus-server.key} + loki_server_crt: {file: ./secrets/pki/loki-server.crt} + loki_server_key: {file: ./secrets/pki/loki-server.key} + tempo_server_crt: {file: ./secrets/pki/tempo-server.crt} + tempo_server_key: {file: ./secrets/pki/tempo-server.key} + grafana_server_crt: {file: ./secrets/pki/grafana-server.crt} + grafana_server_key: {file: ./secrets/pki/grafana-server.key} + otel_gateway_server_crt: {file: ./secrets/pki/otel-gateway-server.crt} + otel_gateway_server_key: {file: ./secrets/pki/otel-gateway-server.key} + otel_client_crt: {file: ./secrets/pki/otel-client.crt} + otel_client_key: {file: ./secrets/pki/otel-client.key} + prometheus_client_crt: {file: ./secrets/pki/prometheus-client.crt} + prometheus_client_key: {file: ./secrets/pki/prometheus-client.key} + negative_test_client_crt: {file: ./secrets/pki/negative-test-client.crt} + negative_test_client_key: {file: ./secrets/pki/negative-test-client.key} + grafana_client_crt: {file: ./secrets/pki/grafana-client.crt} + grafana_client_key: {file: ./secrets/pki/grafana-client.key} + grafana_admin_password: {file: ./secrets/grafana_admin_password} + +volumes: + postgres_data: + redis_data: + broker_data: + s3_data: + s3_tls: + bao_data: + prometheus_data: + loki_data: + tempo_data: + grafana_data: + +networks: + backend: {internal: true} + edge: {internal: true} + ingress: {} + telemetry_ingress: {internal: true} + telemetry: {internal: true} diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a9777..f55ff3d3 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,37 +1,26 @@ -# Матрица доверия — заполнить в решении lab7 +# Матрица доверия — конфигурация Compose -Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. +Все сертификаты подписываются локальным корневым CA, закрытый ключ которого хранит оператор. Leaf-сертификаты выпускает промежуточный CA OpenBao. Клиенты проверяют цепочку CA и DNS SAN. Файлы секретов находятся в игнорируемом Git каталоге secrets/. Compose публикует порты только на loopback. -| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | -| --- | --- | --- | --- | -| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | -| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | -| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | -| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | -| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | -| 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 | +| Связь | Проверка сервера / порт | Identity клиента и авторизация | Область действия секрета / срок | Негативная проверка | +| --- | --- | --- | --- | --- | +| Пользователь → LB (lb:8443, публикация 127.0.0.1:8443) | internal-ca.crt, SAN localhost, TLS 1.2+ | HTTPS Bearer-сессия; Nginx LB ограничивает вход | TTL сессии из SESSION_TTL_SECONDS; общий Redis-счетчик живет 60 секунд | make test-security; scripts/security_negative.py проверяет доверенный и недоверенный сервер | +| LB → каждая API-реплика (api:8443, сеть edge) | api-server.crt, SAN api; LB проверяет внутренний CA и имя | Обязательный mTLS; Nginx API допускает точный subject CN=messenger-lb; порт API не опубликован на хост | Сертификат lb-client, срок выдачи 6 часов | security-probe: без сертификата, сертификат от чужого CA с правильным CN и доверенный сертификат messenger-prometheus должны быть отклонены; lb-client должен пройти | +| API/dispatcher/worker → PostgreSQL (db:5432) | verify-full, SAN db, внутренний CA | PostgreSQL требует TLS и сертификат клиента; pg_ident сопоставляет точный CN с разными ролями messenger_api, messenger_dispatcher, messenger_worker | Отдельный leaf на сервис; у рабочих ролей нет пароля. Миграция использует пароль оператора БД поверх проверенного TLS | scripts/postgres-init.sh, pg_hba.conf, pg_ident.conf, migrations/007_workload_roles.sql; отдельно проверить чужой CN и права ролей | +| API/worker → RustFS S3 (s3:9000) | HTTPS, SAN s3; boto проверяет /run/secrets/internal-ca.crt | Разные учетные записи RustFS. API пишет в staging/* и читает готовые объекты; worker читает/удаляет staging и пишет/читает готовые объекты | Отдельные ключи API/worker создаются локально; операторские root credentials используются только при разовой настройке | src/app/s3_bootstrap.py проверяет анонимный доступ, видимость bucket и запрещенные чтение/запись вне разрешенного префикса | +| Dispatcher/worker → Redis Streams broker (broker:6379) | Redis TLS, SAN broker, tls-auth-clients yes | Нужен клиентский сертификат; Redis ACL разделяет producer dispatcher и consumer worker, ограничивая пользователей и ключи | Отдельные Redis-пароли и leaf-сертификаты; пароли считываются из OpenBao при старте | Проверить подключения без сертификата, от чужого CA и с неверным ACL-пользователем/ключом; использовать redis-cli --tls и тестовые identity | +| API → Redis для сессий (redis:6379) | Redis TLS, SAN redis, проверка CA | Нужен клиентский сертификат; ACL api ограничивает префиксы session/login и команды | Пароль только для API и сертификат api-client | Проверить неверные сертификат/пароль и запрет доступа к ключам другого сервиса | +| API/worker/dispatcher → telemetry gateway (otel-gateway:4318) | HTTPS, SAN otel-gateway; OTLP exporter проверяет CA и имя | Обязательный mTLS. Nginx gateway допускает только CN messenger-api, messenger-worker, messenger-dispatcher, затем подключается к Collector со своим клиентским сертификатом | Сервисный leaf; identity gateway→Collector — messenger-otel-collector | infra/otel/nginx.conf: без сертификата TLS handshake должен завершиться отказом; CA-подписанный иной CN получает 403; доступны только пути /v1/{traces,metrics,logs} | +| Gateway → OTel Collector (otel-collector:4318) | HTTPS, SAN otel-collector | mTLS с identity gateway; Collector находится в сети telemetry без опубликованного порта | Сертификат otel-client | Nginx проверяет upstream TLS; сеть не дает API/worker напрямую обратиться к Collector | +| Collector → Prometheus/Loki/Tempo | TLS, соответственно SAN prometheus, loki, tempo; проверка CA | mTLS; backend требует CA-подписанный сертификат клиента. Prometheus принимает remote write, Loki/Tempo принимают свои OTLP сигналы | Identity Collector otel-client; данные хранятся в named volumes | Backend TLS listener должен отклонять отсутствие сертификата или чужой CA | +| Grafana → Prometheus/Loki/Tempo | TLS с SAN backend и внутренним CA | mTLS с grafana-client; Grafana admin доступен локально, пароль подключен файлом | Отдельный сертификат клиента Grafana и локальный admin-пароль | Удалить сертификат клиента или задать неправильный CA и убедиться, что datasource не подключается | +| Сервис → OpenBao (openbao:8200) | TLS, SAN openbao; каждый клиент проверяет CA | cert auth сопоставляет точный service CN и назначает только его policy | KV v2 путь API/worker/dispatcher; TTL login token 15 минут, максимум 1 час; новая аутентификация при старте | scripts/bao_policy_probe.py проверяет чтение своего пути, запрет чужого пути и записи policy | +| Оператор → OpenBao | API не опубликован на host; Compose helper подключается к `openbao:8200` по сети backend | Init/unseal и root token — только действия оператора; приложения не получают эти учетные данные | Закрытый ключ root CA и shares unseal хранятся вне Git и не монтируются в приложения | Проверить отсутствие опубликованного host port; operator/policy probes запускать через внутреннюю Compose-сеть | +| API → срок жизни сессии Redis | Та же TLS и ACL защита | Случайный bearer token хранится в виде hash; TTL сессии enforced | Redis AOF; TTL задается приложением | Smoke проверяет logout/expiry; persistence-проверка — сессию после рестарта | +| Репликация/кластерные связи | Межузловая репликация не настроена | Не применимо | Не применимо | Не применимо: один узел lab | -Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. +## Границы и ограничения -## Обязательные отрицательные проверки +Сеть edge изолирована; только lb публикует ingress. API-контейнеры подключены к edge и backend, но их порты не опубликованы; dispatcher и worker подключены к backend и telemetry_ingress. Telemetry gateway — единственный мост из telemetry_ingress в отдельную сеть telemetry. PostgreSQL, Redis, broker, object storage, OpenBao и telemetry-хранилища используют persistent named volumes. Стенд Compose работает на одном хосте; Docker-сети не заменяют firewall или production network policy. -1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». -2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. -3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. -4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. -5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. -6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. - -## Bootstrap и эксплуатация - -В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. - -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 — хорошее расширение, но не обязательное название технологии. - -Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. +OpenBao инициализирует и unseal оператор вручную. После рестарта OpenBao запечатывается; перед перезапуском приложений оператор должен снова выполнить unseal. Контейнеры приложений не получают root token, закрытый ключ CA или shares. Статические секреты хранятся отдельно в KV v2 и загружаются только при старте; автоматическое продление или live reload не реализованы. Непроверенные и ограниченные места перечислены в REPORT.md. diff --git a/evidence/track2-crl-run1.json b/evidence/track2-crl-run1.json new file mode 100644 index 00000000..96ad75c4 --- /dev/null +++ b/evidence/track2-crl-run1.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.531, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1.916, + "successful_latency_ms": { + "p50": 2093.0, + "p95": 2110.0, + "p99": 2125.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-crl-run2.json b/evidence/track2-crl-run2.json new file mode 100644 index 00000000..e17154a0 --- /dev/null +++ b/evidence/track2-crl-run2.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.453, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1.919, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2110.0, + "p99": 2156.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-crl-run3.json b/evidence/track2-crl-run3.json new file mode 100644 index 00000000..042ee659 --- /dev/null +++ b/evidence/track2-crl-run3.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.39, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1.921, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2110.0, + "p99": 2125.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-final-run1.json b/evidence/track2-final-run1.json new file mode 100644 index 00000000..21494233 --- /dev/null +++ b/evidence/track2-final-run1.json @@ -0,0 +1,19 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.344, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "failure_categories": {}, + "failure_window_seconds": null, + "successful_rps": 1.922, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2094.0, + "p99": 2141.0 + }, + "note": "Latency percentiles cover successes only. Failure offsets/categories help locate interruption windows but are not a maximum-capacity estimate. Closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-final-run2.json b/evidence/track2-final-run2.json new file mode 100644 index 00000000..ff84d6df --- /dev/null +++ b/evidence/track2-final-run2.json @@ -0,0 +1,19 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.188, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "failure_categories": {}, + "failure_window_seconds": null, + "successful_rps": 1.927, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2109.0, + "p99": 2125.0 + }, + "note": "Latency percentiles cover successes only. Failure offsets/categories help locate interruption windows but are not a maximum-capacity estimate. Closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-final-run3.json b/evidence/track2-final-run3.json new file mode 100644 index 00000000..d0e88f13 --- /dev/null +++ b/evidence/track2-final-run3.json @@ -0,0 +1,19 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.344, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "failure_categories": {}, + "failure_window_seconds": null, + "successful_rps": 1.922, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2110.0, + "p99": 2125.0 + }, + "note": "Latency percentiles cover successes only. Failure offsets/categories help locate interruption windows but are not a maximum-capacity estimate. Closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-lb-rotation-run2.json b/evidence/track2-lb-rotation-run2.json new file mode 100644 index 00000000..ecb9e4ab --- /dev/null +++ b/evidence/track2-lb-rotation-run2.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 240.0, + "elapsed_seconds": 241.328, + "concurrency": 4, + "successful_requests": 464, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1.923, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2110.0, + "p99": 2140.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-lb-rotation-run3.json b/evidence/track2-lb-rotation-run3.json new file mode 100644 index 00000000..fb3dad1a --- /dev/null +++ b/evidence/track2-lb-rotation-run3.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 240.0, + "elapsed_seconds": 240.125, + "concurrency": 4, + "successful_requests": 446, + "failed_requests": 14, + "error_ratio": 0.030435, + "successful_rps": 1.857, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2110.0, + "p99": 2188.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-lb-rotation-run4.json b/evidence/track2-lb-rotation-run4.json new file mode 100644 index 00000000..4af8fd83 --- /dev/null +++ b/evidence/track2-lb-rotation-run4.json @@ -0,0 +1,25 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 240.0, + "elapsed_seconds": 241.39, + "concurrency": 4, + "successful_requests": 445, + "failed_requests": 19, + "error_ratio": 0.040948, + "failure_categories": { + "http_502": 19 + }, + "failure_window_seconds": { + "first_failure_seconds": 4.187, + "last_failure_seconds": 12.453, + "span_seconds": 8.266 + }, + "successful_rps": 1.843, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2110.0, + "p99": 2156.0 + }, + "note": "Latency percentiles cover successes only. Failure offsets/categories help locate interruption windows but are not a maximum-capacity estimate. Closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-lb-rotation-run5.json b/evidence/track2-lb-rotation-run5.json new file mode 100644 index 00000000..16105e80 --- /dev/null +++ b/evidence/track2-lb-rotation-run5.json @@ -0,0 +1,25 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 240.0, + "elapsed_seconds": 241.562, + "concurrency": 4, + "successful_requests": 449, + "failed_requests": 13, + "error_ratio": 0.028139, + "failure_categories": { + "http_502": 13 + }, + "failure_window_seconds": { + "first_failure_seconds": 29.921, + "last_failure_seconds": 36.046, + "span_seconds": 6.125 + }, + "successful_rps": 1.859, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2125.0, + "p99": 2359.0 + }, + "note": "Latency percentiles cover successes only. Failure offsets/categories help locate interruption windows but are not a maximum-capacity estimate. Closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-lb-rotation.json b/evidence/track2-lb-rotation.json new file mode 100644 index 00000000..f8334ac0 --- /dev/null +++ b/evidence/track2-lb-rotation.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 240.0, + "elapsed_seconds": 240.937, + "concurrency": 4, + "successful_requests": 448, + "failed_requests": 12, + "error_ratio": 0.026087, + "successful_rps": 1.859, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2110.0, + "p99": 2171.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-post-upgrade-run1.json b/evidence/track2-post-upgrade-run1.json new file mode 100644 index 00000000..d51fc38d --- /dev/null +++ b/evidence/track2-post-upgrade-run1.json @@ -0,0 +1,19 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 61.609, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "failure_categories": {}, + "failure_window_seconds": null, + "successful_rps": 1.883, + "successful_latency_ms": { + "p50": 2094.0, + "p95": 2297.0, + "p99": 2313.0 + }, + "note": "Latency percentiles cover successes only. Failure offsets/categories help locate interruption windows but are not a maximum-capacity estimate. Closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-post-upgrade-run2.json b/evidence/track2-post-upgrade-run2.json new file mode 100644 index 00000000..86139b0c --- /dev/null +++ b/evidence/track2-post-upgrade-run2.json @@ -0,0 +1,19 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 61.687, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "failure_categories": {}, + "failure_window_seconds": null, + "successful_rps": 1.88, + "successful_latency_ms": { + "p50": 2109.0, + "p95": 2219.0, + "p99": 2234.0 + }, + "note": "Latency percentiles cover successes only. Failure offsets/categories help locate interruption windows but are not a maximum-capacity estimate. Closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-post-upgrade-run3.json b/evidence/track2-post-upgrade-run3.json new file mode 100644 index 00000000..32409357 --- /dev/null +++ b/evidence/track2-post-upgrade-run3.json @@ -0,0 +1,19 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 61.391, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "failure_categories": {}, + "failure_window_seconds": null, + "successful_rps": 1.89, + "successful_latency_ms": { + "p50": 2094.0, + "p95": 2250.0, + "p99": 2250.0 + }, + "note": "Latency percentiles cover successes only. Failure offsets/categories help locate interruption windows but are not a maximum-capacity estimate. Closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-run1.json b/evidence/track2-run1.json new file mode 100644 index 00000000..16c413fb --- /dev/null +++ b/evidence/track2-run1.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.328, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1.923, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2109.0, + "p99": 2110.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-run2.json b/evidence/track2-run2.json new file mode 100644 index 00000000..48ec1d23 --- /dev/null +++ b/evidence/track2-run2.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.219, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1.926, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2109.0, + "p99": 2110.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track2-run3.json b/evidence/track2-run3.json new file mode 100644 index 00000000..10e58965 --- /dev/null +++ b/evidence/track2-run3.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.312, + "concurrency": 4, + "successful_requests": 116, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1.923, + "successful_latency_ms": { + "p50": 2078.0, + "p95": 2110.0, + "p99": 2110.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/trivy-summary-20261205.md b/evidence/trivy-summary-20261205.md new file mode 100644 index 00000000..81f52250 --- /dev/null +++ b/evidence/trivy-summary-20261205.md @@ -0,0 +1,17 @@ +# Trivy summary — 2026-12-05 + +Scanner: Trivy 0.77.0. Scan time: approximately 22:42 MSK. The scan covered 12 runtime images after building local Alpine-upgraded derivatives. + +## Results + +- Images: 0 CRITICAL, 118 HIGH (21 unique vulnerability IDs). +- 41 Alpine package findings disappeared after rebuilding the OpenBao, Grafana, Nginx, Redis, and RustFS images with `apk upgrade --no-cache`. +- Remaining image findings: 93 `affected` without a fixed version, 23 Go module findings with a fixed version available upstream but still present in the shipped binaries, and 2 `fix_deferred` Perl findings. +- Filesystem: 0 dependency vulnerabilities, 5 misconfigurations, no secrets detected. +- Misconfigurations: 2 HIGH `DS-0002` root-user findings in the PostgreSQL and operator-renew Dockerfiles; 3 LOW `DS-0026` missing Dockerfile HEALTHCHECK findings. Runtime Compose healthchecks are defined for services. + +## Scope and limits + +The scan covered the API, bao-renew, PostgreSQL, OpenBao 2.7.3, Redis 7.4.12, RustFS 1.0.7, Nginx 1.31.10, OpenTelemetry Collector 0.166.0, Prometheus 3.16.0, Loki 3.6.23, Tempo 2.10.10, and Grafana 13.3.2 images. The scan is not clean: unresolved HIGH findings and the two HIGH misconfigurations remain documented in `REPORT.md`. + +Raw per-image Trivy JSON was generated locally as `evidence/trivy-20261205-224145-*.json` and is excluded from Git; this compact summary is the versioned scan evidence. diff --git a/infra/README.md b/infra/README.md index 5a39e862..ed2d7c53 100644 --- a/infra/README.md +++ b/infra/README.md @@ -1,7 +1,25 @@ -# Инфраструктура студента +# Состав инфраструктуры -Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли. +| Роль | Compose-сервис / образ | Готовность | Постоянное состояние | Порт / сеть | Учетные данные | +| --- | --- | --- | --- | --- | --- | +| OpenBao | openbao, openbao/openbao:2.6.6 | bao status по TLS; sealed допустим до unseal оператором | Raft volume bao_data | 127.0.0.1:8200, backend | Серверный сертификат локального CA; operator init/unseal; приложения входят по клиентским сертификатам | +| PostgreSQL | db, локальная сборка на базе postgres:16.16-alpine3.24 | pg_isready | postgres_data | Только backend, 5432 | TLS cert auth для ролей приложений; file secret для миграции; su-exec заменяет gosu | +| Redis для сессий | redis, redis:7.4.1-alpine | TLS Redis PING от identity API | redis_data, AOF | Только backend, 6379 TLS | mTLS и Redis ACL | +| Durable broker | broker, redis:7.4.1-alpine Streams | TLS Redis PING от identity dispatcher | broker_data, AOF | Только backend, 6379 TLS | mTLS и ACL producer/consumer | +| S3-хранилище | s3, rustfs/rustfs:1.0.5 | Проверенный TLS /health/ready | s3_data | Только backend, 9000 TLS; консоль выключена | Root keys только для разовой настройки; отдельные ограниченные учетные записи API/worker | +| Миграция схемы | migrate, локальный API image | Успешное завершение | Нет | Только backend | Пароль оператора PostgreSQL через проверенный TLS | +| Создание bucket | s3-bootstrap, локальный API image | Успешное завершение | Нет | Только backend | Разовая root identity; создает private bucket и ограниченные учетные записи | +| API | Две реплики api, локальный Python image | Внутренняя readiness; внешний трафик только через LB | Нет | backend, edge и telemetry_ingress; внутренний 8443 | mTLS LB; cert auth OpenBao; ограниченные DB/Redis/S3; OTLP cert | +| Load balancer | lb, nginx:1.28.0-alpine | Проверка Nginx config | Нет | 127.0.0.1:8443, edge | Сертификат ingress и клиентский сертификат к API | +| Dispatcher | dispatcher, локальный Python image | Рабочий процесс | Нет | backend и telemetry_ingress | Отдельные DB, broker, OpenBao и OTLP identity | +| Worker | worker, локальный Python image | Рабочий процесс consumer | Нет | backend и telemetry_ingress | Отдельные DB, broker, S3, OpenBao и OTLP identity | +| Telemetry gateway | otel-gateway, nginx:1.28.0-alpine | Проверка Nginx config | Нет | telemetry_ingress и telemetry; без host-порта | mTLS CN allowlist, затем собственная identity к Collector | +| Collector | otel-collector, otel/opentelemetry-collector-contrib:0.145.0 | Процесс Collector | Нет | Только telemetry, без host-порта | mTLS receiver и проверенные mTLS exporters | +| Метрики | prometheus, prom/prometheus:v3.8.1 | Проверка процесса | prometheus_data | 127.0.0.1:9091, telemetry | mTLS web listener и remote-write receiver | +| Логи | loki, grafana/loki:3.6.2 | Проверка config | loki_data | Только telemetry | TLS/mTLS | +| Трейсы | tempo, grafana/tempo:2.9.0 | Проверка процесса | tempo_data | Только telemetry | TLS/mTLS | +| Дашборды | grafana, grafana/grafana:12.3.0 | Процесс Grafana | grafana_data | 127.0.0.1:3000, telemetry | Локальный пароль admin-файлом и отдельный datasource client cert | -В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд. +Все сетевые слушатели используют TLS. Сети edge, backend, telemetry_ingress и telemetry внутренние. Публикуются только loopback административные порты и loopback HTTPS ingress. API, worker и dispatcher работают не от root, с read-only root filesystem, tmpfs для /tmp, no-new-privileges, сброшенными Linux capabilities и лимитами ресурсов в Compose. Stateful vendor-сервисы сохраняют writable volumes и потому не используют read-only root FS; host network, privileged и Docker socket не используются. Одноразовые помощники bao-init, s3-init и s3-tls-init запускаются от root только для настройки владельца и режима named volumes, затем завершаются; постоянных процессов и сетевых слушателей у них нет. -Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику. +Порядок bootstrap, миграций, восстановления и проверок описан в корневом REPORT.md. Compose-стенд готов к запуску после scripts/bootstrap-local.ps1 и ручного init/unseal/PKI bootstrap OpenBao, которые создают локальные игнорируемые файлы в secrets/. diff --git a/infra/api-nginx.conf b/infra/api-nginx.conf new file mode 100644 index 00000000..3e438b8c --- /dev/null +++ b/infra/api-nginx.conf @@ -0,0 +1,40 @@ +proxy_temp_path /tmp/nginx-proxy 1 2; +fastcgi_temp_path /tmp/nginx-fastcgi 1 2; +uwsgi_temp_path /tmp/nginx-uwsgi 1 2; +scgi_temp_path /tmp/nginx-scgi 1 2; + +server { + access_log /dev/stdout; + error_log /dev/stderr warn; + listen 8443 ssl; + server_name api; + + ssl_certificate /run/secrets/api-server.crt; + ssl_certificate_key /tmp/api-server.key; + ssl_client_certificate /run/secrets/internal-ca.crt; + ssl_crl /run/secrets/pki-int.crl.pem; + ssl_verify_client on; + ssl_verify_depth 1; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_tickets off; + + # Chain validation alone is insufficient: only the dedicated load-balancer + # identity may cross this boundary. + if ($ssl_client_s_dn != "CN=messenger-lb") { return 403; } + + client_max_body_size 11m; + client_body_temp_path /tmp/nginx-client-body 1 2; + location / { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + # This listener accepts only the LB's authenticated certificate, and + # the LB overwrites X-Forwarded-For with the socket peer address. + proxy_set_header X-Forwarded-For $http_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + proxy_set_header X-Request-Id $request_id; + proxy_request_buffering off; + proxy_buffering off; + } +} diff --git a/infra/grafana/dashboards/messenger-overview.json b/infra/grafana/dashboards/messenger-overview.json new file mode 100644 index 00000000..d4ada6fc --- /dev/null +++ b/infra/grafana/dashboards/messenger-overview.json @@ -0,0 +1,23 @@ +{ + "id": null, + "uid": "messenger-lab6", + "title": "Messenger Lab 6 — Observability", + "tags": ["mtusi", "messenger", "lab6"], + "timezone": "browser", + "schemaVersion": 39, + "version": 1, + "refresh": "5s", + "time": {"from": "now-15m", "to": "now"}, + "panels": [ + {"id": 1, "type": "timeseries", "title": "HTTP requests / second", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"x": 0, "y": 0, "w": 12, "h": 8}, "targets": [{"expr": "sum(rate(messenger_http_server_requests_total{http_route!~\"/health.*\"}[5m]))", "legendFormat": "requests/s", "refId": "A"}]}, + {"id": 2, "type": "timeseries", "title": "HTTP 5xx ratio (SLI)", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"x": 12, "y": 0, "w": 12, "h": 8}, "targets": [{"expr": "sum(rate(messenger_http_server_requests_total{http_response_status_class=\"5xx\",http_route!~\"/health.*\"}[5m])) / clamp_min(sum(rate(messenger_http_server_requests_total{http_route!~\"/health.*\"}[5m])), 0.001)", "legendFormat": "5xx / all", "refId": "A"}]}, + {"id": 3, "type": "timeseries", "title": "HTTP latency p50 / p95 / p99 (seconds)", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"x": 0, "y": 8, "w": 12, "h": 8}, "targets": [{"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))", "legendFormat": "p50", "refId": "A"}, {"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "B"}, {"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))", "legendFormat": "p99", "refId": "C"}]}, + {"id": 4, "type": "timeseries", "title": "Worker jobs / second", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"x": 12, "y": 8, "w": 12, "h": 8}, "targets": [{"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[5m]))", "legendFormat": "{{outcome}}", "refId": "A"}]}, + {"id": 5, "type": "timeseries", "title": "Queue depth / oldest age (seconds)", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"x": 0, "y": 16, "w": 12, "h": 8}, "targets": [{"expr": "messenger_queue_depth", "legendFormat": "queued", "refId": "A"}, {"expr": "messenger_queue_oldest_job_age_seconds", "legendFormat": "oldest seconds", "refId": "B"}]}, + {"id": 6, "type": "timeseries", "title": "Postgres pool used / capacity", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"x": 12, "y": 16, "w": 12, "h": 8}, "targets": [{"expr": "sum(messenger_db_pool_used)", "legendFormat": "used", "refId": "A"}, {"expr": "sum(messenger_db_pool_capacity)", "legendFormat": "capacity", "refId": "B"}]}, + {"id": 7, "type": "timeseries", "title": "Process CPU / RAM", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"x": 0, "y": 24, "w": 12, "h": 8}, "targets": [{"expr": "messenger_process_cpu_utilization_percent", "legendFormat": "cpu % {{service_role}}", "refId": "A"}, {"expr": "messenger_process_memory_usage_bytes", "legendFormat": "rss bytes {{service_role}}", "refId": "B"}]}, + {"id": 8, "type": "logs", "title": "Structured application logs", "datasource": {"type": "loki", "uid": "loki"}, "gridPos": {"x": 12, "y": 24, "w": 12, "h": 8}, "targets": [{"expr": "{service_name=~\"messenger-api|messenger-worker|messenger-dispatcher\"}", "queryType": "range", "refId": "A"}]}, + {"id": 9, "type": "timeseries", "title": "Worker active / capacity", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"x": 0, "y": 32, "w": 12, "h": 8}, "targets": [{"expr": "sum(messenger_worker_active)", "legendFormat": "active", "refId": "A"}, {"expr": "sum(messenger_worker_capacity)", "legendFormat": "capacity", "refId": "B"}]}, + {"id": 10, "type": "timeseries", "title": "Attachment upload-to-ready latency p50 / p95 / p99", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"x": 12, "y": 32, "w": 12, "h": 8}, "targets": [{"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_jobs_end_to_end_ready_duration_seconds_bucket[5m])))", "legendFormat": "p50", "refId": "A"}, {"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_jobs_end_to_end_ready_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "B"}, {"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_jobs_end_to_end_ready_duration_seconds_bucket[5m])))", "legendFormat": "p99", "refId": "C"}]} + ] +} diff --git a/infra/grafana/provisioning/dashboards/dashboards.yaml b/infra/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 00000000..577847e0 --- /dev/null +++ b/infra/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,10 @@ +apiVersion: 1 +providers: + - name: Messenger + orgId: 1 + folder: Lab 6 + type: file + disableDeletion: true + editable: false + options: + path: /var/lib/grafana/dashboards diff --git a/infra/grafana/provisioning/datasources/datasources.yaml b/infra/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 00000000..9f6f50e7 --- /dev/null +++ b/infra/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,52 @@ +apiVersion: 1 +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: https://prometheus:9090 + isDefault: true + editable: false + jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: prometheus + secureJsonData: + tlsCACert: "$__file{/run/secrets/internal-ca.crt}" + tlsClientCert: "$__file{/run/secrets/grafana-client.crt}" + tlsClientKey: "$__file{/run/secrets/grafana-client.key}" + - name: Loki + uid: loki + type: loki + access: proxy + url: https://loki:3100 + editable: false + jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: loki + secureJsonData: + tlsCACert: "$__file{/run/secrets/internal-ca.crt}" + tlsClientCert: "$__file{/run/secrets/grafana-client.crt}" + tlsClientKey: "$__file{/run/secrets/grafana-client.key}" + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: https://tempo:3200 + editable: false + jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: tempo + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: "1h" + spanEndTimeShift: "1h" + tags: [{key: service.name, value: service_name}] + serviceMap: + datasourceUid: prometheus + secureJsonData: + tlsCACert: "$__file{/run/secrets/internal-ca.crt}" + tlsClientCert: "$__file{/run/secrets/grafana-client.crt}" + tlsClientKey: "$__file{/run/secrets/grafana-client.key}" diff --git a/infra/images/Dockerfile.alpine-upgrade b/infra/images/Dockerfile.alpine-upgrade new file mode 100644 index 00000000..edff75bf --- /dev/null +++ b/infra/images/Dockerfile.alpine-upgrade @@ -0,0 +1,7 @@ +ARG BASE_IMAGE=nginx:1.31.10-alpine3.24 +FROM ${BASE_IMAGE} + +ARG RUNTIME_USER=101:101 +USER root +RUN apk upgrade --no-cache +USER ${RUNTIME_USER} diff --git a/infra/loki/config.yaml b/infra/loki/config.yaml new file mode 100644 index 00000000..b25759f4 --- /dev/null +++ b/infra/loki/config.yaml @@ -0,0 +1,46 @@ +auth_enabled: false +server: + http_listen_port: 3100 + grpc_listen_port: 9096 + tls_min_version: VersionTLS12 + http_tls_config: + cert_file: /run/secrets/loki-server.crt + key_file: /run/secrets/loki-server.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-ca.crt + grpc_tls_config: + cert_file: /run/secrets/loki-server.crt + key_file: /run/secrets/loki-server.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-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 + otlp_config: + resource_attributes: + attributes_config: + - action: index_label + attributes: [service.name, deployment.environment.name] +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 00000000..5ba544c8 --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,47 @@ +limit_req_zone $binary_remote_addr zone=login_limit:10m rate=10r/m; + +upstream messenger_api { + zone messenger_api 64k; + resolver 127.0.0.11 valid=1s ipv6=off; + server api:8443 resolve max_fails=1 fail_timeout=2s; + keepalive 16; +} + +server { + listen 8443 ssl; + server_name localhost; + + ssl_certificate /run/secrets/ingress.crt; + ssl_certificate_key /run/secrets/ingress.key; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_tickets off; + ssl_session_cache shared:TLS:10m; + + client_max_body_size 11m; + client_body_buffer_size 64k; + client_body_temp_path /tmp/nginx-client-body 1 2; + client_body_timeout 15s; + proxy_connect_timeout 2s; + proxy_send_timeout 15s; + proxy_read_timeout 15s; + + location = /api/v1/auth/sessions { + limit_req zone=login_limit burst=5 nodelay; + limit_req_status 429; + error_page 429 = @login_rate_limited; + proxy_pass https://messenger_api; + include /etc/nginx/proxy-mtls.conf; + } + + location @login_rate_limited { + default_type application/json; + add_header Retry-After "60" always; + add_header Cache-Control "no-store" always; + return 429 '{"error":{"code":"rate_limited","message":"Too many login attempts","request_id":"$request_id"}}'; + } + + location / { + proxy_pass https://messenger_api; + include /etc/nginx/proxy-mtls.conf; + } +} diff --git a/infra/openbao/Dockerfile.renew b/infra/openbao/Dockerfile.renew new file mode 100644 index 00000000..af3411c7 --- /dev/null +++ b/infra/openbao/Dockerfile.renew @@ -0,0 +1,12 @@ +FROM python:3.12.16-slim-trixie + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +RUN apt-get update \ + && apt-get upgrade -y --no-install-recommends \ + && apt-get install -y --no-install-recommends ca-certificates openssl \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /lab +ENTRYPOINT ["python3", "scripts/renew_leaf.py", "--all"] diff --git a/infra/openbao/README.md b/infra/openbao/README.md index 0850e237..38d6c3bc 100644 --- a/infra/openbao/README.md +++ b/infra/openbao/README.md @@ -1,7 +1,100 @@ -# OpenBao — реализовать конфигурацию и политики +# Bootstrap OpenBao для оператора -Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key. +OpenBao работает не в dev-mode, хранит Raft в bao_data, слушает проверенный TLS endpoint и пишет аудит в файл внутри того же защищенного volume. Root token и shares unseal не передаются через Compose environment, контейнеры приложений или Git. События аудита используют HMAC OpenBao; доступ к volume ограничивается оператором, а для длительной работы нужно настроить хранение/ротацию журнала. -Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения. +Выполните из PowerShell в корне репозитория: -Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md. +~~~powershell +.\scripts\bootstrap-local.ps1 +docker compose up -d openbao +docker compose exec openbao bao operator init -key-shares=3 -key-threshold=2 -format=json +~~~ + +Сохраните три unseal shares отдельно от этого хоста и друг от друга. Root token храните в менеджере секретов оператора. Не сохраняйте JSON с выводом команды в репозитории, журнале терминала или переписке. Затем введите два shares интерактивно: + +~~~powershell +docker compose exec openbao bao operator unseal +docker compose exec openbao bao operator unseal +~~~ + +Не передавайте shares аргументами командной строки. API OpenBao остается только во внутренней сети backend и не публикуется на хост. Запустите одноразовый операторский bootstrap helper в этой сети. Запрос root token отображается скрыто; token не сохраняется: + +~~~powershell +docker compose --profile operator run --rm bao-bootstrap +~~~ + +Bootstrap создает KV v2, cert auth, intermediate CA под управлением OpenBao, подписанный локальным offline root, ограниченные policies messenger-api, messenger-worker и messenger-dispatcher, а также короткоживущие leaf-сертификаты. Каждая роль ограничена точными DNS/CN и назначением сертификата. Runtime-сертификаты и начальные scoped secrets записываются только в игнорируемый каталог secrets/. Сервисная identity читает только собственный KV путь. Root token оператора не попадает в приложение. + +После bootstrap загружается подписанный OpenBao CRL в `secrets/pki/pki-int.crl.pem`; API Nginx использует его вместе с обязательной проверкой клиентского сертификата. `bootstrap-local.ps1` создает только временный marker, чтобы Compose мог разобрать модель до запуска OpenBao. До запуска API обязательно завершите операторский bootstrap либо обновите CRL. + +После этого поднимите стенд: + +~~~powershell +docker compose up -d --build --scale api=2 +docker compose ps +~~~ + +После каждого рестарта OpenBao оператор должен повторно выполнить unseal двумя shares. Если Bao запечатан, старт приложения завершается отказом; Compose повторит запуск, plaintext fallback отсутствует. После unseal пересоздайте не запустившиеся сервисы командой docker compose up -d --force-recreate api worker dispatcher. + +Leaf-сертификаты имеют TTL 6 часов; Compose file secrets являются снимками файлов. После долгого простоя проверьте `notAfter` сертификатов и до старта потребителей обновите все OpenBao-issued leaves одним действием. Сервис ниже работает во внутренней сети, запрашивает root token скрытым вводом и не сохраняет его: + +~~~powershell +docker compose --profile operator run --rm bao-renew +~~~ + +После сообщения `Staged 19 replacement leaf certificate(s)` пересоздайте потребителей, чтобы они перечитали файлы. Сети и volumes сохраняются; OpenBao не перезапускайте этой командой. + +~~~powershell +docker compose up -d --no-deps --force-recreate db redis broker s3 api dispatcher worker lb otel-collector otel-gateway prometheus loki tempo grafana +docker compose ps +~~~ + +Эта операция заменяет локальные cert/key пары, но не отзывает предыдущие serials. До отдельной проверки CRL и отзыва старый сертификат нельзя считать отозванным; автоматический rollover CA также не реализован. + +Для контролируемой ротации сертификата клиента LB без окна, когда LB продолжает предъявлять уже отозванный сертификат, сначала выдайте новый leaf без отзыва старого, переключите LB, затем отзовите сохраненный старый leaf и обновите CRL на API: + +~~~powershell +docker compose --profile operator run --rm bao-renew scripts/renew_leaf.py lb-client +docker compose up -d --no-deps --force-recreate lb +docker compose --profile operator run --rm bao-renew scripts/renew_leaf.py lb-client --revoke-saved-previous +docker compose up -d --no-deps --force-recreate --scale api=2 api +docker compose --profile security-test run --rm security-probe +~~~ + +Первый вызов атомарно заменяет leaf-файлы и сохраняет старую пару; прежний сертификат остается действительным, пока LB перечитывает новый файл. Второй вызов отзывает сохраненный serial через OpenBao, проверяет подпись CRL и обновляет локальный CRL. API пересоздаются после переключения LB, чтобы принять CRL, а `security-probe` подтверждает отказ предыдущей паре. Для первоначальной публикации CRL без ротации запустите `docker compose --profile operator run --rm bao-renew scripts/renew_leaf.py --refresh-crl`. + +Если выдача нового leaf прошла, а отзыв вернул ошибку, не запускайте повторно `--revoke-previous`: это заменит файл `.previous`. После исправления причины отзывайте сохраненную пару напрямую: `docker compose --profile operator run --rm bao-renew scripts/renew_leaf.py lb-client --revoke-saved-previous`. + +Проверка истечения не заменяет живой сертификат LB. Одноразовый helper выдает отдельную identity `messenger-lb` с TTL две минуты в игнорируемый каталог `secrets/revocation-probe/`; приватный ключ не печатается. Запустите security probe сразу после выдачи — он должен принять эту identity. Примерно через 150 секунд запустите probe снова — он должен отклонить истекший сертификат и принять действующий сертификат LB: + +~~~powershell +docker compose --profile operator run --rm bao-renew scripts/issue_expiry_probe.py +docker compose --profile security-test run --rm security-probe +Start-Sleep -Seconds 150 +docker compose --profile security-test run --rm security-probe +~~~ + +Этот сценарий проверяет отказ при истечении без остановки текущего LB и восстановление через его действующую identity. Удалять файлы probe из secrets/ перед сохранением доказательств не нужно; весь каталог исключен из Git. + +### Переключение на новый intermediate CA + +Операторский сценарий создаёт отдельный mount `pki_rollover`, новый intermediate с закрытым ключом внутри OpenBao и CSR, подписанный существующим offline root. Старый и новый intermediate остаются одновременно доверенными через root; составной CRL содержит root CRL и CRL обоих intermediate. Сначала API загружают обе CRL, затем LB переключается на leaf нового intermediate, после чего старый leaf отзывается и API загружают обновлённую CRL: + +~~~powershell +docker compose --profile operator run --rm bao-renew scripts/rollover_intermediate.py prepare +docker compose up -d --no-deps --force-recreate --scale api=2 api +docker compose --profile security-test run --rm security-probe +docker compose --profile operator run --rm bao-renew scripts/rollover_intermediate.py activate +docker compose up -d --no-deps --force-recreate lb +docker compose --profile operator run --rm bao-renew scripts/renew_leaf.py lb-client --revoke-saved-previous +docker compose up -d --no-deps --force-recreate --scale api=2 api +docker compose --profile security-test run --rm security-probe +~~~ + +Первый `security-probe` должен принять активный leaf старого intermediate и staged leaf нового intermediate. Второй должен принять текущий leaf нового intermediate и отклонить отозванный старый leaf. Выполнение команд само по себе не подтверждает CA rollover: сохраните оба результата и готовность контейнеров. + +Запускайте `prepare` и `activate` по одному разу на rollover. `activate` откажется повторно сохранять уже активный leaf как previous; отзыв previous также проверяет, что serial не совпадает с текущим сертификатом и отправляет serial в mount, который подписал сохраненный leaf. + +Bootstrap повторно использует существующие mount, policies, intermediate и leaf-сертификаты. Он не сохраняет root token или unseal material и не печатает значения секретов. Для намеренного полного сброса остановите Compose и удалите named volumes и локальный secrets/ только после сохранения нужных доказательств. Hook проверки сохранности данные не удаляет. + +Это локальный учебный стенд: статические KV-секреты загружаются при старте. Операторский сценарий меняет intermediate под тем же offline root; он не заменяет root CA и не доказывает автоматическое продление или rollover в живых процессах. Для полного track 2 приложите измерения ротации, оба результата CA overlap и негативных проверок. diff --git a/infra/openbao/server.hcl b/infra/openbao/server.hcl new file mode 100644 index 00000000..f93f59f4 --- /dev/null +++ b/infra/openbao/server.hcl @@ -0,0 +1,25 @@ +ui = false +disable_mlock = true +api_addr = "https://openbao:8200" +cluster_addr = "https://openbao:8201" + +storage "raft" { + path = "/openbao/data" + node_id = "lab7-openbao-1" +} + +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/run/secrets/openbao-server.crt" + tls_key_file = "/run/secrets/openbao-server.key" + tls_min_version = "tls12" + tls_disable = false + tls_disable_client_certs = false +} + +audit "file" "persistent" { + options { + file_path = "/openbao/data/audit.log" + mode = "0600" + } +} diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 00000000..5d5c8a4a --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,85 @@ +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + max_recv_msg_size_mib: 4 + tls: + cert_file: /run/secrets/otel-server.crt + key_file: /run/secrets/otel-server.key + client_ca_file: /run/secrets/internal-ca.crt + min_version: "1.2" + http: + endpoint: 0.0.0.0:4318 + tls: + cert_file: /run/secrets/otel-server.crt + key_file: /run/secrets/otel-server.key + client_ca_file: /run/secrets/internal-ca.crt + min_version: "1.2" +processors: + memory_limiter: + check_interval: 1s + limit_mib: 160 + spike_limit_mib: 32 + batch: + timeout: 1s + send_batch_size: 256 + send_batch_max_size: 512 +exporters: + otlp/tempo: + endpoint: tempo:4317 + tls: + ca_file: /run/secrets/internal-ca.crt + cert_file: /run/secrets/otel-client.crt + key_file: /run/secrets/otel-client.key + server_name_override: tempo + sending_queue: + enabled: true + queue_size: 512 + num_consumers: 2 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 10s + otlphttp/loki: + endpoint: https://loki:3100/otlp + tls: + ca_file: /run/secrets/internal-ca.crt + cert_file: /run/secrets/otel-client.crt + key_file: /run/secrets/otel-client.key + server_name_override: loki + sending_queue: + enabled: true + queue_size: 512 + num_consumers: 2 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 10s + prometheusremotewrite: + endpoint: https://prometheus:9090/api/v1/write + tls: + ca_file: /run/secrets/internal-ca.crt + cert_file: /run/secrets/otel-client.crt + key_file: /run/secrets/otel-client.key + server_name_override: prometheus + remote_write_queue: + enabled: true + queue_size: 512 + num_consumers: 2 +service: + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheusremotewrite] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] diff --git a/infra/otel/nginx.conf b/infra/otel/nginx.conf new file mode 100644 index 00000000..9b663253 --- /dev/null +++ b/infra/otel/nginx.conf @@ -0,0 +1,44 @@ +map $ssl_client_s_dn $client_identity_allowed { + default 0; + ~^CN=messenger-(api|worker|dispatcher)$ 1; +} + +upstream otel_receiver { + zone otel_receiver 64k; + server otel-collector:4318; + keepalive 16; +} + +proxy_temp_path /tmp/nginx-proxy-temp 1 2; + +server { + listen 4318 ssl; + server_name otel-gateway; + access_log /dev/stdout; + error_log /dev/stderr warn; + + ssl_certificate /run/secrets/otel-gateway.crt; + ssl_certificate_key /run/secrets/otel-gateway.key; + ssl_client_certificate /run/secrets/internal-ca.crt; + ssl_verify_client on; + ssl_verify_depth 1; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_tickets off; + + if ($client_identity_allowed = 0) { return 403; } + client_max_body_size 4m; + client_body_temp_path /tmp/nginx-client-body 1 2; + + location ~ ^/v1/(traces|metrics|logs)$ { + proxy_pass https://otel_receiver; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_ssl_server_name on; + proxy_ssl_name otel-collector; + proxy_ssl_verify on; + proxy_ssl_trusted_certificate /run/secrets/internal-ca.crt; + proxy_ssl_certificate /run/secrets/otel-client.crt; + proxy_ssl_certificate_key /run/secrets/otel-client.key; + } + location / { return 404; } +} diff --git a/infra/postgres/Dockerfile b/infra/postgres/Dockerfile new file mode 100644 index 00000000..e2084ce9 --- /dev/null +++ b/infra/postgres/Dockerfile @@ -0,0 +1,9 @@ +FROM postgres:16.16-alpine3.24 + +# The upstream image bundles gosu built with Go 1.24.6. This service only +# needs its privilege-dropping behavior, which Alpine's small su-exec provides. +RUN apk upgrade --no-cache \ + && apk add --no-cache su-exec \ + && rm -f /usr/local/bin/gosu /usr/local/bin/su-exec \ + && ln -s /sbin/su-exec /usr/local/bin/gosu \ + && gosu nobody true diff --git a/infra/postgres/pg_hba.conf b/infra/postgres/pg_hba.conf new file mode 100644 index 00000000..6f658e3f --- /dev/null +++ b/infra/postgres/pg_hba.conf @@ -0,0 +1,13 @@ +# Unix-domain socket is available only inside the database container and is +# used by its entrypoint for one-time role initialization. +local all all trust + +# Applications authenticate with distinct client certificates and mapped CNs. +hostssl messenger messenger_api all cert map=lab7_services +hostssl messenger messenger_dispatcher all cert map=lab7_services +hostssl messenger messenger_worker all cert map=lab7_services + +# Only the migration/bootstrap job uses the local operator password. +hostssl messenger postgres all scram-sha-256 +hostnossl all all all reject +hostssl all all all reject diff --git a/infra/postgres/pg_ident.conf b/infra/postgres/pg_ident.conf new file mode 100644 index 00000000..c9f737e8 --- /dev/null +++ b/infra/postgres/pg_ident.conf @@ -0,0 +1,4 @@ +# MAPNAME SYSTEM-USERNAME DATABASE-USERNAME +lab7_services messenger-api messenger_api +lab7_services messenger-dispatcher messenger_dispatcher +lab7_services messenger-worker messenger_worker diff --git a/infra/postgres/postgresql.conf b/infra/postgres/postgresql.conf new file mode 100644 index 00000000..f39a6209 --- /dev/null +++ b/infra/postgres/postgresql.conf @@ -0,0 +1,6 @@ +listen_addresses = '*' +ssl = on +password_encryption = 'scram-sha-256' +ident_file = '/etc/postgresql/pg_ident.conf' +max_connections = 100 +shared_buffers = '256MB' diff --git a/infra/prometheus/alerts.yml b/infra/prometheus/alerts.yml new file mode 100644 index 00000000..a3970e6d --- /dev/null +++ b/infra/prometheus/alerts.yml @@ -0,0 +1,19 @@ +groups: + - name: messenger-sli + rules: + - alert: MessengerHighHttp5xxRatio + expr: sum(rate(messenger_http_server_requests_total{http_response_status_class="5xx",http_route!~"/health.*"}[5m])) / clamp_min(sum(rate(messenger_http_server_requests_total{http_route!~"/health.*"}[5m])), 0.001) > 0.05 + for: 2m + labels: + severity: warning + annotations: + summary: API 5xx ratio is above 5% for 2 minutes + description: Inspect API traces for database or object-store spans and follow infra/runbooks/high-errors.md. + - alert: MessengerQueueLagHigh + expr: messenger_queue_oldest_job_age_seconds{queue_name="attachment-jobs"} > 60 + for: 2m + labels: + severity: warning + annotations: + summary: Oldest queued attachment job is older than 60 seconds + description: Inspect worker health, queue depth and follow infra/runbooks/queue-lag.md. diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml new file mode 100644 index 00000000..c1029c5c --- /dev/null +++ b/infra/prometheus/prometheus.yml @@ -0,0 +1,5 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s +rule_files: [] +scrape_configs: [] diff --git a/infra/prometheus/web.yml b/infra/prometheus/web.yml new file mode 100644 index 00000000..1de1e7f9 --- /dev/null +++ b/infra/prometheus/web.yml @@ -0,0 +1,6 @@ +tls_server_config: + cert_file: /run/secrets/prometheus-server.crt + key_file: /run/secrets/prometheus-server.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-ca.crt + min_version: TLS12 diff --git a/infra/proxy-mtls.conf b/infra/proxy-mtls.conf new file mode 100644 index 00000000..fcc125c0 --- /dev/null +++ b/infra/proxy-mtls.conf @@ -0,0 +1,18 @@ +proxy_http_version 1.1; +proxy_set_header Connection ""; +proxy_set_header Host $host; +proxy_set_header X-Forwarded-For $remote_addr; +proxy_set_header X-Forwarded-Proto https; +proxy_set_header X-Request-Id $request_id; +proxy_ssl_server_name on; +proxy_ssl_name api; +proxy_ssl_verify on; +proxy_ssl_verify_depth 2; +proxy_ssl_trusted_certificate /run/secrets/internal-ca.crt; +proxy_ssl_certificate /run/secrets/lb-client.crt; +proxy_ssl_certificate_key /run/secrets/lb-client.key; +proxy_next_upstream error timeout http_502 http_503 http_504; +proxy_next_upstream_tries 2; +proxy_next_upstream_timeout 2s; +proxy_request_buffering off; +proxy_buffering off; diff --git a/infra/runbooks/high-errors.md b/infra/runbooks/high-errors.md new file mode 100644 index 00000000..8a81ff44 --- /dev/null +++ b/infra/runbooks/high-errors.md @@ -0,0 +1,7 @@ +# Runbook: рост доли HTTP 5xx API + +1. Проверьте алерт MessengerHighHttp5xxRatio и убедитесь, что health endpoints исключены из знаменателя. +2. В Grafana сравните частоту запросов и latency, затем откройте trace неуспешного запроса в Tempo. +3. Проверьте дочерние spans PostgreSQL или S3; spans БД намеренно не содержат SQL и bind-параметры. +4. Сопоставьте trace ID с записью Loki. Не копируйте authorization headers или тела запросов в отчет. +5. Восстановите зависимость либо откатите изменение; убедитесь, что alert перешел в resolved и успешные запросы возобновились. diff --git a/infra/runbooks/queue-lag.md b/infra/runbooks/queue-lag.md new file mode 100644 index 00000000..0e9f3665 --- /dev/null +++ b/infra/runbooks/queue-lag.md @@ -0,0 +1,7 @@ +# Runbook: задержка задачи вложения + +1. Сравните глубину очереди и возраст самой старой задачи. Старый возраст при нулевой глубине может означать устаревшие данные или остановку telemetry pipeline. +2. Проверьте worker и его загрузку в dashboard; изучите журналы и traces на наличие retry и ошибок. +3. Сравните загрузку пула PostgreSQL с лимитом и проверьте S3 spans, чтобы отличить задержку зависимости от обработки изображения. +4. Восстанавливайте по одной зависимости. Убедитесь, что возраст очереди уменьшается, задачи переходят в ready, а alert становится resolved. +5. Compose на одном хосте не защищает от потери самого Docker-хоста или диска PostgreSQL. diff --git a/infra/runbooks/telemetry-backend.md b/infra/runbooks/telemetry-backend.md new file mode 100644 index 00000000..62348d7c --- /dev/null +++ b/infra/runbooks/telemetry-backend.md @@ -0,0 +1,23 @@ +# Runbook: отказ telemetry backend + +## Симптомы + +- Запросы приложения и задачи вложений продолжают работать, но новые traces/logs перестают появляться в Tempo/Loki. +- В журналах API/worker могут появиться короткие OTLP timeouts. Экспорт telemetry не является условием готовности приложения. + +## Диагностика + +1. Проверьте docker compose ps и готовность otel-gateway, otel-collector, tempo, loki и prometheus. +2. Изучите docker compose logs --tail 100 otel-collector на ошибки exporter или receiver. +3. Счетчики otelcol_receiver_refused_spans и otelcol_exporter_enqueue_failed_spans доступны по адресу https://localhost:9091/graph. Используйте secrets/pki/internal-ca.crt, prometheus-client.crt и prometheus-client.key для проверки TLS/mTLS. +4. Убедитесь, что API готов и синтетическая загрузка вложения доходит до ready. + +## Восстановление + +1. Восстановите недоступный telemetry backend, затем запустите/перезапустите только его и при необходимости Collector. +2. Проверьте состояние Collector и поступление новых traces/logs. Сигналы, потерянные при отказе backend, не воспроизводятся после исчерпания ограниченных очередей SDK/Collector. +3. Запишите длительность отказа, счетчики принятых/отправленных/отклоненных/enqueue-failed сигналов и влияние на бизнес-запросы в REPORT.md. + +## Лимиты и ограничения + +Очереди spans/logs SDK ограничены 2048 записями, timeout экспорта — 2 секунды. Память Collector ограничена 160 MiB с запасом 32 MiB; очереди exporter вмещают максимум 512 batches, retry завершается через 10 секунд. Это ограничивает рост буфера, но не гарантирует отсутствие потерь telemetry и не защищает от отказа единственного Docker-хоста. diff --git a/infra/supervisord.conf b/infra/supervisord.conf new file mode 100644 index 00000000..3fceb602 --- /dev/null +++ b/infra/supervisord.conf @@ -0,0 +1,32 @@ +[supervisord] +nodaemon=true +user=appuser +logfile=/tmp/supervisord.log +pidfile=/tmp/supervisord.pid + +[program:api] +command=python -m src.app.secrets_bootstrap api -- uvicorn src.app.main:app --host 127.0.0.1 --port 8080 --workers 1 --timeout-graceful-shutdown 5 --no-server-header --proxy-headers --forwarded-allow-ips=127.0.0.1 +directory=/app +user=appuser +autostart=true +autorestart=true +startsecs=5 +stopasgroup=true +killasgroup=true +stdout_logfile=/dev/fd/1 +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/fd/2 +stderr_logfile_maxbytes=0 + +[program:nginx] +command=/usr/sbin/nginx -g "daemon off;" +user=appuser +autostart=true +autorestart=true +startsecs=1 +stopasgroup=true +killasgroup=true +stdout_logfile=/dev/fd/1 +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/fd/2 +stderr_logfile_maxbytes=0 diff --git a/infra/tempo/config.yaml b/infra/tempo/config.yaml new file mode 100644 index 00000000..c4d2f73b --- /dev/null +++ b/infra/tempo/config.yaml @@ -0,0 +1,45 @@ +server: + http_listen_port: 3200 + grpc_listen_port: 9095 + tls_min_version: VersionTLS12 + http_tls_config: + cert_file: /run/secrets/tempo-server.crt + key_file: /run/secrets/tempo-server.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-ca.crt + grpc_tls_config: + cert_file: /run/secrets/tempo-server.crt + key_file: /run/secrets/tempo-server.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-ca.crt +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + tls: + cert_file: /run/secrets/tempo-server.crt + key_file: /run/secrets/tempo-server.key + client_ca_file: /run/secrets/internal-ca.crt + min_version: "1.2" + http: + endpoint: 0.0.0.0:4318 + tls: + cert_file: /run/secrets/tempo-server.crt + key_file: /run/secrets/tempo-server.key + client_ca_file: /run/secrets/internal-ca.crt + min_version: "1.2" +ingester: + max_block_duration: 5m + complete_block_timeout: 10m +compactor: + compaction: + block_retention: 72h +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 00000000..f329638f --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,36 @@ +CREATE TABLE users ( + id UUID PRIMARY KEY, + username VARCHAR(32) NOT NULL UNIQUE + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name VARCHAR(100) NOT NULL + CHECK (char_length(display_name) BETWEEN 1 AND 100 AND btrim(display_name) <> ''), + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE chats ( + id UUID PRIMARY KEY, + title VARCHAR(100) NOT NULL + CHECK (char_length(title) BETWEEN 1 AND 100 AND btrim(title) <> ''), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_id_idx ON chat_members(user_id, chat_id); + +CREATE TABLE messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL, + sender_id UUID NOT NULL, + text VARCHAR(4000) NOT NULL + CHECK (char_length(text) BETWEEN 1 AND 4000 AND btrim(text) <> ''), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT messages_sender_is_chat_member_fk + FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members(chat_id, user_id) ON DELETE CASCADE +); +CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id); diff --git a/migrations/002_idempotency.sql b/migrations/002_idempotency.sql new file mode 100644 index 00000000..231eb768 --- /dev/null +++ b/migrations/002_idempotency.sql @@ -0,0 +1,16 @@ +CREATE TABLE idempotency_records ( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + method VARCHAR(8) NOT NULL, + path VARCHAR(200) NOT NULL, + idempotency_key VARCHAR(128) NOT NULL, + request_hash CHAR(64) NOT NULL, + response_body JSONB NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at TIMESTAMPTZ NOT NULL, + CONSTRAINT idempotency_records_scope_key_uq + UNIQUE (user_id, method, path, idempotency_key), + CHECK (method = 'POST'), + CHECK (char_length(idempotency_key) BETWEEN 1 AND 128) +); +CREATE INDEX idempotency_records_expires_at_idx ON idempotency_records(expires_at); diff --git a/migrations/003_attachments.sql b/migrations/003_attachments.sql new file mode 100644 index 00000000..29eb1e0a --- /dev/null +++ b/migrations/003_attachments.sql @@ -0,0 +1,48 @@ +-- Lab 4: S3 stores file bytes, while PostgreSQL owns metadata and chat relations. +ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_check; +ALTER TABLE messages + ADD CONSTRAINT messages_text_length_ck CHECK (char_length(text) BETWEEN 0 AND 4000); +ALTER TABLE messages + ADD CONSTRAINT messages_id_chat_id_uq UNIQUE (id, chat_id); + +CREATE TABLE attachments ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL, + owner_id UUID NOT NULL, + filename VARCHAR(255) NOT NULL, + content_type VARCHAR(32) NOT NULL, + size_bytes INTEGER NOT NULL, + sha256 CHAR(64) NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'ready', + variants JSONB NOT NULL DEFAULT '[]'::jsonb, + error_code VARCHAR(64), + object_key TEXT NOT NULL UNIQUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT attachments_owner_is_chat_member_fk + FOREIGN KEY (chat_id, owner_id) + REFERENCES chat_members(chat_id, user_id) ON DELETE CASCADE, + CONSTRAINT attachments_id_chat_id_uq UNIQUE (id, chat_id), + CONSTRAINT attachments_filename_length_ck CHECK (char_length(filename) BETWEEN 1 AND 255), + CONSTRAINT attachments_content_type_ck CHECK (content_type IN ('image/png', 'image/jpeg')), + CONSTRAINT attachments_size_bytes_ck CHECK (size_bytes BETWEEN 1 AND 10485760), + CONSTRAINT attachments_sha256_ck CHECK (sha256 ~ '^[a-f0-9]{64}$'), + CONSTRAINT attachments_status_ck CHECK (status = 'ready') +); +CREATE INDEX attachments_chat_created_idx ON attachments(chat_id, created_at, id); + +CREATE TABLE message_attachments ( + message_id UUID NOT NULL, + attachment_id UUID NOT NULL, + chat_id UUID NOT NULL, + position SMALLINT NOT NULL CHECK (position BETWEEN 0 AND 9), + PRIMARY KEY (message_id, attachment_id), + CONSTRAINT message_attachments_message_chat_fk + FOREIGN KEY (message_id, chat_id) + REFERENCES messages(id, chat_id) ON DELETE CASCADE, + CONSTRAINT message_attachments_attachment_chat_fk + FOREIGN KEY (attachment_id, chat_id) + REFERENCES attachments(id, chat_id) ON DELETE CASCADE, + CONSTRAINT message_attachments_position_uq UNIQUE (message_id, position) +); +CREATE INDEX message_attachments_attachment_idx ON message_attachments(attachment_id); diff --git a/migrations/004_attachment_schema_compat.sql b/migrations/004_attachment_schema_compat.sql new file mode 100644 index 00000000..a11ba832 --- /dev/null +++ b/migrations/004_attachment_schema_compat.sql @@ -0,0 +1,32 @@ +-- Bring databases that already recorded an earlier 003_attachments layout +-- forward without dropping attachment metadata or stored object references. +ALTER TABLE attachments ADD COLUMN IF NOT EXISTS variants JSONB NOT NULL DEFAULT '[]'::jsonb; +ALTER TABLE attachments ADD COLUMN IF NOT EXISTS error_code VARCHAR(64); +ALTER TABLE attachments ADD COLUMN IF NOT EXISTS width INTEGER; +ALTER TABLE attachments ADD COLUMN IF NOT EXISTS height INTEGER; +ALTER TABLE attachments ALTER COLUMN width DROP NOT NULL; +ALTER TABLE attachments ALTER COLUMN height DROP NOT NULL; + +ALTER TABLE message_attachments ADD COLUMN IF NOT EXISTS chat_id UUID; +UPDATE message_attachments AS link +SET chat_id = message.chat_id +FROM messages AS message +WHERE message.id = link.message_id + AND (link.chat_id IS NULL OR link.chat_id <> message.chat_id); +ALTER TABLE message_attachments ALTER COLUMN chat_id SET NOT NULL; + +-- Drop referencing foreign keys before replacing their referenced unique keys. +ALTER TABLE message_attachments DROP CONSTRAINT IF EXISTS message_attachments_message_chat_fk; +ALTER TABLE message_attachments DROP CONSTRAINT IF EXISTS message_attachments_attachment_chat_fk; + +ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_id_chat_id_uq; +ALTER TABLE messages ADD CONSTRAINT messages_id_chat_id_uq UNIQUE (id, chat_id); +ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_id_chat_id_uq; +ALTER TABLE attachments ADD CONSTRAINT attachments_id_chat_id_uq UNIQUE (id, chat_id); + +ALTER TABLE message_attachments + ADD CONSTRAINT message_attachments_message_chat_fk + FOREIGN KEY (message_id, chat_id) REFERENCES messages(id, chat_id) ON DELETE CASCADE; +ALTER TABLE message_attachments + ADD CONSTRAINT message_attachments_attachment_chat_fk + FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments(id, chat_id) ON DELETE CASCADE; diff --git a/migrations/005_async_attachment_jobs.sql b/migrations/005_async_attachment_jobs.sql new file mode 100644 index 00000000..260f3af6 --- /dev/null +++ b/migrations/005_async_attachment_jobs.sql @@ -0,0 +1,45 @@ +-- Lab 5: durable staging, transactional outbox and leased image jobs. +ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_status_ck; +ALTER TABLE attachments ADD CONSTRAINT attachments_status_ck CHECK (status IN ('queued', 'processing', 'ready', 'failed')); +ALTER TABLE attachments ALTER COLUMN status SET DEFAULT 'queued'; +ALTER TABLE attachments ADD COLUMN IF NOT EXISTS staging_key TEXT; +CREATE UNIQUE INDEX IF NOT EXISTS attachments_staging_key_uq ON attachments(staging_key) WHERE staging_key IS NOT NULL; + +CREATE TABLE attachment_jobs ( + id UUID PRIMARY KEY, + attachment_id UUID NOT NULL UNIQUE REFERENCES attachments(id) ON DELETE CASCADE, + pipeline_version INTEGER NOT NULL DEFAULT 1 CHECK (pipeline_version >= 1), + attempt INTEGER NOT NULL DEFAULT 1 CHECK (attempt >= 1), + attempts_in_cycle INTEGER NOT NULL DEFAULT 1, + max_attempts INTEGER NOT NULL CHECK (max_attempts BETWEEN 1 AND 20), + status VARCHAR(16) NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'processing', 'succeeded', 'failed')), + available_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + lease_until TIMESTAMPTZ, + last_error_code VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + completed_at TIMESTAMPTZ, + CONSTRAINT attachment_jobs_cycle_attempt_ck CHECK (attempts_in_cycle BETWEEN 1 AND max_attempts) +); +CREATE INDEX attachment_jobs_due_idx ON attachment_jobs(status, available_at); +CREATE INDEX attachment_jobs_lease_idx ON attachment_jobs(status, lease_until); + +CREATE TABLE job_outbox ( + id UUID PRIMARY KEY, + job_id UUID NOT NULL REFERENCES attachment_jobs(id) ON DELETE CASCADE, + attempt INTEGER NOT NULL CHECK (attempt >= 1), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + published_at TIMESTAMPTZ, + CONSTRAINT job_outbox_job_attempt_uq UNIQUE (job_id, attempt) +); +CREATE INDEX job_outbox_pending_idx ON job_outbox(published_at, created_at); + +CREATE TABLE job_replay_audit ( + id UUID PRIMARY KEY, + job_id UUID NOT NULL REFERENCES attachment_jobs(id) ON DELETE CASCADE, + previous_attempt INTEGER NOT NULL, + new_attempt INTEGER NOT NULL, + operator VARCHAR(100) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (new_attempt > previous_attempt) +); diff --git a/migrations/006_telemetry_context.sql b/migrations/006_telemetry_context.sql new file mode 100644 index 00000000..3e6b2258 --- /dev/null +++ b/migrations/006_telemetry_context.sql @@ -0,0 +1,2 @@ +ALTER TABLE job_outbox ADD COLUMN traceparent VARCHAR(128); +ALTER TABLE job_outbox ADD COLUMN tracestate VARCHAR(512); diff --git a/migrations/007_workload_roles.sql b/migrations/007_workload_roles.sql new file mode 100644 index 00000000..5e557ea3 --- /dev/null +++ b/migrations/007_workload_roles.sql @@ -0,0 +1,13 @@ +-- Separate SQL identities for API, dispatcher and worker. The API receives +-- the business tables, and background services receive only job-pipeline tables. +GRANT USAGE ON SCHEMA public TO messenger_api, messenger_dispatcher, messenger_worker; +GRANT SELECT, INSERT, UPDATE, DELETE ON users, chats, chat_members, messages, + idempotency_records, attachments, message_attachments TO messenger_api; +GRANT SELECT, INSERT, UPDATE, DELETE ON attachment_jobs, job_outbox TO messenger_api; +GRANT SELECT, UPDATE ON attachments, attachment_jobs TO messenger_dispatcher; +GRANT INSERT, UPDATE ON job_outbox TO messenger_dispatcher; +GRANT SELECT, UPDATE ON attachments, attachment_jobs TO messenger_worker; +GRANT SELECT ON job_outbox TO messenger_worker; + +ALTER DEFAULT PRIVILEGES IN SCHEMA public + GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO messenger_api; diff --git a/migrations/008_dispatcher_outbox_read.sql b/migrations/008_dispatcher_outbox_read.sql new file mode 100644 index 00000000..7e115ccf --- /dev/null +++ b/migrations/008_dispatcher_outbox_read.sql @@ -0,0 +1 @@ +GRANT SELECT ON job_outbox TO messenger_dispatcher; diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..a2d5c4c3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,18 @@ +fastapi==0.165.1 +starlette==1.10.0 +uvicorn[standard]==0.30.6 +pydantic==2.9.2 +SQLAlchemy==2.0.36 +psycopg[binary]==3.2.3 +redis==5.2.0 +argon2-cffi==23.1.0 +boto3==1.44.1 +Pillow==13.0.0 +opentelemetry-api==1.45.2 +opentelemetry-sdk==1.45.2 +opentelemetry-exporter-otlp-proto-http==1.45.2 +psutil==7.1.3 +supervisor==4.3.0 +wheel==0.46.2 +# Keep setuptools above the versions flagged by the current Trivy database. +setuptools==84.1.0 diff --git a/scripts/bao_bootstrap.py b/scripts/bao_bootstrap.py new file mode 100644 index 00000000..797f013e --- /dev/null +++ b/scripts/bao_bootstrap.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Initialize OpenBao policies, PKI and scoped app secrets for the local lab.""" +from __future__ import annotations + +import getpass +import json +import os +from pathlib import Path +import shutil +import ssl +import subprocess +import sys +from urllib.error import HTTPError, URLError +from urllib.request import Request, urlopen +from urllib.parse import urlsplit + + +ROOT = Path(__file__).resolve().parents[1] +SECRETS = ROOT / "secrets" +PKI = SECRETS / "pki" +BAO_ADDR = os.environ.get("BAO_ADDR", "https://localhost:8200").rstrip("/") +def _openssl_path() -> str: + configured = os.environ.get("OPENSSL") + if configured: + return configured + found = shutil.which("openssl") + if found: + return found + git = shutil.which("git") + if git: + candidate = Path(git).resolve().parents[1] / "usr" / "bin" / "openssl.exe" + if candidate.is_file(): + return str(candidate) + return "openssl" + + +OPENSSL = _openssl_path() + +SERVER_CERTS = { + "ingress": ("localhost", ["localhost"], "server"), + "api-server": ("api", ["api"], "server"), + "postgres-server": ("db", ["db", "postgres"], "server"), + "s3-server": ("s3", ["s3"], "server"), + "redis-server": ("redis", ["redis"], "server"), + "broker-server": ("broker", ["broker"], "server"), + "otel-server": ("otel-collector", ["otel-collector"], "server"), + "otel-gateway-server": ("otel-gateway", ["otel-gateway"], "server"), + "prometheus-server": ("prometheus", ["prometheus", "localhost"], "server"), + "loki-server": ("loki", ["loki"], "server"), + "tempo-server": ("tempo", ["tempo"], "server"), + "grafana-server": ("grafana", ["grafana", "localhost"], "server"), +} +CLIENT_CERTS = { + "lb-client": "messenger-lb", + "api-client": "messenger-api", + "worker-client": "messenger-worker", + "dispatcher-client": "messenger-dispatcher", + "otel-client": "messenger-otel-collector", + "prometheus-client": "messenger-prometheus", + "grafana-client": "messenger-grafana", +} + + +class Bao: + def __init__(self, token: str): + if urlsplit(BAO_ADDR).scheme != "https": + raise RuntimeError("OpenBao operator API must use HTTPS") + self.token = token + self.context = ssl.create_default_context(cafile=str(PKI / "internal-ca.crt")) + + def request(self, method: str, path: str, payload: dict | None = None, *, allow_missing: bool = False, include_errors: bool = False) -> dict: + body = json.dumps(payload, separators=(",", ":")).encode("utf-8") if payload is not None else None + headers = {"Content-Type": "application/json", "X-Vault-Token": self.token} + request = Request(f"{BAO_ADDR}/v1/{path}", data=body, headers=headers, method=method) + try: + with urlopen(request, context=self.context, timeout=5) as response: + raw = response.read(2_000_000) + return json.loads(raw) if raw else {} + except HTTPError as exc: + if allow_missing and exc.code == 404: + return {} + detail = "" + if include_errors: + try: + error_body = json.loads(exc.read(2048)) + errors = error_body.get("errors", []) + safe_errors = [str(item).replace(self.token, "[redacted]").replace("\r", " ").replace("\n", " ")[:200] for item in errors[:3]] + if safe_errors: + detail = ": " + "; ".join(safe_errors) + except (ValueError, AttributeError, TypeError): + pass + raise RuntimeError(f"OpenBao rejected {method} {path} (HTTP {exc.code}){detail}") from None + except (URLError, TimeoutError, ValueError) as exc: + reason = getattr(exc, "reason", None) + detail = str(reason or exc) + raise RuntimeError( + f"OpenBao request failed at {method} {path} ({type(exc).__name__}): {detail}" + ) from None + + def request_text(self, path: str, *, allow_missing: bool = False) -> str: + request = Request( + f"{BAO_ADDR}/v1/{path}", + headers={"X-Vault-Token": self.token}, + method="GET", + ) + try: + with urlopen(request, context=self.context, timeout=5) as response: + return response.read(2_000_000).decode("ascii").strip() + except HTTPError as exc: + if allow_missing and exc.code == 404: + return "" + raise RuntimeError(f"OpenBao rejected GET {path} (HTTP {exc.code})") from None + except (URLError, TimeoutError, UnicodeDecodeError) as exc: + reason = getattr(exc, "reason", None) + detail = str(reason or exc) + raise RuntimeError( + f"OpenBao request failed at GET {path} ({type(exc).__name__}): {detail}" + ) from None + + def ensure_mount(self, path: str, kind: str, options: dict | None = None) -> None: + mounts = self.request("GET", "sys/mounts") + if path + "/" not in mounts.get("data", {}): + self.request("POST", "sys/mounts/" + path, {"type": kind, "options": options or {}}) + + +def _read_secret(name: str) -> str: + value = (SECRETS / name).read_text(encoding="utf-8").strip() + if not value: + raise RuntimeError(f"Local bootstrap file is empty: {name}") + return value + + +def _issue_leaf(bao: Bao, role: str, common_name: str, names: list[str], usage: str, *, ttl: str = "6h") -> None: + cert_path = PKI / f"{role}.crt" + key_path = PKI / f"{role}.key" + if cert_path.exists() and key_path.exists(): + return + body = {"common_name": common_name, "ttl": ttl} + if names: + body["alt_names"] = ",".join(names) + result = bao.request("POST", f"pki_int/issue/{role}", body).get("data", {}) + certificate = result.get("certificate") + private_key = result.get("private_key") + if not certificate or not private_key: + raise RuntimeError(f"OpenBao did not issue {role}") + chain = result.get("ca_chain") or [] + cert_path.write_text(certificate.rstrip() + "\n" + "\n".join(item.rstrip() for item in chain) + "\n", encoding="ascii") + key_path.write_text(private_key.rstrip() + "\n", encoding="ascii") + + +def _setup_intermediate(bao: Bao) -> str: + mounts = bao.request("GET", "sys/mounts").get("data", {}) + if "pki_int/" not in mounts: + bao.request("POST", "sys/mounts/pki_int", {"type": "pki"}) + bao.request("POST", "sys/mounts/pki_int/tune", {"max_lease_ttl": "87600h"}) + + current = bao.request_text("pki_int/ca/pem", allow_missing=True) + if current: + return current + + generated = bao.request("POST", "pki_int/intermediate/generate/internal", { + "common_name": "MTUSI Lab7 Intermediate CA", + "key_type": "rsa", + "key_bits": 4096, + "ttl": "43800h", + }).get("data", {}) + csr = generated.get("csr") + if not csr: + raise RuntimeError("OpenBao did not generate the intermediate CSR") + csr_path = PKI / "pki-int.csr" + cert_path = PKI / "pki-int.crt" + ext_path = PKI / "pki-int.ext" + csr_path.write_text(csr, encoding="ascii") + ext_path.write_text( + "basicConstraints=critical,CA:TRUE,pathlen:0\n" + "keyUsage=critical,keyCertSign,cRLSign\n" + "subjectKeyIdentifier=hash\n" + "authorityKeyIdentifier=keyid,issuer\n", + encoding="ascii", + ) + try: + subprocess.run([ + OPENSSL, "x509", "-req", "-sha256", "-in", str(csr_path), + "-CA", str(PKI / "internal-ca.crt"), "-CAkey", str(PKI / "internal-ca.key.pem"), + "-CAcreateserial", "-days", "1825", "-extfile", str(ext_path), "-out", str(cert_path), + ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except (OSError, subprocess.CalledProcessError): + raise RuntimeError("Could not sign the OpenBao intermediate with the offline lab CA") from None + signed = cert_path.read_text(encoding="ascii") + bao.request("POST", "pki_int/intermediate/set-signed", {"certificate": signed}) + csr_path.unlink(missing_ok=True) + ext_path.unlink(missing_ok=True) + return bao.request_text("pki_int/ca/pem") + + +def _configure(bao: Bao) -> None: + bao.ensure_mount("kv", "kv", {"version": "2"}) + auth_methods = bao.request("GET", "sys/auth").get("data", {}) + if "cert/" not in auth_methods: + bao.request("POST", "sys/auth/cert", {"type": "cert"}) + intermediate = _setup_intermediate(bao) + if not intermediate: + raise RuntimeError("OpenBao PKI intermediate certificate is empty") + bao.request("POST", "pki_int/config/urls", { + "issuing_certificates": f"{BAO_ADDR}/v1/pki_int/ca", + "crl_distribution_points": f"{BAO_ADDR}/v1/pki_int/crl", + }) + + identities: dict[str, tuple[str, list[str], str]] = { + **SERVER_CERTS, + **{name: (cn, [], "client") for name, cn in CLIENT_CERTS.items()}, + } + for role, (common_name, dns_names, kind) in identities.items(): + names = {"server": (True, False, ["ServerAuth"]), "client": (False, True, ["ClientAuth"])}[kind] + domains = sorted(set([common_name, *dns_names])) + bao.request("POST", f"pki_int/roles/{role}", { + "allowed_domains": domains, + "allow_bare_domains": True, + "allow_subdomains": False, + "allow_wildcard_certificates": False, + "enforce_hostnames": True, + "allow_ip_sans": False, + "max_ttl": "12h", + "key_type": "rsa", + "key_bits": 2048, + "server_flag": names[0], + "client_flag": names[1], + "key_usage": ["DigitalSignature", "KeyEncipherment"], + "ext_key_usage": names[2], + }) + _issue_leaf(bao, role, common_name, dns_names, kind) + + policies = { + "messenger-api": 'path "kv/data/messenger/api" { capabilities = ["read"] }', + "messenger-worker": 'path "kv/data/messenger/worker" { capabilities = ["read"] }', + "messenger-dispatcher": 'path "kv/data/messenger/dispatcher" { capabilities = ["read"] }', + } + for name, policy in policies.items(): + bao.request("PUT", f"sys/policies/acl/{name}", {"policy": policy}) + + for name, common_name in (("messenger-api", "messenger-api"), ("messenger-worker", "messenger-worker"), ("messenger-dispatcher", "messenger-dispatcher")): + bao.request("POST", f"auth/cert/certs/{name}", { + "display_name": name, + "certificate": (PKI / "internal-ca.crt").read_text(encoding="ascii"), + "allowed_common_names": [common_name], + "token_policies": name, + "token_ttl": "15m", + "token_max_ttl": "1h", + }) + + def redis_url(username: str, secret_name: str, cert: str) -> str: + password = _read_secret(secret_name) + return ( + f"rediss://{username}:{password}@{{host}}:6379/0" + f"?ssl_cert_reqs=required&ssl_ca_certs=/run/secrets/internal-ca.crt" + f"&ssl_certfile=/run/secrets/{cert}.crt&ssl_keyfile=/run/secrets/{cert}.key" + ) + + api = { + "cache_url": redis_url("api", "redis_api_password", "api-client").format(host="redis"), + "s3_access_key_id": _read_secret("s3_access_key_id"), + "s3_secret_access_key": _read_secret("s3_secret_access_key"), + } + worker = { + "broker_url": redis_url("messenger-worker", "redis_worker_password", "worker-client").format(host="broker"), + "s3_access_key_id": _read_secret("s3_worker_access_key_id"), + "s3_secret_access_key": _read_secret("s3_worker_secret_access_key"), + } + dispatcher = { + "broker_url": redis_url("messenger-dispatcher", "redis_dispatcher_password", "dispatcher-client").format(host="broker"), + } + for role, values in (("api", api), ("worker", worker), ("dispatcher", dispatcher)): + bao.request("POST", f"kv/data/messenger/{role}", {"data": values}) + + # Nginx consumes the issuer's signed CRL to reject revoked LB client leaves. + # Keep it in the local ignored secrets directory and refresh it before API + # containers are created. + intermediate_crl = bao.request_text("pki_int/crl/pem") + root_crl_path = PKI / "root-ca.crl.pem" + if not intermediate_crl.startswith("-----BEGIN X509 CRL-----"): + raise RuntimeError("OpenBao returned an invalid PKI CRL") + if not root_crl_path.is_file() or not root_crl_path.read_text(encoding="ascii").startswith("-----BEGIN X509 CRL-----"): + raise RuntimeError("Offline root CRL is missing; rerun scripts/bootstrap-local.ps1") + crl_path = PKI / "pki-int.crl.pem" + crl_tmp = PKI / "pki-int.crl.pem.tmp" + rollover_crl = bao.request_text("pki_rollover/crl/pem", allow_missing=True) + if rollover_crl and not rollover_crl.startswith("-----BEGIN X509 CRL-----"): + raise RuntimeError("OpenBao returned an invalid rollover intermediate CRL") + crl_tmp.write_text( + root_crl_path.read_text(encoding="ascii").rstrip() + "\n" + intermediate_crl.rstrip() + "\n" + + (rollover_crl.rstrip() + "\n" if rollover_crl else ""), + encoding="ascii", + ) + os.replace(crl_tmp, crl_path) + + +def main() -> None: + if not (PKI / "internal-ca.crt").exists() or not (PKI / "internal-ca.key.pem").exists(): + raise SystemExit("Run scripts/bootstrap-local.ps1 first") + token = getpass.getpass("OpenBao operator root token (not saved): ") + if not token: + raise SystemExit("An operator token is required") + try: + _configure(Bao(token)) + except RuntimeError as exc: + raise SystemExit(str(exc)) from None + print("OpenBao policies, short-lived PKI roles, and service secrets are ready; token was not saved.") + + +if __name__ == "__main__": + main() diff --git a/scripts/bao_policy_probe.py b/scripts/bao_policy_probe.py new file mode 100644 index 00000000..106e0e92 --- /dev/null +++ b/scripts/bao_policy_probe.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Prove service cert-auth can read only its own KV v2 path.""" +from __future__ import annotations + +import json +import os +import ssl +from pathlib import Path +from urllib.error import HTTPError, URLError +from urllib.request import Request, urlopen + +ROOT = Path(__file__).resolve().parents[1] +PKI = ROOT / "secrets" / "pki" +ADDR = os.environ.get("BAO_ADDR", "https://localhost:8200").rstrip("/") +WORKLOADS = { + "api": ("messenger-api", "messenger/api"), + "worker": ("messenger-worker", "messenger/worker"), + "dispatcher": ("messenger-dispatcher", "messenger/dispatcher"), +} + + +def call(context: ssl.SSLContext, path: str, *, token: str | None = None, method: str = "GET", body: dict | None = None) -> tuple[int, dict]: + headers = {"Content-Type": "application/json"} + if token: + headers["X-Vault-Token"] = token + payload = json.dumps(body).encode() if body is not None else None + req = Request(f"{ADDR}/v1/{path}", data=payload, headers=headers, method=method) + try: + with urlopen(req, context=context, timeout=4) as response: + return response.status, json.loads(response.read(1_000_000) or b"{}") + except HTTPError as exc: + return exc.code, {} + except (URLError, TimeoutError) as exc: + raise RuntimeError(f"OpenBao probe failed ({type(exc).__name__})") from None + + +def main() -> None: + for service, (auth_name, own_path) in WORKLOADS.items(): + context = ssl.create_default_context(cafile=str(PKI / "internal-ca.crt")) + context.load_cert_chain(str(PKI / f"{service}-client.crt"), str(PKI / f"{service}-client.key")) + status, login = call(context, "auth/cert/login", method="POST", body={"name": auth_name}) + assert status == 200 and login.get("auth", {}).get("client_token"), f"{service}: cert auth failed" + token = login["auth"]["client_token"] + assert call(context, f"kv/data/{own_path}", token=token)[0] == 200, f"{service}: own secret denied" + other_path = "messenger/worker" if service != "worker" else "messenger/api" + assert call(context, f"kv/data/{other_path}", token=token)[0] == 403, f"{service}: cross-service read was not denied" + assert call(context, "sys/policies/acl/attacker", token=token, method="PUT", body={"policy": 'path "*" { capabilities=["read"] }'})[0] == 403, f"{service}: policy write was not denied" + print("PASS: each workload reads only its own KV v2 path; cross-read and policy write denied") + + +if __name__ == "__main__": + main() diff --git a/scripts/bootstrap-local.ps1 b/scripts/bootstrap-local.ps1 new file mode 100644 index 00000000..fe5fa736 --- /dev/null +++ b/scripts/bootstrap-local.ps1 @@ -0,0 +1,152 @@ +$ErrorActionPreference = 'Stop' + +$repo = Split-Path -Parent $PSScriptRoot +$secretRoot = Join-Path $repo 'secrets' +$pkiRoot = Join-Path $secretRoot 'pki' +$openssl = (Get-Command openssl -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Source) +if (-not $openssl) { + $git = Get-Command git -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Source + if ($git) { + $candidate = Join-Path (Split-Path (Split-Path $git -Parent) -Parent) 'usr\bin\openssl.exe' + if (Test-Path -LiteralPath $candidate) { $openssl = $candidate } + } +} +if (-not $openssl) { throw 'OpenSSL is required. Install Git for Windows or OpenSSL and retry.' } + +New-Item -ItemType Directory -Force -Path $pkiRoot | Out-Null +$rootKey = Join-Path $pkiRoot 'internal-ca.key.pem' +$rootCert = Join-Path $pkiRoot 'internal-ca.crt' +$hasRootKey = Test-Path -LiteralPath $rootKey +$hasRootCert = Test-Path -LiteralPath $rootCert +if ($hasRootKey -ne $hasRootCert) { throw 'Local CA is incomplete. Restore its matching key/certificate pair from backup.' } + +function Invoke-OpenSsl([string[]]$Arguments) { + & $openssl @Arguments + if ($LASTEXITCODE -ne 0) { throw "OpenSSL failed: $($Arguments[0])" } +} + +function New-RandomHex([int]$Bytes) { + $buffer = [byte[]]::new($Bytes) + $generator = [System.Security.Cryptography.RandomNumberGenerator]::Create() + try { $generator.GetBytes($buffer) } finally { $generator.Dispose() } + return ([BitConverter]::ToString($buffer).Replace('-', '').ToLowerInvariant()) +} + +function Save-Secret([string]$Name,[string]$Value) { + $path = Join-Path $secretRoot $Name + if (-not (Test-Path -LiteralPath $path)) { Set-Content -LiteralPath $path -Value $Value -NoNewline -Encoding ascii } +} + +$postgresPassword = New-RandomHex 32 +Save-Secret 'postgres_password' $postgresPassword +Save-Secret 'database_url' "postgresql+psycopg://postgres:${postgresPassword}@db:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/internal-ca.crt" +Save-Secret 's3_root_access_key_id' (New-RandomHex 20) +Save-Secret 's3_root_secret_access_key' (New-RandomHex 32) +Save-Secret 's3_access_key_id' (New-RandomHex 20) +Save-Secret 's3_secret_access_key' (New-RandomHex 32) +Save-Secret 's3_worker_access_key_id' (New-RandomHex 20) +Save-Secret 's3_worker_secret_access_key' (New-RandomHex 32) +Save-Secret 'redis_api_password' (New-RandomHex 32) +Save-Secret 'redis_dispatcher_password' (New-RandomHex 32) +Save-Secret 'redis_worker_password' (New-RandomHex 32) +Save-Secret 'grafana_admin_password' (New-RandomHex 32) + +$acl = @( + 'user default off', + "user api on >$(Get-Content (Join-Path $secretRoot 'redis_api_password') -Raw) ~session:v1:* ~login:v1:* +ping +get +set +del +eval +incr +expire +ttl", + "user messenger-dispatcher on >$(Get-Content (Join-Path $secretRoot 'redis_dispatcher_password') -Raw) ~messenger:attachment-jobs:v1* ~lab5:failpoint:* +ping +set +xadd", + "user messenger-worker on >$(Get-Content (Join-Path $secretRoot 'redis_worker_password') -Raw) ~messenger:attachment-jobs:v1* ~lab5:failpoint:* ~lab6:failpoint:* +ping +get +set +xadd +xgroup +xreadgroup +xack +xautoclaim" +) +Set-Content -LiteralPath (Join-Path $secretRoot 'redis-users.acl') -Value $acl -Encoding ascii + +if (-not $hasRootKey) { + Invoke-OpenSsl @('req','-x509','-newkey','rsa:4096','-sha256','-nodes','-days','3650', + '-keyout',$rootKey,'-out',$rootCert,'-subj','/CN=MTUSI-Lab7-Local-Root', + '-addext','basicConstraints=critical,CA:TRUE,pathlen:1', + '-addext','keyUsage=critical,keyCertSign,cRLSign') +} + +function New-Leaf([string]$Name,[string]$CommonName,[string]$Usage,[string[]]$DnsNames,[string[]]$IpNames=@()) { + $key = Join-Path $pkiRoot "$Name.key.pem" + $csr = Join-Path $pkiRoot "$Name.csr.pem" + $cert = Join-Path $pkiRoot "$Name.crt" + $ext = Join-Path $pkiRoot "$Name.ext" + $hasKey = Test-Path -LiteralPath $key + $hasCert = Test-Path -LiteralPath $cert + if ($hasKey -and $hasCert) { return } + if ($hasKey -or $hasCert) { throw "Leaf $Name is incomplete. Restore its matching key/certificate pair or remove both and regenerate." } + $san = @($DnsNames | ForEach-Object { "DNS:$_" }) + @($IpNames | ForEach-Object { "IP:$_" }) + @( + 'basicConstraints=critical,CA:FALSE', + 'keyUsage=critical,digitalSignature,keyEncipherment', + "extendedKeyUsage=$Usage", + "subjectAltName=$($san -join ',')" + ) | Set-Content -LiteralPath $ext -Encoding ascii + Invoke-OpenSsl @('req','-new','-newkey','rsa:2048','-sha256','-nodes','-keyout',$key,'-out',$csr,'-subj',"/CN=$CommonName") + Invoke-OpenSsl @('x509','-req','-sha256','-in',$csr,'-CA',$rootCert,'-CAkey',$rootKey,'-CAcreateserial','-days','90','-extfile',$ext,'-out',$cert) + Remove-Item -LiteralPath $csr,$ext -Force +} + +# Only OpenBao's listener certificate is bootstrapped by the offline CA. +# Internal leaves are issued by OpenBao's intermediate during its bootstrap. +New-Leaf 'openbao-server' 'openbao' 'serverAuth' @('openbao','localhost') @('127.0.0.1') + +# Nginx enables CRL checking for the whole client certificate chain. Publish an +# empty root CRL as well as OpenBao's intermediate CRL so the chain can be +# checked without treating the absence of a root CRL as an authentication error. +$rootCrlState = Join-Path $pkiRoot 'root-crl-state' +New-Item -ItemType Directory -Force -Path $rootCrlState | Out-Null +$rootCrlIndex = Join-Path $rootCrlState 'index.txt' +$rootCrlNumber = Join-Path $rootCrlState 'crlnumber' +$rootCrlConfig = Join-Path $rootCrlState 'openssl.cnf' +$rootCrl = Join-Path $pkiRoot 'root-ca.crl.pem' +if (-not (Test-Path -LiteralPath $rootCrlIndex)) { Set-Content -LiteralPath $rootCrlIndex -Value '' -NoNewline -Encoding ascii } +if (-not (Test-Path -LiteralPath $rootCrlNumber)) { Set-Content -LiteralPath $rootCrlNumber -Value '01' -Encoding ascii } +$rootCertConfigPath = ([System.IO.Path]::GetFullPath($rootCert)).Replace('\','/') +$rootKeyConfigPath = ([System.IO.Path]::GetFullPath($rootKey)).Replace('\','/') +$rootIndexConfigPath = ([System.IO.Path]::GetFullPath($rootCrlIndex)).Replace('\','/') +$rootNumberConfigPath = ([System.IO.Path]::GetFullPath($rootCrlNumber)).Replace('\','/') +$rootCrlConfigText = @( + '[ ca ]', + 'default_ca = CA_default', + '[ CA_default ]', + "database = `"$rootIndexConfigPath`"", + "certificate = `"$rootCertConfigPath`"", + "private_key = `"$rootKeyConfigPath`"", + "crlnumber = `"$rootNumberConfigPath`"", + 'default_md = sha256', + 'default_days = 365', + 'default_crl_days = 365' +) +Set-Content -LiteralPath $rootCrlConfig -Value $rootCrlConfigText -Encoding ascii +Invoke-OpenSsl @('ca','-batch','-config',$rootCrlConfig,'-gencrl','-out',$rootCrl) + +# Compose needs the source path to exist before the first OpenBao bootstrap. +# The operator bootstrap replaces this marker with the signed issuer CRL before +# any API container is started; an invalid placeholder therefore fails closed. +$crlPath = Join-Path $pkiRoot 'pki-int.crl.pem' +if (-not (Test-Path -LiteralPath $crlPath)) { + Set-Content -LiteralPath $crlPath -Value '# OpenBao bootstrap must replace this placeholder with a signed CRL.' -Encoding ascii +} + +# Test-only identity: correct LB CN, deliberately signed by a separate CA. +$foreignCaKey = Join-Path $pkiRoot 'negative-test-ca.key.pem' +$foreignCaCert = Join-Path $pkiRoot 'negative-test-ca.crt' +$foreignClientKey = Join-Path $pkiRoot 'negative-test-client.key' +$foreignClientCsr = Join-Path $pkiRoot 'negative-test-client.csr' +$foreignClientCert = Join-Path $pkiRoot 'negative-test-client.crt' +if (-not ((Test-Path -LiteralPath $foreignCaKey) -and (Test-Path -LiteralPath $foreignCaCert) -and (Test-Path -LiteralPath $foreignClientKey) -and (Test-Path -LiteralPath $foreignClientCert))) { + Invoke-OpenSsl @('req','-x509','-newkey','rsa:2048','-sha256','-nodes','-days','7', + '-keyout',$foreignCaKey,'-out',$foreignCaCert,'-subj','/CN=MTUSI-Lab7-Negative-Test-CA', + '-addext','basicConstraints=critical,CA:TRUE,pathlen:0', + '-addext','keyUsage=critical,keyCertSign,cRLSign') + Invoke-OpenSsl @('req','-new','-newkey','rsa:2048','-sha256','-nodes', + '-keyout',$foreignClientKey,'-out',$foreignClientCsr,'-subj','/CN=messenger-lb') + @('basicConstraints=critical,CA:FALSE','keyUsage=critical,digitalSignature,keyEncipherment','extendedKeyUsage=clientAuth') | + Set-Content -LiteralPath (Join-Path $pkiRoot 'negative-test-client.ext') -Encoding ascii + Invoke-OpenSsl @('x509','-req','-sha256','-in',$foreignClientCsr,'-CA',$foreignCaCert,'-CAkey',$foreignCaKey, + '-CAcreateserial','-days','7','-extfile',(Join-Path $pkiRoot 'negative-test-client.ext'),'-out',$foreignClientCert) + Remove-Item -LiteralPath $foreignClientCsr,(Join-Path $pkiRoot 'negative-test-client.ext') -Force +} + +Write-Host 'Local PKI created under secrets/pki. Private keys are excluded from Git; keep the CA key with the operator.' diff --git a/scripts/issue_expiry_probe.py b/scripts/issue_expiry_probe.py new file mode 100644 index 00000000..709ebc26 --- /dev/null +++ b/scripts/issue_expiry_probe.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Issue a short-lived LB client certificate for the expiry security probe.""" +from __future__ import annotations + +import getpass +import os +from pathlib import Path +import tempfile + +from bao_bootstrap import Bao, CLIENT_CERTS, PKI + + +def main() -> None: + role = "lb-client" + common_name = CLIENT_CERTS[role] + token = getpass.getpass("OpenBao operator root token (not saved): ") + if not token: + raise SystemExit("An operator token is required") + try: + data = Bao(token).request("POST", f"pki_int/issue/{role}", { + "common_name": common_name, + "ttl": "2m", + }).get("data", {}) + certificate = data.get("certificate") + private_key = data.get("private_key") + if not certificate or not private_key: + raise RuntimeError("OpenBao did not issue the short-lived probe certificate") + chain = data.get("ca_chain") or [] + cert_bytes = (certificate.rstrip() + "\n" + "\n".join(item.rstrip() for item in chain) + "\n").encode("ascii") + key_bytes = (private_key.rstrip() + "\n").encode("ascii") + target = Path("secrets/revocation-probe") + target.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="expiry-probe-", dir=target) as temp_dir: + temp = Path(temp_dir) + cert_tmp = temp / "lb-client.expiry.crt" + key_tmp = temp / "lb-client.expiry.key" + cert_tmp.write_bytes(cert_bytes) + key_tmp.write_bytes(key_bytes) + os.replace(cert_tmp, target / "lb-client.expiry.crt") + os.replace(key_tmp, target / "lb-client.expiry.key") + except (OSError, RuntimeError) as exc: + raise SystemExit(f"Expiry probe issuance failed ({type(exc).__name__}): {exc}") from None + print("Issued a two-minute LB identity for the expiry probe; private key was not displayed.") + print("Run security-probe now, then again after the certificate expires (allow about 150 seconds).") + + +if __name__ == "__main__": + main() diff --git a/scripts/postgres-init.sh b/scripts/postgres-init.sh new file mode 100644 index 00000000..f5b032fd --- /dev/null +++ b/scripts/postgres-init.sh @@ -0,0 +1,32 @@ +#!/bin/sh +set -eu + +# Safe to run during fresh initialization or after an interrupted initdb. +# Application roles have no passwords: pg_ident maps their client certificate +# subjects, and pg_hba rejects every non-TLS network connection. +export LAB7_POSTGRES_PASSWORD="$(cat "$POSTGRES_PASSWORD_FILE")" +psql --username "$POSTGRES_USER" --dbname postgres --set=ON_ERROR_STOP=1 <<'SQL' +\getenv lab7_database POSTGRES_DB +\getenv lab7_owner POSTGRES_USER +\getenv lab7_password LAB7_POSTGRES_PASSWORD +SELECT format('CREATE DATABASE %I OWNER %I', :'lab7_database', :'lab7_owner') +WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = :'lab7_database') +\gexec +ALTER ROLE :"lab7_owner" WITH PASSWORD :'lab7_password'; +SQL + +psql --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" --set=ON_ERROR_STOP=1 <<'SQL' +DO $$ +BEGIN + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'messenger_api') THEN + CREATE ROLE messenger_api LOGIN; + END IF; + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'messenger_dispatcher') THEN + CREATE ROLE messenger_dispatcher LOGIN; + END IF; + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'messenger_worker') THEN + CREATE ROLE messenger_worker LOGIN; + END IF; +END +$$; +SQL diff --git a/scripts/renew_leaf.py b/scripts/renew_leaf.py new file mode 100644 index 00000000..1dcbeca6 --- /dev/null +++ b/scripts/renew_leaf.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +"""Issue and atomically stage a replacement leaf; operator recreates its consumers.""" +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import getpass +import os +from pathlib import Path +import subprocess +import tempfile + +from bao_bootstrap import Bao, CLIENT_CERTS, OPENSSL, PKI, SERVER_CERTS + + +ROOT = Path(__file__).resolve().parents[1] +SECRETS = ROOT / "secrets" +IDENTITIES = { + **{role: (cn, names, "server") for role, (cn, names, _kind) in SERVER_CERTS.items()}, + **{role: (cn, [], "client") for role, cn in CLIENT_CERTS.items()}, +} + + +def openssl(args: list[str], step: str) -> bytes: + try: + completed = subprocess.run( + [OPENSSL, *args], check=True, capture_output=True, text=True + ) + return completed.stdout.encode("ascii") + except subprocess.CalledProcessError as exc: + detail = (exc.stderr or "").strip().splitlines() + suffix = f": {detail[-1][:240]}" if detail else "" + raise RuntimeError(f"OpenSSL {step} failed{suffix}") from None + + +def stage(bao: Bao, role: str) -> tuple[Path, Path, str]: + cn, dns_names, kind = IDENTITIES[role] + result = bao.request("POST", f"pki_int/issue/{role}", { + "common_name": cn, + "alt_names": ",".join(dns_names), + "ttl": "6h", + }).get("data", {}) + cert, key = result.get("certificate"), result.get("private_key") + if not cert or not key: + raise RuntimeError("OpenBao did not issue a replacement leaf") + chain = result.get("ca_chain") or [] + certificate = cert.rstrip() + "\n" + "\n".join(item.rstrip() for item in chain) + "\n" + target_cert = PKI / f"{role}.crt" + target_key = PKI / f"{role}.key" + PKI.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="renew-", dir=PKI) as tmp: + candidate_cert = Path(tmp) / "candidate.crt" + candidate_chain = Path(tmp) / "candidate-chain.crt" + candidate_key = Path(tmp) / "candidate.key" + candidate_cert.write_text(cert.rstrip() + "\n", encoding="ascii") + if chain: + candidate_chain.write_text("\n".join(item.rstrip() for item in chain) + "\n", encoding="ascii") + candidate_key.write_text(key.rstrip() + "\n", encoding="ascii") + trust_args = ["verify", "-CAfile", str(PKI / "internal-ca.crt")] + if chain: + trust_args.extend(["-untrusted", str(candidate_chain)]) + openssl([*trust_args, str(candidate_cert)], "certificate-chain verification") + if kind == "server": + openssl(["x509", "-in", str(candidate_cert), "-noout", "-checkhost", cn], "server-name verification") + else: + client_args = ["verify", "-purpose", "sslclient", "-CAfile", str(PKI / "internal-ca.crt")] + if chain: + client_args.extend(["-untrusted", str(candidate_chain)]) + openssl([*client_args, str(candidate_cert)], "client-purpose verification") + cert_public = openssl(["x509", "-in", str(candidate_cert), "-noout", "-pubkey"], "certificate public-key extraction") + key_public = openssl(["pkey", "-in", str(candidate_key), "-pubout"], "private-key match verification") + if cert_public.strip() != key_public.strip(): + raise RuntimeError("replacement private key does not match the issued certificate") + cert_backup = PKI / f"{role}.previous.crt" + key_backup = PKI / f"{role}.previous.key" + candidate_bundle = Path(tmp) / "candidate-bundle.crt" + candidate_bundle.write_text(certificate, encoding="ascii") + if target_cert.exists() and target_key.exists(): + cert_backup.write_bytes(target_cert.read_bytes()) + key_backup.write_bytes(target_key.read_bytes()) + os.replace(candidate_bundle, target_cert) + os.replace(candidate_key, target_key) + return target_cert, target_key, datetime.now(timezone.utc).isoformat() + + +def publish_crl(bao: Bao) -> Path: + intermediate_crl = bao.request_text("pki_int/crl/pem") + if not intermediate_crl.startswith("-----BEGIN X509 CRL-----"): + raise RuntimeError("OpenBao returned an invalid PKI CRL") + root_crl_path = PKI / "root-ca.crl.pem" + if not root_crl_path.is_file(): + raise RuntimeError("Offline root CRL is missing; rerun scripts/bootstrap-local.ps1") + PKI.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="crl-", dir=PKI) as tmp: + root_candidate = Path(tmp) / "root.crl.pem" + intermediate_candidate = Path(tmp) / "intermediate.crl.pem" + candidate = Path(tmp) / "candidate.crl.pem" + root_candidate.write_bytes(root_crl_path.read_bytes()) + intermediate_candidate.write_text(intermediate_crl.rstrip() + "\n", encoding="ascii") + openssl(["crl", "-in", str(root_candidate), "-noout"], "root CRL parsing") + openssl(["crl", "-in", str(intermediate_candidate), "-noout"], "intermediate CRL parsing") + openssl(["crl", "-in", str(root_candidate), "-CAfile", str(PKI / "internal-ca.crt"), "-verify", "-noout"], "root CRL signature verification") + intermediate = PKI / "pki-int.crt" + if not intermediate.is_file(): + raise RuntimeError("OpenBao intermediate certificate is missing; rerun the operator bootstrap") + openssl(["crl", "-in", str(intermediate_candidate), "-CAfile", str(intermediate), "-verify", "-noout"], "intermediate CRL signature verification") + parts = [root_candidate.read_bytes().rstrip(), intermediate_candidate.read_bytes().rstrip()] + rollover_crl = bao.request_text("pki_rollover/crl/pem", allow_missing=True) + if rollover_crl: + rollover_ca = PKI / "pki-rollover.crt" + if not rollover_crl.startswith("-----BEGIN X509 CRL-----") or not rollover_ca.is_file(): + raise RuntimeError("Rollover issuer CRL or certificate is invalid") + rollover_candidate = Path(tmp) / "rollover.crl.pem" + rollover_candidate.write_text(rollover_crl.rstrip() + "\n", encoding="ascii") + openssl(["crl", "-in", str(rollover_candidate), "-noout"], "rollover intermediate CRL parsing") + openssl(["crl", "-in", str(rollover_candidate), "-CAfile", str(rollover_ca), "-verify", "-noout"], "rollover intermediate CRL signature verification") + parts.append(rollover_candidate.read_bytes().rstrip()) + candidate.write_bytes(b"\n".join(parts) + b"\n") + target = PKI / "pki-int.crl.pem" + os.replace(candidate, target) + return PKI / "pki-int.crl.pem" + + +def revoke_previous(bao: Bao, role: str) -> str: + previous_cert = PKI / f"{role}.previous.crt" + previous_key = PKI / f"{role}.previous.key" + if not previous_cert.is_file() or not previous_key.is_file(): + raise RuntimeError(f"No backed-up previous certificate pair exists for {role}") + serial_output = openssl(["x509", "-in", str(previous_cert), "-noout", "-serial"], "previous certificate serial extraction") + serial_line = serial_output.decode("ascii").strip() + if not serial_line.lower().startswith("serial="): + raise RuntimeError("OpenSSL returned no serial for the previous certificate") + serial_hex = serial_line.split("=", 1)[1].strip().replace(":", "") + if not serial_hex or any(char not in "0123456789abcdefABCDEF" for char in serial_hex): + raise RuntimeError("OpenSSL returned a malformed previous certificate serial") + if len(serial_hex) % 2: + serial_hex = "0" + serial_hex + serial = ":".join(serial_hex[index:index + 2].lower() for index in range(0, len(serial_hex), 2)) + current_cert = PKI / f"{role}.crt" + if current_cert.is_file(): + current_serial = openssl(["x509", "-in", str(current_cert), "-noout", "-serial"], "current certificate serial extraction") + if current_serial.decode("ascii").strip().split("=", 1)[-1].replace(":", "").lower() == serial_hex.lower(): + raise RuntimeError("saved previous certificate is also the current certificate; refusing to revoke the active leaf") + issuer_line = openssl(["x509", "-in", str(previous_cert), "-noout", "-issuer", "-nameopt", "RFC2253"], "previous certificate issuer extraction").decode("ascii").strip() + issuer_name = issuer_line.split("=", 1)[-1] + issuer_mount = None + for mount, issuer_file in (("pki_int", PKI / "pki-int.crt"), ("pki_rollover", PKI / "pki-rollover.crt")): + if not issuer_file.is_file(): + continue + subject_line = openssl(["x509", "-in", str(issuer_file), "-noout", "-subject", "-nameopt", "RFC2253"], "issuer subject extraction").decode("ascii").strip() + if subject_line.split("=", 1)[-1] == issuer_name: + issuer_mount = mount + break + if issuer_mount is None: + raise RuntimeError("saved previous certificate issuer does not match a configured intermediate; refusing revocation") + bao.request("POST", issuer_mount + "/revoke", {"serial_number": serial}, include_errors=True) + crl_path = publish_crl(bao) + if role == "lb-client": + probe_dir = SECRETS / "revocation-probe" + probe_dir.mkdir(parents=True, exist_ok=True) + (probe_dir / "lb-client.previous.crt").write_bytes(previous_cert.read_bytes()) + (probe_dir / "lb-client.previous.key").write_bytes(previous_key.read_bytes()) + return serial + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("role", nargs="?", choices=sorted(IDENTITIES)) + parser.add_argument("--all", action="store_true", help="renew every OpenBao-issued leaf") + parser.add_argument("--revoke-previous", action="store_true", help="after renewing one role, revoke its backed-up prior serial and publish the CRL") + parser.add_argument("--revoke-saved-previous", action="store_true", help="revoke a role's already-saved previous certificate without issuing another leaf") + parser.add_argument("--refresh-crl", action="store_true", help="download and validate the current issuer CRL without renewing leaves") + args = parser.parse_args() + if sum((args.all, args.role is not None, args.refresh_crl)) != 1: + parser.error("choose one identity role, --all, or --refresh-crl") + if args.revoke_previous and args.revoke_saved_previous: + parser.error("choose only one revocation mode") + if (args.revoke_previous or args.revoke_saved_previous) and (args.all or args.role is None or args.refresh_crl): + parser.error("a revocation mode requires exactly one identity role") + if args.revoke_previous and not ( + (PKI / f"{args.role}.crt").is_file() and (PKI / f"{args.role}.key").is_file() + ): + parser.error("--revoke-previous requires an existing certificate/key pair to rotate") + if args.revoke_saved_previous and not ( + (PKI / f"{args.role}.previous.crt").is_file() and (PKI / f"{args.role}.previous.key").is_file() + ): + parser.error("--revoke-saved-previous requires an existing saved previous certificate/key pair") + if not (PKI / "internal-ca.crt").is_file(): + raise SystemExit("Run scripts/bootstrap-local.ps1 first") + token = getpass.getpass("OpenBao operator root token (not saved): ") + if not token: + raise SystemExit("An operator token is required") + roles = sorted(IDENTITIES) if args.all else [args.role] + current_role = "OpenBao authentication" + try: + bao = Bao(token) + if args.refresh_crl: + crl = publish_crl(bao) + print(f"Validated current issuer CRL at {crl.name}; no certificates were changed.") + return + for role in roles: + current_role = role + if args.revoke_saved_previous: + serial = revoke_previous(bao, role) + print(f"Revoked saved previous {role} serial {serial}; validated and published pki-int.crl.pem.") + else: + cert, key, issued_at = stage(bao, role) + print(f"Staged replacement for {role} at {issued_at}; files are {cert.name} and {key.name}.") + if args.revoke_previous: + serial = revoke_previous(bao, role) + print(f"Revoked the previous {role} serial {serial}; validated and published pki-int.crl.pem.") + except (RuntimeError, OSError, subprocess.CalledProcessError) as exc: + raise SystemExit(f"Leaf renewal stopped for {current_role}: {exc}; do not recreate consumers yet") from None + if not args.revoke_saved_previous: + print(f"Staged {len(roles)} replacement leaf certificate(s).") + print("Compose file secrets are snapshots: recreate consumers only after all replacements are staged, then verify readiness.") + if not (args.revoke_previous or args.revoke_saved_previous): + print("Previous leaves remain unrevoked. Use one role with --revoke-previous for a revocation experiment.") + + +if __name__ == "__main__": + main() diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..536dfd30 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env sh +set -eu +cd "$(dirname "$0")/.." + +# OpenBao stays running and unsealed; app secrets are fetched again on startup. +# No named volumes are removed or re-created. +if ! docker compose exec -T \ + -e BAO_ADDR=https://127.0.0.1:8200 \ + -e BAO_CACERT=/run/secrets/internal-ca.crt \ + openbao bao status 2>/dev/null | grep -Eq '^Sealed[[:space:]]+false$'; then + echo 'OpenBao is sealed or unreachable; unseal it before restarting application services. Nothing was stopped.' >&2 + exit 1 +fi + +docker compose stop lb api dispatcher worker +docker compose restart db redis broker s3 + +attempt=0 +until docker compose exec -T db pg_isready -U postgres -d messenger >/dev/null 2>&1 \ + && docker compose exec -T redis sh -ec 'REDISCLI_AUTH="$(cat /run/secrets/redis_api_password)" redis-cli --tls --cacert /run/secrets/internal-ca.crt --cert /run/secrets/api-client.crt --key /run/secrets/api-client.key --user api ping | grep -q PONG' >/dev/null 2>&1 \ + && docker compose exec -T broker sh -ec 'REDISCLI_AUTH="$(cat /run/secrets/redis_dispatcher_password)" redis-cli --tls --cacert /run/secrets/internal-ca.crt --cert /run/secrets/dispatcher-client.crt --key /run/secrets/dispatcher-client.key --user messenger-dispatcher ping | grep -q PONG' >/dev/null 2>&1 \ + && docker compose exec -T s3 curl --fail --silent --resolve s3:9000:127.0.0.1 --cacert /run/secrets/internal-ca.crt https://s3:9000/health/ready >/dev/null 2>&1; do + attempt=$((attempt + 1)) + if [ "$attempt" -ge 60 ]; then + echo 'Database, cache, broker, or object store did not become ready within 60 seconds.' >&2 + exit 1 + fi + sleep 1 +done + +docker compose run --rm --no-deps s3-bootstrap +docker compose run --rm --no-deps migrate +# All dependencies were checked or bootstrapped above. Do not let Compose +# restart OpenBao here: a restarted OpenBao seals and makes workloads fail. +docker compose up -d --no-deps dispatcher worker +docker compose up -d --no-deps --scale api=2 api lb diff --git a/scripts/rollover_intermediate.py b/scripts/rollover_intermediate.py new file mode 100644 index 00000000..60b544d9 --- /dev/null +++ b/scripts/rollover_intermediate.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +"""Prepare or activate a new OpenBao intermediate while the old CA remains trusted.""" +from __future__ import annotations + +import argparse +import getpass +import os +from pathlib import Path +import subprocess +import tempfile + +from bao_bootstrap import BAO_ADDR, Bao, CLIENT_CERTS, OPENSSL, PKI, SERVER_CERTS + + +ROOT = Path(__file__).resolve().parents[1] +SECRETS = ROOT / "secrets" +MOUNT = "pki_rollover" +ROLE = "lb-client" + + +def openssl(args: list[str], step: str) -> bytes: + try: + result = subprocess.run([OPENSSL, *args], check=True, capture_output=True, text=True) + return result.stdout.encode("ascii") + except (OSError, subprocess.CalledProcessError) as exc: + detail = "" + if isinstance(exc, subprocess.CalledProcessError) and exc.stderr: + lines = exc.stderr.strip().splitlines() + if lines: + detail = ": " + lines[-1][:240] + raise RuntimeError(f"OpenSSL {step} failed{detail}") from None + + +def prepare_mount(bao: Bao) -> None: + mounts = bao.request("GET", "sys/mounts").get("data", {}) + if MOUNT + "/" not in mounts: + bao.request("POST", "sys/mounts/" + MOUNT, {"type": "pki"}) + bao.request("POST", "sys/mounts/" + MOUNT + "/tune", {"max_lease_ttl": "87600h"}) + issuer = bao.request_text(MOUNT + "/ca/pem", allow_missing=True) + if not issuer: + generated = bao.request("POST", MOUNT + "/intermediate/generate/internal", { + "common_name": "MTUSI Lab7 Rollover Intermediate CA", + "key_type": "rsa", + "key_bits": 4096, + "ttl": "43800h", + }).get("data", {}) + csr = generated.get("csr") + if not csr: + raise RuntimeError("OpenBao did not generate the rollover intermediate CSR") + with tempfile.TemporaryDirectory(prefix="pki-rollover-", dir=PKI) as tmp: + tmp_path = Path(tmp) + csr_path = tmp_path / "rollover.csr" + cert_path = tmp_path / "rollover.crt" + ext_path = tmp_path / "rollover.ext" + csr_path.write_text(csr, encoding="ascii") + ext_path.write_text( + "basicConstraints=critical,CA:TRUE,pathlen:0\n" + "keyUsage=critical,keyCertSign,cRLSign\n" + "subjectKeyIdentifier=hash\n" + "authorityKeyIdentifier=keyid,issuer\n", + encoding="ascii", + ) + openssl([ + "x509", "-req", "-sha256", "-in", str(csr_path), + "-CA", str(PKI / "internal-ca.crt"), + "-CAkey", str(PKI / "internal-ca.key.pem"), + "-CAcreateserial", "-days", "1825", "-extfile", str(ext_path), + "-out", str(cert_path), + ], "offline-root signing of rollover intermediate") + bao.request("POST", MOUNT + "/intermediate/set-signed", { + "certificate": cert_path.read_text(encoding="ascii"), + }) + issuer = bao.request_text(MOUNT + "/ca/pem") + if not issuer.startswith("-----BEGIN CERTIFICATE-----"): + raise RuntimeError("OpenBao returned an invalid rollover intermediate") + (PKI / "pki-rollover.crt").write_text(issuer.rstrip() + "\n", encoding="ascii") + bao.request("POST", MOUNT + "/config/urls", { + "issuing_certificates": f"{BAO_ADDR}/v1/{MOUNT}/ca", + "crl_distribution_points": f"{BAO_ADDR}/v1/{MOUNT}/crl", + }) + + +def configure_roles(bao: Bao) -> None: + identities: dict[str, tuple[str, list[str], str]] = { + **SERVER_CERTS, + **{name: (cn, [], "client") for name, cn in CLIENT_CERTS.items()}, + } + for role, (common_name, dns_names, kind) in identities.items(): + server = kind == "server" + bao.request("POST", f"{MOUNT}/roles/{role}", { + "allowed_domains": sorted(set([common_name, *dns_names])), + "allow_bare_domains": True, + "allow_subdomains": False, + "allow_wildcard_certificates": False, + "enforce_hostnames": True, + "allow_ip_sans": False, + "max_ttl": "12h", + "key_type": "rsa", + "key_bits": 2048, + "server_flag": server, + "client_flag": not server, + "key_usage": ["DigitalSignature", "KeyEncipherment"], + "ext_key_usage": ["ServerAuth"] if server else ["ClientAuth"], + }) + + +def publish_overlap_crl(bao: Bao) -> None: + root_crl_path = PKI / "root-ca.crl.pem" + old_ca = PKI / "pki-int.crt" + new_ca = PKI / "pki-rollover.crt" + if not root_crl_path.is_file() or not old_ca.is_file() or not new_ca.is_file(): + raise RuntimeError("Root or intermediate CA material is missing") + crls = [ + (root_crl_path.read_text(encoding="ascii"), PKI / "internal-ca.crt", "root"), + (bao.request_text("pki_int/crl/pem"), old_ca, "current intermediate"), + (bao.request_text(MOUNT + "/crl/pem"), new_ca, "rollover intermediate"), + ] + with tempfile.TemporaryDirectory(prefix="crl-overlap-", dir=PKI) as tmp: + pieces: list[bytes] = [] + for index, (pem, issuer, label) in enumerate(crls): + if not pem.startswith("-----BEGIN X509 CRL-----"): + raise RuntimeError(f"OpenBao returned an invalid {label} CRL") + path = Path(tmp) / f"crl-{index}.pem" + path.write_text(pem.rstrip() + "\n", encoding="ascii") + openssl(["crl", "-in", str(path), "-CAfile", str(issuer), "-verify", "-noout"], f"{label} CRL signature verification") + pieces.append(path.read_bytes().rstrip()) + candidate = Path(tmp) / "combined.crl.pem" + candidate.write_bytes(b"\n".join(pieces) + b"\n") + os.replace(candidate, PKI / "pki-int.crl.pem") + + +def stage_lb_leaf(bao: Bao) -> None: + issued = bao.request("POST", f"{MOUNT}/issue/{ROLE}", { + "common_name": CLIENT_CERTS[ROLE], + "ttl": "6h", + }).get("data", {}) + certificate, private_key = issued.get("certificate"), issued.get("private_key") + if not certificate or not private_key: + raise RuntimeError("OpenBao did not issue a rollover LB certificate") + chain = issued.get("ca_chain") or [] + combined = certificate.rstrip() + "\n" + "\n".join(item.rstrip() for item in chain) + "\n" + rollover_dir = PKI / "rollover" + rollover_dir.mkdir(parents=True, exist_ok=True) + probe_dir = SECRETS / "revocation-probe" + probe_dir.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="rollover-leaf-", dir=rollover_dir) as tmp: + tmp_path = Path(tmp) + cert = tmp_path / "lb-client.crt" + key = tmp_path / "lb-client.key" + cert.write_text(combined, encoding="ascii") + key.write_text(private_key.rstrip() + "\n", encoding="ascii") + openssl([ + "verify", "-purpose", "sslclient", "-CAfile", str(PKI / "internal-ca.crt"), + "-untrusted", str(PKI / "pki-rollover.crt"), str(cert), + ], "rollover leaf chain verification") + openssl(["x509", "-in", str(cert), "-noout", "-checkhost", CLIENT_CERTS[ROLE]], "rollover leaf identity verification") + cert_target = rollover_dir / "lb-client.crt" + key_target = rollover_dir / "lb-client.key" + os.replace(cert, cert_target) + os.replace(key, key_target) + (probe_dir / "lb-client.rollover.crt").write_bytes((rollover_dir / "lb-client.crt").read_bytes()) + (probe_dir / "lb-client.rollover.key").write_bytes((rollover_dir / "lb-client.key").read_bytes()) + + +def activate_lb_leaf() -> None: + rollover_dir = PKI / "rollover" + source_cert = rollover_dir / "lb-client.crt" + source_key = rollover_dir / "lb-client.key" + current_cert = PKI / "lb-client.crt" + current_key = PKI / "lb-client.key" + if not source_cert.is_file() or not source_key.is_file() or not current_cert.is_file() or not current_key.is_file(): + raise RuntimeError("Staged rollover leaf or current LB pair is missing; run prepare first") + if current_cert.read_bytes() == source_cert.read_bytes() and current_key.read_bytes() == source_key.read_bytes(): + raise RuntimeError("Staged rollover leaf is already active; refusing to overwrite the saved previous pair") + (PKI / "lb-client.previous.crt").write_bytes(current_cert.read_bytes()) + (PKI / "lb-client.previous.key").write_bytes(current_key.read_bytes()) + with tempfile.TemporaryDirectory(prefix="activate-rollover-", dir=PKI) as tmp: + tmp_path = Path(tmp) + cert_tmp = tmp_path / "lb-client.crt" + key_tmp = tmp_path / "lb-client.key" + cert_tmp.write_bytes(source_cert.read_bytes()) + key_tmp.write_bytes(source_key.read_bytes()) + os.replace(cert_tmp, current_cert) + os.replace(key_tmp, current_key) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("prepare", "activate")) + args = parser.parse_args() + if not (PKI / "internal-ca.crt").is_file() or not (PKI / "internal-ca.key.pem").is_file(): + raise SystemExit("Run scripts/bootstrap-local.ps1 first") + try: + if args.action == "prepare": + token = getpass.getpass("OpenBao operator root token (not saved): ") + if not token: + raise SystemExit("An operator token is required") + bao = Bao(token) + prepare_mount(bao) + configure_roles(bao) + publish_overlap_crl(bao) + stage_lb_leaf(bao) + print("Prepared a new offline-root-signed intermediate and a staged LB leaf.") + print("Recreate API first to load both intermediate CRLs; security-probe should accept old and staged LB identities.") + print("Then run action 'activate', recreate LB, revoke saved previous leaf, and recreate API.") + else: + activate_lb_leaf() + print("Activated the staged rollover LB leaf; the previous LB pair remains saved for revocation.") + print("Recreate LB before revoking the saved previous leaf.") + except (OSError, RuntimeError, subprocess.CalledProcessError) as exc: + raise SystemExit(f"Intermediate rollover stopped ({type(exc).__name__}): {exc}") from None + + +if __name__ == "__main__": + main() diff --git a/scripts/scan-images.ps1 b/scripts/scan-images.ps1 new file mode 100644 index 00000000..2275bdf2 --- /dev/null +++ b/scripts/scan-images.ps1 @@ -0,0 +1,39 @@ +$ErrorActionPreference = 'Stop' + +$repo = Split-Path -Parent $PSScriptRoot +$trivy = Get-Command trivy -ErrorAction SilentlyContinue +if (-not $trivy) { throw 'Install Trivy and ensure it is on PATH before running this scan.' } +Push-Location $repo +try { + docker compose build api db bao-renew openbao redis s3 lb grafana + $images = @( + 'mtusi-messenger-lab7-api:local', + 'mtusi-messenger-lab7-bao-renew:local', + 'mtusi-messenger-lab7-openbao:local', + 'mtusi-messenger-lab7-postgres:local', + 'mtusi-messenger-lab7-redis:local', + 'mtusi-messenger-lab7-rustfs:local', + 'mtusi-messenger-lab7-nginx:local', + 'otel/opentelemetry-collector-contrib:0.166.0', + 'prom/prometheus:v3.16.0', + 'grafana/loki:3.6.23', + 'grafana/tempo:2.10.10', + 'mtusi-messenger-lab7-grafana:local' + ) + New-Item -ItemType Directory -Force evidence | Out-Null + $stamp = Get-Date -Format 'yyyyMMdd-HHmmss' + foreach ($image in $images) { + $safe = $image -replace '[^A-Za-z0-9._-]', '_' + $output = Join-Path 'evidence' "trivy-$stamp-$safe.json" + & $trivy.Source image --scanners vuln --severity HIGH,CRITICAL --ignorefile .trivyignore.yaml --show-suppressed --format json --output $output $image + if ($LASTEXITCODE -ne 0) { throw "Trivy could not scan image $image" } + Write-Host "Saved scan: $output" + } + $fsOutput = Join-Path 'evidence' "trivy-$stamp-filesystem.json" + # Dockerfile.example is an intentionally non-runnable teaching outline. + & $trivy.Source fs --scanners vuln,misconfig,secret --skip-dirs .git,.venv,secrets --skip-files Dockerfile.example --format json --output $fsOutput . + if ($LASTEXITCODE -ne 0) { throw 'Trivy could not scan the repository filesystem.' } + Write-Host "Saved scan: $fsOutput" +} finally { + Pop-Location +} diff --git a/scripts/security_negative.py b/scripts/security_negative.py new file mode 100644 index 00000000..6ad5f017 --- /dev/null +++ b/scripts/security_negative.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Run from the Compose security-test profile; never prints credential material.""" +from __future__ import annotations + +import socket +import ssl +from pathlib import Path +import time + + +SECRETS = Path("/run/secrets") + + +def request(host: str, server_name: str, context: ssl.SSLContext, cert: str | None = None, key: str | None = None, *, method: str = "GET", path: str = "/health/ready") -> bytes: + if cert and key: + cert_path = Path(cert) + key_path = Path(key) + context.load_cert_chain( + str(cert_path if cert_path.is_absolute() else SECRETS / cert_path), + str(key_path if key_path.is_absolute() else SECRETS / key_path), + ) + with socket.create_connection((host, 8443), timeout=3) as raw: + with context.wrap_socket(raw, server_hostname=server_name) as tls: + tls.sendall(f"{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Length: 0\r\n\r\n".encode("ascii")) + chunks = [] + while True: + chunk = tls.recv(4096) + if not chunk: + break + chunks.append(chunk) + response = b"".join(chunks) + return response + + +def status_code(response: bytes) -> int: + status = response.split(b"\r\n", 1)[0].split() + if len(status) < 2: + raise RuntimeError("peer returned no HTTP status") + return int(status[1]) + + +def expect_tls_rejection(host: str, server_name: str, *, trusted_ca: bool = False) -> None: + if trusted_ca: + context = ssl.create_default_context(cafile=str(SECRETS / "internal-ca.crt")) + else: + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.verify_mode = ssl.CERT_REQUIRED + context.check_hostname = True + try: + request(host, server_name, context) + except (ssl.SSLError, OSError): + return + raise AssertionError("untrusted TLS server was accepted") + + +def expect_client_certificate_rejection(cert: str | None = None, key: str | None = None) -> int | None: + context = ssl.create_default_context(cafile=str(SECRETS / "internal-ca.crt")) + try: + return status_code(request("api", "api", context, cert, key)) + except (ssl.SSLError, OSError): + return None + + +def main() -> None: + ca = ssl.create_default_context(cafile=str(SECRETS / "internal-ca.crt")) + public_status = status_code(request("lb", "localhost", ca)) + assert public_status == 200, f"trusted public TLS ingress failed with HTTP {public_status}" + expect_tls_rejection("lb", "localhost") + expect_tls_rejection("lb", "wrong-host.invalid", trusted_ca=True) + + no_certificate_status = expect_client_certificate_rejection() + # Nginx may complete TLS and reject the HTTP request with its standard + # 400 response when ssl_verify_client is on. A TLS alert (None) is also a + # valid rejection; a successful or unrelated HTTP response is not. + assert no_certificate_status in (None, 400), ( + f"API did not reject a request without a client certificate (HTTP {no_certificate_status})" + ) + foreign_ca_status = expect_client_certificate_rejection( + "negative-test-client.crt", "negative-test-client.key" + ) + assert foreign_ca_status in (None, 400), ( + "API did not reject a correct-CN certificate from a foreign CA " + f"(HTTP {foreign_ca_status})" + ) + wrong_identity = expect_client_certificate_rejection("prometheus-client.crt", "prometheus-client.key") + assert wrong_identity == 403, f"trusted but unauthorized identity returned {wrong_identity}" + assert expect_client_certificate_rejection("lb-client.crt", "lb-client.key") == 200, "authorized LB identity failed" + + previous_cert = Path("/revocation/lb-client.previous.crt") + previous_key = Path("/revocation/lb-client.previous.key") + if previous_cert.is_file() and previous_key.is_file(): + previous_status = expect_client_certificate_rejection(str(previous_cert), str(previous_key)) + assert previous_status in (None, 400), ( + "API accepted the revoked previous LB certificate " + f"(HTTP {previous_status}); verify the mounted CRL and recreate API" + ) + + expiry_cert = Path("/revocation/lb-client.expiry.crt") + expiry_key = Path("/revocation/lb-client.expiry.key") + if expiry_cert.is_file() and expiry_key.is_file(): + cert_info = ssl._ssl._test_decode_cert(str(expiry_cert)) + still_valid = ssl.cert_time_to_seconds(cert_info["notAfter"]) > time.time() + expiry_status = expect_client_certificate_rejection(str(expiry_cert), str(expiry_key)) + if still_valid: + assert expiry_status == 200, f"short-lived LB certificate failed before expiry (HTTP {expiry_status})" + print("PASS: short-lived LB certificate accepted before expiry") + else: + assert expiry_status in (None, 400), ( + f"API accepted the expired LB certificate (HTTP {expiry_status})" + ) + assert expect_client_certificate_rejection("lb-client.crt", "lb-client.key") == 200, ( + "valid replacement LB identity did not recover after the expiry rejection" + ) + print("PASS: expired LB certificate rejected; current LB identity remains accepted") + + rollover_cert = Path("/revocation/lb-client.rollover.crt") + rollover_key = Path("/revocation/lb-client.rollover.key") + if rollover_cert.is_file() and rollover_key.is_file(): + rollover_status = expect_client_certificate_rejection(str(rollover_cert), str(rollover_key)) + assert rollover_status == 200, ( + f"new-intermediate LB identity was not accepted during overlap (HTTP {rollover_status})" + ) + print("PASS: LB identities signed by old and rollover intermediates are accepted during overlap") + + throttled = [] + for _ in range(20): + throttled.append(request("lb", "localhost", ca, method="POST", path="/api/v1/auth/sessions")) + limited = [response for response in throttled if status_code(response) == 429] + assert limited, "login requests did not reach the 429 rate limit" + assert any(b"retry-after:" in response.lower() for response in limited), "429 response lacks Retry-After" + if previous_cert.is_file() and previous_key.is_file(): + print("PASS: TLS trust, API client CA/identity, revoked prior LB certificate, login 429 and Retry-After") + else: + print("PASS: TLS trust, API client CA/identity, login 429 and Retry-After (no prior revoked LB cert staged)") + + +if __name__ == "__main__": + main() diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..b4d74d4e --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}" + +for container_id in $(docker compose ps -q api); do + hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id") + instance_id=$(printf '%s' "$hostname" | sha256sum | cut -c1-12) + if [[ "$instance_id" == "$TARGET_INSTANCE_ID" ]]; then + docker stop --time 6 "$container_id" >/dev/null + exit 0 + fi +done + +printf 'No running API container matches TARGET_INSTANCE_ID.\n' >&2 +exit 1 diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 31da287d..4d182ba9 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -1,19 +1,38 @@ -# Модель угроз — заполнить +# Модель угроз -## Активы и акторы +## Активы, участники и допущения -TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. +Защищаемые активы: пароли и bearer-сессии пользователей; членство в чатах, сообщения и вложения; содержимое PostgreSQL, Redis и S3; политики и секреты OpenBao; корневой/промежуточный CA и ключи сертификатов; телеметрия. Участники: анонимный внешний клиент, пользователь вне чата, скомпрометированный API/dispatcher/worker, скомпрометированный процесс телеметрии и оператор хоста. Хост Docker и оператор считаются доверенными. Взлом хоста, злонамеренный администратор и кража закрытого ключа root CA не покрываются. ## Границы доверия -TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. +- Клиент → LB: HTTPS, localhost:8443. +- LB → две API-реплики: обязательный mTLS и allowlist identity CN. +- API → PostgreSQL, Redis, RustFS: TLS; отдельные роли и права. +- Dispatcher/worker → Redis Streams: TLS, клиентские сертификаты и Redis ACL. +- API/dispatcher/worker → telemetry gateway: mTLS и проверка разрешенного CN; gateway → OTel Collector: TLS/mTLS. +- API/dispatcher/worker → OpenBao: TLS, cert-аутентификация и scoped KV v2 policy. +- Collector → Prometheus/Loki/Tempo и Grafana → хранилища: TLS/mTLS. -| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | -| --- | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | TODO | +Оператор создает локальный root CA, инициализирует и unseal OpenBao, затем настраивает intermediate и leaf-сертификаты. Закрытый ключ root остается у оператора. Приложения получают короткоживущий сертификат и ограниченный KV token при старте; в окружение процесса попадают только нужные значения. API и worker не могут запросить секреты других сервисов. -На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. +## Пути атаки и контроли -## Lifecycle и инциденты +| Путь атаки | Инвариант | Контроль и проверка | Остаточный риск | +| --- | --- | --- | --- | +| Перехват ingress или подмена сервера | Клиент проверяет сервер | TLS 1.2+, проверка CA и SAN localhost; tests/security.py и security probe проверяют недоверенный CA и неправильное имя | Компрометация локального root CA обходит проверку | +| Прямой вызов API в обход LB | Запрос проходит проверку identity LB | Порт API не опубликован; Nginx API требует mTLS и точный CN messenger-lb; probe проверяет отсутствие сертификата | Администратор Docker-хоста может изменить сети | +| Сертификат другого сервиса предъявлен API | Доверенный CA не дает автоматический доступ | Точный allowlist subject; CA-подписанный prometheus-client должен получить 403 | Безопасность зависит от прав выдачи сертификатов | +| Украденная сессия используется после logout/expiry | Завершенная сессия не авторизует запрос | Bearer token хранится как hash; Redis TTL и удаление при logout; общий login limit; smoke и security probe проверяют logout/expiry и 429/Retry-After | Активная сессия пригодна до logout или expiry | +| Посторонний пользователь подбирает ID сообщения/вложения | Данные видны участникам чата | Проверка членства и прав на вложения; публичный smoke проверяет чужого пользователя и поддельный X-User-Id | Внешний fuzz/penetration тест не выполнялся | +| Worker читает объект вне разрешенного префикса или меняет бизнес-данные | Worker ограничен обработкой очереди | Раздельные S3 policies, DB grants, Redis ACL и собственная OpenBao policy; S3 bootstrap проверяет запрет чтения/записи вне префикса | DB/Redis denial нужно подтвердить на живом стенде | +| Чужой процесс отправляет телеметрию | Ingest доступен только разрешенным сервисам | Изолированная telemetry-ingress сеть, CA и allowlist CN на gateway; проверить без сертификата и с чужим CN | Collector доступен только внутри Compose | +| Компрометированный контейнер использует host/socket или пишет в image | Последствия процесса ограничены | API/worker/dispatcher не от root, read-only FS, tmpfs, no-new-privileges, capabilities сброшены; сверить Compose и скан образов | Stateful образы требуют writable volumes; сканирование еще не выполнялось | +| OpenBao запечатан, секреты недоступны | Нет plaintext/default fallback | TLS и cert auth; процесс завершается при ошибке Bao; проверить пересозданием API во время sealed состояния | Для восстановления нужен операторский unseal; работающий процесс не обновляет KV секреты | +| Старый leaf используется после ротации | Просроченная/отозванная identity блокируется | Leaf имеет ограниченный TTL; требуется заменить секрет, пересоздать процесс, отозвать старый serial и проверить новое соединение | Это испытание трека 2 не выполнено; Compose secrets требуют пересоздания контейнеров | -TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. +## Жизненный цикл и инциденты + +При чистом запуске оператор создает локальные секреты и CA, запускает OpenBao не в dev-mode, выполняет operator init, отдельно хранит threshold shares, делает unseal и запускает bootstrap со скрытым вводом root token. Скрипты не сохраняют token. Обычный рестарт OpenBao требует повторного unseal. При sealed Bao bootstrap приложения завершается отказом; plaintext fallback отсутствует. После unseal оператор пересоздает нужные workload. + +Обновление короткоживущего leaf, отзыв старой identity, пересоздание потребителей, измерение expiry под нагрузкой и rollover CA с временным доверием обоим CA обязательны для трека 5. Нельзя заявлять трек завершенным без повторяемых измерений запросов, ошибок, latency, времени восстановления и проверки отсутствия plaintext fallback. Сканирование образов и зависимостей нужно выполнить и разобрать: версия компонента, применимость, исправление или остаточный риск, повторная проверка. diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 00000000..2f310d5d --- /dev/null +++ b/src/__init__.py @@ -0,0 +1 @@ +"""MTUSI Lab 2 API.""" diff --git a/src/app/__init__.py b/src/app/__init__.py new file mode 100644 index 00000000..2f310d5d --- /dev/null +++ b/src/app/__init__.py @@ -0,0 +1 @@ +"""MTUSI Lab 2 API.""" diff --git a/src/app/db.py b/src/app/db.py new file mode 100644 index 00000000..7e8f85ef --- /dev/null +++ b/src/app/db.py @@ -0,0 +1,73 @@ +import os + +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from sqlalchemy import event +from opentelemetry import trace +from opentelemetry.trace import Status, StatusCode + +from .settings import load_database_url + + +_connect_args = { + "connect_timeout": 3, + "options": "-c statement_timeout=5000", + "sslmode": "verify-full", + "sslrootcert": os.environ.get("DB_TLS_CA_FILE", "/run/secrets/internal-ca.crt"), +} +_client_cert = os.environ.get("DB_TLS_CERT_FILE") +_client_key = os.environ.get("DB_TLS_KEY_FILE") +if bool(_client_cert) != bool(_client_key): + raise RuntimeError("DB_TLS_CERT_FILE and DB_TLS_KEY_FILE must be set together") +if _client_cert and _client_key: + _connect_args.update({"sslcert": _client_cert, "sslkey": _client_key}) + +engine = create_engine( + load_database_url(), + pool_size=5, + max_overflow=5, + pool_timeout=3, + pool_recycle=1800, + pool_pre_ping=True, + # App roles add distinct client certs above; the maintenance migration job + # uses password auth but still verifies PostgreSQL TLS and hostname. + connect_args=_connect_args, +) +SessionLocal = sessionmaker(bind=engine, expire_on_commit=False) + + +@event.listens_for(engine, "before_cursor_execute") +def _trace_sql_start(connection, _cursor, statement, _parameters, _context, _many): + # Record the operation only; SQL parameters and statement contents are omitted. + operation = statement.lstrip().split(None, 1)[0].upper() if statement.strip() else "OTHER" + span = trace.get_tracer("messenger.database").start_span( + f"postgresql {operation}", + attributes={"db.system.name": "postgresql", "db.operation.name": operation}, + ) + scope = trace.use_span(span, end_on_exit=False) + scope.__enter__() + connection.info.setdefault("_otel_db_scopes", []).append((span, scope)) + + +@event.listens_for(engine, "after_cursor_execute") +def _trace_sql_end(connection, *_args): + scopes = connection.info.get("_otel_db_scopes", []) + if scopes: + span, scope = scopes.pop() + scope.__exit__(None, None, None) + span.end() + + +@event.listens_for(engine, "handle_error") +def _trace_sql_error(exception_context): + connection = exception_context.connection + if connection is None: + return + scopes = connection.info.get("_otel_db_scopes", []) + if scopes: + span, scope = scopes.pop() + exc = exception_context.original_exception + span.record_exception(exc) + span.set_status(Status(StatusCode.ERROR)) + scope.__exit__(type(exc), exc, exc.__traceback__) + span.end() diff --git a/src/app/dispatcher.py b/src/app/dispatcher.py new file mode 100644 index 00000000..220b48fd --- /dev/null +++ b/src/app/dispatcher.py @@ -0,0 +1,162 @@ +"""Publish PostgreSQL outbox rows to a persistent Redis Stream.""" +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +import argparse +import logging +import os +import random +import time +import uuid + +from redis import Redis +from sqlalchemy import or_, select + +from .db import SessionLocal +from .models import Attachment, AttachmentJob, JobOutbox +from .settings import load_settings +from .telemetry import add_process_observations, configure, meter +from .telemetry import ENABLED as TELEMETRY_ENABLED, tracer +from opentelemetry import propagate +from opentelemetry.trace import SpanKind + + +settings = load_settings(require_cache=False, require_s3=False) +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") +logger = logging.getLogger("messenger.dispatcher") +configure("messenger-dispatcher") +add_process_observations(role="dispatcher") +dispatch_meter = meter("messenger.jobs") +published_jobs = dispatch_meter.create_counter("messenger.jobs.published", unit="{job}") +broker = Redis.from_url(settings.broker_url, decode_responses=True, socket_connect_timeout=2, socket_timeout=3) + + +def _retry_delay(attempts_in_cycle: int) -> float: + ceiling = min(60.0, 2.0 ** min(attempts_in_cycle, 6)) + return random.uniform(ceiling / 2, ceiling) + + +def recover_expired_leases() -> int: + now = datetime.now(timezone.utc) + recovered = 0 + with SessionLocal.begin() as session: + jobs = session.scalars( + select(AttachmentJob) + .where(AttachmentJob.status == "processing", AttachmentJob.lease_until <= now) + .order_by(AttachmentJob.lease_until) + .limit(100) + .with_for_update(skip_locked=True) + ).all() + for job in jobs: + attachment = session.get(Attachment, job.attachment_id, with_for_update=True) + if job.attempts_in_cycle < job.max_attempts: + job.attempt += 1 + job.attempts_in_cycle += 1 + job.status = "queued" + job.available_at = now + timedelta(seconds=_retry_delay(job.attempts_in_cycle)) + job.lease_until = None + job.last_error_code = "worker_lease_expired" + if attachment is not None: + attachment.status = "queued" + attachment.error_code = None + session.add(JobOutbox(job_id=job.id, attempt=job.attempt)) + else: + job.status = "failed" + job.lease_until = None + job.last_error_code = "retry_exhausted" + job.completed_at = now + if attachment is not None: + attachment.status = "failed" + attachment.error_code = "retry_exhausted" + recovered += 1 + return recovered + + +def dispatch_once(batch_size: int = 50) -> int: + now = datetime.now(timezone.utc) + published = 0 + with SessionLocal.begin() as session: + rows = session.execute( + select(JobOutbox, AttachmentJob) + .join(AttachmentJob, AttachmentJob.id == JobOutbox.job_id) + .where( + or_( + JobOutbox.published_at.is_(None), + JobOutbox.published_at <= now - timedelta(seconds=settings.job_lease_seconds), + ), + JobOutbox.attempt == AttachmentJob.attempt, + AttachmentJob.status == "queued", + AttachmentJob.available_at <= now, + ) + .order_by(JobOutbox.created_at, JobOutbox.id) + .limit(batch_size) + .with_for_update(skip_locked=True, of=JobOutbox) + ).all() + for outbox, job in rows: + attachment = session.get(Attachment, job.attachment_id) + if attachment is None: + outbox.published_at = now + continue + failpoint_attachment = os.environ.get("DISPATCHER_FAILPOINT_ATTACHMENT_ID") + if failpoint_attachment == str(attachment.id): + marker = "lab5:failpoint:before-publish:" + str(attachment.id) + if broker.set(marker, "used", nx=True, ex=86400): + logger.warning("test_failpoint_before_publish attachment_id=%s", attachment.id) + # Raising inside the SQL transaction simulates a dispatcher + # crash after the API commit but before Redis accepts the job. + raise SystemExit(75) + event = { + "schema_version": "1", + "job_id": str(job.id), + "type": "attachment.process.v1", + "attachment_id": str(attachment.id), + "pipeline_version": str(job.pipeline_version), + "attempt": str(job.attempt), + "created_at": now.isoformat(timespec="microseconds").replace("+00:00", "Z"), + } + parent_carrier = {key: value for key, value in { + "traceparent": outbox.traceparent, + "tracestate": outbox.tracestate, + }.items() if value} + parent_context = propagate.extract(parent_carrier) if TELEMETRY_ENABLED else None + if TELEMETRY_ENABLED: + with tracer("messenger.dispatcher").start_as_current_span( + "attachment.publish", context=parent_context, kind=SpanKind.PRODUCER, + attributes={"messaging.system": "redis", "messaging.operation.type": "publish", "messaging.destination.name": "attachment-jobs"}, + ): + propagate.inject(event) + broker.xadd(settings.broker_stream, event) + else: + broker.xadd(settings.broker_stream, event) + # If the process dies after XADD but before this commit, the same + # outbox event is published again. The stable job/effect keys make + # redelivery safe. + outbox.published_at = now + published += 1 + published_jobs.add(1, {"job.type": "attachment.process.v1"}) + return published + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--once", action="store_true", help="run one recovery/dispatch cycle and exit") + args = parser.parse_args() + logger.info("outbox_dispatcher_started stream=%s", settings.broker_stream) + if args.once: + recovered = recover_expired_leases() + published = dispatch_once() + logger.info("outbox_cycle recovered=%s published=%s", recovered, published) + return + while True: + try: + recovered = recover_expired_leases() + published = dispatch_once() + if recovered or published: + logger.info("outbox_cycle recovered=%s published=%s", recovered, published) + except Exception as exc: + logger.warning("outbox_cycle_failed type=%s", type(exc).__name__) + time.sleep(0.5) + + +if __name__ == "__main__": + main() diff --git a/src/app/errors.py b/src/app/errors.py new file mode 100644 index 00000000..ecafd8a6 --- /dev/null +++ b/src/app/errors.py @@ -0,0 +1,23 @@ +from fastapi import Request +from fastapi.responses import JSONResponse + + +class ApiError(Exception): + def __init__(self, code: str, message: str, status: int, challenge: str | None = None): + super().__init__(message) + self.code = code + self.message = message + self.status = status + self.challenge = challenge + + +def error_response(request: Request, code: str, message: str, status: int, challenge: str | None = None): + request_id = getattr(request.state, "request_id", "unknown") + headers = {"X-Request-Id": request_id, "Cache-Control": "no-store"} + if challenge: + headers["WWW-Authenticate"] = challenge + return JSONResponse( + status_code=status, + headers=headers, + content={"error": {"code": code, "message": message, "request_id": request_id}}, + ) diff --git a/src/app/explain_history.py b/src/app/explain_history.py new file mode 100644 index 00000000..81a194c5 --- /dev/null +++ b/src/app/explain_history.py @@ -0,0 +1,71 @@ +"""Create 10,000 disposable rows and record the indexed keyset-page plan.""" +import json +import uuid + +from sqlalchemy import text + +from .db import engine + + +def run() -> None: + user_id = uuid.uuid4() + chat_id = uuid.uuid4() + plan_json = None + with engine.connect() as connection: + transaction = connection.begin() + try: + connection.execute( + text("INSERT INTO users(id, username, display_name, password_hash) " + "VALUES (:id, :username, 'Synthetic plan fixture', 'not-a-login-hash')"), + {"id": user_id, "username": "plan_" + uuid.uuid4().hex[:20]}, + ) + connection.execute( + text("INSERT INTO chats(id, title) VALUES (:id, 'Synthetic plan fixture')"), + {"id": chat_id}, + ) + connection.execute( + text("INSERT INTO chat_members(chat_id, user_id) VALUES (:chat_id, :user_id)"), + {"chat_id": chat_id, "user_id": user_id}, + ) + connection.execute( + text(""" + INSERT INTO messages(id, chat_id, sender_id, text, created_at) + SELECT gen_random_uuid(), :chat_id, :sender_id, + 'synthetic message ' || n::text, + TIMESTAMPTZ '2025-01-01 00:00:00+00' + n * INTERVAL '1 microsecond' + FROM generate_series(1, 10000) AS n + """), + {"chat_id": chat_id, "sender_id": user_id}, + ) + connection.exec_driver_sql("ANALYZE messages") + raw = connection.execute( + text(""" + EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = :chat_id + AND (created_at, id) > (TIMESTAMPTZ '2025-01-01 00:00:00+00', + '00000000-0000-0000-0000-000000000000'::uuid) + ORDER BY created_at, id + LIMIT 50 + """), + {"chat_id": chat_id}, + ).scalar_one() + plan_json = raw if isinstance(raw, list) else json.loads(raw) + finally: + transaction.rollback() + + document = plan_json[0] + + def contains_history_index(node: dict) -> bool: + if node.get("Index Name") == "messages_history_idx": + return True + return any(contains_history_index(child) for child in node.get("Plans", [])) + + if not contains_history_index(document["Plan"]): + raise SystemExit("Planner did not use messages_history_idx; inspect and revise the query/index.") + print(json.dumps(document, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + run() diff --git a/src/app/image_pipeline.py b/src/app/image_pipeline.py new file mode 100644 index 00000000..e85b02a2 --- /dev/null +++ b/src/app/image_pipeline.py @@ -0,0 +1,76 @@ +"""Bounded, deterministic image transformations for attachment pipeline v1.""" +from __future__ import annotations + +from hashlib import sha256 +from io import BytesIO + +from PIL import Image, ImageOps, UnidentifiedImageError + + +class PermanentImageError(Exception): + """An input image cannot be processed; retrying the same bytes will not help.""" + + +def _rgb(image: Image.Image) -> Image.Image: + if image.mode in {"RGBA", "LA"} or "transparency" in image.info: + rgba = image.convert("RGBA") + background = Image.new("RGB", rgba.size, (255, 255, 255)) + background.paste(rgba, mask=rgba.getchannel("A")) + return background + return image.convert("RGB") + + +def _encoded(image: Image.Image, fmt: str, **options) -> bytes: + buffer = BytesIO() + image.save(buffer, format=fmt, **options) + return buffer.getvalue() + + +def process_image(data: bytes, claimed_content_type: str, max_pixels: int, attachment_id: str, pipeline_version: int = 1) -> list[dict]: + """Decode once, apply EXIF orientation, and create the three grade-4 variants.""" + try: + with Image.open(BytesIO(data)) as opened: + actual_type = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(opened.format or "") + if actual_type is None or actual_type != claimed_content_type: + raise PermanentImageError("invalid_image") + width, height = opened.size + if width < 1 or height < 1 or width * height > max_pixels: + raise PermanentImageError("image_too_large") + opened.load() + oriented = ImageOps.exif_transpose(opened) + base = _rgb(oriented) + except PermanentImageError: + raise + except (UnidentifiedImageError, OSError, SyntaxError, ValueError, Image.DecompressionBombError): + raise PermanentImageError("invalid_image") from None + + variants = [] + thumb = base.copy() + thumb.thumbnail((256, 256), Image.Resampling.LANCZOS) + variants.append(("thumbnail", "image/jpeg", "jpg", _encoded(thumb, "JPEG", quality=85, optimize=True))) + del thumb + + crop = ImageOps.fit(base, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)) + variants.append(("crop", "image/jpeg", "jpg", _encoded(crop, "JPEG", quality=85, optimize=True))) + del crop + + optimized = base.copy() + optimized.thumbnail((1280, 1280), Image.Resampling.LANCZOS) + variants.append(("optimized", "image/webp", "webp", _encoded(optimized, "WEBP", quality=82, method=4))) + del optimized, base + + result = [] + for name, content_type, extension, body in variants: + with Image.open(BytesIO(body)) as check: + out_width, out_height = check.size + result.append({ + "name": name, + "content_type": content_type, + "size_bytes": len(body), + "width": out_width, + "height": out_height, + "sha256": sha256(body).hexdigest(), + "object_key": f"variants/v{pipeline_version}/{attachment_id}/{name}.{extension}", + "body": body, + }) + return result diff --git a/src/app/main.py b/src/app/main.py new file mode 100644 index 00000000..edac77bc --- /dev/null +++ b/src/app/main.py @@ -0,0 +1,937 @@ +import base64 +import binascii +import asyncio +from datetime import datetime, timedelta, timezone +from email.message import Message as EmailMessage +import hashlib +import json +import logging +import re +import secrets +import socket +import tempfile +import unicodedata +import uuid + +from argon2 import PasswordHasher, Type +from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError +from fastapi import FastAPI, Header, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse, StreamingResponse +from PIL import Image, UnidentifiedImageError +from botocore.exceptions import BotoCoreError, ClientError +from redis import Redis +from redis.exceptions import RedisError +from sqlalchemy import and_, delete, func, or_, select, text, tuple_, update +from sqlalchemy.dialects.postgresql import insert as pg_insert +from sqlalchemy.exc import DBAPIError, OperationalError, TimeoutError as SQLAlchemyTimeoutError +from starlette.concurrency import run_in_threadpool +from starlette.exceptions import HTTPException as StarletteHTTPException +from opentelemetry import propagate, trace +from opentelemetry.trace import SpanKind, Status, StatusCode + +from .db import SessionLocal, engine +from .errors import ApiError, error_response +from .models import Attachment, AttachmentJob, Chat, ChatMember, IdempotencyRecord, JobOutbox, Message, MessageAttachment, User +from .schemas import ( + AttachmentOut, + ChatOut, + ChatPage, + CreateChat, + CreateMessage, + CreateUser, + Health, + MessageOut, + MessagePage, + SessionOut, + UserOut, +) +from .settings import load_settings +from .storage import s3 +from .telemetry import ENABLED as TELEMETRY_ENABLED, add_process_observations, add_queue_observations, configure, current_trace_headers, meter, operation_span, tracer + +settings = load_settings() + + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s %(message)s", +) +logger = logging.getLogger("messenger.api") +password_hasher = PasswordHasher( + time_cost=2, + memory_cost=19_456, + parallelism=1, + hash_len=32, + salt_len=16, + type=Type.ID, +) +DUMMY_PASSWORD_HASH = password_hasher.hash("dummy-password-for-timing-only") +redis_client = Redis.from_url( + settings.cache_url, + decode_responses=True, + socket_connect_timeout=2, + socket_timeout=2, + health_check_interval=30, +) +_LOGIN_RATE_LIMIT = """ +local value = redis.call('INCR', KEYS[1]) +local ttl = redis.call('TTL', KEYS[1]) +-- Repair counters created by an earlier version without an expiry. +if ttl < 0 then + redis.call('EXPIRE', KEYS[1], ARGV[1]) + ttl = redis.call('TTL', KEYS[1]) +end +return {value, ttl} +""" + +app = FastAPI(title="MTUSI Messenger — Lab 6", version="1.6.0") +configure("messenger-api") +add_process_observations(role="api", db_engine=engine) +add_queue_observations(engine) +http_meter = meter("messenger.http") +http_requests = http_meter.create_counter("messenger.http.server.requests", unit="{request}") +http_duration = http_meter.create_histogram("messenger.http.server.duration", unit="s") + +BEARER_CHALLENGE = 'Bearer realm="messenger"' +BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' +USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$") +TOKEN_RE = re.compile(r"^[A-Za-z0-9_-]{43}$") +IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$", re.ASCII) +# Docker assigns each container a stable hostname equal to its container ID. +# The load balancer forwards this value so tests can prove requests changed replicas. +INSTANCE_ID = hashlib.sha256(socket.gethostname().encode("utf-8")).hexdigest()[:12] +UPLOAD_LIMITER = asyncio.Semaphore(1) + + +def _iso(value: datetime) -> str: + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") + + +def _user_out(user: User) -> dict: + return { + "id": str(user.id), + "username": user.username, + "display_name": user.display_name, + "created_at": _iso(user.created_at), + } + + +def _message_out(message: Message, attachment_ids: list[uuid.UUID | str] | None = None) -> dict: + return { + "id": str(message.id), + "chat_id": str(message.chat_id), + "sender_id": str(message.sender_id), + "text": message.text, + "created_at": _iso(message.created_at), + "attachment_ids": [str(item) for item in (attachment_ids or [])], + } + + +def _attachment_out(attachment: Attachment) -> dict: + public_variants = [ + {key: variant[key] for key in ("name", "content_type", "size_bytes", "width", "height", "sha256")} + for variant in (attachment.variants or []) + ] + return { + "id": str(attachment.id), + "chat_id": str(attachment.chat_id), + "owner_id": str(attachment.owner_id), + "filename": attachment.filename, + "content_type": attachment.content_type, + "size_bytes": attachment.size_bytes, + "sha256": attachment.sha256, + "status": attachment.status, + "variants": public_variants, + "error_code": attachment.error_code, + "created_at": _iso(attachment.created_at), + "updated_at": _iso(attachment.updated_at), + } + + +def _message_attachment_ids(session, message_id: uuid.UUID) -> list[uuid.UUID]: + return session.scalars( + select(MessageAttachment.attachment_id) + .where(MessageAttachment.message_id == message_id) + .order_by(MessageAttachment.position) + ).all() + + +def _validate_image(file_obj, claimed_content_type: str) -> str: + file_obj.seek(0) + try: + with Image.open(file_obj) as image: + detected = { + "PNG": "image/png", + "JPEG": "image/jpeg", + }.get(image.format or "") + if detected is None or detected != claimed_content_type: + raise _api_error("unsupported_media_type", "Формат изображения не поддерживается", 415) + width, height = image.size + if width < 1 or height < 1 or width * height > settings.max_image_pixels: + raise _api_error("payload_too_large", "Размер изображения превышает допустимый предел", 413) + image.verify() + file_obj.seek(0) + with Image.open(file_obj) as image: + image.load() + except ApiError: + raise + except (UnidentifiedImageError, OSError, SyntaxError, ValueError, Image.DecompressionBombError): + raise _api_error("unsupported_media_type", "Изображение повреждено или не поддерживается", 415) from None + finally: + file_obj.seek(0) + return claimed_content_type + + +def _probe_upload(file_obj, claimed_content_type: str) -> str: + """Check the image header and dimensions without decoding pixels in the API.""" + if claimed_content_type == "image/png": + file_obj.seek(0) + png_header = file_obj.read(33) + file_obj.seek(0) + if ( + len(png_header) == 33 + and png_header[:8] == b"\x89PNG\r\n\x1a\n" + and int.from_bytes(png_header[8:12], "big") == 13 + and png_header[12:16] == b"IHDR" + and (binascii.crc32(png_header[12:29]) & 0xFFFFFFFF) + == int.from_bytes(png_header[29:33], "big") + ): + width = int.from_bytes(png_header[16:20], "big") + height = int.from_bytes(png_header[20:24], "big") + if width < 1 or height < 1 or width * height > settings.max_image_pixels: + raise _api_error("payload_too_large", "Размер изображения превышает допустимый предел", 413) + + file_obj.seek(0) + try: + with Image.open(file_obj) as image: + detected = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format or "") + if detected is None or detected != claimed_content_type: + raise _api_error("unsupported_media_type", "Поддерживаются только PNG и JPEG", 415) + width, height = image.size + if width < 1 or height < 1 or width * height > settings.max_image_pixels: + raise _api_error("payload_too_large", "Размер изображения превышает допустимый предел", 413) + # Pillow's verify checks file structure but does not materialize the + # decoded pixel buffer. Full decode and transforms run in the worker. + image.verify() + except ApiError: + raise + except (UnidentifiedImageError, OSError, SyntaxError, ValueError, Image.DecompressionBombError): + raise _api_error("unsupported_media_type", "Изображение повреждено или не поддерживается", 415) from None + finally: + file_obj.seek(0) + return claimed_content_type + + +def _valid_filename(filename: str) -> bool: + if not 1 <= len(filename) <= 255: + return False + if "/" in filename or "\\" in filename: + return False + return not any(unicodedata.category(char) == "Cc" for char in filename) + + +def _is_not_found_s3(exc: ClientError) -> bool: + code = str(exc.response.get("Error", {}).get("Code", "")) + return code in {"404", "NoSuchKey", "NoSuchBucket", "NotFound"} + + +def _chat_out(session, chat: Chat) -> dict: + members = session.scalars( + select(ChatMember.user_id) + .where(ChatMember.chat_id == chat.id) + .order_by(ChatMember.user_id) + ).all() + return { + "id": str(chat.id), + "title": chat.title, + "member_ids": [str(member_id) for member_id in members], + "created_at": _iso(chat.created_at), + } + + +def _api_error(code: str, message: str, status: int, challenge: str | None = None) -> ApiError: + return ApiError(code, message, status, challenge) + + +def _unauthorized(challenge: str = BEARER_CHALLENGE) -> ApiError: + return _api_error("unauthorized", "Нет действительной идентификации", 401, challenge) + + +def _encode_cursor(payload: dict) -> str: + raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8") + return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") + + +def _decode_cursor(value: str) -> dict: + try: + padded = value + ("=" * ((4 - len(value) % 4) % 4)) + raw = base64.b64decode(padded.encode("ascii"), altchars=b"-_", validate=True) + payload = json.loads(raw.decode("utf-8")) + if not isinstance(payload, dict): + raise ValueError("cursor must be an object") + return payload + except (ValueError, UnicodeError, binascii.Error, json.JSONDecodeError) as exc: + raise _api_error("invalid_request", "Неверный cursor", 400) from exc + + +def _cursor_position(payload: dict) -> tuple[datetime, uuid.UUID]: + try: + created_at = datetime.fromisoformat(payload["t"].replace("Z", "+00:00")) + if created_at.tzinfo is None: + raise ValueError("cursor time must include timezone") + item_id = uuid.UUID(payload["i"]) + return created_at.astimezone(timezone.utc), item_id + except (KeyError, TypeError, ValueError, AttributeError) as exc: + raise _api_error("invalid_request", "Неверный cursor", 400) from exc + + +def _session_key(token: str) -> str: + digest = hashlib.sha256(token.encode("ascii")).hexdigest() + return "session:v1:" + digest + + +def _parse_bearer(request: Request) -> str: + header = request.headers.get("authorization", "") + scheme, separator, token = header.partition(" ") + if scheme.lower() != "bearer" or not separator or not TOKEN_RE.fullmatch(token): + raise _unauthorized() + return token + + +def _load_session(token: str) -> dict: + value = redis_client.get(_session_key(token)) + if value is None: + raise _unauthorized() + try: + session = json.loads(value) + user_id = uuid.UUID(session["user_id"]) + expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00")) + if expires_at.tzinfo is None or datetime.now(timezone.utc) >= expires_at: + redis_client.delete(_session_key(token)) + raise _unauthorized() + return {"user_id": user_id, "expires_at": expires_at} + except ApiError: + raise + except (KeyError, TypeError, ValueError, AttributeError, json.JSONDecodeError): + redis_client.delete(_session_key(token)) + raise _unauthorized() from None + + +def _current_user(request: Request) -> tuple[User, str]: + token = _parse_bearer(request) + session_data = _load_session(token) + with SessionLocal() as session: + user = session.get(User, session_data["user_id"]) + if user is None: + redis_client.delete(_session_key(token)) + raise _unauthorized() + return user, token + + +def _parse_basic(header: str) -> tuple[str, str]: + scheme, separator, encoded = header.partition(" ") + if scheme.lower() != "basic" or not separator or not encoded: + raise _unauthorized(BASIC_CHALLENGE) + try: + decoded = base64.b64decode(encoded.encode("ascii"), validate=True).decode("utf-8") + username, password = decoded.split(":", 1) + except (UnicodeError, ValueError, binascii.Error): + raise _unauthorized(BASIC_CHALLENGE) from None + if not USERNAME_RE.fullmatch(username) or not password: + raise _unauthorized(BASIC_CHALLENGE) + return username, password + + +def _password_matches(password_hash: str, password: str) -> bool: + try: + return password_hasher.verify(password_hash, password) + except (VerifyMismatchError, VerificationError, InvalidHashError): + return False + + +def _create_session(username: str, password: str) -> dict: + with SessionLocal.begin() as session: + user = session.scalar(select(User).where(User.username == username)) + stored_hash = user.password_hash if user is not None else DUMMY_PASSWORD_HASH + password_ok = _password_matches(stored_hash, password) + if user is None or not password_ok: + raise _unauthorized(BASIC_CHALLENGE) + # Rehash credentials created by an earlier lab/configuration using the + # current Argon2id parameters after the user proves knowledge of them. + if password_hasher.check_needs_rehash(stored_hash): + user.password_hash = password_hasher.hash(password) + user_payload = _user_out(user) + + expires_at = datetime.now(timezone.utc) + timedelta(seconds=settings.session_ttl_seconds) + for _ in range(3): + token = secrets.token_urlsafe(32) + stored_value = json.dumps( + {"user_id": user_payload["id"], "expires_at": _iso(expires_at)}, + separators=(",", ":"), + ) + if redis_client.set(_session_key(token), stored_value, ex=settings.session_ttl_seconds, nx=True): + return { + "token": token, + "token_type": "Bearer", + "expires_at": _iso(expires_at), + "user": user_payload, + } + logger.error("session_token_collision_limit_reached") + raise _api_error("unavailable", "Сервис временно недоступен", 503) + + +def _get_chat_for_member(session, chat_id: uuid.UUID, user_id: uuid.UUID) -> Chat | None: + return session.scalar( + select(Chat) + .join(ChatMember, ChatMember.chat_id == Chat.id) + .where(Chat.id == chat_id, ChatMember.user_id == user_id) + ) + + +@app.middleware("http") +async def request_metadata_middleware(request: Request, call_next): + request_id = str(uuid.uuid4()) + request.state.request_id = request_id + started = asyncio.get_running_loop().time() + parent = propagate.extract(dict(request.headers)) if TELEMETRY_ENABLED else None + span_context = trace.use_span + span = tracer("messenger.api").start_span( + f"{request.method} request", context=parent, kind=SpanKind.SERVER, + attributes={"http.request.method": request.method}, + ) if TELEMETRY_ENABLED else None + try: + if span is not None: + with span_context(span, end_on_exit=False): + response = await call_next(request) + else: + response = await call_next(request) + except Exception as exc: + logger.error("internal_error request_id=%s type=%s", request_id, type(exc).__name__) + response = error_response(request, "internal_error", "Внутренняя ошибка", 500) + finally: + elapsed = max(0.0, asyncio.get_running_loop().time() - started) + status_code = response.status_code + route = getattr(request.scope.get("route"), "path", "/unmatched") + if span is not None: + span.update_name(f"{request.method} {route}") + span.set_attribute("http.route", route) + span.set_attribute("http.response.status_code", status_code) + if status_code >= 500: + span.set_status(Status(StatusCode.ERROR)) + span.end() + labels = {"http.request.method": request.method, "http.route": route, "http.response.status_class": f"{status_code // 100}xx"} + http_requests.add(1, labels) + http_duration.record(elapsed, labels) + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = INSTANCE_ID + return response + + +@app.exception_handler(ApiError) +async def handle_api_error(request: Request, exc: ApiError): + return error_response(request, exc.code, exc.message, exc.status, exc.challenge) + + +@app.exception_handler(RequestValidationError) +async def handle_validation_error(request: Request, _exc: RequestValidationError): + return error_response(request, "invalid_request", "Неверный запрос", 400) + + +@app.exception_handler(StarletteHTTPException) +async def handle_http_error(request: Request, exc: StarletteHTTPException): + if exc.status_code == 404: + return error_response(request, "not_found", "Объект не найден", 404) + return error_response(request, "invalid_request", "Неверный запрос", 400) + + +@app.exception_handler(OperationalError) +@app.exception_handler(SQLAlchemyTimeoutError) +async def handle_database_unavailable(request: Request, exc: Exception): + logger.warning("database_unavailable request_id=%s type=%s", request.state.request_id, type(exc).__name__) + return error_response(request, "unavailable", "Сервис временно недоступен", 503) + + +@app.exception_handler(RedisError) +async def handle_cache_unavailable(request: Request, exc: RedisError): + logger.warning("session_store_unavailable request_id=%s type=%s", request.state.request_id, type(exc).__name__) + return error_response(request, "unavailable", "Сервис временно недоступен", 503) + + +@app.exception_handler(ClientError) +@app.exception_handler(BotoCoreError) +async def handle_object_store_unavailable(request: Request, exc: Exception): + logger.warning("object_store_unavailable request_id=%s type=%s", request.state.request_id, type(exc).__name__) + return error_response(request, "unavailable", "Сервис временно недоступен", 503) + + +@app.exception_handler(DBAPIError) +async def handle_database_error(request: Request, exc: DBAPIError): + if exc.connection_invalidated: + logger.warning("database_connection_lost request_id=%s", request.state.request_id) + return error_response(request, "unavailable", "Сервис временно недоступен", 503) + logger.error("database_error request_id=%s type=%s", request.state.request_id, type(exc).__name__) + return error_response(request, "internal_error", "Внутренняя ошибка", 500) + + +@app.exception_handler(Exception) +async def handle_unexpected_error(request: Request, exc: Exception): + logger.error("internal_error request_id=%s type=%s", request.state.request_id, type(exc).__name__) + return error_response(request, "internal_error", "Внутренняя ошибка", 500) + + +@app.get("/health/live", response_model=Health) +def live(): + return {"status": "ok"} + + +@app.get("/health/ready", response_model=Health, responses={503: {"description": "Dependency unavailable"}}) +def ready(): + with SessionLocal() as session: + session.execute(text("SELECT 1")) + redis_client.ping() + s3.get_bucket_location(Bucket=settings.s3_bucket) + return {"status": "ok"} + + +@app.post("/api/v1/users", response_model=UserOut, status_code=201) +def register_user(payload: CreateUser): + password_hash = password_hasher.hash(payload.password) + user = User(username=payload.username, display_name=payload.display_name, password_hash=password_hash) + try: + with SessionLocal.begin() as session: + session.add(user) + session.flush() + except DBAPIError as exc: + if getattr(getattr(exc, "orig", None), "sqlstate", None) == "23505": + raise _api_error("conflict", "username занят", 409) from exc + raise + return _user_out(user) + + +@app.post("/api/v1/auth/sessions", response_model=SessionOut, status_code=201) +async def create_session(request: Request): + # The only network peer is the LB mTLS listener. It overwrites X-Forwarded-For + # with the socket peer, and Uvicorn trusts forwarded headers only from the + # local API Nginx process. Redis then shares this per-client counter across replicas. + source = request.client.host if request.client else "unknown" + bucket = hashlib.sha256(source.encode("utf-8", errors="replace")).hexdigest() + count, ttl = redis_client.eval(_LOGIN_RATE_LIMIT, 1, "login:v1:" + bucket, 60) + if int(count) > settings.login_rate_limit_per_minute: + retry_after = max(1, int(ttl)) + return JSONResponse( + status_code=429, + headers={"Retry-After": str(retry_after), "Cache-Control": "no-store"}, + content={"error": {"code": "rate_limited", "message": "Слишком много попыток входа", "request_id": getattr(request.state, "request_id", "unknown")}}, + ) + if await request.body(): + raise _api_error("invalid_request", "Basic authentication must not include a body", 400) + username, password = _parse_basic(request.headers.get("authorization", "")) + return await run_in_threadpool(_create_session, username, password) + + +@app.delete("/api/v1/auth/sessions/current", status_code=204) +def revoke_session(request: Request): + _user, token = _current_user(request) + redis_client.delete(_session_key(token)) + return None + + +@app.get("/api/v1/users/me", response_model=UserOut) +def current_user(request: Request): + user, _token = _current_user(request) + return _user_out(user) + + +@app.post("/api/v1/chats", response_model=ChatOut, status_code=201) +def create_chat(payload: CreateChat, request: Request): + user, _token = _current_user(request) + member_ids = [uuid.UUID(value) for value in payload.member_ids] + if user.id not in member_ids: + raise _api_error("invalid_request", "Вызывающий должен входить в member_ids", 400) + + try: + with SessionLocal.begin() as session: + chat = Chat(title=payload.title) + session.add(chat) + session.flush() + session.add_all(ChatMember(chat_id=chat.id, user_id=member_id) for member_id in member_ids) + session.flush() + result = _chat_out(session, chat) + except DBAPIError as exc: + if getattr(getattr(exc, "orig", None), "sqlstate", None) in {"23503", "23505"}: + raise _api_error("invalid_request", "Неизвестный участник", 400) from exc + raise + return result + + +@app.get("/api/v1/chats", response_model=ChatPage) +def list_chats(request: Request, limit: int = 50, cursor: str | None = None): + user, _token = _current_user(request) + if limit < 1 or limit > 100: + raise _api_error("invalid_request", "limit вне диапазона", 400) + statement = ( + select(Chat) + .join(ChatMember, ChatMember.chat_id == Chat.id) + .where(ChatMember.user_id == user.id) + .order_by(Chat.created_at, Chat.id) + ) + if cursor is not None: + payload = _decode_cursor(cursor) + if payload.get("u") != str(user.id): + raise _api_error("invalid_request", "Неверный cursor", 400) + created_at, chat_id = _cursor_position(payload) + statement = statement.where(tuple_(Chat.created_at, Chat.id) > tuple_(created_at, chat_id)) + + with SessionLocal() as session: + chats = session.scalars(statement.limit(limit + 1)).all() + has_more = len(chats) > limit + page = chats[:limit] + items = [_chat_out(session, chat) for chat in page] + next_cursor = None + if has_more: + last = page[-1] + next_cursor = _encode_cursor({"u": str(user.id), "t": _iso(last.created_at), "i": str(last.id)}) + return {"items": items, "next_cursor": next_cursor} + + +@app.get("/api/v1/chats/{chat_id}", response_model=ChatOut) +def get_chat(chat_id: uuid.UUID, request: Request): + user, _token = _current_user(request) + with SessionLocal() as session: + chat = _get_chat_for_member(session, chat_id, user.id) + if chat is None: + raise _api_error("not_found", "Объект не найден", 404) + return _chat_out(session, chat) + + +@app.post("/api/v1/chats/{chat_id}/messages", response_model=MessageOut, status_code=201) +def create_message( + chat_id: uuid.UUID, + payload: CreateMessage, + request: Request, + idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"), +): + user, _token = _current_user(request) + if idempotency_key is None or not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key): + raise _api_error("invalid_request", "Нужен корректный Idempotency-Key", 400) + if not payload.text.strip() and not payload.attachment_ids: + raise _api_error("invalid_request", "Сообщение не может состоять только из пробелов", 400) + + # Hash the validated semantic JSON, not the raw bytes, so whitespace and + # object key order do not change the identity of a request. + canonical_body = json.dumps( + {"text": payload.text, "attachment_ids": payload.attachment_ids}, + ensure_ascii=False, sort_keys=True, separators=(",", ":"), + ) + body_hash = hashlib.sha256(canonical_body.encode("utf-8")).hexdigest() + legacy_hash = hashlib.sha256( + json.dumps({"text": payload.text}, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + path = request.url.path + now = datetime.now(timezone.utc) + expires_at = now + timedelta(hours=24) + scope = ( + IdempotencyRecord.user_id == user.id, + IdempotencyRecord.method == "POST", + IdempotencyRecord.path == path, + IdempotencyRecord.idempotency_key == idempotency_key, + ) + + with SessionLocal.begin() as session: + chat = _get_chat_for_member(session, chat_id, user.id) + if chat is None: + raise _api_error("not_found", "Объект не найден", 404) + attachment_ids = [uuid.UUID(value) for value in payload.attachment_ids] + if attachment_ids: + attached = session.scalars( + select(Attachment).where( + Attachment.chat_id == chat_id, + Attachment.id.in_(attachment_ids), + ) + ).all() + if len(attached) != len(attachment_ids): + raise _api_error("not_found", "Объект не найден", 404) + if any(item.status == "failed" for item in attached): + raise _api_error("conflict", "Вложение не удалось обработать", 409) + + # A key becomes reusable only after its 24-hour retention window. + session.execute(delete(IdempotencyRecord).where(*scope, IdempotencyRecord.expires_at <= now)) + insert_record = ( + pg_insert(IdempotencyRecord) + .values( + user_id=user.id, + method="POST", + path=path, + idempotency_key=idempotency_key, + request_hash=body_hash, + response_body={}, + expires_at=expires_at, + ) + .on_conflict_do_nothing(constraint="idempotency_records_scope_key_uq") + .returning(IdempotencyRecord.id) + ) + record_id = session.execute(insert_record).scalar_one_or_none() + + if record_id is None: + # A concurrent insert waits on the unique constraint. At READ + # COMMITTED the winning transaction is visible to this SELECT. + existing = session.scalar(select(IdempotencyRecord).where(*scope)) + if existing is None: + raise _api_error("unavailable", "Сервис временно недоступен", 503) + if existing.request_hash != body_hash and not (not attachment_ids and existing.request_hash == legacy_hash): + raise _api_error("conflict", "Idempotency-Key уже использован для другого запроса", 409) + result = dict(existing.response_body) + result.setdefault("attachment_ids", []) + else: + message = Message(chat_id=chat_id, sender_id=user.id, text=payload.text) + session.add(message) + session.flush() + session.add_all( + MessageAttachment( + message_id=message.id, + attachment_id=attachment_id, + chat_id=chat_id, + position=position, + ) + for position, attachment_id in enumerate(attachment_ids) + ) + result = _message_out(message, attachment_ids) + session.execute( + update(IdempotencyRecord) + .where(IdempotencyRecord.id == record_id) + .values(response_body=result) + ) + return result + + +@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage) +def list_messages(chat_id: uuid.UUID, request: Request, limit: int = 50, cursor: str | None = None): + user, _token = _current_user(request) + with SessionLocal() as session: + chat = _get_chat_for_member(session, chat_id, user.id) + if chat is None: + raise _api_error("not_found", "Объект не найден", 404) + if limit < 1 or limit > 100: + raise _api_error("invalid_request", "limit вне диапазона", 400) + after = None + if cursor is not None: + payload = _decode_cursor(cursor) + if payload.get("c") != str(chat_id): + raise _api_error("invalid_request", "cursor от другого чата", 400) + after = _cursor_position(payload) + statement = select(Message).where(Message.chat_id == chat_id) + if after is not None: + statement = statement.where(tuple_(Message.created_at, Message.id) > tuple_(*after)) + statement = statement.order_by(Message.created_at, Message.id).limit(limit + 1) + rows = session.scalars(statement).all() + has_more = len(rows) > limit + page = rows[:limit] + attachment_rows = session.execute( + select(MessageAttachment.message_id, MessageAttachment.attachment_id) + .where(MessageAttachment.message_id.in_([message.id for message in page])) + .order_by(MessageAttachment.message_id, MessageAttachment.position) + ).all() if page else [] + ids_by_message: dict[uuid.UUID, list[uuid.UUID]] = {} + for message_id, attachment_id in attachment_rows: + ids_by_message.setdefault(message_id, []).append(attachment_id) + items = [_message_out(message, ids_by_message.get(message.id, [])) for message in page] + + next_cursor = None + if has_more: + last = page[-1] + next_cursor = _encode_cursor({"c": str(chat_id), "t": _iso(last.created_at), "i": str(last.id)}) + return {"items": items, "next_cursor": next_cursor} + + +@app.post( + "/api/v1/chats/{chat_id}/attachments", + response_model=AttachmentOut, + status_code=202, +) +async def upload_attachment( + chat_id: uuid.UUID, + request: Request, + filename: str, +): + user, _token = _current_user(request) + with SessionLocal() as session: + if _get_chat_for_member(session, chat_id, user.id) is None: + raise _api_error("not_found", "Объект не найден", 404) + + if not _valid_filename(filename): + raise _api_error("invalid_request", "Неверное имя файла", 400) + content_type_header = request.headers.get("content-type", "") + header = EmailMessage() + try: + header["Content-Type"] = content_type_header + claimed_type = header.get_content_type().lower() + except (TypeError, ValueError): + claimed_type = "" + if claimed_type not in {"image/png", "image/jpeg"}: + raise _api_error("unsupported_media_type", "Поддерживаются только PNG и JPEG", 415) + content_length = request.headers.get("content-length") + if content_length is not None: + try: + if int(content_length) > settings.max_upload_bytes: + raise _api_error("payload_too_large", "Файл превышает допустимый размер", 413) + except ValueError: + raise _api_error("invalid_request", "Неверный Content-Length", 400) from None + + async with UPLOAD_LIMITER: + with tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b", dir="/tmp") as temporary: + size_bytes = 0 + digest = hashlib.sha256() + async for chunk in request.stream(): + if not chunk: + continue + size_bytes += len(chunk) + if size_bytes > settings.max_upload_bytes: + raise _api_error("payload_too_large", "Файл превышает допустимый размер", 413) + digest.update(chunk) + temporary.write(chunk) + if size_bytes == 0: + raise _api_error("unsupported_media_type", "Файл пуст", 415) + + detected_type = await run_in_threadpool(_probe_upload, temporary, claimed_type) + attachment_id = uuid.uuid4() + object_key = f"originals/{attachment_id.hex}/original" + staging_key = f"staging/{attachment_id.hex}/original" + temporary.seek(0) + try: + with operation_span("s3.put_object.staging", **{"db.system.name": "s3", "server.address": "s3"}): + await run_in_threadpool( + s3.put_object, + Bucket=settings.s3_bucket, + Key=staging_key, + Body=temporary, + ContentLength=size_bytes, + ContentType=detected_type, + Metadata={"sha256": digest.hexdigest()}, + ) + except (ClientError, BotoCoreError): + try: + await run_in_threadpool(s3.delete_object, Bucket=settings.s3_bucket, Key=staging_key) + except Exception as cleanup_exc: + logger.warning( + "attachment_compensation_failed request_id=%s type=%s", + request.state.request_id, + type(cleanup_exc).__name__, + ) + raise _api_error("unavailable", "Сервис временно недоступен", 503) from None + + with SessionLocal.begin() as session: + attachment = Attachment( + id=attachment_id, + chat_id=chat_id, + owner_id=user.id, + filename=filename, + content_type=detected_type, + size_bytes=size_bytes, + sha256=digest.hexdigest(), + status="queued", + variants=[], + error_code=None, + object_key=object_key, + staging_key=staging_key, + ) + session.add(attachment) + job = AttachmentJob( + id=uuid.uuid4(), + attachment_id=attachment_id, + pipeline_version=1, + attempt=1, + max_attempts=settings.job_max_attempts, + status="queued", + available_at=datetime.now(timezone.utc), + ) + session.add(job) + session.flush() + trace_headers = current_trace_headers() + session.add(JobOutbox( + job_id=job.id, + attempt=1, + traceparent=trace_headers.get("traceparent"), + tracestate=trace_headers.get("tracestate"), + )) + session.flush() + result = _attachment_out(attachment) + return result + + +@app.get("/api/v1/attachments/{attachment_id}", response_model=AttachmentOut) +def get_attachment(attachment_id: uuid.UUID, request: Request): + user, _token = _current_user(request) + with SessionLocal() as session: + attachment = session.scalar( + select(Attachment) + .join(ChatMember, ChatMember.chat_id == Attachment.chat_id) + .where(Attachment.id == attachment_id, ChatMember.user_id == user.id) + ) + if attachment is None: + raise _api_error("not_found", "Объект не найден", 404) + return _attachment_out(attachment) + + +@app.get("/api/v1/attachments/{attachment_id}/content") +async def download_attachment( + attachment_id: uuid.UUID, + request: Request, + variant: str = "original", +): + user, _token = _current_user(request) + with SessionLocal() as session: + attachment = session.scalar( + select(Attachment) + .join(ChatMember, ChatMember.chat_id == Attachment.chat_id) + .where(Attachment.id == attachment_id, ChatMember.user_id == user.id) + ) + if attachment is None: + raise _api_error("not_found", "Объект не найден", 404) + if attachment.status != "ready": + raise _api_error("conflict", "Вложение ещё не готово", 409) + if variant == "original": + object_key = attachment.object_key + content_type = attachment.content_type + size_bytes = attachment.size_bytes + else: + selected = next((item for item in (attachment.variants or []) if item.get("name") == variant), None) + if selected is None: + raise _api_error("not_found", "Объект не найден", 404) + object_key = selected["object_key"] + content_type = selected["content_type"] + size_bytes = selected["size_bytes"] + + try: + stored = await run_in_threadpool(s3.get_object, Bucket=settings.s3_bucket, Key=object_key) + except ClientError as exc: + if _is_not_found_s3(exc): + logger.error("attachment_object_missing request_id=%s", request.state.request_id) + raise _api_error("unavailable", "Сервис временно недоступен", 503) from None + raise _api_error("unavailable", "Сервис временно недоступен", 503) from None + except BotoCoreError: + raise _api_error("unavailable", "Сервис временно недоступен", 503) from None + + body = stored["Body"] + + async def chunks(): + try: + while True: + chunk = await run_in_threadpool(body.read, 64 * 1024) + if not chunk: + break + yield chunk + finally: + await run_in_threadpool(body.close) + + return StreamingResponse( + chunks(), + media_type=content_type, + headers={ + "Content-Length": str(size_bytes), + "Cache-Control": "private, no-store", + "X-Content-Type-Options": "nosniff", + }, + ) diff --git a/src/app/migrate.py b/src/app/migrate.py new file mode 100644 index 00000000..48c83839 --- /dev/null +++ b/src/app/migrate.py @@ -0,0 +1,36 @@ +from pathlib import Path + +from sqlalchemy import text + +from .db import engine + + +MIGRATIONS = Path(__file__).resolve().parents[2] / "migrations" + + +def migrate() -> None: + with engine.begin() as connection: + connection.exec_driver_sql("SELECT pg_advisory_xact_lock(2026102202)") + connection.exec_driver_sql( + "CREATE TABLE IF NOT EXISTS schema_migrations " + "(version VARCHAR(128) PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP)" + ) + applied = set(connection.execute(text("SELECT version FROM schema_migrations")).scalars()) + for path in sorted(MIGRATIONS.glob("*.sql")): + version = path.stem + if version in applied: + continue + sql = path.read_text(encoding="utf-8") + for statement in sql.split(";"): + if statement.strip(): + connection.exec_driver_sql(statement) + connection.execute( + text("INSERT INTO schema_migrations(version) VALUES (:version)"), + {"version": version}, + ) + print(f"Applied migration {version}") + engine.dispose() + + +if __name__ == "__main__": + migrate() diff --git a/src/app/models.py b/src/app/models.py new file mode 100644 index 00000000..8f5bbbce --- /dev/null +++ b/src/app/models.py @@ -0,0 +1,211 @@ +import uuid +from datetime import datetime + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, ForeignKeyConstraint, Index, Integer, String, Text, UniqueConstraint, func +from sqlalchemy.dialects.postgresql import JSONB, UUID +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + + +class Base(DeclarativeBase): + pass + + +class User(Base): + __tablename__ = "users" + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + username: Mapped[str] = mapped_column(String(32), nullable=False, unique=True) + display_name: Mapped[str] = mapped_column(String(100), nullable=False) + password_hash: Mapped[str] = mapped_column(Text, nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) + + +class Chat(Base): + __tablename__ = "chats" + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + title: Mapped[str] = mapped_column(String(100), nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) + + +class ChatMember(Base): + __tablename__ = "chat_members" + __table_args__ = ( + Index("chat_members_user_id_idx", "user_id", "chat_id"), + ) + + chat_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True + ) + user_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("users.id", ondelete="RESTRICT"), primary_key=True + ) + + +class Message(Base): + __tablename__ = "messages" + __table_args__ = ( + ForeignKeyConstraint( + ["chat_id", "sender_id"], + ["chat_members.chat_id", "chat_members.user_id"], + name="messages_sender_is_chat_member_fk", + ondelete="CASCADE", + ), + UniqueConstraint("id", "chat_id", name="messages_id_chat_id_uq"), + Index("messages_history_idx", "chat_id", "created_at", "id"), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) + sender_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) + text: Mapped[str] = mapped_column(String(4000), nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) + + +class IdempotencyRecord(Base): + """Shared, transactional result cache for retried message POST requests.""" + + __tablename__ = "idempotency_records" + __table_args__ = ( + UniqueConstraint( + "user_id", "method", "path", "idempotency_key", + name="idempotency_records_scope_key_uq", + ), + Index("idempotency_records_expires_at_idx", "expires_at"), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + user_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False + ) + method: Mapped[str] = mapped_column(String(8), nullable=False) + path: Mapped[str] = mapped_column(String(200), nullable=False) + idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False) + request_hash: Mapped[str] = mapped_column(String(64), nullable=False) + response_body: Mapped[dict] = mapped_column(JSONB, nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) + expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + + +class Attachment(Base): + __tablename__ = "attachments" + __table_args__ = ( + ForeignKeyConstraint( + ["chat_id", "owner_id"], + ["chat_members.chat_id", "chat_members.user_id"], + name="attachments_owner_is_chat_member_fk", + ondelete="CASCADE", + ), + UniqueConstraint("id", "chat_id", name="attachments_id_chat_id_uq"), + CheckConstraint("char_length(filename) BETWEEN 1 AND 255", name="attachments_filename_length_ck"), + CheckConstraint("content_type IN ('image/png', 'image/jpeg')", name="attachments_content_type_ck"), + CheckConstraint("size_bytes BETWEEN 1 AND 10485760", name="attachments_size_bytes_ck"), + CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="attachments_sha256_ck"), + CheckConstraint("status IN ('queued', 'processing', 'ready', 'failed')", name="attachments_status_ck"), + Index("attachments_chat_created_idx", "chat_id", "created_at", "id"), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) + owner_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) + filename: Mapped[str] = mapped_column(String(255), nullable=False) + content_type: Mapped[str] = mapped_column(String(32), nullable=False) + size_bytes: Mapped[int] = mapped_column(Integer, nullable=False) + sha256: Mapped[str] = mapped_column(String(64), nullable=False) + status: Mapped[str] = mapped_column(String(16), nullable=False, default="ready") + variants: Mapped[list] = mapped_column(JSONB, nullable=False, default=list, server_default="[]") + error_code: Mapped[str | None] = mapped_column(String(64), nullable=True) + object_key: Mapped[str] = mapped_column(Text, nullable=False, unique=True) + staging_key: Mapped[str | None] = mapped_column(Text, nullable=True, unique=True) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()) + + +class AttachmentJob(Base): + """One logical image pipeline; broker deliveries are only wake-up signals.""" + + __tablename__ = "attachment_jobs" + __table_args__ = ( + UniqueConstraint("attachment_id", name="attachment_jobs_attachment_uq"), + CheckConstraint("attempt >= 1", name="attachment_jobs_attempt_ck"), + CheckConstraint("max_attempts BETWEEN 1 AND 20", name="attachment_jobs_max_attempts_ck"), + CheckConstraint("attempts_in_cycle BETWEEN 1 AND max_attempts", name="attachment_jobs_cycle_attempt_ck"), + CheckConstraint("status IN ('queued', 'processing', 'succeeded', 'failed')", name="attachment_jobs_status_ck"), + Index("attachment_jobs_due_idx", "status", "available_at"), + Index("attachment_jobs_lease_idx", "status", "lease_until"), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + attachment_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("attachments.id", ondelete="CASCADE"), nullable=False + ) + pipeline_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1) + attempt: Mapped[int] = mapped_column(Integer, nullable=False, default=1) + attempts_in_cycle: Mapped[int] = mapped_column(Integer, nullable=False, default=1) + max_attempts: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(String(16), nullable=False, default="queued") + available_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) + lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + last_error_code: Mapped[str | None] = mapped_column(String(64), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()) + completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + + +class JobOutbox(Base): + """Transactional intent to publish a logical job attempt to Redis Streams.""" + + __tablename__ = "job_outbox" + __table_args__ = ( + UniqueConstraint("job_id", "attempt", name="job_outbox_job_attempt_uq"), + Index("job_outbox_pending_idx", "published_at", "created_at"), + ) + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + job_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("attachment_jobs.id", ondelete="CASCADE"), nullable=False + ) + attempt: Mapped[int] = mapped_column(Integer, nullable=False) + traceparent: Mapped[str | None] = mapped_column(String(128), nullable=True) + tracestate: Mapped[str | None] = mapped_column(String(512), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) + published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + + +class JobReplayAudit(Base): + """Operator initiated replay history; replay never creates a second job.""" + + __tablename__ = "job_replay_audit" + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + job_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("attachment_jobs.id", ondelete="CASCADE"), nullable=False + ) + previous_attempt: Mapped[int] = mapped_column(Integer, nullable=False) + new_attempt: Mapped[int] = mapped_column(Integer, nullable=False) + operator: Mapped[str] = mapped_column(String(100), nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) + + +class MessageAttachment(Base): + __tablename__ = "message_attachments" + __table_args__ = ( + ForeignKeyConstraint( + ["message_id", "chat_id"], + ["messages.id", "messages.chat_id"], + name="message_attachments_message_chat_fk", + ondelete="CASCADE", + ), + ForeignKeyConstraint( + ["attachment_id", "chat_id"], + ["attachments.id", "attachments.chat_id"], + name="message_attachments_attachment_chat_fk", + ondelete="CASCADE", + ), + UniqueConstraint("message_id", "position", name="message_attachments_position_uq"), + Index("message_attachments_attachment_idx", "attachment_id"), + ) + + message_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + attachment_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False) + position: Mapped[int] = mapped_column(Integer, nullable=False) diff --git a/src/app/reconcile_s3_orphans.py b/src/app/reconcile_s3_orphans.py new file mode 100644 index 00000000..fefa1e63 --- /dev/null +++ b/src/app/reconcile_s3_orphans.py @@ -0,0 +1,97 @@ +"""Dry-run-first cleanup of unknown S3 objects and expired staging sources.""" +import argparse +from datetime import datetime, timedelta, timezone +import os + +import boto3 +from botocore.config import Config +from sqlalchemy import select + +from .db import SessionLocal +from .models import Attachment +from .settings import _secret + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--apply", action="store_true", help="delete confirmed stale objects; default is dry-run") + args = parser.parse_args() + endpoint = os.environ.get("S3_ENDPOINT", "https://s3:9000").rstrip("/") + if not endpoint.startswith("https://") and os.environ.get("APP_ENV", "lab").lower() != "test": + raise SystemExit("cleanup requires verified HTTPS outside explicit test mode") + region = os.environ.get("S3_REGION", "us-east-1") + bucket = os.environ.get("S3_BUCKET", "messenger-attachments") + try: + grace_seconds = int(os.environ.get("ORPHAN_GRACE_SECONDS", "86400")) + staging_retention = int(os.environ.get("STAGING_RETENTION_SECONDS", "86400")) + except ValueError as exc: + raise SystemExit("cleanup retention settings must be integers") from exc + if grace_seconds < 3600 or staging_retention < 3600: + raise SystemExit("cleanup grace/retention must be at least 3600 seconds") + + client = boto3.client( + "s3", + endpoint_url=endpoint, + region_name=region, + aws_access_key_id=_secret("S3_ROOT_ACCESS_KEY_FILE", "S3_ROOT_ACCESS_KEY"), + aws_secret_access_key=_secret("S3_ROOT_SECRET_ACCESS_KEY_FILE", "S3_ROOT_SECRET_ACCESS_KEY"), + verify=os.environ.get("S3_CA_FILE", "/run/secrets/internal-ca.crt"), + config=Config(connect_timeout=2, read_timeout=5, retries={"total_max_attempts": 1}, s3={"addressing_style": "path"}), + ) + with SessionLocal() as session: + attachments = session.scalars(select(Attachment)).all() + known_keys = set() + tracked_staging = {} + for attachment in attachments: + known_keys.add(attachment.object_key) + for variant in attachment.variants or []: + if variant.get("object_key"): + known_keys.add(variant["object_key"]) + if attachment.staging_key: + tracked_staging[attachment.staging_key] = ( + attachment.id, + attachment.status, + attachment.updated_at, + ) + + now = datetime.now(timezone.utc) + orphan_cutoff = now - timedelta(seconds=grace_seconds) + staging_cutoff = now - timedelta(seconds=staging_retention) + scanned = stale = deleted = cleared_staging = 0 + paginator = client.get_paginator("list_objects_v2") + for prefix in ("originals/", "variants/", "staging/"): + for page in paginator.paginate(Bucket=bucket, Prefix=prefix): + for obj in page.get("Contents", []): + scanned += 1 + key = obj["Key"] + modified = obj.get("LastModified") + tracked = tracked_staging.get(key) if prefix == "staging/" else None + if tracked: + _attachment_id, status, updated_at = tracked + safe_cleanup = status == "ready" or (status == "failed" and updated_at <= staging_cutoff) + if not safe_cleanup: + continue + elif key in known_keys or modified is None or modified > orphan_cutoff: + continue + stale += 1 + if args.apply: + client.delete_object(Bucket=bucket, Key=key) + deleted += 1 + if tracked: + attachment_id, _status, _updated_at = tracked + with SessionLocal.begin() as session: + attachment = session.scalar( + select(Attachment).where(Attachment.id == attachment_id).with_for_update() + ) + if attachment and attachment.staging_key == key: + attachment.staging_key = None + cleared_staging += 1 + print( + f"orphan_reconciliation mode={'apply' if args.apply else 'dry-run'} " + f"grace_seconds={grace_seconds} staging_retention_seconds={staging_retention} " + f"scanned={scanned} stale={stale} deleted={deleted} staging_refs_cleared={cleared_staging}" + ) + + +if __name__ == "__main__": + main() diff --git a/src/app/replay_job.py b/src/app/replay_job.py new file mode 100644 index 00000000..8b319e5a --- /dev/null +++ b/src/app/replay_job.py @@ -0,0 +1,53 @@ +"""Explicit local operator replay for one failed attachment pipeline.""" +import argparse +from datetime import datetime, timezone +import getpass +import uuid + +from sqlalchemy import select + +from .db import SessionLocal +from .models import Attachment, AttachmentJob, JobOutbox, JobReplayAudit + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("attachment_id", help="UUID of a failed attachment") + args = parser.parse_args() + try: + attachment_id = uuid.UUID(args.attachment_id) + except ValueError: + raise SystemExit("attachment_id must be a UUID") from None + + with SessionLocal.begin() as session: + attachment = session.scalar(select(Attachment).where(Attachment.id == attachment_id).with_for_update()) + if attachment is None: + raise SystemExit("attachment not found") + job = session.scalar(select(AttachmentJob).where(AttachmentJob.attachment_id == attachment_id).with_for_update()) + if job is None or job.status != "failed": + raise SystemExit("only a failed attachment can be replayed") + if not attachment.staging_key: + raise SystemExit("staging source is absent; replay is unsafe") + previous_attempt = job.attempt + job.attempt += 1 + job.attempts_in_cycle = 1 + job.status = "queued" + job.available_at = datetime.now(timezone.utc) + job.lease_until = None + job.last_error_code = None + job.completed_at = None + attachment.status = "queued" + attachment.error_code = None + attachment.updated_at = datetime.now(timezone.utc) + session.add(JobReplayAudit( + job_id=job.id, + previous_attempt=previous_attempt, + new_attempt=job.attempt, + operator=getpass.getuser()[:100] or "local-operator", + )) + session.add(JobOutbox(job_id=job.id, attempt=job.attempt)) + print(f"PASS: replay queued for attachment {attachment_id}; attempt {previous_attempt + 1} recorded.") + + +if __name__ == "__main__": + main() diff --git a/src/app/s3_bootstrap.py b/src/app/s3_bootstrap.py new file mode 100644 index 00000000..863c18ae --- /dev/null +++ b/src/app/s3_bootstrap.py @@ -0,0 +1,251 @@ +"""Idempotently create the private bucket and a bucket-scoped API service account.""" +import json +import os +import ssl +import time +from urllib.error import HTTPError, URLError +from urllib.parse import quote +from urllib.request import Request, urlopen + +import boto3 +from botocore.auth import S3SigV4Auth +from botocore.awsrequest import AWSRequest +from botocore.config import Config +from botocore.credentials import Credentials +from botocore.exceptions import ClientError + +from .settings import _secret + + +def _endpoint() -> str: + endpoint = os.environ.get("S3_ENDPOINT", "https://s3:9000").rstrip("/") + if not endpoint.startswith("https://") and os.environ.get("APP_ENV", "lab").lower() != "test": + raise RuntimeError("S3 bootstrap requires HTTPS outside explicit test mode") + return endpoint + + +def _tls_context() -> ssl.SSLContext: + context = ssl.create_default_context(cafile=os.environ.get("S3_CA_FILE", "/run/secrets/internal-ca.crt")) + client_cert = os.environ.get("S3_CLIENT_CERT_FILE") + client_key = os.environ.get("S3_CLIENT_KEY_FILE") + if client_cert and client_key: + context.load_cert_chain(client_cert, client_key) + return context + + +def _admin_request(method: str, path: str, payload: dict | None = None) -> tuple[int, str | None]: + endpoint = _endpoint() + region = os.environ.get("S3_REGION", "us-east-1") + access = _secret("S3_ROOT_ACCESS_KEY_FILE", "S3_ROOT_ACCESS_KEY") + secret = _secret("S3_ROOT_SECRET_ACCESS_KEY_FILE", "S3_ROOT_SECRET_ACCESS_KEY") + body = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8") if payload is not None else None + url = endpoint + path + # RustFS 1.0.5's admin API may reject a signed GET with an empty body + # when Content-Length is omitted by urllib. Sign and send the explicit + # zero length so the request is unambiguous to its SigV4 verifier. + headers = {"Content-Type": "application/json"} if body is not None else {"Content-Length": "0"} + signed = AWSRequest(method=method, url=url, data=body, headers=headers) + S3SigV4Auth(Credentials(access, secret), "s3", region).add_auth(signed) + request = Request(url, data=body, headers=dict(signed.headers), method=method) + try: + with urlopen(request, timeout=3, context=_tls_context()) as response: + response.read(1024 * 1024) + return response.status, None + except HTTPError as exc: + raw = exc.read(1024 * 1024) + detail = "" + try: + document = json.loads(raw) + except (json.JSONDecodeError, UnicodeDecodeError): + document = None + if isinstance(document, dict): + detail = "; ".join( + str(document[key]) + for key in ("Code", "code", "Message", "message", "error") + if document.get(key) + ) + if not detail: + detail = raw.decode("utf-8", errors="replace") + detail = " ".join(detail.split())[:240] + # RustFS can echo request details in an error response. Redact every + # credential before including a short diagnostic in the container log. + for file_variable, value_variable in ( + ("S3_ROOT_ACCESS_KEY_FILE", "S3_ROOT_ACCESS_KEY"), + ("S3_ROOT_SECRET_ACCESS_KEY_FILE", "S3_ROOT_SECRET_ACCESS_KEY"), + ("S3_ACCESS_KEY_ID_FILE", "S3_ACCESS_KEY_ID"), + ("S3_SECRET_ACCESS_KEY_FILE", "S3_SECRET_ACCESS_KEY"), + ("S3_WORKER_ACCESS_KEY_ID_FILE", "S3_WORKER_ACCESS_KEY_ID"), + ("S3_WORKER_SECRET_ACCESS_KEY_FILE", "S3_WORKER_SECRET_ACCESS_KEY"), + ): + try: + credential = _secret(file_variable, value_variable) + except RuntimeError: + continue + detail = detail.replace(credential, "[redacted]") + detail = detail.replace(quote(credential, safe=""), "[redacted]") + return exc.code, detail or None + + +def _failure(action: str, status: int, detail: str | None) -> RuntimeError: + suffix = f": {detail}" if detail else "" + return RuntimeError(f"RustFS API service-account {action} failed with HTTP {status}{suffix}") + + +def _create_service_account(endpoint: str, region: str, bucket: str, *, name: str, access_key: str, secret_key: str, policy: dict) -> None: + """Idempotently create/update one prefix-scoped RustFS account.""" + client = boto3.client( + "s3", + endpoint_url=endpoint, + region_name=region, + aws_access_key_id=access_key, + aws_secret_access_key=secret_key, + verify=os.environ.get("S3_CA_FILE", "/run/secrets/internal-ca.crt"), + config=Config(connect_timeout=2, read_timeout=3, retries={"total_max_attempts": 1}, s3={"addressing_style": "path"}), + ) + encoded_key = quote(access_key, safe="") + info_path = f"/rustfs/admin/v3/info-service-account?accessKey={encoded_key}" + status, detail = _admin_request("GET", info_path) + if status == 404: + status, detail = _admin_request("PUT", "/rustfs/admin/v3/add-service-account", { + "accessKey": access_key, + "secretKey": secret_key, + "name": name, + "description": f"Scoped {name} attachment service account", + "policy": policy, + }) + if status not in (200, 201, 204): + raise _failure(f"{name} creation", status, detail) + elif status == 200: + status, detail = _admin_request("POST", f"/rustfs/admin/v3/update-service-account?accessKey={encoded_key}", { + "policy": policy, + "name": name, + "description": f"Scoped {name} attachment service account", + }) + if status not in (200, 204): + raise _failure(f"{name} policy update", status, detail) + else: + raise _failure(f"{name} lookup", status, detail) + + client.get_bucket_location(Bucket=bucket) + try: + visible = {item.get("Name") for item in client.list_buckets().get("Buckets", [])} + except ClientError as exc: + code = str(exc.response.get("Error", {}).get("Code", "")) + if code not in {"AccessDenied", "403"}: + raise RuntimeError(f"RustFS {name} identity did not return an explicit ListAllMyBuckets denial") from None + else: + if visible - {bucket}: + raise RuntimeError(f"RustFS {name} identity can see buckets outside its attachment bucket") + + +def _service_policies(bucket: str) -> tuple[dict, dict]: + api = { + "Version": "2012-10-17", + "Statement": [ + {"Sid": "BucketLocation", "Effect": "Allow", "Action": ["s3:GetBucketLocation"], "Resource": [f"arn:aws:s3:::{bucket}"]}, + {"Sid": "UploadStaging", "Effect": "Allow", "Action": ["s3:PutObject"], "Resource": [f"arn:aws:s3:::{bucket}/staging/*"]}, + {"Sid": "DownloadCompleted", "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": [f"arn:aws:s3:::{bucket}/originals/*", f"arn:aws:s3:::{bucket}/variants/*"]}, + ], + } + worker = { + "Version": "2012-10-17", + "Statement": [ + {"Sid": "BucketLocation", "Effect": "Allow", "Action": ["s3:GetBucketLocation"], "Resource": [f"arn:aws:s3:::{bucket}"]}, + {"Sid": "ReadAndDeleteStaging", "Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject"], "Resource": [f"arn:aws:s3:::{bucket}/staging/*"]}, + {"Sid": "WriteCompleted", "Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject"], "Resource": [f"arn:aws:s3:::{bucket}/originals/*", f"arn:aws:s3:::{bucket}/variants/*"]}, + ], + } + return api, worker + + +def _create_service_accounts(endpoint: str, region: str, bucket: str) -> None: + api_access = _secret("S3_ACCESS_KEY_ID_FILE", "S3_ACCESS_KEY_ID") + api_secret = _secret("S3_SECRET_ACCESS_KEY_FILE", "S3_SECRET_ACCESS_KEY") + worker_access = _secret("S3_WORKER_ACCESS_KEY_ID_FILE", "S3_WORKER_ACCESS_KEY_ID") + worker_secret = _secret("S3_WORKER_SECRET_ACCESS_KEY_FILE", "S3_WORKER_SECRET_ACCESS_KEY") + api_policy, worker_policy = _service_policies(bucket) + _create_service_account(endpoint, region, bucket, name="messenger-api", access_key=api_access, secret_key=api_secret, policy=api_policy) + _create_service_account(endpoint, region, bucket, name="messenger-worker", access_key=worker_access, secret_key=worker_secret, policy=worker_policy) + + +def _assert_prefix_denied(endpoint: str, region: str, bucket: str, root) -> None: + probe_key = "policy-probe/forbidden-prefix-check" + identities = ( + ("api", _secret("S3_ACCESS_KEY_ID_FILE", "S3_ACCESS_KEY_ID"), _secret("S3_SECRET_ACCESS_KEY_FILE", "S3_SECRET_ACCESS_KEY")), + ("worker", _secret("S3_WORKER_ACCESS_KEY_ID_FILE", "S3_WORKER_ACCESS_KEY_ID"), _secret("S3_WORKER_SECRET_ACCESS_KEY_FILE", "S3_WORKER_SECRET_ACCESS_KEY")), + ) + root.put_object(Bucket=bucket, Key=probe_key, Body=b"lab7 policy scope probe") + try: + for name, access, secret in identities: + client = boto3.client( + "s3", endpoint_url=endpoint, region_name=region, + aws_access_key_id=access, aws_secret_access_key=secret, + verify=os.environ.get("S3_CA_FILE", "/run/secrets/internal-ca.crt"), + config=Config(connect_timeout=2, read_timeout=3, retries={"total_max_attempts": 1}, s3={"addressing_style": "path"}), + ) + for operation, callback in ( + ("read", lambda: client.get_object(Bucket=bucket, Key=probe_key)), + ("write", lambda: client.put_object(Bucket=bucket, Key=probe_key, Body=b"deny")), + ): + try: + callback() + except ClientError as exc: + code = str(exc.response.get("Error", {}).get("Code", "")) + if code in {"AccessDenied", "403"}: + continue + raise RuntimeError(f"RustFS {name} unexpectedly allowed out-of-prefix {operation}") + finally: + root.delete_object(Bucket=bucket, Key=probe_key) + + +def main() -> None: + endpoint = _endpoint() + region = os.environ.get("S3_REGION", "us-east-1") + bucket = os.environ.get("S3_BUCKET", "messenger-attachments") + root_access = _secret("S3_ROOT_ACCESS_KEY_FILE", "S3_ROOT_ACCESS_KEY") + root_secret = _secret("S3_ROOT_SECRET_ACCESS_KEY_FILE", "S3_ROOT_SECRET_ACCESS_KEY") + root = boto3.client( + "s3", + endpoint_url=endpoint, + region_name=region, + aws_access_key_id=root_access, + aws_secret_access_key=root_secret, + verify=os.environ.get("S3_CA_FILE", "/run/secrets/internal-ca.crt"), + config=Config(connect_timeout=2, read_timeout=3, retries={"total_max_attempts": 1}, s3={"addressing_style": "path"}), + ) + last_error = None + for _ in range(60): + try: + try: + root.head_bucket(Bucket=bucket) + except ClientError as exc: + code = str(exc.response.get("Error", {}).get("Code", "")) + if code in {"404", "NoSuchBucket", "NotFound"}: + root.create_bucket(Bucket=bucket) + else: + raise + break + except Exception as exc: + last_error = exc + time.sleep(1) + else: + raise RuntimeError("RustFS did not become ready for bucket bootstrap") from last_error + + anonymous_url = f"{endpoint}/{quote(bucket, safe='')}" + try: + with urlopen(Request(anonymous_url, method="GET"), timeout=2, context=_tls_context()) as response: + if response.status < 400: + raise RuntimeError("The attachment bucket allows anonymous access") + except HTTPError as exc: + if exc.code != 403: + raise RuntimeError(f"Anonymous bucket check returned unexpected HTTP {exc.code}") from None + except URLError as exc: + raise RuntimeError("Could not verify private bucket access") from exc + + _create_service_accounts(endpoint, region, bucket) + _assert_prefix_denied(endpoint, region, bucket, root) + print("PASS: private bucket and separate API/worker prefix policies are ready.") + + +if __name__ == "__main__": + main() diff --git a/src/app/schemas.py b/src/app/schemas.py new file mode 100644 index 00000000..4fb9ea6d --- /dev/null +++ b/src/app/schemas.py @@ -0,0 +1,123 @@ +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +import uuid + + +class StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class CreateUser(StrictModel): + username: StrictStr = Field(min_length=3, max_length=32, pattern=r"^[a-z0-9_]{3,32}$") + display_name: StrictStr = Field(min_length=1, max_length=100) + password: StrictStr = Field(min_length=12, max_length=128) + + @field_validator("display_name") + @classmethod + def display_name_not_blank(cls, value: str) -> str: + if not value.strip(): + raise ValueError("display_name must contain a non-whitespace character") + return value + + +class UserOut(BaseModel): + id: str + username: str + display_name: str + created_at: str + + +class CreateChat(StrictModel): + title: StrictStr = Field(min_length=1, max_length=100) + member_ids: list[StrictStr] = Field(min_length=1, max_length=100) + + @field_validator("title") + @classmethod + def title_not_blank(cls, value: str) -> str: + if not value.strip(): + raise ValueError("title must contain a non-whitespace character") + return value + + @field_validator("member_ids") + @classmethod + def members_are_unique_uuids(cls, values: list[str]) -> list[str]: + import uuid + + try: + normalized = [str(uuid.UUID(value)) for value in values] + except (ValueError, AttributeError, TypeError) as exc: + raise ValueError("member_ids must contain UUIDs") from exc + if len(normalized) != len(set(normalized)): + raise ValueError("member_ids must be unique") + return normalized + + +class ChatOut(BaseModel): + id: str + title: str + member_ids: list[str] + created_at: str + + +class ChatPage(BaseModel): + items: list[ChatOut] + next_cursor: str | None + + +class CreateMessage(StrictModel): + text: StrictStr = Field(max_length=4000) + attachment_ids: list[StrictStr] = Field(default_factory=list, max_length=10) + + @field_validator("attachment_ids") + @classmethod + def attachment_ids_are_unique_uuids(cls, values: list[str]) -> list[str]: + try: + normalized = [str(uuid.UUID(value)) for value in values] + except (ValueError, AttributeError, TypeError) as exc: + raise ValueError("attachment_ids must contain UUIDs") from exc + if len(normalized) != len(set(normalized)): + raise ValueError("attachment_ids must be unique") + return normalized + + +class MessageOut(BaseModel): + id: str + chat_id: str + sender_id: str + text: str + created_at: str + attachment_ids: list[str] + + +class AttachmentOut(BaseModel): + id: str + chat_id: str + owner_id: str + filename: str + content_type: str + size_bytes: int + sha256: str + status: str = "ready" + variants: list[dict] = Field(default_factory=list) + error_code: str | None = None + created_at: str + updated_at: str + + +class MessagePage(BaseModel): + items: list[MessageOut] + next_cursor: str | None + + +class SessionOut(BaseModel): + token: str + token_type: str = "Bearer" + expires_at: str + user: UserOut + + +class Health(BaseModel): + status: str = "ok" + + +class ErrorBody(BaseModel): + error: dict[str, str] diff --git a/src/app/secrets_bootstrap.py b/src/app/secrets_bootstrap.py new file mode 100644 index 00000000..4329bf88 --- /dev/null +++ b/src/app/secrets_bootstrap.py @@ -0,0 +1,96 @@ +"""Fetch one workload's scoped startup secrets from OpenBao, then exec it.""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import ssl +import sys +from urllib.parse import urlsplit +from urllib.error import HTTPError, URLError +from urllib.request import Request, urlopen + + +WORKLOADS = { + "api": ("messenger-api", "messenger/api", {"CACHE_URL", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"}), + "worker": ("messenger-worker", "messenger/worker", {"BROKER_URL", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"}), + "dispatcher": ("messenger-dispatcher", "messenger/dispatcher", {"BROKER_URL"}), +} + + +def _read(path: str) -> str: + with open(path, "r", encoding="utf-8") as source: + return source.read().strip() + + +def _secure_private_key(source_path: str, target_path: str) -> str: + """Copy a Compose-mounted key to tmpfs with permissions accepted by OpenSSL/libpq.""" + source = Path(source_path) + target = Path(target_path) + target.write_bytes(source.read_bytes()) + target.chmod(0o600) + return str(target) + + +def _bao_request(path: str, *, context: ssl.SSLContext, payload: dict | None = None, token: str | None = None) -> dict: + body = json.dumps(payload, separators=(",", ":")).encode("utf-8") if payload is not None else None + headers = {"Content-Type": "application/json"} + if token: + headers["X-Vault-Token"] = token + request = Request(os.environ["BAO_ADDR"].rstrip("/") + "/v1/" + path, data=body, headers=headers) + try: + with urlopen(request, context=context, timeout=3) as response: + return json.loads(response.read(1_048_576)) + except (HTTPError, URLError, TimeoutError, ValueError) as exc: + # Deliberately omit URL paths, request bodies, tokens, and server body. + raise RuntimeError(f"OpenBao request failed ({type(exc).__name__})") from None + + +def load_secrets(workload: str) -> dict[str, str]: + auth_role, secret_path, allowed_keys = WORKLOADS[workload] + if urlsplit(os.environ["BAO_ADDR"]).scheme != "https": + raise RuntimeError("OpenBao must use HTTPS") + context = ssl.create_default_context(cafile=os.environ["BAO_CA_CERT"]) + context.load_cert_chain(os.environ["BAO_CLIENT_CERT"], os.environ["BAO_CLIENT_KEY"]) + login = _bao_request( + "auth/cert/login", + context=context, + payload={"name": auth_role}, + ) + token = login.get("auth", {}).get("client_token") + if not isinstance(token, str) or not token: + raise RuntimeError("OpenBao certificate authentication returned no token") + result = _bao_request("kv/data/" + secret_path, context=context, token=token) + values = result.get("data", {}).get("data", {}) + if not isinstance(values, dict): + raise RuntimeError("OpenBao secret has an invalid shape") + secrets = {} + for key in allowed_keys: + value = values.get(key.lower()) + if not isinstance(value, str) or not value: + raise RuntimeError(f"OpenBao secret is missing required field {key.lower()}") + secrets[key] = value + return secrets + + +def main() -> None: + if len(sys.argv) < 4 or sys.argv[2] != "--": + raise SystemExit("usage: python -m src.app.secrets_bootstrap WORKLOAD -- COMMAND [ARG ...]") + workload = sys.argv[1] + if workload not in WORKLOADS: + raise SystemExit("unknown workload") + mounted_client_key = os.environ["BAO_CLIENT_KEY"] + secure_client_key = _secure_private_key( + mounted_client_key, + f"/tmp/{workload}-client.key", + ) + os.environ["BAO_CLIENT_KEY"] = secure_client_key + for variable in ("DB_TLS_KEY_FILE", "OTEL_EXPORTER_OTLP_CLIENT_KEY"): + if os.environ.get(variable) == mounted_client_key: + os.environ[variable] = secure_client_key + os.environ.update(load_secrets(workload)) + os.execvp(sys.argv[3], sys.argv[3:]) + + +if __name__ == "__main__": + main() diff --git a/src/app/settings.py b/src/app/settings.py new file mode 100644 index 00000000..5f81014d --- /dev/null +++ b/src/app/settings.py @@ -0,0 +1,116 @@ +from dataclasses import dataclass +import os +from pathlib import Path + + +def _secret(file_variable: str, value_variable: str) -> str: + file_path = os.environ.get(file_variable) + if file_path: + value = Path(file_path).read_text(encoding="utf-8").strip() + else: + value = os.environ.get(value_variable, "").strip() + if not value: + raise RuntimeError(f"Required setting {file_variable} is missing") + return value + + +def load_database_url() -> str: + return _secret("DATABASE_URL_FILE", "DATABASE_URL") + + +@dataclass(frozen=True) +class Settings: + cache_url: str + broker_url: str + broker_stream: str + session_ttl_seconds: int + s3_endpoint: str + s3_region: str + s3_bucket: str + s3_access_key_id: str + s3_secret_access_key: str + max_upload_bytes: int + max_image_pixels: int + worker_concurrency: int + job_max_attempts: int + job_timeout_seconds: int + job_lease_seconds: int + staging_retention_seconds: int + login_rate_limit_per_minute: int + + +def load_settings(*, require_cache: bool = True, require_broker: bool = True, require_s3: bool = True) -> Settings: + try: + ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) + except ValueError as exc: + raise RuntimeError("SESSION_TTL_SECONDS must be an integer") from exc + if ttl < 1 or ttl > 31_536_000: + raise RuntimeError("SESSION_TTL_SECONDS must be between 1 and 31536000") + try: + max_upload_bytes = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760")) + max_image_pixels = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000")) + worker_concurrency = int(os.environ.get("WORKER_CONCURRENCY", "1")) + job_max_attempts = int(os.environ.get("JOB_MAX_ATTEMPTS", "5")) + job_timeout_seconds = int(os.environ.get("JOB_TIMEOUT_SECONDS", "60")) + job_lease_seconds = int(os.environ.get("JOB_LEASE_SECONDS", "180")) + staging_retention_seconds = int(os.environ.get("STAGING_RETENTION_SECONDS", "86400")) + login_rate_limit_per_minute = int(os.environ.get("LOGIN_RATE_LIMIT_PER_MINUTE", "10")) + except ValueError as exc: + raise RuntimeError("upload, worker and job settings must be integers") from exc + if not 1 <= max_upload_bytes <= 10_485_760: + raise RuntimeError("MAX_UPLOAD_BYTES must be between 1 and 10485760") + if not 1 <= max_image_pixels <= 40_000_000: + raise RuntimeError("MAX_IMAGE_PIXELS must be between 1 and 40000000") + endpoint = os.environ.get("S3_ENDPOINT", "https://s3:9000").strip() + region = os.environ.get("S3_REGION", "us-east-1").strip() + bucket = os.environ.get("S3_BUCKET", "messenger-attachments").strip() + if not endpoint.startswith("http://") and not endpoint.startswith("https://"): + raise RuntimeError("S3_ENDPOINT must be an HTTP(S) URL") + if os.environ.get("APP_ENV", "lab").lower() != "test" and not endpoint.startswith("https://"): + raise RuntimeError("S3_ENDPOINT must use HTTPS outside explicit test mode") + if not region or not bucket: + raise RuntimeError("S3_REGION and S3_BUCKET are required") + if worker_concurrency != 1: + raise RuntimeError("WORKER_CONCURRENCY is fixed at 1 per worker; scale worker replicas for more throughput") + if not 1 <= job_max_attempts <= 20: + raise RuntimeError("JOB_MAX_ATTEMPTS must be between 1 and 20") + if not 5 <= job_timeout_seconds <= 600 or job_lease_seconds <= job_timeout_seconds: + raise RuntimeError("JOB_LEASE_SECONDS must exceed JOB_TIMEOUT_SECONDS (5..600)") + if staging_retention_seconds < 3600: + raise RuntimeError("STAGING_RETENTION_SECONDS must be at least 3600") + if not 1 <= login_rate_limit_per_minute <= 120: + raise RuntimeError("LOGIN_RATE_LIMIT_PER_MINUTE must be between 1 and 120") + cache_file = os.environ.get("CACHE_URL_FILE") + cache_value = os.environ.get("CACHE_URL", "").strip() + cache_url = _secret("CACHE_URL_FILE", "CACHE_URL") if require_cache or cache_file or cache_value else "" + # API processes do not publish directly; falling back keeps them independent + # from broker credentials while the dispatcher and worker use the explicit URL. + broker_file = os.environ.get("BROKER_URL_FILE") + broker_url = Path(broker_file).read_text(encoding="utf-8").strip() if broker_file else os.environ.get("BROKER_URL", cache_url) + if require_broker and not broker_url: + raise RuntimeError("BROKER_URL_FILE is empty") + if cache_url and os.environ.get("APP_ENV", "lab").lower() != "test" and not cache_url.startswith("rediss://"): + raise RuntimeError("CACHE_URL must use verified TLS (rediss://)") + if broker_url and require_broker and os.environ.get("APP_ENV", "lab").lower() != "test" and not broker_url.startswith("rediss://"): + raise RuntimeError("BROKER_URL must use verified TLS (rediss://)") + s3_access_key_id = _secret("S3_ACCESS_KEY_ID_FILE", "S3_ACCESS_KEY_ID") if require_s3 else "" + s3_secret_access_key = _secret("S3_SECRET_ACCESS_KEY_FILE", "S3_SECRET_ACCESS_KEY") if require_s3 else "" + return Settings( + cache_url=cache_url, + broker_url=broker_url, + broker_stream=os.environ.get("BROKER_STREAM", "messenger:attachment-jobs:v1"), + session_ttl_seconds=ttl, + s3_endpoint=endpoint.rstrip("/"), + s3_region=region, + s3_bucket=bucket, + s3_access_key_id=s3_access_key_id, + s3_secret_access_key=s3_secret_access_key, + max_upload_bytes=max_upload_bytes, + max_image_pixels=max_image_pixels, + worker_concurrency=worker_concurrency, + job_max_attempts=job_max_attempts, + job_timeout_seconds=job_timeout_seconds, + job_lease_seconds=job_lease_seconds, + staging_retention_seconds=staging_retention_seconds, + login_rate_limit_per_minute=login_rate_limit_per_minute, + ) diff --git a/src/app/storage.py b/src/app/storage.py new file mode 100644 index 00000000..dd384f54 --- /dev/null +++ b/src/app/storage.py @@ -0,0 +1,23 @@ +import os + +from botocore.config import Config +import boto3 + +from .settings import load_settings + + +settings = load_settings(require_cache=False, require_broker=False, require_s3=True) +s3 = boto3.client( + "s3", + endpoint_url=settings.s3_endpoint, + region_name=settings.s3_region, + aws_access_key_id=settings.s3_access_key_id, + aws_secret_access_key=settings.s3_secret_access_key, + verify=os.environ.get("S3_CA_FILE", "/run/secrets/internal-ca.crt"), + config=Config( + connect_timeout=1, + read_timeout=2, + retries={"total_max_attempts": 1, "mode": "standard"}, + s3={"addressing_style": "path"}, + ), +) diff --git a/src/app/telemetry.py b/src/app/telemetry.py new file mode 100644 index 00000000..44fce8a3 --- /dev/null +++ b/src/app/telemetry.py @@ -0,0 +1,186 @@ +"""Bounded OpenTelemetry setup shared by API, dispatcher and worker.""" +from __future__ import annotations + +import logging +import os +import re +import socket +import threading +import time +from contextlib import contextmanager + +from opentelemetry import metrics, trace +from opentelemetry._logs import set_logger_provider +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased + +ENABLED = os.environ.get("OTEL_ENABLED", "true").lower() not in {"0", "false", "no"} +_configured = False +_lock = threading.Lock() + + +class _EventNameFilter(logging.Filter): + """Give each existing application log a bounded OTel event attribute.""" + def filter(self, record: logging.LogRecord) -> bool: + message = record.msg if isinstance(record.msg, str) else "event" + first = message.split(maxsplit=1)[0] if message else "event" + event_name = re.sub(r"[^A-Za-z0-9_.-]", "_", first)[:64] or "event" + setattr(record, "event.name", event_name) + return True + + +def configure(service_name: str | None = None) -> None: + global _configured + if not ENABLED or _configured: + return + with _lock: + if _configured: + return + endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "https://otel-collector:4318").rstrip("/") + if not endpoint.startswith("https://") and os.environ.get("APP_ENV", "lab").lower() != "test": + raise RuntimeError("OTEL_EXPORTER_OTLP_ENDPOINT must use HTTPS outside explicit test mode") + tls = { + "certificate_file": os.environ.get("OTEL_EXPORTER_OTLP_CERTIFICATE", "/run/secrets/internal-ca.crt"), + "client_certificate_file": os.environ.get("OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE", "/run/secrets/otel-client.crt"), + "client_key_file": os.environ.get("OTEL_EXPORTER_OTLP_CLIENT_KEY", "/run/secrets/otel-client.key"), + } + resource = Resource.create({ + "service.name": service_name or os.environ.get("OTEL_SERVICE_NAME", "messenger"), + "service.version": os.environ.get("APP_VERSION", "1.6.0"), + "service.instance.id": socket.gethostname(), + "deployment.environment.name": os.environ.get("APP_ENV", "lab"), + }) + ratio = float(os.environ.get("OTEL_TRACES_SAMPLER_ARG", "0.1")) + if not 0.0 <= ratio <= 1.0: + raise RuntimeError("OTEL_TRACES_SAMPLER_ARG must be between 0 and 1") + + tracer_provider = TracerProvider(resource=resource, sampler=ParentBased(TraceIdRatioBased(ratio))) + tracer_provider.add_span_processor(BatchSpanProcessor( + OTLPSpanExporter(endpoint=f"{endpoint}/v1/traces", timeout=2, **tls), + max_queue_size=2048, max_export_batch_size=256, + schedule_delay_millis=1000, export_timeout_millis=2000, + )) + trace.set_tracer_provider(tracer_provider) + + interval = max(1000, int(os.environ.get("OTEL_METRIC_EXPORT_INTERVAL", "5000"))) + reader = PeriodicExportingMetricReader( + OTLPMetricExporter(endpoint=f"{endpoint}/v1/metrics", timeout=2, **tls), + export_interval_millis=interval, export_timeout_millis=2000, + ) + metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader])) + + logger_provider = LoggerProvider(resource=resource) + logger_provider.add_log_record_processor(BatchLogRecordProcessor( + OTLPLogExporter(endpoint=f"{endpoint}/v1/logs", timeout=2, **tls), + max_queue_size=2048, max_export_batch_size=256, + schedule_delay_millis=1000, export_timeout_millis=2000, + )) + set_logger_provider(logger_provider) + root = logging.getLogger() + handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider) + handler.addFilter(_EventNameFilter()) + root.addHandler(handler) + _configured = True + + +def tracer(name: str): + return trace.get_tracer(name) + + +def meter(name: str): + return metrics.get_meter(name) + + +def add_process_observations(*, role: str, db_engine=None) -> None: + """Export bounded process and SQLAlchemy pool gauges without identifiers.""" + if not ENABLED: + return + import psutil + process = psutil.Process() + m = meter("messenger.runtime") + + def cpu(_options): + yield metrics.Observation(process.cpu_percent(interval=None), {"service.role": role}) + + def memory(_options): + yield metrics.Observation(process.memory_info().rss, {"service.role": role}) + + m.create_observable_gauge("messenger.process.cpu.utilization", callbacks=[cpu], unit="%") + m.create_observable_gauge("messenger.process.memory.usage", callbacks=[memory], unit="By") + if db_engine is not None: + def pool_used(_options): + pool = db_engine.pool + yield metrics.Observation(pool.checkedout(), {"pool": "postgres"}) + + def pool_capacity(_options): + pool = db_engine.pool + yield metrics.Observation(pool.size() + pool._max_overflow, {"pool": "postgres"}) + + m.create_observable_gauge("messenger.db.pool.used", callbacks=[pool_used], unit="{connection}") + m.create_observable_gauge("messenger.db.pool.capacity", callbacks=[pool_capacity], unit="{connection}") + + +def current_trace_headers() -> dict[str, str]: + """Return only standard W3C propagation fields for the durable job event.""" + if not ENABLED: + return {} + from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator + carrier: dict[str, str] = {} + TraceContextTextMapPropagator().inject(carrier) + return {key: value for key, value in carrier.items() if key in {"traceparent", "tracestate"}} + + +@contextmanager +def operation_span(name: str, **attributes): + if not ENABLED: + yield None + return + with tracer("messenger.dependencies").start_as_current_span(name, attributes=attributes) as span: + try: + yield span + except Exception as exc: + from opentelemetry.trace import Status, StatusCode + span.record_exception(exc) + span.set_status(Status(StatusCode.ERROR)) + raise + + +def add_queue_observations(db_engine) -> None: + if not ENABLED: + return + from sqlalchemy import func, select + from .models import AttachmentJob + from .db import SessionLocal + m = meter("messenger.queue") + + def queue_depth(_options): + try: + with SessionLocal() as session: + value = session.scalar(select(func.count()).select_from(AttachmentJob).where(AttachmentJob.status == "queued")) + yield metrics.Observation(value or 0, {"queue.name": "attachment-jobs"}) + except Exception: + return + + def oldest_age(_options): + try: + with SessionLocal() as session: + value = session.scalar(select(func.extract("epoch", func.now() - func.min(AttachmentJob.created_at))).where(AttachmentJob.status == "queued")) + yield metrics.Observation(max(0.0, float(value or 0.0)), {"queue.name": "attachment-jobs"}) + except Exception: + return + + m.create_observable_gauge("messenger.queue.depth", callbacks=[queue_depth], unit="{job}") + m.create_observable_gauge("messenger.queue.oldest_job_age", callbacks=[oldest_age], unit="s") + + +def observed_duration(histogram, started: float, **attributes) -> None: + histogram.record(max(0.0, time.perf_counter() - started), attributes) diff --git a/src/app/worker.py b/src/app/worker.py new file mode 100644 index 00000000..40da4c68 --- /dev/null +++ b/src/app/worker.py @@ -0,0 +1,441 @@ +"""At-least-once Redis Streams consumer for the versioned image pipeline.""" +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +import json +import argparse +from contextvars import ContextVar +import logging +import os +import random +import signal +import socket +import time +import uuid + +from botocore.exceptions import BotoCoreError, ClientError +from redis import Redis +from redis.exceptions import ResponseError +from sqlalchemy import select + +from .db import SessionLocal, engine +from .image_pipeline import PermanentImageError, process_image +from .models import Attachment, AttachmentJob, JobOutbox +from .settings import load_settings +from .storage import s3 +from .telemetry import ENABLED as TELEMETRY_ENABLED, add_process_observations, configure, current_trace_headers, meter, operation_span, tracer +from opentelemetry import propagate, trace +from opentelemetry.metrics import Observation +from opentelemetry.trace import SpanKind, Status, StatusCode + + +settings = load_settings(require_cache=False, require_s3=True) +STREAM = settings.broker_stream +GROUP = "attachment-workers-v1" +DEAD_STREAM = STREAM + ":dead" +CONSUMER = socket.gethostname() + "-" + uuid.uuid4().hex[:8] +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") +logger = logging.getLogger("messenger.worker") +configure("messenger-worker") +add_process_observations(role="worker", db_engine=engine) +job_meter = meter("messenger.jobs") +job_count = job_meter.create_counter("messenger.jobs.processed", unit="{job}") +job_duration = job_meter.create_histogram("messenger.jobs.duration", unit="s") +ready_duration = job_meter.create_histogram("messenger.jobs.end_to_end_ready_duration", unit="s") +active_jobs = job_meter.create_up_down_counter("messenger.worker.active", unit="{job}") +_job_outcome: ContextVar[str] = ContextVar("job_outcome", default="completed") +job_meter.create_observable_gauge( + "messenger.worker.capacity", + callbacks=[lambda _options: [Observation(settings.worker_concurrency, {"job.type": "attachment.process.v1"})]], + unit="{job}", +) +broker = Redis.from_url(settings.broker_url, decode_responses=True, socket_connect_timeout=2, socket_timeout=10) + + +class RetryableJobError(Exception): + def __init__(self, error_code: str): + self.error_code = error_code + + +def _deadline_handler(_signum, _frame) -> None: + raise RetryableJobError("processing_timeout") + + +def _process_with_deadline(fields: dict, message_id: str) -> None: + # The worker is a single-threaded process. A wall-clock timer makes the + # configured deadline effective even if an image decoder or storage call + # takes longer than expected; S3 calls also have short socket timeouts. + context = propagate.extract(fields) if TELEMETRY_ENABLED else None + started = time.perf_counter() + span = tracer("messenger.worker").start_span( + "attachment.process", context=context, kind=SpanKind.CONSUMER, + attributes={"messaging.system": "redis", "messaging.operation.type": "process", "messaging.destination.name": "attachment-jobs"}, + ) if TELEMETRY_ENABLED else None + active_jobs.add(1, {"job.type": "attachment.process.v1"}) + outcome_token = _job_outcome.set("completed") + try: + if span is not None: + with trace.use_span(span, end_on_exit=False): + _process_with_deadline_inner(fields, message_id) + else: + _process_with_deadline_inner(fields, message_id) + except BaseException: + _job_outcome.set("failed") + if span is not None: + span.set_attribute("job.outcome", "failed") + span.set_status(Status(StatusCode.ERROR)) + raise + finally: + elapsed = max(0.0, time.perf_counter() - started) + outcome = _job_outcome.get() + if outcome in {"completed", "failed"}: + job_count.add(1, {"job.type": "attachment.process.v1", "outcome": outcome}) + job_duration.record(elapsed, {"job.type": "attachment.process.v1", "outcome": outcome}) + if span is not None: + span.set_attribute("job.outcome", outcome) + if outcome == "failed": + span.set_status(Status(StatusCode.ERROR)) + active_jobs.add(-1, {"job.type": "attachment.process.v1"}) + if span is not None: + span.end() + _job_outcome.reset(outcome_token) + + +def _process_with_deadline_inner(fields: dict, message_id: str) -> None: + if not hasattr(signal, "setitimer"): + _process(fields, message_id) + return + previous = signal.signal(signal.SIGALRM, _deadline_handler) + signal.setitimer(signal.ITIMER_REAL, settings.job_timeout_seconds) + try: + _process(fields, message_id) + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, previous) + + +def _ensure_group() -> None: + try: + broker.xgroup_create(STREAM, GROUP, id="0-0", mkstream=True) + except ResponseError as exc: + if "BUSYGROUP" not in str(exc): + raise + + +def _ack(message_id: str) -> None: + broker.xack(STREAM, GROUP, message_id) + + +def _dead_letter(message_id: str, fields: dict, error_code: str) -> None: + _job_outcome.set("failed") + broker.xadd(DEAD_STREAM, { + "source_id": message_id, + "error_code": error_code, + "payload": json.dumps(fields, sort_keys=True, separators=(",", ":"))[:2048], + }) + _ack(message_id) + + +def _parse_event(fields: dict) -> tuple[uuid.UUID, uuid.UUID, int, int]: + if fields.get("schema_version") != "1" or fields.get("type") != "attachment.process.v1": + raise ValueError("unsupported_job_schema") + job_id = uuid.UUID(fields["job_id"]) + attachment_id = uuid.UUID(fields["attachment_id"]) + attempt = int(fields["attempt"]) + pipeline = int(fields["pipeline_version"]) + if attempt < 1 or pipeline != 1: + raise ValueError("invalid_job_version") + return job_id, attachment_id, attempt, pipeline + + +def _claim(job_id: uuid.UUID, attachment_id: uuid.UUID, attempt: int, pipeline: int) -> tuple[str, str | None]: + now = datetime.now(timezone.utc) + with SessionLocal.begin() as session: + job = session.scalar(select(AttachmentJob).where(AttachmentJob.id == job_id).with_for_update()) + attachment = session.scalar(select(Attachment).where(Attachment.id == attachment_id).with_for_update()) + if job is None or attachment is None or job.attachment_id != attachment_id: + return "ack", None + if job.pipeline_version != pipeline or job.attempt != attempt: + return "ack", None + if job.status == "succeeded": + return "finished", attachment.staging_key + if job.status == "failed": + return "ack", None + if job.status == "processing" and job.lease_until and job.lease_until > now: + return "ack", None # duplicate outbox publish while another worker owns the lease + if job.available_at > now: + return "wait", None + if not attachment.staging_key: + job.status = "failed" + job.last_error_code = "staging_missing" + job.completed_at = now + attachment.status = "failed" + attachment.error_code = "staging_missing" + return "ack", None + job.status = "processing" + job.lease_until = now + timedelta(seconds=settings.job_lease_seconds) + job.updated_at = now + attachment.status = "processing" + attachment.error_code = None + return "process", attachment.staging_key + + +def _retry_delay(attempts_in_cycle: int) -> float: + ceiling = min(60.0, 2.0 ** min(attempts_in_cycle, 6)) + return random.uniform(ceiling / 2, ceiling) + + +def _record_failure(job_id: uuid.UUID, attachment_id: uuid.UUID, attempt: int, error_code: str, permanent: bool) -> None: + _job_outcome.set("failed") + now = datetime.now(timezone.utc) + with SessionLocal.begin() as session: + job = session.scalar(select(AttachmentJob).where(AttachmentJob.id == job_id).with_for_update()) + attachment = session.scalar(select(Attachment).where(Attachment.id == attachment_id).with_for_update()) + if job is None or attachment is None or job.attempt != attempt or job.status != "processing": + return + job.last_error_code = error_code + job.lease_until = None + job.updated_at = now + if permanent: + job.status = "failed" + job.completed_at = now + attachment.status = "failed" + attachment.error_code = error_code + elif job.attempts_in_cycle < job.max_attempts: + job.attempt += 1 + job.attempts_in_cycle += 1 + job.status = "queued" + job.available_at = now + timedelta(seconds=_retry_delay(job.attempts_in_cycle)) + attachment.status = "queued" + attachment.error_code = None + trace_headers = current_trace_headers() + session.add(JobOutbox( + job_id=job.id, + attempt=job.attempt, + traceparent=trace_headers.get("traceparent"), + tracestate=trace_headers.get("tracestate"), + )) + else: + job.status = "failed" + job.last_error_code = "retry_exhausted" + job.completed_at = now + attachment.status = "failed" + attachment.error_code = "retry_exhausted" + + +def _cleanup_staging(attachment_id: uuid.UUID, staging_key: str | None) -> None: + if not staging_key: + return + try: + s3.delete_object(Bucket=settings.s3_bucket, Key=staging_key) + except (ClientError, BotoCoreError) as exc: + logger.warning("staging_cleanup_failed attachment_id=%s type=%s", attachment_id, type(exc).__name__) + return + with SessionLocal.begin() as session: + attachment = session.scalar(select(Attachment).where(Attachment.id == attachment_id).with_for_update()) + if attachment and attachment.status == "ready" and attachment.staging_key == staging_key: + attachment.staging_key = None + + +def _process(fields: dict, message_id: str) -> None: + started = time.monotonic() + try: + job_id, attachment_id, attempt, pipeline = _parse_event(fields) + except (ValueError, KeyError, TypeError): + _dead_letter(message_id, fields, "invalid_job_event") + return + + action, staging_key = _claim(job_id, attachment_id, attempt, pipeline) + if action == "ack": + _job_outcome.set("duplicate") + _ack(message_id) + return + if action == "wait": + _job_outcome.set("deferred") + return + if action == "finished": + _job_outcome.set("duplicate") + _cleanup_staging(attachment_id, staging_key) + _ack(message_id) + return + if os.environ.get("WORKER_FAILPOINT_PERMANENT_ATTACHMENT_ID") == str(attachment_id): + marker = "lab5:failpoint:permanent:" + str(attachment_id) + if broker.set(marker, "used", nx=True, ex=86400): + _record_failure(job_id, attachment_id, attempt, "test_permanent_failure", permanent=True) + _ack(message_id) + return + if os.environ.get("WORKER_FAILPOINT_RETRY_ONCE_ATTACHMENT_ID") == str(attachment_id): + marker = "lab6:failpoint:retry-once:" + str(attachment_id) + expected_key = "lab6:failpoint:retry-trace:" + str(attachment_id) + result_key = "lab6:failpoint:retry-trace-result:" + str(attachment_id) + traceparent = current_trace_headers().get("traceparent", "") + parts = traceparent.split("-") + observed_trace_id = parts[1] if len(parts) == 4 else "" + if broker.set(marker, "used", nx=True, ex=86400): + broker.set(expected_key, observed_trace_id, ex=86400) + logger.warning( + "test_retry_trace_capture attachment_id=%s attempt=%s trace_id=%s", + attachment_id, attempt, observed_trace_id or "missing", + ) + _record_failure(job_id, attachment_id, attempt, "test_transient_failure", permanent=False) + _ack(message_id) + return + expected_trace_id = broker.get(expected_key) or "" + trace_matches = bool(expected_trace_id and observed_trace_id == expected_trace_id) + broker.set(result_key, "match" if trace_matches else "mismatch", ex=86400) + logger.info( + "test_retry_trace_context_%s attachment_id=%s expected_trace_id=%s observed_trace_id=%s", + "match" if trace_matches else "mismatch", attachment_id, + expected_trace_id or "missing", observed_trace_id or "missing", + ) + + with SessionLocal() as session: + attachment = session.get(Attachment, attachment_id) + if attachment is None: + _ack(message_id) + return + content_type = attachment.content_type + size_expected = attachment.size_bytes + digest_expected = attachment.sha256 + object_key = attachment.object_key + filename = attachment.filename + try: + with operation_span("s3.get_object", **{"db.system.name": "s3", "server.address": "s3"}): + stored = s3.get_object(Bucket=settings.s3_bucket, Key=staging_key) + original = stored["Body"].read(settings.max_upload_bytes + 1) + stored["Body"].close() + if len(original) != size_expected or len(original) > settings.max_upload_bytes: + raise PermanentImageError("invalid_image") + import hashlib + if hashlib.sha256(original).hexdigest() != digest_expected: + raise PermanentImageError("staging_checksum_mismatch") + variants = process_image(original, content_type, settings.max_image_pixels, attachment_id.hex, pipeline) + if time.monotonic() - started > settings.job_timeout_seconds: + raise RetryableJobError("processing_timeout") + with operation_span("s3.put_object.original", **{"db.system.name": "s3", "server.address": "s3"}): + s3.put_object( + Bucket=settings.s3_bucket, + Key=object_key, + Body=original, + ContentLength=len(original), + ContentType=content_type, + Metadata={"sha256": digest_expected, "pipeline-version": str(pipeline)}, + ) + public_variants = [] + for item in variants: + body = item.pop("body") + with operation_span("s3.put_object.variant", **{"db.system.name": "s3", "server.address": "s3"}): + s3.put_object( + Bucket=settings.s3_bucket, + Key=item["object_key"], + Body=body, + ContentLength=len(body), + ContentType=item["content_type"], + Metadata={"sha256": item["sha256"], "pipeline-version": str(pipeline)}, + ) + public_variants.append(item) + if time.monotonic() - started > settings.job_timeout_seconds: + raise RetryableJobError("processing_timeout") + except PermanentImageError as exc: + _record_failure(job_id, attachment_id, attempt, str(exc) or "invalid_image", permanent=True) + _ack(message_id) + return + except ClientError as exc: + code = str(exc.response.get("Error", {}).get("Code", "")) + if code in {"AccessDenied", "InvalidAccessKeyId", "SignatureDoesNotMatch", "NoSuchBucket"}: + _record_failure(job_id, attachment_id, attempt, "storage_configuration", permanent=True) + else: + _record_failure(job_id, attachment_id, attempt, "storage_unavailable", permanent=False) + _ack(message_id) + return + except RetryableJobError as exc: + _record_failure(job_id, attachment_id, attempt, exc.error_code, permanent=False) + _ack(message_id) + return + except BotoCoreError: + _record_failure(job_id, attachment_id, attempt, "processing_unavailable", permanent=False) + _ack(message_id) + return + except Exception as exc: + logger.warning("job_attempt_failed job_id=%s type=%s", job_id, type(exc).__name__) + _record_failure(job_id, attachment_id, attempt, "processing_unavailable", permanent=False) + _ack(message_id) + return + + now = datetime.now(timezone.utc) + with SessionLocal.begin() as session: + job = session.scalar(select(AttachmentJob).where(AttachmentJob.id == job_id).with_for_update()) + attachment = session.scalar(select(Attachment).where(Attachment.id == attachment_id).with_for_update()) + if job is not None and attachment is not None and job.status == "processing" and job.attempt == attempt: + attachment.status = "ready" + attachment.variants = public_variants + attachment.error_code = None + attachment.updated_at = now + job.status = "succeeded" + job.lease_until = None + job.last_error_code = None + job.completed_at = now + job.updated_at = now + # Optional, isolated fault-injection point used only by the defense scenario. + # It exits after durable result commit and before staging cleanup or XACK. + if os.environ.get("WORKER_FAILPOINT_AFTER_COMMIT_ATTACHMENT_ID") == str(attachment_id): + marker = "lab5:failpoint:after-commit:" + str(attachment_id) + if broker.set(marker, "used", nx=True, ex=86400): + logger.warning("test_failpoint_after_result_commit attachment_id=%s", attachment_id) + raise SystemExit(75) + _cleanup_staging(attachment_id, staging_key) + _ack(message_id) + try: + created = datetime.fromisoformat(fields["created_at"].replace("Z", "+00:00")) + ready_duration.record(max(0.0, (now - created).total_seconds()), {"job.type": "attachment.process.v1", "outcome": "completed"}) + except (KeyError, ValueError, TypeError): + pass + logger.info("attachment_ready attachment_id=%s pipeline_version=%s elapsed_seconds=%.3f", attachment_id, pipeline, time.monotonic() - started) + + +def _next_message(min_idle_ms: int | None = None): + reclaimed = broker.xautoclaim( + STREAM, GROUP, CONSUMER, + min_idle_time=settings.job_lease_seconds * 1000 if min_idle_ms is None else min_idle_ms, + start_id="0-0", + count=1, + ) + if len(reclaimed) > 1 and reclaimed[1]: + return reclaimed[1][0] + batches = broker.xreadgroup(GROUP, CONSUMER, {STREAM: ">"}, count=1, block=1000) + if batches and batches[0][1]: + return batches[0][1][0] + return None + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--once", action="store_true", help="process one available or reclaimable event and exit") + parser.add_argument("--idle-ms", type=int, default=None, help="test-only reclaim idle override for --once") + args = parser.parse_args() + if args.idle_ms is not None and (not args.once or args.idle_ms < 0): + raise SystemExit("--idle-ms requires --once and must be non-negative") + _ensure_group() + logger.info("attachment_worker_started consumer=%s concurrency=%s lease_seconds=%s", CONSUMER, settings.worker_concurrency, settings.job_lease_seconds) + if args.once: + while True: + message = _next_message(args.idle_ms) + if message is not None: + _process_with_deadline(message[1], message[0]) + logger.info("worker_once_complete message_id=%s", message[0]) + return + time.sleep(0.25) + while True: + try: + message = _next_message() + if message is not None: + _process_with_deadline(message[1], message[0]) + except SystemExit: + raise + except Exception as exc: + logger.warning("worker_loop_failed type=%s", type(exc).__name__, exc_info=True) + time.sleep(1) + + +if __name__ == "__main__": + main() diff --git a/tests/load.py b/tests/load.py index ad81d596..1fa38a0e 100644 --- a/tests/load.py +++ b/tests/load.py @@ -1,9 +1,11 @@ #!/usr/bin/env python3 """Small closed-loop HTTP write benchmark; not an open-loop capacity proof.""" from concurrent.futures import ThreadPoolExecutor +from collections import Counter import json import math from pathlib import Path +import re import threading import time from client import Client, Failure, LAB, arguments, check, run @@ -19,32 +21,52 @@ def main(): check(1<=args.concurrency<=128,'concurrency must be 1..128') c = Client(args.base_url,args.ca_file) alice,bob,eve,chat = c.bootstrap() - barrier = threading.Barrier(args.concurrency) + benchmark_started = [None] + barrier = threading.Barrier( + args.concurrency, + action=lambda: benchmark_started.__setitem__(0, time.monotonic()), + ) def worker(worker_id): local = Client(args.base_url,args.ca_file,timeout=5) barrier.wait() - deadline = time.monotonic()+args.duration - latencies,errors = [],0 + deadline = benchmark_started[0]+args.duration + latencies, failure_offsets, failure_categories = [], [], [] index = 0 while time.monotonic()