diff --git a/.env.example b/.env.example index 2e9f054..13897b3 100644 --- a/.env.example +++ b/.env.example @@ -1,41 +1,20 @@ -# 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 -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 +# Optional non-secret overrides for the local synthetic lab7 stand. +# Credentials, private keys and AppRole SecretIDs are generated under ignored +# secrets/ and .operator/ directories by `make init-secrets` / `make bootstrap`. + +HTTPS_PORT=8443 +OPENBAO_PORT=18200 +GRAFANA_PORT=13000 +PROMETHEUS_PORT=19090 +LOKI_PORT=13100 +TEMPO_PORT=13200 + 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 -MAX_UPLOAD_BYTES=10485760 -MAX_IMAGE_PIXELS=40000000 -BROKER_URL_FILE=/run/secrets/broker_url -WORKER_CONCURRENCY=2 -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. +SESSION_TTL_SECONDS=3600 +LOGIN_RATE_LIMIT=5 +LOGIN_RATE_WINDOW_SECONDS=60 + +# Grade-3 floor. Lower values are rejected by the application. ARGON2_MEMORY_KIB=19456 ARGON2_ITERATIONS=2 ARGON2_PARALLELISM=1 diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8aef0ff..ded8873 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,18 @@ ## Лабораторная 7 -Автор / группа: TODO -Целевая оценка (3/4/5): TODO -Трек 5, если заявлен: TODO +Автор / группа: Чурилин Данила / БВТ2301 +Целевая оценка (3/4/5): 4 +Трек 5, если заявлен: не заявлен -Что реализовано и что перенесено: TODO -Команды запуска из чистого clone: TODO -Результаты проверок и ссылка на REPORT.md: TODO -Ограничения / известные ошибки: TODO -Источники и использование ИИ: TODO +Что реализовано и что перенесено: возможности lab6 перенесены без ослабления; добавлены TLS/mTLS trust boundaries, least-privilege ACL, OpenBao AppRole lifecycle, password rehash и общий login limiter, runtime hardening, secret/leaf rotation, telemetry leak audit и dependency/image scan. +Команды запуска из чистого clone: `make up`, затем `make test`, `make test-security-grade4`, `make test-acl-grade4`, `make test-telemetry-leak-grade4`; полный список — в `REPORT.md`. +Результаты проверок и ссылка на REPORT.md: воспроизводимые команды, фактические результаты и ограничения приведены в `REPORT.md`, `evidence/grade3-summary.md` и `evidence/grade4-summary.md`. +Ограничения / известные ошибки: single-host стенд; stateful stores и CA не HA; нет background renewal agent, CA rollover, CRL/OCSP, KMS/HSM и уровня 5. +Источники и использование ИИ: Go standard library и зависимости из `go.mod`; версии инфраструктуры из `compose.yaml`; OpenAI Codex использовался для переноса и подготовки решения, результат проверен перечисленными тестами. -- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. -- [ ] Контракт и публичные тесты не ослаблены. -- [ ] make check и make test выполнены; приложен реальный вывод. -- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. -- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. -- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. +- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [x] Контракт и публичные тесты не ослаблены. +- [x] make check и make test выполнены; приложен реальный вывод. +- [x] Сценарии отказов/безопасности своего уровня воспроизведены. +- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. +- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. diff --git a/.gitignore b/.gitignore index b5a7189..b39a2c4 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ .env.* !.env.example secrets/ +.operator/ certs/private/ *.key *.p12 @@ -15,6 +16,7 @@ data/ backups/ # Runtime/build artifacts .venv/ +.cache/ __pycache__/ *.py[cod] node_modules/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..fa16cb5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,42 @@ +FROM golang:1.27.3-alpine@sha256:fa3d596898d9f126af7c01d14ee7597bab3f39cccf392ef36b69fe77cd681f18 AS builder + +WORKDIR /build + +COPY go.mod go.sum ./ +RUN go mod download + +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ + + +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/server ./cmd/server/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/reconciler ./cmd/reconciler/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/worker ./cmd/worker/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/dispatcher ./cmd/dispatcher/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/jobctl ./cmd/jobctl/main.go + +FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf + +RUN apk upgrade --no-cache && \ + apk add --no-cache ca-certificates curl openssl + +RUN addgroup -g 1000 appgroup && \ + adduser -u 1000 -G appgroup -s /bin/sh -D appuser + +WORKDIR /app + +COPY --from=builder /build/server /app/server +COPY --from=builder /build/reconciler /app/reconciler +COPY --from=builder /build/worker /app/worker +COPY --from=builder /build/dispatcher /app/dispatcher +COPY --from=builder /build/jobctl /app/jobctl + +RUN chown -R appuser:appgroup /app + +USER appuser:appgroup + +EXPOSE 8444 + + +ENTRYPOINT ["/app/server"] + diff --git a/Makefile b/Makefile index 5ad43ad..29049ef 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,29 @@ PYTHON ?= python3 -BASE_URL ?= https://localhost:8443 -CA_FILE ?= +BASE_URL ?= https://127.0.0.1:8443 +CA_FILE ?= secrets/pki/ca.crt ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover test-security +.PHONY: help init-secrets bootstrap up down check validate test load test-security test-security-grade3 test-security-grade4 test-acl-grade4 test-state-pruning-grade4 test-telemetry-leak-grade4 test-rate-limit-grade3 test-openbao-policy test-openbao-lifecycle-grade4 rotate-secret-grade4 rotate-leaf-grade4 scan-grade4 test-persistence test-failover argon2-benchmark login-dos-benchmark cleanup-lab help: - @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "init-secrets, bootstrap, up, down, check, validate, test, load" + @echo "test-security-grade3, test-security-grade4, test-acl-grade4, test-state-pruning-grade4" + @echo "test-rate-limit-grade3, test-openbao-policy, test-openbao-lifecycle-grade4" + @echo "rotate-secret-grade4, rotate-leaf-grade4, scan-grade4, cleanup-lab" + +init-secrets: + ./scripts/init-secrets.sh + +bootstrap: init-secrets + ./scripts/bootstrap-dependencies.sh + ./scripts/bootstrap-openbao.sh + +up: bootstrap + docker compose up -d --build + +down: + docker compose down --remove-orphans check: $(PYTHON) scripts/check_contract.py @@ -21,13 +37,55 @@ test: load: $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) +test-security: + $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-security-grade3: + ./tests/security_grade3.sh + +test-security-grade4: + ./tests/security_grade4.sh + +test-acl-grade4: + ./tests/acl_audit_grade4.sh + +test-state-pruning-grade4: + ./tests/state_pruning_grade4.sh + +test-telemetry-leak-grade4: + ./tests/telemetry_leak_grade4.sh + +test-rate-limit-grade3: + $(PYTHON) tests/rate_limit_grade3.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-openbao-policy: + ./tests/openbao_policy.sh + +test-openbao-lifecycle-grade4: + ./tests/openbao_lifecycle_grade4.sh + +rotate-secret-grade4: + ./scripts/rotate-secret-grade4.sh + +rotate-leaf-grade4: + ./scripts/rotate-leaf-grade4.sh + +scan-grade4: + ./scripts/scan-grade4.sh + test-persistence: - @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) + @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT=scripts/restart.sh"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) test-failover: - @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) + @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT=scripts/stop-one.sh"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) -test-security: - $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) +argon2-benchmark: + go test -run '^$$' -bench BenchmarkHashPasswordGrade3 -benchtime=5x ./internal/security + +login-dos-benchmark: + go test -run '^$$' -bench BenchmarkVerifyPasswordGrade4 -benchtime=20x ./internal/security + +cleanup-lab: + ./scripts/cleanup-lab.sh diff --git a/REPORT.md b/REPORT.md index 9801db4..028721c 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,121 @@ # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Чурилин Данила, БВТ2301. +- Целевая оценка: 4. Трек оценки 5 не заявлен и не реализовывался. +- Ветка: `solution/bvt2301-churilin`. Commit/PR не создавались по условию локальной подготовки. +- Использованные источники и ПО: Go standard library; зависимости из `go.mod`; PostgreSQL, Redis, MinIO, RabbitMQ, HAProxy, OpenBao, OpenTelemetry Collector, Prometheus, Loki, Tempo и Grafana в версиях из `compose.yaml`. Для переноса собственной реализации lab6 и подготовки lab7 использовался OpenAI Codex; результат проверен тестами ниже. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Проверенный стенд: Ubuntu/WSL2, Go 1.27.4, Docker Engine 29.7.2, Docker Compose 5.5.0, OpenSSL 3.5.5. Нужны также Python 3 и GNU Make. Полная OpenAPI-валидация требует отдельного Python virtualenv: + +```sh +python3 -m venv .venv +.venv/bin/pip install -r requirements-dev.txt +make check +PYTHON=.venv/bin/python make validate +``` + +Локальные ключи, пароли и operator material создаются вне Git. Значения не нужно записывать в `.env`; файл содержит только необязательные несекретные overrides. + +```sh +cp .env.example .env # необязательно +make up # init secrets, bootstrap stores/OpenBao, build, start +make test +make test-security +make test-security-grade3 +make test-security-grade4 +make test-acl-grade4 +make test-telemetry-leak-grade4 +make test-rate-limit-grade3 +make test-state-pruning-grade4 +make test-openbao-policy +make test-openbao-lifecycle-grade4 +make rotate-secret-grade4 +make rotate-leaf-grade4 +make scan-grade4 +./tests/minio_policy.sh +``` + +`make up` повторяем: миграции, bucket/policies, RabbitMQ ACL и AppRole настраиваются идемпотентно. При первом запуске `scripts/bootstrap-openbao.sh` инициализирует non-dev OpenBao. Root token и единственный unseal share сохраняются только в игнорируемом `.operator/openbao-init.json` с mode 0600. После перезапуска OpenBao оператор вручную запускает этот скрипт или `scripts/restart.sh`; приложения unseal/root material не получают. + +Внешний API: `https://127.0.0.1:8443`; CA: `secrets/pki/ca.crt`. Локальные интерфейсы: OpenBao `18200`, Grafana `13000`, Prometheus `19090`, Loki `13100`, Tempo `13200`. Последние три требуют допустимый клиентский сертификат; Grafana требует логин; S3/RabbitMQ/Redis/PostgreSQL наружу не опубликованы. + +Безопасная остановка сохраняет named volumes и OpenBao file storage: + +```sh +make down +``` + +`make cleanup-lab` дополнительно удаляет только четыре локально собранных образа с префиксом `mtusi2026lab7`, но сохраняет данные и сторонние образы. Намеренное удаление учебных named volumes выполняется отдельно командой `docker compose down -v --remove-orphans`; ignored-каталоги `volumes/openbao`, `secrets` и `.operator` удаляются оператором только после отдельной проверки абсолютного пути и создания нужной резервной копии. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Путь запроса: клиент — TLS 1.3 → HAProxy ingress — mTLS 1.3 → две API-реплики. Ingress проверяет DNS SAN `api`, API проверяет CA клиента и точную URI SAN allowlist из отдельного runtime-файла. Это позволяет удалить старую LB identity и принять новый leaf без пересборки image. Порт API 8444 только `expose`, host binding отсутствует. Случайный hostname не используется как публичный instance id: каждая реплика создаёт непрозрачный `api-` в `/tmp/instance-id`. + +PostgreSQL остаётся источником истины для пользователей, сессий, сообщений, idempotency, вложений, job и общего login limiter. Транзакции, миграции 1–8 и outbox/job state machine перенесены из lab6; добавлена таблица `login_rate_limits`. Истёкшие sessions/idempotency/limiter rows удаляются индексированными batch по 256 записей: первый раз после запуска и далее амортизированно раз в 128 операций. Для limiter cutoff равен `now - LOGIN_RATE_WINDOW`, поэтому активное окно не сбрасывается. Redis используется только как cache с ACL. S3 и RabbitMQ сохраняют раздельные API/worker и dispatcher/worker credentials. + +Продукты без native TLS в выбранной конфигурации доступны только через HAProxy TLS gateway. Plaintext backend hop находится на отдельной `internal: true` сети, где присутствуют только gateway и конкретный backend; обходной порт не опубликован. PostgreSQL и OpenBao используют native TLS. Dispatcher/worker → RabbitMQ и API/worker/dispatcher → OTLP Collector требуют mTLS: у `api`, `worker`, `dispatcher` разные clientAuth leaf, HAProxy проверяет CA и точный CN ACL; same-CA `intruder` получает отказ. API напрямую не использует broker: transactional outbox публикует отдельный `dispatcher`, поэтому API identity на broker намеренно запрещена. Collector → Loki/Tempo, Prometheus → Collector и Grafana → data sources также используют mTLS с отдельными CN/URI identities. Полное сопоставление находится в `contracts/trust-matrix.md`. + +OpenBao 2.4.4 работает с file storage `volumes/openbao`, TLS 1.3 и AppRole `api`, `worker`, `dispatcher`. Каждая policy читает только `secret/data/`. App token: TTL 15 минут, max TTL 30 минут; SecretID: 168 часов. Приложение использует token только для стартового чтения allowlisted ключей и не хранит root token. + +Пароли хешируются Argon2id с индивидуальными 16-byte salt и параметрами внутри PHC-строки. Минимум, который код не позволяет понизить: `m=19456 KiB, t=2, p=1`. После успешной проверки legacy PHC параметры сравниваются с текущей policy; hash заменяется новым через compare-and-set, не меняя результат параллельного login. Session token хранится только как SHA-256 hash. Unknown user и wrong password имеют одинаковые status/challenge/code/message/длину тела; ошибки credential state не возвращают hash/credential details. Измеренный verify — 23.485943 ms/op; limiter выполняется до Argon2 и допускает 5 попыток на normalized username за 60 s, то есть около 117 ms Argon2 CPU/min на один identifier на этом CPU. Limiter атомарно обновляется в PostgreSQL и общий для обеих реплик; шестая попытка получает 429 и `Retry-After`. + +App/worker/dispatcher запускаются UID 1000 с read-only rootfs, `no-new-privileges`, `cap_drop: ALL`, отдельным tmpfs `/tmp` (`nosuid,nodev,noexec`) и CPU/RAM limits. Worker имеет 1 CPU, 512 MiB, `GOMEMLIMIT=448MiB`, timeout 60 s и concurrency 1: две параллельные полные декодировки разрешённых 40-мегапиксельных изображений не конкурируют за один CPU и memory cgroup. Те же read-only/no-new-privileges controls применены к stateless ingress/gateways и Collector. Stateful PostgreSQL/MinIO/RabbitMQ/Loki/Tempo/Prometheus/Grafana/OpenBao сохраняют writable только свои data volumes: это совместимые исключения, а не writable application rootfs. Нет `privileged`, host network или Docker socket. Secret values не входят в image layers и проверяются на отсутствие в Loki. `.env.example` соответствует параметрам портов, числа реплик, TTL, rate limit и Argon2. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Контракт и OpenAPI | `make check`; `PYTHON=.venv/bin/python make validate` | обе проверки PASS | `scripts/check_contract.py`, `scripts/validate_openapi.py` | +| Предыдущие возможности через HTTPS | `make test` | `PASS: lab7 public API scenario` включая auth, ACL, idempotency, S3/worker и logout | `tests/smoke.py` | +| Доверенный/недоверенный внешний TLS | `make test-security` | правильный CA проходит; пустой trust store даёт certificate verification error | `tests/security.py` | +| LB → API mTLS и отсутствие обхода | `make test-security-grade3` | no cert, foreign CA и wrong same-CA identity отклонены; LB identity принята; host binding 8444 отсутствует | `tests/security_grade3.sh` | +| Broker/Collector mTLS identities | `make test-security-grade4` | no cert и same-CA intruder deny; broker принимает worker/dispatcher и запрещает API без broker edge; Collector принимает разные api/worker/dispatcher | `tests/security_grade4.sh`, `infrastructure/gateways/*.cfg` | +| TLS и ACL всей матрицы | `make test-acl-grade4`; grade3/4 security; policy tests | PostgreSQL verify-full; dispatcher recovery получает только нужные `SELECT,UPDATE` на attachments и не читает users/не удаляет attachments; остальные DB/Redis/Rabbit/S3/OpenBao allow/deny подтверждены | `tests/acl_audit_grade4.sh`, `contracts/trust-matrix.md` | +| OpenBao non-dev и least privilege | `make test-openbao-policy` | own path allow; worker path, policy admin и KV write deny | `tests/openbao_policy.sh`, `infrastructure/openbao/*` | +| Раздельные S3 права | `./tests/minio_policy.sh` | API staging write-only, attachments read-only; bucket create и anonymous GET deny | `infrastructure/minio/*-policy.template.json` | +| Argon2id floor и измерение | `make argon2-benchmark`; `go test ./internal/security` | `m=19456,t=2,p=1`, 23.485943 ms/op; слабая конфигурация отклоняется | `internal/security/password.go`, `password_test.go` | +| Rehash и login DoS budget | `go test ./student_tests ./internal/security`; `make login-dos-benchmark` | legacy `m=8192,t=1` обновлён после успешного login; verify 23.485943 ms/op; 5/60s ≈117 ms/identifier/min | `student_tests/password_rehash_test.go`, `password_test.go` | +| Общий login rate limit | `make test-rate-limit-grade3` | запросы прошли обе реплики; 5×401, затем 429 + Retry-After | `tests/rate_limit_grade3.py`, migration 000008 | +| Ограниченный cleanup auth state | `make test-state-pruning-grade4` | истёкшая limiter row удалена, активное окно с attempts=4 сохранено; batch/частота ограничены | `internal/adapter/postgres/maintenance.go`, `tests/state_pruning_grade4.sh` | +| Session expiry/logout, размер, ACL | `go test ./...`; `make test` | expired token и logout проверены; JSON/attachment reads ограничены; outsider/X-User-Id tests PASS | `student_tests/auth_test.go`, `internal/transport/http/handlers/handler.go` | +| Hardening, worker bounds и порты | `make test-security-grade4`; `tests/attachment_boundaries.py` | app rootfs read-only, no-new-privileges, CapDrop ALL; worker 1 CPU/512 MiB, concurrency 1, GOMEMLIMIT 448 MiB, timeout 60 s; ровно 40 Мп обработаны без OOM | `compose.yaml`, `tests/security_grade4.sh`, `tests/attachment_boundaries.py` | +| Secret/leaf rotation и revoke | `make rotate-secret-grade4`; `make rotate-leaf-grade4` | broker worker password заменён и старый отвергнут; новый LB leaf принят, старый URI и expired leaf отвергнут; image IDs неизменны | `scripts/rotate-*-grade4.sh` | +| OpenBao renewal/expiry/seal | `make test-openbao-lifecycle-grade4` | one-use SecretID reuse deny; token renewal работает после original TTL и прекращается на max TTL; running API жив при seal, fresh API fail-closed, unseal восстанавливает | `tests/openbao_lifecycle_grade4.sh` | +| Отсутствие credential telemetry | `make test-telemetry-leak-grade4` | Loki содержит structured events, но не login probe, Basic/Bearer, request body и значения ignored secret files | `tests/telemetry_leak_grade4.sh` | +| Перезапуск с данными и unseal | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | подтверждённые данные, attachment и существующая сессия сохранены | `scripts/restart.sh` | +| Одна API-реплика остановлена | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 2 instance до отказа; 110 успешных writes, 8 transient failures; восстановление 4.932 s; потерь/дублей нет | `scripts/stop-one.sh` | +| Dependency/image scan | `make scan-grade4` | `govulncheck`: no reachable vulnerabilities; strict Trivy: app/ingress 0 HIGH/CRITICAL fixed; vendor scan: MinIO 40 HIGH/4 CRITICAL, mc 26 HIGH/1 CRITICAL — архивированный upstream, применимость и production-блокер зафиксированы | `security/SCAN_TRIAGE.md`, `scripts/scan-grade4.sh` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Стенд: Intel Core i5-1135G7, 8 vCPU WSL, доступно 3.7 GiB RAM. Compose limits: каждая API 0.5 CPU/256 MiB, ingress 0.25 CPU/128 MiB, PostgreSQL 1 CPU/512 MiB. Нагрузка — closed-loop POST messages, 4 клиента, 30 s, без retry и без прогрева. Это измерение одного ноутбука, а не capacity/SLO proof. + +- 1959 успешных, 0 ошибок, 65.095 successful RPS. +- p50 87.901 ms, p95 100.057 ms, p99 106.397 ms. +- Снимок во время нагрузки: API-1 10.19% CPU / 16.38 MiB; API-2 11.07% / 21.2 MiB; ingress 25.09% / 23.41 MiB; PostgreSQL 13.89% / 68.33 MiB. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Restart stateful stores с volumes, seal/unseal OpenBao, recreate app | API временно недоступен, затем старая session/data работают | persistence PASS, operator hook завершён < 90 s | потеря подтверждённых данных: 0 | +| Stop одной из двух API-реплик | HAProxy исключает реплику и продолжает через вторую | 110 writes успешны, 8 transient failures в окне обнаружения | 4.932 s до первого успеха; потерь/дублей: 0 | +| mTLS negative probes | handshake/authorization deny до business API | все negative cases отклонены, correct identities приняты | немедленно; данных не меняет | + +Raw sanitized summaries находятся в `evidence/grade3-summary.md` и `evidence/grade4-summary.md`; session tokens и secret values туда не записаны. + +## Финальный аудит bottleneck/error paths + +- Максимальная разрешённая граница проверена реальной декодировкой PNG: 10 MiB и ровно 40 000 000 pixels прошли, immediately-after-test worker memory составила 426.3 MiB из 512 MiB, `OOMKilled=false`. Concurrency уменьшена с 2 до 1; это осознанно ограничивает throughput одного worker, но убирает риск двух одновременных полных декодировок в одном cgroup. +- Рост `sessions`, `message_idempotency` и `login_rate_limits` ограничен batch cleanup. Запросы используют существующие индексы, `LIMIT 256` и `FOR UPDATE SKIP LOCKED`; cleanup не выполняется на каждом запросе. Отдельный regression test защищает от преждевременного удаления активного rate-limit window. +- На реальном просроченном attachment job обнаружена и устранена permission loop: dispatcher требовался `UPDATE` для `SELECT ... FOR UPDATE` и смены статуса attachment. После точечного grant reaper восстановил job как следующую попытку; destructive/unrelated права остались запрещены. +- Две API-реплики и предыдущий 30-секундный closed-loop load не показали saturation приложения/БД; ingress был самым загруженным компонентом (25.09% выделенного CPU). Эти цифры не являются production capacity proof. +- Оставшиеся архитектурные bottlenecks осознанны для оценки 4: один worker, один dispatcher, один ingress и single-instance stateful services. Горизонтальный/host-level HA относится к следующему уровню и не заявлен. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Это single-host учебный стенд: отказ Docker host, единственных ingress/PostgreSQL/OpenBao/CA не переживается. Две API-реплики дают только process failover. HAProxy TLS proxy создаёт намеренный локальный plaintext hop к Redis/MinIO/RabbitMQ и telemetry backends; hop закрыт отдельной internal network, но не равен end-to-end TLS внутри продукта. + +Статические DB/S3/Rabbit/Redis credentials требуют operator rotation; сценарий уровня 4 доказывает это для рабочего RabbitMQ secret, но автоматические dynamic database credentials не реализованы. AppRole SecretID имеет 7-дневный TTL и unlimited uses для штатных сервисов; отдельный lifecycle test доказывает one-use revoke. Leaf certificates действуют 365 дней, CA — 10 лет; отзыв leaf реализован exact identity allowlist, но автоматических CRL/OCSP и фонового renewal agent нет. Запущенные процессы продолжают работу при seal/OpenBao с уже загруженными credentials, новый процесс fail-closed не стартует до operator unseal. + +Уровень 5 не заявлен: нет исследовательского compromise/PKI lifecycle track, автоматической CA rotation, multi-host HA и production KMS/HSM. Официальные MinIO/mc upstream архивированы; их известные vendor dependency findings приняты только для учебного стенда и являются production-блокером до замены storage/maintained fork. Image scan — снимок базы на дату проверки, а не гарантия отсутствия будущих CVE. diff --git a/cmd/dispatcher/main.go b/cmd/dispatcher/main.go new file mode 100644 index 0000000..9463d51 --- /dev/null +++ b/cmd/dispatcher/main.go @@ -0,0 +1,169 @@ +package main + +import ( + "context" + "errors" + "log" + "os" + "os/signal" + "syscall" + "time" + + "mtusi2026lab7/internal/adapter/broker" + "mtusi2026lab7/internal/adapter/postgres" + "mtusi2026lab7/internal/config" + "mtusi2026lab7/internal/database" + "mtusi2026lab7/internal/domain" + appsecrets "mtusi2026lab7/internal/secrets" + apptelemetry "mtusi2026lab7/internal/telemetry" + "mtusi2026lab7/internal/worker" +) + +const defaultBeforePublishFaultFile = "/tmp/mtusi-fault-before-publish" + +func main() { + secretContext, secretCancel := context.WithTimeout(context.Background(), 15*time.Second) + err := appsecrets.LoadOpenBaoEnvironment(secretContext) + secretCancel() + if err != nil { + log.Fatalf("[FATAL] OpenBao secret bootstrap failed: %v", err) + } + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + if cfg.BrokerURL == "" { + log.Fatal("[FATAL] BROKER_URL or BROKER_URL_FILE is required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + telemetryRuntime, err := apptelemetry.Start(ctx, "messenger-dispatcher", cfg.InstanceID, "lab") + if err != nil { + log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err) + } + defer func() { + shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil { + log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr) + } + }() + pool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer pool.Close() + if err = apptelemetry.RegisterDBPool(telemetryRuntime, pool); err != nil { + log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err) + } + store := postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout) + queueRecorder, err := apptelemetry.NewQueueRecorder(telemetryRuntime) + if err != nil { + log.Fatalf("[FATAL] Queue observability initialization failed: %v", err) + } + client, err := broker.Open(cfg.BrokerURL, 0) + if err != nil { + log.Fatalf("[FATAL] RabbitMQ initialization failed: %v", err) + } + defer client.Close() + + faultFile := os.Getenv("DISPATCHER_FAULT_BEFORE_PUBLISH_FILE") + if faultFile == "" { + faultFile = defaultBeforePublishFaultFile + } + ticker := time.NewTicker(250 * time.Millisecond) + defer ticker.Stop() + log.Println("[INFO] Attachment job dispatcher and lease reaper started") + nextQueueObservation := time.Time{} + + for { + now := time.Now().UTC() + if !now.Before(nextQueueObservation) { + depth, ageSeconds, statsErr := store.AttachmentQueueStats(ctx, now) + if statsErr != nil { + if ctx.Err() == nil { + log.Printf("[WARN] Read queue stats failed: %v", statsErr) + } + } else { + queueRecorder.Record(ctx, depth, ageSeconds) + } + nextQueueObservation = now.Add(time.Second) + } + expired, queryErr := store.ListExpiredAttachmentJobs(ctx, now, 50) + if queryErr != nil { + if ctx.Err() != nil { + return + } + log.Printf("[WARN] List expired jobs failed: %v", queryErr) + } else { + for _, job := range expired { + delay := worker.RetryDelay( + job.JobID, + job.Attempt+1, + cfg.JobRetryBase, + cfg.JobRetryMax, + ) + recovered, final, recoverErr := store.RetryAttachmentJob( + ctx, + job.JobID, + "lease_expired", + now.Add(delay), + now, + "lease_recovered", + ) + if recoverErr != nil { + log.Printf("[WARN] Recover expired job %s failed: %v", job.JobID, recoverErr) + continue + } + if final && recovered.Status == domain.AttachmentJobFailed { + log.Printf("[WARN] Expired job %s exhausted retries", job.JobID) + } else if !final { + log.Printf("[INFO] Recovered expired job %s as attempt %d", job.JobID, recovered.Attempt) + } + } + } + + jobs, queryErr := store.ListUnpublishedAttachmentJobs(ctx, 50) + if queryErr != nil { + if ctx.Err() != nil { + return + } + log.Printf("[WARN] List unpublished jobs failed: %v", queryErr) + } else { + for _, job := range jobs { + removeErr := os.Remove(faultFile) + if removeErr == nil { + log.Printf("[FAULT] exiting after DB commit and before publish for job %s", job.JobID) + os.Exit(87) + } + if removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) { + log.Printf("[WARN] Consume before-publish fault marker: %v", removeErr) + } + + publishContext, cancel := context.WithTimeout(ctx, 10*time.Second) + publishErr := client.Publish(publishContext, job) + cancel() + if publishErr != nil { + log.Fatalf("[FATAL] Publish job %s failed: %v", job.JobID, publishErr) + } + if err = store.MarkAttachmentJobPublished( + ctx, + job.JobID, + job.Attempt, + time.Now().UTC(), + ); err != nil { + // Publisher confirm proves broker acceptance. Leaving the + // marker unset intentionally causes a safe duplicate. + log.Printf("[WARN] Job %s was confirmed but publish marker failed: %v", job.JobID, err) + } + } + } + + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} diff --git a/cmd/jobctl/main.go b/cmd/jobctl/main.go new file mode 100644 index 0000000..e01253c --- /dev/null +++ b/cmd/jobctl/main.go @@ -0,0 +1,259 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "os" + "strconv" + "time" + + "mtusi2026lab7/internal/adapter/broker" + "mtusi2026lab7/internal/adapter/objectstore" + "mtusi2026lab7/internal/adapter/postgres" + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/config" + "mtusi2026lab7/internal/database" + "mtusi2026lab7/internal/domain" + + "github.com/google/uuid" +) + +type jobView struct { + JobID string `json:"job_id"` + AttachmentID string `json:"attachment_id"` + PipelineVersion int `json:"pipeline_version"` + Status domain.AttachmentJobStatus `json:"status"` + Attempt int `json:"attempt"` + MaxAttempts int `json:"max_attempts"` + ErrorCode *string `json:"error_code"` + ReplayCount int `json:"replay_count"` + UpdatedAt time.Time `json:"updated_at"` +} + +func main() { + if len(os.Args) < 2 { + usage() + } + switch os.Args[1] { + case "list-failed": + runListFailed() + case "replay": + runReplay() + case "inject": + runInject() + case "upgrade": + runUpgrade() + default: + usage() + } +} + +func openStore(ctx context.Context, cfg config.Config) (*postgres.PostgreSQLStore, func()) { + pool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("PostgreSQL initialization failed: %v", err) + } + return postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout), pool.Close +} + +func runListFailed() { + limit := 100 + if len(os.Args) == 3 { + parsed, err := strconv.Atoi(os.Args[2]) + if err != nil || parsed < 1 || parsed > 1000 { + log.Fatal("limit must be an integer between 1 and 1000") + } + limit = parsed + } else if len(os.Args) != 2 { + usage() + } + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + jobs, err := store.ListFailedAttachmentJobs(ctx, limit) + if err != nil { + log.Fatalf("list failed jobs: %v", err) + } + views := make([]jobView, 0, len(jobs)) + for _, job := range jobs { + views = append(views, view(job)) + } + writeJSON(views) +} + +func runReplay() { + if len(os.Args) != 3 { + usage() + } + jobID := requireUUID(os.Args[2], "job_id") + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + job, err := store.ReplayFailedAttachmentJob(ctx, jobID, time.Now().UTC()) + if errors.Is(err, postgres.ErrConflict) { + log.Fatal("replay rejected: job is not the active failed pipeline or retained staging is unavailable") + } + if errors.Is(err, postgres.ErrNotFound) { + log.Fatal("replay rejected: job not found") + } + if err != nil { + log.Fatalf("replay failed: %v", err) + } + writeJSON(view(job)) +} + +func runInject() { + if len(os.Args) != 3 { + usage() + } + jobID := requireUUID(os.Args[2], "job_id") + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + job, err := store.GetAttachmentJob(ctx, jobID) + if errors.Is(err, postgres.ErrNotFound) { + log.Fatal("inject rejected: job not found") + } + if err != nil { + log.Fatalf("read job for injection: %v", err) + } + client, err := broker.Open(cfg.BrokerURL, 1) + if err != nil { + log.Fatalf("RabbitMQ initialization failed: %v", err) + } + defer client.Close() + if err = client.Publish(ctx, job); err != nil { + log.Fatalf("inject broker message: %v", err) + } + writeJSON(view(job)) +} + +func runUpgrade() { + if len(os.Args) != 4 { + usage() + } + attachmentID := requireUUID(os.Args[2], "attachment_id") + targetVersion, err := strconv.Atoi(os.Args[3]) + if err != nil || targetVersion != 2 { + log.Fatal("target pipeline version must be 2") + } + cfg, err := config.LoadWorker() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + attachment, err := store.GetAttachmentForProcessing(ctx, attachmentID) + if errors.Is(err, postgres.ErrNotFound) { + log.Fatal("upgrade rejected: attachment not found") + } + if err != nil { + log.Fatalf("read attachment for upgrade: %v", err) + } + if attachment.PipelineVersion+1 != targetVersion { + log.Fatalf("upgrade rejected: current pipeline is v%d", attachment.PipelineVersion) + } + objects, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("object storage initialization failed: %v", err) + } + source, err := objects.Get(ctx, attachment.ObjectKey) + if err != nil { + log.Fatalf("upgrade source original is unavailable: %v", err) + } + defer source.Body.Close() + stagingKey := fmt.Sprintf("staging/%s/v%d/original", attachment.ID, targetVersion) + if err = objects.Put(ctx, application.ObjectPut{ + Key: stagingKey, + ContentType: attachment.ContentType, + SizeBytes: attachment.SizeBytes, + Body: source.Body, + }); err != nil { + log.Fatalf("create durable upgrade staging: %v", err) + } + now := time.Now().UTC() + job := domain.AttachmentJob{ + SchemaVersion: 1, + JobID: uuid.NewString(), + Type: domain.AttachmentJobType, + AttachmentID: attachment.ID, + PipelineVersion: targetVersion, + Attempt: 1, + MaxAttempts: cfg.JobMaxAttempts, + Status: domain.AttachmentJobQueued, + AvailableAt: now, + CreatedAt: now, + UpdatedAt: now, + } + job, err = store.UpgradeAttachmentPipeline(ctx, attachment.ID, targetVersion, stagingKey, job, now) + if errors.Is(err, postgres.ErrConflict) { + log.Fatal("upgrade rejected: attachment is not in an upgradeable state or target is not the next version") + } + if err != nil { + // Keep the copied source: a COMMIT error is ambiguous and cleanup can + // safely remove an actual orphan after the retention period. + log.Fatalf("upgrade pipeline: %v", err) + } + writeJSON(view(job)) +} + +func requireUUID(value, name string) string { + if _, err := uuid.Parse(value); err != nil { + log.Fatalf("%s must be a UUID", name) + } + return value +} + +func view(job domain.AttachmentJob) jobView { + return jobView{ + JobID: job.JobID, + AttachmentID: job.AttachmentID, + PipelineVersion: job.PipelineVersion, + Status: job.Status, + Attempt: job.Attempt, + MaxAttempts: job.MaxAttempts, + ErrorCode: job.ErrorCode, + ReplayCount: job.ReplayCount, + UpdatedAt: job.UpdatedAt, + } +} + +func writeJSON(value any) { + encoder := json.NewEncoder(os.Stdout) + encoder.SetEscapeHTML(true) + if err := encoder.Encode(value); err != nil { + log.Fatalf("encode output: %v", err) + } +} + +func usage() { + fmt.Fprintln(os.Stderr, "usage: jobctl list-failed [limit] | replay | inject | upgrade 2") + os.Exit(2) +} diff --git a/cmd/reconciler/main.go b/cmd/reconciler/main.go new file mode 100644 index 0000000..8973cf2 --- /dev/null +++ b/cmd/reconciler/main.go @@ -0,0 +1,75 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "log" + "os" + "time" + + "mtusi2026lab7/internal/adapter/objectstore" + "mtusi2026lab7/internal/adapter/postgres" + "mtusi2026lab7/internal/config" + "mtusi2026lab7/internal/database" + "mtusi2026lab7/internal/reconcile" +) + +func main() { + apply := flag.Bool("apply", false, "apply safe repairs; default is dry-run") + gracePeriod := flag.Duration("grace-period", 15*time.Minute, + "ignore metadata and objects newer than this duration") + timeout := flag.Duration("timeout", 2*time.Minute, "maximum reconciliation runtime") + flag.Parse() + + if *gracePeriod <= 0 || *timeout <= 0 { + log.Fatal("[FATAL] grace-period and timeout must be positive") + } + cfg, err := config.Load() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + databasePool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer databasePool.Close() + metadataStore := postgres.NewPostgreSQLStore(databasePool, cfg.DatabaseQueryTimeout) + + objectStore, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Invalid object storage configuration: %v", err) + } + if err = objectStore.Ping(ctx); err != nil { + log.Fatalf("[FATAL] Object storage unavailable: %v", err) + } + + reconciler, err := reconcile.New(metadataStore, objectStore) + if err != nil { + log.Fatalf("[FATAL] Reconciler initialization failed: %v", err) + } + result, err := reconciler.Run(ctx, *gracePeriod, *apply) + if err != nil { + log.Fatalf("[FATAL] Reconciliation failed: %v", err) + } + + encoder := json.NewEncoder(os.Stdout) + encoder.SetIndent("", " ") + if err = encoder.Encode(result); err != nil { + log.Fatalf("[FATAL] Encode reconciliation result: %v", err) + } + if !*apply && len(result.Issues) > 0 { + fmt.Fprintln(os.Stderr, "dry-run found reconciliation issues; rerun with --apply after review") + } +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..04270ec --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,310 @@ +package main + +import ( + "context" + "errors" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + cacheadapter "mtusi2026lab7/internal/adapter/cache" + "mtusi2026lab7/internal/adapter/health" + "mtusi2026lab7/internal/adapter/objectstore" + "mtusi2026lab7/internal/adapter/postgres" + redisadapter "mtusi2026lab7/internal/adapter/redis" + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/config" + "mtusi2026lab7/internal/database" + appsecrets "mtusi2026lab7/internal/secrets" + appsecurity "mtusi2026lab7/internal/security" + apptelemetry "mtusi2026lab7/internal/telemetry" + "mtusi2026lab7/internal/transport/http/handlers" + "mtusi2026lab7/internal/transport/http/middleware" +) + +func main() { + secretContext, secretCancel := context.WithTimeout(context.Background(), 15*time.Second) + err := appsecrets.LoadOpenBaoEnvironment(secretContext) + secretCancel() + if err != nil { + log.Fatalf("[FATAL] OpenBao secret bootstrap failed: %v", err) + } + cfg, err := config.Load() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + if instanceIDFile := os.Getenv("INSTANCE_ID_FILE"); instanceIDFile != "" { + if err = os.WriteFile(instanceIDFile, []byte(cfg.InstanceID), 0o600); err != nil { + log.Fatalf("[FATAL] Persist runtime instance alias: %v", err) + } + } + telemetryRuntime, err := apptelemetry.Start( + context.Background(), + "messenger-api", + cfg.InstanceID, + "lab", + ) + if err != nil { + log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err) + } + defer func() { + shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil { + log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr) + } + }() + + startupContext, startupCancel := context.WithTimeout( + context.Background(), + cfg.DatabaseConnectTimeout, + ) + + databasePool, err := database.Open(startupContext, cfg) + startupCancel() + + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer databasePool.Close() + if err = apptelemetry.RegisterDBPool(telemetryRuntime, databasePool); err != nil { + log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err) + } + + postgresStore := postgres.NewPostgreSQLStore( + databasePool, + cfg.DatabaseQueryTimeout, + ) + minioStore, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Invalid object storage configuration: %v", err) + } + storageContext, storageCancel := context.WithTimeout( + context.Background(), + cfg.S3OperationTimeout, + ) + if err = minioStore.Ping(storageContext); err != nil { + log.Printf("[WARN] Object storage unavailable at startup: %v", err) + } + storageCancel() + + var applicationStore application.Repository = postgresStore + + if cfg.RedisURL != "" { + redisChatCache, cacheError := redisadapter.NewRedisChatCache( + cfg.RedisURL, + cfg.RedisCacheTTL, + cfg.RedisOperationTimeout, + cfg.RedisPoolSize, + ) + if cacheError != nil { + log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError) + } + defer func() { + if closeError := redisChatCache.Close(); closeError != nil { + log.Printf("[WARN] Redis client close failed: %v", closeError) + } + }() + + cacheContext, cacheCancel := context.WithTimeout( + context.Background(), + cfg.RedisOperationTimeout, + ) + if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil { + log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError) + } else { + log.Println("[INFO] Redis chat cache is available") + } + cacheCancel() + + applicationStore = cacheadapter.NewCachedRepository( + postgresStore, + redisChatCache, + log.Default(), + ) + } + + cursorCodec, err := application.NewCursorCodec(cfg.CursorSigningKey) + if err != nil { + log.Fatalf("[FATAL] Invalid cursor configuration: %v", err) + } + + service, err := application.NewService( + applicationStore, + cursorCodec, + cfg.SessionTTL, + application.WithIdempotencyTTL(cfg.IdempotencyTTL), + application.WithObjectStore(minioStore), + application.WithJobMaxAttempts(cfg.JobMaxAttempts), + ) + if err != nil { + log.Fatalf("[FATAL] Application initialization failed: %v", err) + } + + handler := handlers.NewHandler( + service, + handlers.WithReadiness( + health.NewMultiChecker(databasePool, minioStore), + cfg.ReadinessTimeout, + ), + handlers.WithSessionCookieSecure(cfg.SessionCookieSecure), + handlers.WithLoginRateLimit(postgresStore, cfg.LoginRateLimit, cfg.LoginRateWindow), + ) + + mux := http.NewServeMux() + + mux.HandleFunc("GET /health/live", handler.HealthLive) + mux.HandleFunc("GET /health/lb", handler.HealthLive) + mux.HandleFunc("GET /health/ready", handler.HealthReady) + + mux.HandleFunc( + "POST /api/v1/auth/sessions", + handler.CreateSession, + ) + + mux.HandleFunc("POST /api/v1/users", handler.CreateUser) + + requireAuth := func(next http.HandlerFunc) http.HandlerFunc { + return middleware.RequireAuth(service, next) + } + + mux.HandleFunc( + "GET /api/v1/users/me", + requireAuth(handler.GetMe), + ) + + mux.HandleFunc( + "DELETE /api/v1/auth/sessions/current", + requireAuth(handler.DeleteCurrentSession), + ) + + mux.HandleFunc( + "POST /api/v1/chats", + requireAuth(handler.CreateChat), + ) + mux.HandleFunc( + "GET /api/v1/chats", + requireAuth(handler.ListChats), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}", + requireAuth(handler.GetChat), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/messages", + requireAuth(handler.CreateMessage), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}/messages", + requireAuth(handler.GetMessages), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/attachments", + requireAuth(handler.UploadAttachment), + ) + mux.HandleFunc( + "GET /api/v1/attachments/{attachment_id}", + requireAuth(handler.GetAttachment), + ) + mux.HandleFunc( + "GET /api/v1/attachments/{attachment_id}/content", + requireAuth(handler.DownloadAttachment), + ) + + var rootHandler http.Handler = mux + rootHandler = middleware.Recovery(rootHandler) + rootHandler, err = middleware.Observability(telemetryRuntime, rootHandler) + if err != nil { + log.Fatalf("[FATAL] HTTP observability initialization failed: %v", err) + } + availabilityGate := middleware.NewAvailabilityGate() + rootHandler = availabilityGate.Middleware(rootHandler) + rootHandler = middleware.RequestID(rootHandler) + rootHandler = middleware.InstanceID(cfg.InstanceID, rootHandler) + + server := &http.Server{ + Addr: cfg.HTTPAddress(), + Handler: rootHandler, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + } + server.TLSConfig, err = appsecurity.ServerMTLSConfig( + os.Getenv("TLS_CLIENT_CA_FILE"), + os.Getenv("TLS_ALLOWED_CLIENT_URI"), + os.Getenv("TLS_ALLOWED_CLIENT_URIS_FILE"), + ) + if err != nil { + log.Fatalf("[FATAL] Invalid internal mTLS configuration: %v", err) + } + tlsCertificateFile := os.Getenv("TLS_CERT_FILE") + tlsKeyFile := os.Getenv("TLS_KEY_FILE") + if tlsCertificateFile == "" || tlsKeyFile == "" { + log.Fatal("[FATAL] TLS_CERT_FILE and TLS_KEY_FILE are required") + } + + serverErrors := make(chan error, 1) + + go func() { + log.Printf( + "[INFO] Server instance %s starting on %s", + cfg.InstanceID, + server.Addr, + ) + serverErrors <- server.ListenAndServeTLS(tlsCertificateFile, tlsKeyFile) + }() + + shutdownSignals := make(chan os.Signal, 1) + signal.Notify( + shutdownSignals, + os.Interrupt, + syscall.SIGTERM, + ) + defer signal.Stop(shutdownSignals) + + select { + case serverError := <-serverErrors: + if !errors.Is(serverError, http.ErrServerClosed) { + log.Fatalf("[FATAL] Server crashed: %v", serverError) + } + + case signalValue := <-shutdownSignals: + log.Printf( + "[INFO] Signal %v received. Starting graceful shutdown...", + signalValue, + ) + + availabilityGate.BeginDrain() + log.Printf( + "[INFO] Readiness disabled; draining new traffic for %s", + cfg.ShutdownDrainDelay, + ) + time.Sleep(cfg.ShutdownDrainDelay) + + shutdownContext, shutdownCancel := context.WithTimeout( + context.Background(), + cfg.ShutdownTimeout, + ) + defer shutdownCancel() + + if err := server.Shutdown(shutdownContext); err != nil { + log.Printf( + "[WARN] Graceful shutdown failed: %v. Forcing close.", + err, + ) + _ = server.Close() + } + + log.Println("[INFO] Server stopped gracefully.") + } +} diff --git a/cmd/worker/main.go b/cmd/worker/main.go new file mode 100644 index 0000000..98512cc --- /dev/null +++ b/cmd/worker/main.go @@ -0,0 +1,280 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "os/signal" + "sync" + "syscall" + "time" + + "mtusi2026lab7/internal/adapter/broker" + "mtusi2026lab7/internal/adapter/objectstore" + "mtusi2026lab7/internal/adapter/postgres" + "mtusi2026lab7/internal/config" + "mtusi2026lab7/internal/database" + "mtusi2026lab7/internal/domain" + appsecrets "mtusi2026lab7/internal/secrets" + apptelemetry "mtusi2026lab7/internal/telemetry" + "mtusi2026lab7/internal/worker" +) + +const ( + defaultBeforeObjectsFaultFile = "/tmp/mtusi-fault-before-objects" + defaultAfterObjectsFaultFile = "/tmp/mtusi-fault-after-objects" +) + +func main() { + secretContext, secretCancel := context.WithTimeout(context.Background(), 15*time.Second) + err := appsecrets.LoadOpenBaoEnvironment(secretContext) + secretCancel() + if err != nil { + log.Fatalf("[FATAL] OpenBao secret bootstrap failed: %v", err) + } + cfg, err := config.LoadWorker() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + if cfg.BrokerURL == "" { + log.Fatal("[FATAL] BROKER_URL or BROKER_URL_FILE is required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + telemetryRuntime, err := apptelemetry.Start( + ctx, + "messenger-worker", + cfg.InstanceID, + "lab", + ) + if err != nil { + log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err) + } + defer func() { + shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil { + log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr) + } + }() + jobRecorder, err := apptelemetry.NewJobRecorder(telemetryRuntime, cfg.WorkerConcurrency) + if err != nil { + log.Fatalf("[FATAL] Worker observability initialization failed: %v", err) + } + pool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer pool.Close() + if err = apptelemetry.RegisterDBPool(telemetryRuntime, pool); err != nil { + log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err) + } + store := postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout) + objects, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Object storage initialization failed: %v", err) + } + + beforeFaultFile := os.Getenv("WORKER_FAULT_BEFORE_OBJECTS_FILE") + if beforeFaultFile == "" { + beforeFaultFile = defaultBeforeObjectsFaultFile + } + afterFaultFile := os.Getenv("WORKER_FAULT_AFTER_OBJECTS_FILE") + if afterFaultFile == "" { + afterFaultFile = defaultAfterObjectsFaultFile + } + processor, err := worker.NewProcessor(store, objects, worker.ProcessorHooks{ + BeforeObjects: func(job domain.AttachmentJob) error { + removeErr := os.Remove(beforeFaultFile) + if errors.Is(removeErr, os.ErrNotExist) { + return nil + } + if removeErr != nil { + return fmt.Errorf("consume before-objects fault marker: %w", removeErr) + } + log.Printf("[FAULT] exiting before object writes for job %s", job.JobID) + os.Exit(85) + return nil + }, + AfterObjects: func(job domain.AttachmentJob) error { + removeErr := os.Remove(afterFaultFile) + if errors.Is(removeErr, os.ErrNotExist) { + return nil + } + if removeErr != nil { + return fmt.Errorf("consume after-objects fault marker: %w", removeErr) + } + log.Printf("[FAULT] exiting after object writes and before DB commit for job %s", job.JobID) + os.Exit(86) + return nil + }, + }) + if err != nil { + log.Fatalf("[FATAL] Worker processor initialization failed: %v", err) + } + + cleaner, err := worker.NewStagingCleaner(store, objects, cfg.StagingRetention) + if err != nil { + log.Fatalf("[FATAL] Staging cleaner initialization failed: %v", err) + } + var maintenance sync.WaitGroup + maintenance.Add(1) + go func() { + defer maintenance.Done() + runCleanup := func() { + cleanupContext, cancel := context.WithTimeout(ctx, cfg.S3OperationTimeout+cfg.DatabaseQueryTimeout) + deleted, cleanupErr := cleaner.RunOnce(cleanupContext, time.Now().UTC()) + cancel() + if cleanupErr != nil && ctx.Err() == nil { + log.Printf("[WARN] Staging cleanup failed: %v", cleanupErr) + } else if deleted > 0 { + log.Printf("[INFO] Staging cleanup removed %d object(s)", deleted) + } + } + runCleanup() + ticker := time.NewTicker(cfg.StagingCleanupInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + runCleanup() + } + } + }() + + client, err := broker.Open(cfg.BrokerURL, cfg.WorkerConcurrency) + if err != nil { + log.Fatalf("[FATAL] RabbitMQ initialization failed: %v", err) + } + defer client.Close() + deliveries, err := client.Consume(cfg.InstanceID) + if err != nil { + log.Fatalf("[FATAL] RabbitMQ consume failed: %v", err) + } + + var group sync.WaitGroup + for index := 0; index < cfg.WorkerConcurrency; index++ { + group.Add(1) + go func(workerIndex int) { + defer group.Done() + workerID := fmt.Sprintf("%s-%d", cfg.InstanceID, workerIndex) + for delivery := range deliveries { + deliveryContext := broker.ContextFromDelivery(ctx, delivery) + message, decodeErr := broker.Decode(delivery) + if decodeErr != nil { + log.Printf("[WARN] Reject invalid broker message: %v", decodeErr) + _ = delivery.Reject(false) + continue + } + now := time.Now().UTC() + job, claimed, claimErr := store.ClaimAttachmentJob( + deliveryContext, + message, + workerID, + now.Add(cfg.JobLease), + ) + if errors.Is(claimErr, postgres.ErrNotFound) { + log.Printf("[INFO] Stale broker message for missing job %s acknowledged", message.JobID) + _ = delivery.Ack(false) + continue + } + if claimErr != nil { + log.Printf("[WARN] Claim job %s failed: %v", message.JobID, claimErr) + _ = delivery.Nack(false, true) + continue + } + if !claimed { + _ = delivery.Ack(false) + continue + } + + jobContext, cancel := context.WithTimeout(deliveryContext, cfg.JobTimeout) + jobContext, observedAttempt := jobRecorder.Start( + jobContext, + domain.AttachmentJobType, + broker.QueueName, + job.Attempt, + job.CreatedAt, + ) + processErr := processor.Process(jobContext, job) + observedAttempt.End(processErr) + cancel() + if processErr == nil { + _ = delivery.Ack(false) + continue + } + + var permanent *worker.PermanentError + if errors.As(processErr, &permanent) { + if failErr := store.FailAttachmentJob( + ctx, + job.JobID, + permanent.Code, + time.Now().UTC(), + ); failErr != nil { + log.Printf("[WARN] Persist permanent failure for job %s failed: %v", job.JobID, failErr) + _ = delivery.Nack(false, true) + } else { + log.Printf("[WARN] Job %s failed permanently with %s", job.JobID, permanent.Code) + _ = delivery.Ack(false) + } + continue + } + + retryAt := time.Now().UTC() + delay := worker.RetryDelay( + job.JobID, + job.Attempt+1, + cfg.JobRetryBase, + cfg.JobRetryMax, + ) + retried, final, retryErr := store.RetryAttachmentJob( + ctx, + job.JobID, + "processing_failed", + retryAt.Add(delay), + retryAt, + "retry_scheduled", + ) + if retryErr != nil { + log.Printf("[WARN] Schedule retry for job %s failed: %v", job.JobID, retryErr) + _ = delivery.Nack(false, true) + continue + } + if final && retried.Status == domain.AttachmentJobFailed { + log.Printf("[WARN] Job %s exhausted retries", job.JobID) + } else if final && retried.Status == domain.AttachmentJobSucceeded { + log.Printf("[INFO] Duplicate delivery for completed job %s acknowledged", job.JobID) + } else if final && retried.Status == domain.AttachmentJobSuperseded { + log.Printf("[INFO] Stale pipeline job %s acknowledged as superseded", job.JobID) + } else { + log.Printf("[INFO] Job %s retry %d scheduled after %s", job.JobID, retried.Attempt, delay) + } + _ = delivery.Ack(false) + } + }(index) + } + log.Printf( + "[INFO] Attachment worker started with concurrency=%d prefetch=%d lease=%s", + cfg.WorkerConcurrency, + cfg.WorkerConcurrency, + cfg.JobLease, + ) + <-ctx.Done() + _ = client.Close() + group.Wait() + maintenance.Wait() + log.Println("[INFO] Attachment worker stopped") +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..7199224 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,630 @@ +name: mtusi2026lab7 + +x-app-security: &app-security + read_only: true + security_opt: [no-new-privileges:true] + cap_drop: [ALL] + tmpfs: + - /tmp:rw,nosuid,nodev,noexec,size=64m + +x-app-environment: &app-environment + APP_ENV: lab + SSL_CERT_FILE: /run/secrets/tls_ca + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/secrets/tls_ca + OTEL_EXPORTER_OTLP_ENDPOINT: https://telemetry-gateway:4318 + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TIMEOUT: "3000" + OTEL_TRACES_SAMPLER: parentbased_always_on + CLIENT_TLS_CA_FILE: /run/secrets/tls_ca + CLIENT_TLS_CERT_FILE: /run/secrets/client_cert + CLIENT_TLS_KEY_FILE: /run/secrets/client_key + BROKER_TLS_SERVER_NAME: dependency-gateway + OTEL_TLS_SERVER_NAME: telemetry-gateway + +services: + ingress: + build: + context: . + dockerfile: infrastructure/haproxy/Dockerfile + image: mtusi2026lab7-ingress + ports: + - "127.0.0.1:${HTTPS_PORT:-8443}:8443" + secrets: [tls_ca, ingress_pem, lb_client_pem] + networks: [host_access, api_ingress] + depends_on: + api: + condition: service_started + healthcheck: + test: [CMD, haproxy, -c, -f, /usr/local/etc/haproxy/haproxy.cfg] + interval: 10s + timeout: 5s + retries: 10 + restart: unless-stopped + read_only: true + security_opt: [no-new-privileges:true] + cap_drop: [ALL] + deploy: + resources: + limits: {cpus: "0.25", memory: 128M} + + api: + build: + context: . + dockerfile: Dockerfile + image: mtusi2026lab7-app + environment: + <<: *app-environment + APP_HOST: 0.0.0.0 + APP_PORT: "8444" + INSTANCE_ID_FILE: /tmp/instance-id + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_COOKIE_SECURE: "true" + IDEMPOTENCY_TTL_SECONDS: "86400" + LOGIN_RATE_LIMIT: ${LOGIN_RATE_LIMIT:-5} + LOGIN_RATE_WINDOW_SECONDS: ${LOGIN_RATE_WINDOW_SECONDS:-60} + ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456} + ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2} + ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1} + S3_ENDPOINT: https://dependency-gateway:9000 + S3_REGION: us-east-1 + S3_BUCKET: messenger-attachments + JOB_MAX_ATTEMPTS: "5" + TLS_CERT_FILE: /run/secrets/api_cert + TLS_KEY_FILE: /run/secrets/api_key + TLS_CLIENT_CA_FILE: /run/secrets/tls_ca + TLS_ALLOWED_CLIENT_URIS_FILE: /run/secrets/api_client_uris + BAO_ROLE_ID_FILE: /run/secrets/bao_role_id + BAO_SECRET_ID_FILE: /run/secrets/bao_secret_id + BAO_SECRET_PATH: api + BAO_ENV_KEYS: DATABASE_URL,CACHE_URL,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY,CURSOR_SIGNING_KEY + secrets: + - tls_ca + - api_cert + - api_key + - api_client_uris + - source: api_client_cert + target: client_cert + - source: api_client_key + target: client_key + - source: bao_api_role_id + target: bao_role_id + - source: bao_api_secret_id + target: bao_secret_id + networks: [api_ingress, postgres_network, dependency_secure, telemetry_secure, openbao_network] + expose: ["8444"] + depends_on: + postgres: {condition: service_healthy} + dependency-gateway: {condition: service_healthy} + telemetry-gateway: {condition: service_healthy} + openbao: {condition: service_healthy} + healthcheck: + disable: true + restart: unless-stopped + <<: *app-security + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: {cpus: "0.50", memory: 256M} + + postgres: + image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea + entrypoint: [/bin/sh, -ec] + command: + - | + install -d -o postgres -g postgres -m 700 /var/lib/postgresql/tls + install -o postgres -g postgres -m 600 /run/secrets/postgres_key /var/lib/postgresql/tls/server.key + install -o postgres -g postgres -m 644 /run/secrets/postgres_cert /var/lib/postgresql/tls/server.crt + install -o postgres -g postgres -m 644 /run/secrets/tls_ca /var/lib/postgresql/tls/ca.crt + exec docker-entrypoint.sh postgres \ + -c ssl=on \ + -c ssl_cert_file=/var/lib/postgresql/tls/server.crt \ + -c ssl_key_file=/var/lib/postgresql/tls/server.key \ + -c ssl_ca_file=/var/lib/postgresql/tls/ca.crt + environment: + POSTGRES_USER: lab7_admin + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_admin_password + secrets: + - postgres_admin_password + - postgres_api_password + - postgres_worker_password + - postgres_dispatcher_password + - postgres_cert + - postgres_key + - tls_ca + - postgres_roles + volumes: [postgres_data:/var/lib/postgresql/data] + networks: [postgres_network] + healthcheck: + test: [CMD-SHELL, pg_isready -U lab7_admin -d messenger] + interval: 5s + timeout: 3s + retries: 20 + restart: unless-stopped + deploy: + resources: + limits: {cpus: "1.00", memory: 512M} + + migrate: + image: migrate/migrate:v4.20.1@sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7 + entrypoint: [/bin/sh, -ec] + command: + - | + password=$$(cat /run/secrets/postgres_admin_password) + exec migrate -path=/migrations \ + -database="postgres://lab7_admin:$${password}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/tls_ca" up + secrets: [postgres_admin_password, tls_ca] + volumes: + - ./migrations:/migrations:ro + networks: [postgres_network] + depends_on: + postgres: {condition: service_healthy} + restart: "no" + deploy: + resources: + limits: {cpus: "0.25", memory: 64M} + + redis: + image: redis:8.10.2-alpine3.23@sha256:3811787313eba226a2ef38658c6ccb91cd5e110edc89c37767de373120a0e5a0 + command: [redis-server, /run/secrets/redis_config] + user: "1000:1000" + secrets: + - redis_config + - redis_api_password + networks: [redis_local] + healthcheck: + test: [CMD-SHELL, 'redis-cli -u "redis://api:$$(cat /run/secrets/redis_api_password)@127.0.0.1:6379/0" ping | grep -q PONG'] + interval: 5s + timeout: 3s + retries: 20 + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.25", memory: 128M} + + minio: + build: + context: . + dockerfile: infrastructure/minio/Dockerfile + target: server + args: {MINIO_VERSION: RELEASE.2025-10-15T17-29-55Z} + image: mtusi2026lab7-minio:RELEASE.2025-10-15T17-29-55Z + command: [server, /data, --address, ":9000"] + environment: + MINIO_ROOT_USER_FILE: /run/secrets/minio_root_user + MINIO_ROOT_PASSWORD_FILE: /run/secrets/minio_root_password + MINIO_BROWSER: "off" + secrets: [minio_root_user, minio_root_password] + volumes: [minio_data:/data] + networks: [s3_local] + healthcheck: + test: [CMD-SHELL, wget -qO- http://127.0.0.1:9000/minio/health/live >/dev/null] + interval: 5s + timeout: 3s + retries: 30 + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.75", memory: 512M} + + minio-bootstrap: + build: + context: . + dockerfile: infrastructure/minio/Dockerfile + target: client + args: {MC_VERSION: RELEASE.2025-08-13T08-35-41Z} + image: mtusi2026lab7-mc:RELEASE.2025-08-13T08-35-41Z + entrypoint: [/bin/sh, -ec] + command: + - | + mc alias set local http://minio:9000 "$$(cat /run/secrets/minio_root_user)" "$$(cat /run/secrets/minio_root_password)" --api S3v4 + mc mb --ignore-existing local/messenger-attachments + mc anonymous set none local/messenger-attachments + sed 's/__BUCKET__/messenger-attachments/g' /policies/api.json > /tmp/api.json + sed 's/__BUCKET__/messenger-attachments/g' /policies/worker.json > /tmp/worker.json + mc admin policy create local messenger-api /tmp/api.json + mc admin policy create local messenger-worker /tmp/worker.json + mc admin user add local "$$(cat /run/secrets/s3_api_access_key)" "$$(cat /run/secrets/s3_api_secret_key)" + mc admin user add local "$$(cat /run/secrets/s3_worker_access_key)" "$$(cat /run/secrets/s3_worker_secret_key)" + mc admin policy attach local messenger-api --user "$$(cat /run/secrets/s3_api_access_key)" + mc admin policy attach local messenger-worker --user "$$(cat /run/secrets/s3_worker_access_key)" + secrets: + - minio_root_user + - minio_root_password + - s3_api_access_key + - s3_api_secret_key + - s3_worker_access_key + - s3_worker_secret_key + volumes: + - ./infrastructure/minio/api-policy.template.json:/policies/api.json:ro + - ./infrastructure/minio/worker-policy.template.json:/policies/worker.json:ro + networks: [s3_local] + depends_on: + minio: {condition: service_healthy} + restart: "no" + + broker: + image: rabbitmq:4.1.4-alpine + hostname: broker + entrypoint: [/bin/sh, -ec] + command: + - | + export RABBITMQ_DEFAULT_USER=dispatcher + export RABBITMQ_DEFAULT_PASS=$$(cat /run/secrets/broker_dispatcher_password) + exec docker-entrypoint.sh rabbitmq-server + secrets: [broker_dispatcher_password, broker_worker_password] + volumes: [broker_data:/var/lib/rabbitmq] + networks: [broker_local] + healthcheck: + test: [CMD, rabbitmq-diagnostics, -q, ping] + interval: 5s + timeout: 5s + retries: 30 + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.50", memory: 384M} + + dependency-gateway: + image: haproxy:3.2-alpine@sha256:dfba86f031bd4c9039f10f8cc5de75991d1b6766d5460f0335b980408503baad + user: "1000:1000" + volumes: + - ./infrastructure/gateways/dependency.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + secrets: [dependency_pem, tls_ca] + networks: [dependency_secure, redis_local, s3_local, broker_local] + depends_on: + redis: {condition: service_healthy} + minio: {condition: service_healthy} + broker: {condition: service_healthy} + healthcheck: + test: [CMD, haproxy, -c, -f, /usr/local/etc/haproxy/haproxy.cfg] + interval: 10s + timeout: 5s + retries: 10 + cap_drop: [ALL] + read_only: true + security_opt: [no-new-privileges:true] + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.25", memory: 128M} + + openbao: + image: openbao/openbao:2.4.4 + user: "1000:1000" + command: [server, -config=/openbao/config/config.hcl] + environment: + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/secrets/tls_ca + secrets: [tls_ca, openbao_cert, openbao_key] + volumes: + - ./volumes/openbao:/openbao/data + - ./infrastructure/openbao/config.hcl:/openbao/config/config.hcl:ro + - ./infrastructure/openbao/api-policy.hcl:/policies/api-policy.hcl:ro + - ./infrastructure/openbao/worker-policy.hcl:/policies/worker-policy.hcl:ro + - ./infrastructure/openbao/dispatcher-policy.hcl:/policies/dispatcher-policy.hcl:ro + - ./secrets/openbao:/bootstrap:ro + networks: [host_access, openbao_network] + ports: + - "127.0.0.1:${OPENBAO_PORT:-18200}:8200" + healthcheck: + test: [CMD-SHELL, 'bao status >/dev/null 2>&1; code=$$?; [ $$code -eq 0 ] || [ $$code -eq 2 ]'] + interval: 5s + timeout: 3s + retries: 30 + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.50", memory: 256M} + + dispatcher: + build: {context: ., dockerfile: Dockerfile} + image: mtusi2026lab7-app + entrypoint: [/app/dispatcher] + environment: + <<: *app-environment + INSTANCE_ID: dispatcher + BAO_ROLE_ID_FILE: /run/secrets/bao_role_id + BAO_SECRET_ID_FILE: /run/secrets/bao_secret_id + BAO_SECRET_PATH: dispatcher + BAO_ENV_KEYS: DATABASE_URL,BROKER_URL + secrets: + - tls_ca + - source: dispatcher_client_cert + target: client_cert + - source: dispatcher_client_key + target: client_key + - source: bao_dispatcher_role_id + target: bao_role_id + - source: bao_dispatcher_secret_id + target: bao_secret_id + networks: [postgres_network, dependency_secure, telemetry_secure, openbao_network] + depends_on: + postgres: {condition: service_healthy} + dependency-gateway: {condition: service_healthy} + telemetry-gateway: {condition: service_healthy} + openbao: {condition: service_healthy} + restart: unless-stopped + <<: *app-security + deploy: + resources: + limits: {cpus: "0.25", memory: 128M} + + worker: + build: {context: ., dockerfile: Dockerfile} + image: mtusi2026lab7-app + entrypoint: [/app/worker] + environment: + <<: *app-environment + INSTANCE_ID: worker + S3_ENDPOINT: https://dependency-gateway:9000 + S3_REGION: us-east-1 + S3_BUCKET: messenger-attachments + WORKER_CONCURRENCY: "1" + JOB_MAX_ATTEMPTS: "5" + JOB_TIMEOUT_SECONDS: "60" + JOB_LEASE_SECONDS: "75" + STAGING_RETENTION_SECONDS: "86400" + BAO_ROLE_ID_FILE: /run/secrets/bao_role_id + BAO_SECRET_ID_FILE: /run/secrets/bao_secret_id + BAO_SECRET_PATH: worker + BAO_ENV_KEYS: DATABASE_URL,BROKER_URL,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY + GOMEMLIMIT: 448MiB + secrets: + - tls_ca + - source: worker_client_cert + target: client_cert + - source: worker_client_key + target: client_key + - source: bao_worker_role_id + target: bao_role_id + - source: bao_worker_secret_id + target: bao_secret_id + networks: [postgres_network, dependency_secure, telemetry_secure, openbao_network] + depends_on: + postgres: {condition: service_healthy} + dependency-gateway: {condition: service_healthy} + telemetry-gateway: {condition: service_healthy} + openbao: {condition: service_healthy} + restart: unless-stopped + <<: *app-security + deploy: + resources: + limits: {cpus: "1.00", memory: 512M} + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.165.0 + command: [--config=/etc/otelcol-contrib/config.yaml] + volumes: + - ./infrastructure/telemetry/otel-collector/config.yaml:/etc/otelcol-contrib/config.yaml:ro + secrets: [tls_ca, collector_client_cert, collector_client_key] + group_add: ["1000"] + networks: [collector_local, telemetry_secure] + depends_on: + loki: {condition: service_started} + tempo: {condition: service_started} + restart: unless-stopped + read_only: true + security_opt: [no-new-privileges:true] + cap_drop: [ALL] + tmpfs: ["/tmp:rw,nosuid,nodev,noexec,size=32m"] + deploy: + resources: + limits: {cpus: "0.50", memory: 256M} + + loki: + image: grafana/loki:3.7.9 + command: [-config.file=/etc/loki/config.yaml] + volumes: + - ./infrastructure/telemetry/loki/config.yaml:/etc/loki/config.yaml:ro + - loki_data:/loki + networks: [loki_local] + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.50", memory: 384M} + + tempo: + image: grafana/tempo:2.10.5 + command: [-config.file=/etc/tempo/config.yaml] + volumes: + - ./infrastructure/telemetry/tempo/config.yaml:/etc/tempo/config.yaml:ro + - tempo_data:/var/tempo + networks: [tempo_local] + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.50", memory: 384M} + + prometheus: + image: prom/prometheus:v3.16.0 + command: + - --config.file=/etc/prometheus/prometheus.yaml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=7d + volumes: + - ./infrastructure/telemetry/prometheus/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro + - ./infrastructure/telemetry/prometheus/rules:/etc/prometheus/rules:ro + - prometheus_data:/prometheus + secrets: [tls_ca, prometheus_client_cert, prometheus_client_key] + group_add: ["1000"] + networks: [prometheus_local, telemetry_secure] + depends_on: + telemetry-gateway: {condition: service_started} + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.50", memory: 384M} + + grafana: + image: grafana/grafana:13.3.0 + user: "0:0" + environment: + GF_AUTH_ANONYMOUS_ENABLED: "false" + GF_SECURITY_ADMIN_USER: lab7-admin + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + GF_ANALYTICS_REPORTING_ENABLED: "false" + GF_ANALYTICS_CHECK_FOR_UPDATES: "false" + SSL_CERT_FILE: /run/secrets/tls_ca + secrets: [tls_ca, grafana_admin_password] + volumes: + - grafana_data:/var/lib/grafana + - ./infrastructure/telemetry/grafana/provisioning:/etc/grafana/provisioning:ro + - ./secrets/grafana-datasources.yaml:/etc/grafana/provisioning/datasources/datasources.yaml:ro + - ./infrastructure/telemetry/grafana/dashboards:/var/lib/grafana/dashboards:ro + networks: [grafana_local, telemetry_secure] + depends_on: + prometheus: {condition: service_started} + loki: {condition: service_started} + tempo: {condition: service_started} + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.50", memory: 384M} + + telemetry-gateway: + image: haproxy:3.2-alpine@sha256:dfba86f031bd4c9039f10f8cc5de75991d1b6766d5460f0335b980408503baad + user: "1000:1000" + volumes: + - ./infrastructure/gateways/telemetry.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + secrets: [telemetry_pem, tls_ca] + networks: [host_access, telemetry_secure, collector_local, loki_local, tempo_local, prometheus_local, grafana_local] + ports: + - "127.0.0.1:${GRAFANA_PORT:-13000}:3000" + - "127.0.0.1:${PROMETHEUS_PORT:-19090}:9090" + - "127.0.0.1:${LOKI_PORT:-13100}:3100" + - "127.0.0.1:${TEMPO_PORT:-13200}:3200" + healthcheck: + test: [CMD, haproxy, -c, -f, /usr/local/etc/haproxy/haproxy.cfg] + interval: 10s + timeout: 5s + retries: 10 + cap_drop: [ALL] + read_only: true + security_opt: [no-new-privileges:true] + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.25", memory: 128M} + + security-test: + profiles: [tests] + build: {context: ., dockerfile: Dockerfile} + image: mtusi2026lab7-app + entrypoint: [curl] + secrets: + - source: tls_ca + target: ca.crt + - source: lb_client_cert + target: lb-client.crt + - source: lb_client_key + target: lb-client.key + - source: wrong_client_cert + target: wrong-client.crt + - source: wrong_client_key + target: wrong-client.key + - source: foreign_client_cert + target: foreign-client.crt + - source: foreign_client_key + target: foreign-client.key + - source: api_client_cert + target: api-client.crt + - source: api_client_key + target: api-client.key + - source: worker_client_cert + target: worker-client.crt + - source: worker_client_key + target: worker-client.key + - source: dispatcher_client_cert + target: dispatcher-client.crt + - source: dispatcher_client_key + target: dispatcher-client.key + networks: [api_ingress, dependency_secure, telemetry_secure] + cap_drop: [ALL] + read_only: true + security_opt: [no-new-privileges:true] + tmpfs: ["/tmp:rw,nosuid,nodev,noexec,size=16m"] + deploy: + resources: + limits: {cpus: "0.10", memory: 64M} + +networks: + # A non-internal bridge is required for Docker to publish the explicitly + # loopback-bound operator ports. Application/dependency traffic stays on + # the isolated internal networks below. + host_access: {} + api_ingress: {internal: true} + postgres_network: {internal: true} + dependency_secure: {internal: true} + redis_local: {internal: true} + s3_local: {internal: true} + broker_local: {internal: true} + openbao_network: {internal: true} + telemetry_secure: {internal: true} + collector_local: {internal: true} + loki_local: {internal: true} + tempo_local: {internal: true} + prometheus_local: {internal: true} + grafana_local: {internal: true} + +volumes: + postgres_data: + minio_data: + broker_data: + prometheus_data: + loki_data: + tempo_data: + grafana_data: + +secrets: + tls_ca: {file: ./secrets/pki/ca.crt} + ingress_pem: {file: ./secrets/pki/ingress.pem} + api_cert: {file: ./secrets/pki/api.crt} + api_key: {file: ./secrets/pki/api.key} + api_client_uris: {file: ./secrets/pki/api-client-uris.txt} + api_client_cert: {file: ./secrets/pki/api-client.crt} + api_client_key: {file: ./secrets/pki/api-client.key} + worker_client_cert: {file: ./secrets/pki/worker-client.crt} + worker_client_key: {file: ./secrets/pki/worker-client.key} + dispatcher_client_cert: {file: ./secrets/pki/dispatcher-client.crt} + dispatcher_client_key: {file: ./secrets/pki/dispatcher-client.key} + lb_client_pem: {file: ./secrets/pki/lb-client.pem} + lb_client_cert: {file: ./secrets/pki/lb-client.crt} + lb_client_key: {file: ./secrets/pki/lb-client.key} + wrong_client_cert: {file: ./secrets/pki/wrong-client.crt} + wrong_client_key: {file: ./secrets/pki/wrong-client.key} + foreign_client_cert: {file: ./secrets/pki/foreign-client.crt} + foreign_client_key: {file: ./secrets/pki/foreign-client.key} + dependency_pem: {file: ./secrets/pki/dependency-gateway.pem} + telemetry_pem: {file: ./secrets/pki/telemetry-gateway.pem} + postgres_cert: {file: ./secrets/pki/postgres.crt} + postgres_key: {file: ./secrets/pki/postgres.key} + openbao_cert: {file: ./secrets/pki/openbao.crt} + openbao_key: {file: ./secrets/pki/openbao.key} + collector_client_cert: {file: ./secrets/pki/collector-client.crt} + collector_client_key: {file: ./secrets/pki/collector-client.key} + prometheus_client_cert: {file: ./secrets/pki/prometheus-client.crt} + prometheus_client_key: {file: ./secrets/pki/prometheus-client.key} + postgres_admin_password: {file: ./secrets/postgres_admin_password.txt} + postgres_api_password: {file: ./secrets/postgres_api_password.txt} + postgres_worker_password: {file: ./secrets/postgres_worker_password.txt} + postgres_dispatcher_password: {file: ./secrets/postgres_dispatcher_password.txt} + postgres_roles: {file: ./secrets/postgres-roles.sql} + redis_config: {file: ./secrets/redis.conf} + redis_api_password: {file: ./secrets/redis_api_password.txt} + minio_root_user: {file: ./secrets/minio_root_user.txt} + minio_root_password: {file: ./secrets/minio_root_password.txt} + s3_api_access_key: {file: ./secrets/s3_api_access_key.txt} + s3_api_secret_key: {file: ./secrets/s3_api_secret_key.txt} + s3_worker_access_key: {file: ./secrets/s3_worker_access_key.txt} + s3_worker_secret_key: {file: ./secrets/s3_worker_secret_key.txt} + broker_dispatcher_password: {file: ./secrets/broker_dispatcher_password.txt} + broker_worker_password: {file: ./secrets/broker_worker_password.txt} + grafana_admin_password: {file: ./secrets/grafana_admin_password.txt} + bao_api_role_id: {file: ./secrets/openbao/api_role_id.txt} + bao_api_secret_id: {file: ./secrets/openbao/api_secret_id.txt} + bao_worker_role_id: {file: ./secrets/openbao/worker_role_id.txt} + bao_worker_secret_id: {file: ./secrets/openbao/worker_secret_id.txt} + bao_dispatcher_role_id: {file: ./secrets/openbao/dispatcher_role_id.txt} + bao_dispatcher_secret_id: {file: ./secrets/openbao/dispatcher_secret_id.txt} diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a977..b415fff 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,37 +1,38 @@ -# Матрица доверия — заполнить в решении lab7 +# Матрица доверия — lab7, уровень 4 -Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. +Локальный root CA создаётся `scripts/init-secrets.sh`: CA действует 3650 дней, leaf certificates — 365 дней. Private keys находятся только в ignored `secrets/pki` с mode 0600/0640; CA certificate может передаваться клиенту. TLS gateways допускают plaintext только на отдельной `internal: true` сети между gateway и одним backend без опубликованного обхода. -| Связь | Минимум на 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 | - -Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. +| Связь | Порт/endpoint и server trust | Client/service identity и права | Срок credential | Положительный/отрицательный тест и конфиг | +| --- | --- | --- | --- | --- | +| Клиент → ingress/LB | `127.0.0.1:8443`, TLS 1.3; local CA; SAN `DNS:localhost, IP:127.0.0.1` | Bearer session; Basic только `POST /auth/sessions`; session в общей PostgreSQL | session 3600 s; leaf 365 d | `make test-security`: CA pass, empty trust store certificate error. `make test`: outsider/X-User-Id/logout. `infrastructure/haproxy/haproxy.cfg` | +| LB → API (обе реплики) | `api:8444`, TLS 1.3; ingress проверяет local CA и `verifyhost api` | mTLS cert с версионируемой URI SAN; API требует CA и точную URI allowlist из runtime secret | leaf 365 d; operator rotation | `make test-security-grade3`; `make rotate-leaf-grade4`: no/foreign/wrong/old/expired deny, active LB allow, host binding отсутствует. `internal/security/mtls.go` | +| API/worker/dispatcher → PostgreSQL | `postgres:5432`, native TLS, `sslmode=verify-full`, local CA, SAN `postgres` | Отдельные `messenger_api`, `messenger_worker`, `messenger_dispatcher`; явные table/sequence GRANT, без admin | static lab password до operator rotation; получается через AppRole token 15m | `scripts/bootstrap-dependencies.sh`; `secrets/postgres-roles.sql` генерируется локально; `compose.yaml` не передаёт admin secret приложению | +| API/worker → S3 | `dependency-gateway:9000`, TLS 1.3, CA + SAN gateway; дальше только закрытая `s3_local` сеть к MinIO 9000 | API: Put `staging/*`, Get `attachments/*`; worker: Get/Delete staging, CRUD attachments; разные access keys | static lab key до operator rotation; выдаётся через scoped OpenBao path | `./tests/minio_policy.sh`: staging read deny, attachment write deny, bucket create/anonymous GET deny. `infrastructure/minio/*-policy.template.json` | +| Dispatcher/worker → broker | `dependency-gateway:5671`, TLS 1.3, CA + SAN gateway; локальный hop к RabbitMQ 5672 только `broker_local` | mTLS exact CN `dispatcher`/`worker` с разными URI SAN; затем `dispatcher` publish-only и `worker` consume-only Rabbit ACL. API cert намеренно deny: API пишет transactional outbox, а не broker | leaf 365 d; password operator-rotated через scoped KV | `make test-security-grade4`: no cert, same-CA intruder/API deny; worker/dispatcher allow. `make test-acl-grade4`; `make rotate-secret-grade4` old password deny | +| API/worker/dispatcher → Collector | `telemetry-gateway:4318`, TLS 1.3, CA + SAN `telemetry-gateway`; локальный hop только `collector_local` | mTLS exact CN ACL; отдельные `api`, `worker`, `dispatcher` clientAuth leaf/URI identities; ingest port не published; headers/body не экспортируются | leaf 365 d | `make test-security-grade4`: no cert и same-CA intruder deny; все три scoped identities allow. `make test-telemetry-leak-grade4` | +| Collector → telemetry backends | HTTPS gateway `3100` (Loki), `4319` (Tempo); CA + SAN gateway | mTLS CN `otel-collector`, URI `spiffe://mtusi/lab7/collector`; Loki допускает collector write/Grafana read, Tempo ingest — только collector | leaf 365 d | HAProxy `verify required` + exact CN ACL. Missing/other client cert rejected; live Collector reports `Everything is ready` | +| Prometheus → Collector metrics | HTTPS gateway `8888/8889`; CA + SAN gateway | mTLS CN `prometheus`, URI `spiffe://mtusi/lab7/prometheus`; эти ports допускают только Prometheus | leaf 365 d | `prometheus.yaml` cert/key; targets scrape через `telemetry-gateway`; no-cert gateway connection rejected | +| Grafana → data sources | HTTPS gateway `9090/3100/3200`; CA + SAN gateway | mTLS CN `grafana`, URI `spiffe://mtusi/lab7/grafana`; generated ignored datasource provisioning embeds local client key, backend ACL разрешает только Grafana (Loki также collector) | leaf 365 d; Grafana admin password static local | `make test-security-grade3`: no cert и LB cert deny, Grafana cert allow на Prometheus. `secrets/grafana-datasources.yaml` не в Git | +| API/worker/dispatcher → OpenBao | `openbao:8200`, native TLS 1.3, CA + SAN `openbao` | AppRole `api`, `worker`, `dispatcher`; каждая policy — read только `secret/data/`; root/unseal отсутствуют в app | token TTL 15m/max 30m; SecretID 168h; lifecycle test uses bounded 10s/24s token and one-use SecretID | policy allow/deny plus `make test-openbao-lifecycle-grade4`: reuse/expiry/seal/fresh-start fail-closed/unseal recovery | +| Оператор → OpenBao/Grafana/S3 admin | OpenBao `127.0.0.1:18200` TLS; Grafana `127.0.0.1:13000` TLS; S3 admin port не published | OpenBao root/unseal только `.operator` 0600; Grafana login password file; MinIO root только one-shot bootstrap service | operator material до ручной rotation; Grafana/MinIO static local | `docker compose ps` показывает loopback binding; API containers не имеют MinIO root/OpenBao root. `./tests/minio_policy.sh` | +| API → Redis | `dependency-gateway:6380`, TLS 1.3, CA + SAN gateway; локальный hop только `redis_local` | Redis ACL user `api`: `~chat:v2:*`, команды get/set/del/ping; default user off | static lab password до operator rotation; scoped API OpenBao path | generated ignored `secrets/redis.conf`; Redis 6379 не published; readiness/cache tests проходят | +| Replication/cluster channels | N/A: PostgreSQL, Redis, MinIO, RabbitMQ, OpenBao и telemetry stores одноузловые | Кластерная/host HA не заявлена; две API-реплики разделяют stores | N/A | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` доказывает только API process failover, не отказ host/store | ## Обязательные отрицательные проверки -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. Покажите новое подключение, иначе тест отзыва может ничего не проверить. +1. `make test-security` различает успешный HTTPS и ошибку certificate verification с пустым trust store. +2. `make test-security-grade3` выполняет четыре LB→API случая и проверяет отсутствие host binding API. Тем же скриптом telemetry backend отвергает отсутствие cert и доверенный LB cert, но принимает Grafana identity. +3. `make test` проверяет, что пользователь вне чата не читает metadata/content, а `X-User-Id` не переопределяет Bearer identity. +4. `make test-openbao-policy` доказывает allow/deny scoped AppRole без передачи root token приложению. +5. `./tests/minio_policy.sh` проверяет реальные prefix rights и отсутствие root credentials в API. +6. `make test-security-grade4` проверяет mTLS broker/Collector, включая чужой сертификат той же CA; `make test-acl-grade4` проверяет DB/Redis/Rabbit permissions. +7. `make rotate-leaf-grade4` удаляет старую LB URI из allowlist, проверяет old/expired deny и active leaf allow без rebuild. +8. `make test-telemetry-leak-grade4` сверяет Loki с credential probe и всеми локальными secret values, не печатая их. ## Bootstrap и эксплуатация -В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. +В Git находятся только генераторы, policy templates и public CA configuration. `secrets/`, `.operator/` и `volumes/` игнорируются. CA key, leaf keys, passwords, SecretID, root token и unseal share не входят в image layers и отчёт. -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 — хорошее расширение, но не обязательное название технологии. +Оператор выполняет `make up`. При первой инициализации OpenBao root/unseal JSON сохраняется отдельно от storage в `.operator` mode 0700/0600. App images не содержат постоянный bootstrap secret: service получает ограниченный по сроку SecretID через runtime mount, обменивает его на bounded token и читает один allowlisted KV path. После рестарта OpenBao sealed; `scripts/bootstrap-openbao.sh` читает operator file, выполняет unseal и обновляет policies/KV/SecretID, после чего app containers пересоздаются. Потеря operator file при initialized storage требует внешней резервной копии unseal material; приложение восстановить trust само не может. -Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. +`scripts/rotate-secret-grade4.sh` меняет worker RabbitMQ password в backend и scoped KV, пересоздаёт только worker с `--no-build` и доказывает old deny. `scripts/rotate-leaf-grade4.sh` выпускает новый LB client leaf, атомарно меняет cert/allowlist, пересоздаёт edge с `--no-build` и доказывает old/expired deny. Образа CA/root material не получают; фонового renewal agent нет, поэтому штатные 7 d SecretID и 365 d leaf обновляет оператор до expiry. diff --git a/evidence/grade3-summary.md b/evidence/grade3-summary.md new file mode 100644 index 0000000..230a06c --- /dev/null +++ b/evidence/grade3-summary.md @@ -0,0 +1,101 @@ +# Sanitized grade-3 evidence — 2026-11-18 + +No passwords, tokens, private keys, Authorization headers or user content are included. + +## Toolchain + +- Go 1.27.4 linux/amd64 +- Docker Engine 29.7.2; Compose 5.5.0 +- OpenSSL 3.5.5 +- Intel Core i5-1135G7, 8 vCPU exposed to WSL, 3.7 GiB RAM + +## Checks + +```text +make check +PASS: offline skeleton structure, local refs and Python syntax + +PYTHON=/tmp/lab7-venv/bin/python make validate +PASS: full OpenAPI 3.1 and JSON Schema validation + +go test ./... +PASS + +go vet ./... +PASS + +make test +PASS: lab7 public API scenario + +make test-security +PASS: trusted HTTPS works; untrusted CA rejected + +make test-security-grade3 +PASS: missing/foreign/wrong-identity LB certificates rejected +PASS: allowed LB identity accepted +PASS: API replicas have no published bypass port +PASS: telemetry missing/wrong identity rejected; Grafana identity accepted + +make test-rate-limit-grade3 +PASS: login limit is shared across replicas and returns 429 with Retry-After + +make test-openbao-policy +PASS: own path allow; foreign path, policy admin and write deny + +./tests/minio_policy.sh +PASS: staging write-only; attachments read-only; bucket create/anonymous GET deny + +go run golang.org/x/vuln/cmd/govulncheck@latest ./... +No vulnerabilities found. (govulncheck v1.10.0) +``` + +## Argon2id benchmark + +```text +BenchmarkHashPasswordGrade3-8 5 32716606 ns/op +``` + +Parameters: Argon2id `m=19456 KiB`, `t=2`, `p=1`; five fixed iterations. This is a local latency observation, not a universal target. + +## Closed-loop synthetic load + +```json +{ + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30, + "elapsed_seconds": 30.094, + "concurrency": 4, + "successful_requests": 1959, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 65.095, + "successful_latency_ms": {"p50": 87.901, "p95": 100.057, "p99": 106.397} +} +``` + +One `docker stats --no-stream` sample during the run: + +| Container | CPU | Memory | +| --- | ---: | ---: | +| API-1 | 10.19% | 16.38 MiB / 256 MiB | +| API-2 | 11.07% | 21.20 MiB / 256 MiB | +| ingress | 25.09% | 23.41 MiB / 128 MiB | +| PostgreSQL | 13.89% | 68.33 MiB / 512 MiB | + +Closed-loop percentiles cover successful requests only and include client overhead/coordinated omission. + +## Failure hooks + +```text +make test-persistence ACTION_SCRIPT=scripts/restart.sh +PASS: persistence preserved confirmed data and existing session + +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +observed_instances_before=2 +successful_writes=110 +failed_attempts=8 +first_recovery_seconds=4.932 +PASS: confirmed data preserved; duplicate messages not observed +``` + +The persistence hook restarted PostgreSQL, Redis, MinIO, RabbitMQ, OpenBao and telemetry stores with volumes, performed operator unseal/bootstrap, then recreated the app processes. The failover hook stopped exactly the API instance named by its opaque `X-Instance-Id` and left the other replica serving. diff --git a/evidence/grade4-summary.md b/evidence/grade4-summary.md new file mode 100644 index 0000000..16f2b36 --- /dev/null +++ b/evidence/grade4-summary.md @@ -0,0 +1,32 @@ +# Санитизированное доказательство уровня 4 + +Дата воспроизведения: 2026-11-22. Стенд и ограничения нагрузки описаны в `REPORT.md`. Secret values, tokens, private keys и полные credential-bearing responses в этот файл не записывались. + +## Identity, ACL и hardening + +- `make test-security-grade4` — PASS. Broker отверг отсутствие client certificate, same-CA intruder и API identity без broker edge; принял отдельные worker/dispatcher identities. OTLP gateway отверг отсутствие cert и same-CA intruder; принял отдельные api/worker/dispatcher identities. +- Тот же сценарий подтвердил read-only rootfs, `no-new-privileges`, `cap_drop: ALL` у application containers и ограничения worker: 1 CPU, 512 MiB, `GOMEMLIMIT=448MiB`, concurrency 1, timeout 60 s. +- `tests/attachment_boundaries.py` — PASS. Ровно 10 MiB и 40 000 000 pixels обработаны; сразу после проверки worker использовал 426.3 MiB/512 MiB, `OOMKilled=false`. +- `make test-acl-grade4` — PASS. PostgreSQL использует `verify-full`; dispatcher имеет `SELECT,UPDATE` только для recovery attachment, не читает users и не удаляет attachments. Redis API user ограничен cache prefix и не управляет ACL; RabbitMQ producer/consumer permissions ограничены одной attachment queue. Реальный reaper восстановил найденную просроченную job после точечного grant. +- `make test-telemetry-leak-grade4` — PASS. Loki содержит structured application events, но не содержит уникальный wrong-password probe, Authorization/Basic/Bearer, request bodies и значения ignored secret files. + +## Credential lifecycle + +- `make rotate-secret-grade4` — PASS. RabbitMQ worker password заменён в backend и scoped OpenBao KV; старый credential отвергнут, новый принят; worker пересоздан с `--no-build`, image ID не изменился. +- `make rotate-leaf-grade4` — PASS. Выпущена новая уникальная LB URI identity; предыдущий и `days=0` leaf отвергнуты, новый принят; app/ingress image IDs не изменились. +- `make test-openbao-lifecycle-grade4` — PASS. One-use SecretID нельзя использовать повторно; renewable token работает после исходного TTL и прекращает работать на max TTL; при seal уже работающий API продолжает использовать загруженные credentials, новый API fail-closed; operator unseal восстанавливает запуск без rebuild. + +## Password и login DoS + +- `go test ./internal/security ./student_tests` — PASS. Legacy Argon2id PHC `m=8192,t=1` после успешной проверки заменяется текущим hash через compare-and-set; wrong password не запускает rehash. +- `make login-dos-benchmark` — `23485943 ns/op` (23.485943 ms/op на этом стенде). Общий PostgreSQL limiter выполняется до KDF и допускает 5 попыток за 60 s: измеренный верхний бюджет около 117 ms Argon2 CPU/min на один normalized identifier. +- `make test-rate-limit-grade3` — PASS: запросы распределились по обеим API replicas, первые пять дали 401, шестой — 429 с `Retry-After`. +- `make test-state-pruning-grade4` — PASS: bounded indexed cleanup удалил истёкшую limiter row, но сохранил активное окно с attempts=4. Session/idempotency и limiter batch ограничен 256 rows и запускается не чаще раза на 128 операций после первого запуска. + +## Регрессия и сканирование + +- `go test ./...`, `go vet ./...`, `make check`, полная `make validate`, `docker compose config --quiet` и `git diff --check` — PASS. +- `make test`, `make test-security-grade3`, `make test-openbao-policy`, `./tests/minio_policy.sh` — PASS; публичный контракт, предыдущий mTLS boundary и scoped policies не ослаблены. +- `make scan-grade4` — PASS по заявленной политике. `govulncheck v1.10.0`: no reachable vulnerabilities; strict Trivy 0.76.2: 0 HIGH/CRITICAL fixed для app и ingress. Обязательный informational scan архивированного upstream показал MinIO 40 HIGH/4 CRITICAL и `mc` 26 HIGH/1 CRITICAL; применимость, компенсирующие меры и production-блокер зафиксированы в `security/SCAN_TRIAGE.md`. + +Все команды воспроизводимы из `REPORT.md`. Это локальная evidence summary, а не CI attestation или cryptographic provenance. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c0b6d2a --- /dev/null +++ b/go.mod @@ -0,0 +1,61 @@ +module mtusi2026lab7 + +go 1.27.1 + +require ( + github.com/disintegration/imaging v1.6.2 + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.11.0 + github.com/mayahiro/go-webp v0.4.0 + github.com/minio/minio-go/v7 v7.4.1 + github.com/rabbitmq/amqp091-go v1.14.0 + github.com/redis/go-redis/v9 v9.23.0 + go.opentelemetry.io/otel v1.46.0 + go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.22.0 + go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.46.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 + go.opentelemetry.io/otel/log v0.22.0 + go.opentelemetry.io/otel/metric v1.46.0 + go.opentelemetry.io/otel/sdk v1.46.0 + go.opentelemetry.io/otel/sdk/log v0.22.0 + go.opentelemetry.io/otel/sdk/metric v1.46.0 + go.opentelemetry.io/otel/trace v1.46.0 + golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2 + golang.org/x/image v0.45.0 +) + +require ( + github.com/cenkalti/backoff/v5 v5.0.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-logr/logr v1.4.4 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/klauspost/compress v1.20.2 // indirect + github.com/klauspost/cpuid/v2 v2.4.0 // indirect + github.com/klauspost/crc32 v1.3.0 // indirect + github.com/minio/crc64nvme v1.1.1 // indirect + github.com/minio/md5-simd v1.1.2 // indirect + github.com/philhofer/fwd v1.2.0 // indirect + github.com/rs/xid v1.6.0 // indirect + github.com/tinylib/msgp v1.6.4 // indirect + github.com/zeebo/xxh3 v1.1.0 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect + go.opentelemetry.io/proto/otlp v1.11.0 // indirect + go.uber.org/atomic v1.12.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 // indirect + google.golang.org/grpc v1.83.2 // indirect + google.golang.org/protobuf v1.36.12 // indirect + gopkg.in/ini.v1 v1.67.3 // indirect +) + diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..d5533a3 --- /dev/null +++ b/go.sum @@ -0,0 +1,143 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c= +github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= +github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo= +github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM= +github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw= +github.com/mayahiro/go-webp v0.4.0 h1:2uHEKvvSBREhAB7iDkYC/oZ4K9gbdigk63mLWPBugDQ= +github.com/mayahiro/go-webp v0.4.0/go.mod h1:Z1wt6V5/6f7pUwPsfhA6EbHb7ZhIcoQ7k7/tY9JNG4c= +github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI= +github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= +github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.4.1 h1:PtU/zIOfQRWZ+QydXAZysc+xZYHdG+BBR4Z6TUvy73w= +github.com/minio/minio-go/v7 v7.4.1/go.mod h1:nQnQi7zTfXR4lREtYXZQWqo5aw0Rqv+ZqCGrTORygRk= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek= +github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= +github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s= +github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0= +github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ= +github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= +github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= +github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc= +go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.22.0 h1:lYk7RmxdLK865qLwibroNGldHa1U7SWKYYvNjlK7PIo= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.22.0/go.mod h1:6GvlND0H0xdUJanOtIAn0xfwLkauh1tmsYEEVSMDdqY= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.46.0 h1:AP23h/mFgb/lc7tdck1Kfn9qxsM8TAeNPCU5C3pzaps= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.46.0/go.mod h1:K4EqCe1b4kGk5WR690ntg9LaBfsPoV32FwthbyoptuA= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM= +go.opentelemetry.io/otel/log v0.22.0 h1:5DBNnfvaJ6CVdkJ+Jle8Tzs50aSSv49TXGj9XRsEYw0= +go.opentelemetry.io/otel/log v0.22.0/go.mod h1:gzOt/R67vF2GniAqWu8Qv0SXy89f71muHcrkz76PCdc= +go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8= +go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o= +go.opentelemetry.io/otel/metric/x v0.68.0 h1:TA/cBT23D3MnxYPwHL7YFOdYGdx0A0v+s7Mzotpd1dU= +go.opentelemetry.io/otel/metric/x v0.68.0/go.mod h1:agudOmvWhwUTjgibWDzxD2PoWYnpw5Ht5jISYOD2Hd4= +go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI= +go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM= +go.opentelemetry.io/otel/sdk/log v0.22.0 h1:PRL+s6P63XT4E/bheEflopPUpVxuvANqZwtt89yhoGk= +go.opentelemetry.io/otel/sdk/log v0.22.0/go.mod h1:JNp0sBELrjCTcu5W3GzABVypeU6vDJjBS+X0JISuz+g= +go.opentelemetry.io/otel/sdk/log/logtest v0.22.0 h1:infPnfNrhCNgOUZRs3gWUg8vhoBUHihq02gwK05gzlg= +go.opentelemetry.io/otel/sdk/log/logtest v0.22.0/go.mod h1:gkQZA3z15Bv3KU9vigBTi8dFechSozRP7v94X4VZv+s= +go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE= +go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4= +go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c= +go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI= +go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= +go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= +go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= +go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2 h1:zGDaB+/Mus2mScKvZ23k+W9NAUbP56sNM9SptgvWI5A= +golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0= +golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688 h1:ax2KzoSRIZU/M0cIxri3pKxy99vniH1PVxWC6si/eZI= +google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688/go.mod h1:1RJ9BQGyNdZwkGc1eTqkErfRZ6RJyYPHZo73BZ1vQqI= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 h1:cYNAzI2sUwhmCcoj9TxvihSrqsxt6uIkj3rDRhSDmW4= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA= +google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= +google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw= +gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= + diff --git a/infra/README.md b/infra/README.md index 5a39e86..295798b 100644 --- a/infra/README.md +++ b/infra/README.md @@ -1,7 +1,31 @@ -# Инфраструктура студента +# Инфраструктура lab7 -Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли. +Основная запускаемая топология находится в `compose.yaml`; `compose.example.yaml` остаётся worksheet задания и не используется. Версии, healthchecks, volumes, internal networks и CPU/RAM limits зафиксированы в Compose. -В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд. +| Роль | Service | Storage | Доступ | +| --- | --- | --- | --- | +| TLS ingress/LB | `ingress` / HAProxy 3.2 | stateless | `127.0.0.1:8443`; mTLS к API | +| API | `api` ×2 / локальный Go image | PostgreSQL/S3 | internal 8444 only | +| Source of truth | `postgres` 16.15 | `postgres_data` | native TLS, internal only | +| Cache | `redis` 8.10.2 | ephemeral | TLS gateway + ACL | +| Objects | `minio` pinned last release | `minio_data` | TLS gateway, scoped API/worker users; archived upstream risk в `security/SCAN_TRIAGE.md` | +| Jobs | `broker` RabbitMQ 4.1.4 | `broker_data` | TLS gateway, producer/consumer ACL | +| Secrets | `openbao` 2.4.4 | `volumes/openbao` | TLS, AppRole; operator port 18200 | +| Telemetry | Collector 0.165, Prometheus 3.16, Loki 3.7.9, Tempo 2.10.5, Grafana 13.3 | named volumes | TLS/mTLS gateway; admin ports loopback | -Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику. +`scripts/bootstrap-dependencies.sh` выполняет migrations, создаёт DB roles/GRANT, private bucket/MinIO policies и RabbitMQ identities/ACL. `scripts/bootstrap-openbao.sh` выполняет operator init/unseal и AppRole/policy/KV bootstrap. Оба сценария повторяемы и не печатают secret values. + +Worker намеренно ограничен одной тяжёлой image job одновременно: 1 CPU, 512 MiB, `GOMEMLIMIT=448MiB`, timeout 60 s. Истёкшие auth/idempotency rows удаляются небольшими индексированными batch, а dispatcher получает `UPDATE` attachments только для lease recovery. + +```sh +make up +docker compose ps +make test +make test-security-grade4 +make test-acl-grade4 +make test-state-pruning-grade4 +make test-telemetry-leak-grade4 +make scan-grade4 +``` + +`scripts/restart.sh` перезапускает реальные stores с сохранением volumes и требует operator unseal. `scripts/stop-one.sh` останавливает ровно одну API-реплику по opaque instance id. `scripts/rotate-secret-grade4.sh` и `scripts/rotate-leaf-grade4.sh` доказывают rotation/revocation без пересборки image. `make cleanup-lab` сохраняет named volumes, ignored operator material и pulled third-party images. diff --git a/infra/openbao/README.md b/infra/openbao/README.md index 0850e23..0019378 100644 --- a/infra/openbao/README.md +++ b/infra/openbao/README.md @@ -1,7 +1,69 @@ -# OpenBao — реализовать конфигурацию и политики +# OpenBao в lab7 -Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key. +Рабочие файлы находятся в `infrastructure/openbao`; эта папка описывает operator procedure. Используется OpenBao 2.4.4 не в dev-mode: file storage `volumes/openbao`, TLS 1.3 listener 8200 и отключённый UI. Host публикует TLS endpoint только на `127.0.0.1:18200`. -Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения. +## Первый запуск -Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md. +```sh +./scripts/init-secrets.sh +docker compose up -d openbao +./scripts/bootstrap-openbao.sh +``` + +Bootstrap идемпотентно: + +1. выполняет `operator init` только для нового storage; +2. сохраняет root token и unseal share в ignored `.operator/openbao-init.json` (directory 0700, file 0600); +3. выполняет unseal по явному запуску оператором; +4. включает KV v2 `secret/` и AppRole; +5. записывает policies и локально подготовленные `secret/{api,worker,dispatcher}`; +6. выдаёт отдельные role ID/SecretID в ignored `secrets/openbao` mode 0600. + +Скрипт не печатает root token, share, service tokens или secret values. `.operator` не монтируется в app/worker/dispatcher и не находится в OpenBao storage. Для реального использования operator file нужно хранить в отдельном защищённом backup; threshold 1/1 — явное упрощение однооператорного учебного стенда. + +## Политики и lifecycle + +- `api-policy.hcl`: `read` только `secret/data/api`. +- `worker-policy.hcl`: `read` только `secret/data/worker`. +- `dispatcher-policy.hcl`: `read` только `secret/data/dispatcher`. +- App token TTL 15 минут, max TTL 30 минут. +- SecretID TTL 168 часов. Приложение получает token через AppRole, читает allowlisted keys один раз при старте и не хранит token как постоянный `BAO_TOKEN`. + +`internal/secrets/openbao.go` требует HTTPS, local CA, TLS 1.3, запрещает redirects и переносит в environment только имена из `BAO_ENV_KEYS`. Неизвестный/отсутствующий ключ завершает startup ошибкой. + +Проверка реальных allow/deny: + +```sh +make test-openbao-policy +``` + +Ожидается: API own path allow; worker path, policy administration и KV write deny. + +Проверка lifecycle использует отдельную временную AppRole с one-use SecretID и token TTL 10 s/max 24 s, не изменяя штатные роли: + +```sh +make test-openbao-lifecycle-grade4 +``` + +Сценарий доказывает запрет повторного SecretID, renewal после исходного TTL, окончательный expiry на max TTL, сохранение уже загруженных credentials у работающего API при seal, fail-closed нового API и восстановление после operator unseal без rebuild. + +## Restart и восстановление + +OpenBao после restart sealed. Работающие процессы продолжают использовать уже прочитанные downstream credentials, но новый процесс fail-closed не запустится. Оператор выполняет: + +```sh +./scripts/bootstrap-openbao.sh +docker compose up -d --force-recreate api worker dispatcher +``` + +Полный проверенный сценарий с рестартом stores, unseal и сохранением данных: + +```sh +make test-persistence ACTION_SCRIPT=scripts/restart.sh +``` + +Если persistent storage initialized, а `.operator/openbao-init.json` потерян, скрипт останавливается и требует от оператора восстановить unseal material из защищённой копии. Он не переинициализирует storage и не создаёт новый root trust автоматически. + +## Компрометация + +Для скомпрометированного service operator отзывает его SecretID/token, создаёт новый SecretID и пересоздаёт только этот контейнер. Статические downstream credentials меняются в соответствующем backend и KV, затем service пересоздаётся. `make rotate-secret-grade4` проверяет этот процесс для рабочего RabbitMQ password: старое значение отозвано, новое принято, image ID не меняется. `make rotate-leaf-grade4` аналогично заменяет LB leaf и runtime URI allowlist, после чего старый и просроченный leaf отвергаются. Фоновый agent автоматической ротации, CA rollover и CRL/OCSP не реализованы. diff --git a/infra/otel/README.md b/infra/otel/README.md index c46fe89..d669ae2 100644 --- a/infra/otel/README.md +++ b/infra/otel/README.md @@ -1,7 +1,21 @@ -# Конфигурация наблюдаемости — реализовать +# Наблюдаемость lab7 -Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend. +Реальные конфиги находятся в `infrastructure/telemetry`. API/worker/dispatcher экспортируют OTLP/HTTP через TLS gateway 4318 в Collector. Collector применяет memory limiter 192 MiB и batch, затем: -Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`. +- metrics предоставляет Prometheus exporter 8889; +- traces отправляет по mTLS в Tempo через gateway 4319; +- logs отправляет по mTLS в Loki через gateway 3100. -Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён. +Prometheus scrape 8888/8889 и Grafana data sources также используют отдельные mTLS client identities. Backend plaintext listeners присутствуют только на отдельных `internal: true` local networks с TLS gateway; host ports loopback. Grafana anonymous access отключён, admin password поступает через file secret. + +Collector не получает HTTP Authorization/session headers и message body из instrumentation. Queue/retry ограничены: два consumers, queue 256, max elapsed retry 30 s; переполнение не превращается в неограниченный рост RAM. + +```sh +docker compose logs otel-collector +docker compose ps telemetry-gateway prometheus loki tempo grafana +make test-security-grade3 +make test-security-grade4 +make test-telemetry-leak-grade4 +``` + +Ожидаемые признаки: Collector `Everything is ready`, gateway backends UP; Prometheus identity проходит scrape, а missing/LB identity к data-source port отклоняется. OTLP gateway требует разные exact-CN identities `api`, `worker`, `dispatcher`: отсутствие сертификата и same-CA intruder отклоняются. Leak-тест отправляет уникальный credential probe, затем подтверждает наличие structured events и отсутствие probe, Authorization/Basic/Bearer, request body и всех локальных secret values в Loki. Alert/incident набор lab6 сохранён. diff --git a/infrastructure/gateways/dependency.cfg b/infrastructure/gateways/dependency.cfg new file mode 100644 index 0000000..63aa480 --- /dev/null +++ b/infrastructure/gateways/dependency.cfg @@ -0,0 +1,33 @@ +global + log stdout format raw local0 + maxconn 1024 + +defaults + log global + mode tcp + timeout connect 3s + timeout client 60s + timeout server 60s + +frontend s3_tls + bind :9000 ssl crt /run/secrets/dependency_pem ssl-min-ver TLSv1.3 + mode http + default_backend s3_plain +backend s3_plain + mode http + server minio minio:9000 check + +frontend broker_tls + bind :5671 ssl crt /run/secrets/dependency_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3 + acl worker_identity ssl_c_s_dn(cn) -m str worker + acl dispatcher_identity ssl_c_s_dn(cn) -m str dispatcher + tcp-request content reject unless worker_identity or dispatcher_identity + default_backend broker_plain +backend broker_plain + server broker broker:5672 check + +frontend redis_tls + bind :6380 ssl crt /run/secrets/dependency_pem ssl-min-ver TLSv1.3 + default_backend redis_plain +backend redis_plain + server redis redis:6379 check diff --git a/infrastructure/gateways/telemetry.cfg b/infrastructure/gateways/telemetry.cfg new file mode 100644 index 0000000..0c8d4a1 --- /dev/null +++ b/infrastructure/gateways/telemetry.cfg @@ -0,0 +1,75 @@ +global + log stdout format raw local0 + maxconn 2048 + +defaults + log global + mode http + timeout connect 3s + timeout client 60s + timeout server 60s + +frontend otlp_tls + bind :4318 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required alpn h2,http/1.1 ssl-min-ver TLSv1.3 + acl api_identity ssl_c_s_dn(cn) -m str api + acl worker_identity ssl_c_s_dn(cn) -m str worker + acl dispatcher_identity ssl_c_s_dn(cn) -m str dispatcher + http-request deny deny_status 403 unless api_identity or worker_identity or dispatcher_identity + default_backend collector_otlp +backend collector_otlp + server collector otel-collector:4318 check + +frontend collector_metrics_tls + bind :8889 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3 + acl prometheus_identity ssl_c_s_dn(cn) -m str prometheus + http-request deny deny_status 403 unless prometheus_identity + default_backend collector_metrics +backend collector_metrics + server collector otel-collector:8889 check + +frontend collector_internal_tls + bind :8888 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3 + acl prometheus_identity ssl_c_s_dn(cn) -m str prometheus + http-request deny deny_status 403 unless prometheus_identity + default_backend collector_internal +backend collector_internal + server collector otel-collector:8888 check + +frontend loki_tls + bind :3100 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3 + acl collector_identity ssl_c_s_dn(cn) -m str otel-collector + acl grafana_identity ssl_c_s_dn(cn) -m str grafana + http-request deny deny_status 403 unless collector_identity or grafana_identity + default_backend loki_plain +backend loki_plain + server loki loki:3100 check + +frontend tempo_query_tls + bind :3200 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3 + acl grafana_identity ssl_c_s_dn(cn) -m str grafana + http-request deny deny_status 403 unless grafana_identity + default_backend tempo_query +backend tempo_query + server tempo tempo:3200 check + +frontend tempo_otlp_tls + bind :4319 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3 + acl collector_identity ssl_c_s_dn(cn) -m str otel-collector + http-request deny deny_status 403 unless collector_identity + default_backend tempo_otlp +backend tempo_otlp + server tempo tempo:4318 check + +frontend prometheus_tls + bind :9090 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3 + acl grafana_identity ssl_c_s_dn(cn) -m str grafana + http-request deny deny_status 403 unless grafana_identity + default_backend prometheus_plain +backend prometheus_plain + server prometheus prometheus:9090 check + +frontend grafana_tls + bind :3000 ssl crt /run/secrets/telemetry_pem alpn h2,http/1.1 ssl-min-ver TLSv1.3 + default_backend grafana_plain +backend grafana_plain + server grafana grafana:3000 check diff --git a/infrastructure/haproxy/Dockerfile b/infrastructure/haproxy/Dockerfile new file mode 100644 index 0000000..caa3d11 --- /dev/null +++ b/infrastructure/haproxy/Dockerfile @@ -0,0 +1,8 @@ +FROM haproxy:3.2-alpine@sha256:dfba86f031bd4c9039f10f8cc5de75991d1b6766d5460f0335b980408503baad + +COPY infrastructure/haproxy/haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg + +USER 1000:1000 + +EXPOSE 8443 + diff --git a/infrastructure/haproxy/haproxy.cfg b/infrastructure/haproxy/haproxy.cfg new file mode 100644 index 0000000..37e42d4 --- /dev/null +++ b/infrastructure/haproxy/haproxy.cfg @@ -0,0 +1,31 @@ +global + log stdout format raw local0 + maxconn 2048 + +defaults + log global + mode http + option httplog + timeout connect 3s + timeout client 30s + timeout server 30s + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 1s + +frontend public_https + bind :8443 ssl crt /run/secrets/ingress_pem alpn h2,http/1.1 ssl-min-ver TLSv1.3 + http-request set-header X-Forwarded-Proto https + default_backend api_mtls + +backend api_mtls + balance leastconn + option httpchk + http-check send meth GET uri /health/lb ver HTTP/1.1 hdr Host api + http-check expect status 200 + default-server check inter 2s fall 2 rise 2 resolvers docker init-addr libc,none ssl ssl-min-ver TLSv1.3 verify required verifyhost api ca-file /run/secrets/tls_ca crt /run/secrets/lb_client_pem + server-template api 8 api:8444 diff --git a/infrastructure/minio/Dockerfile b/infrastructure/minio/Dockerfile new file mode 100644 index 0000000..833208a --- /dev/null +++ b/infrastructure/minio/Dockerfile @@ -0,0 +1,43 @@ +FROM golang:1.27.3-alpine@sha256:fa3d596898d9f126af7c01d14ee7597bab3f39cccf392ef36b69fe77cd681f18 AS minio-builder + +ARG MINIO_VERSION=RELEASE.2025-10-15T17-29-55Z +RUN CGO_ENABLED=0 GOBIN=/out go install github.com/minio/minio@${MINIO_VERSION} + +FROM golang:1.27.3-alpine@sha256:fa3d596898d9f126af7c01d14ee7597bab3f39cccf392ef36b69fe77cd681f18 AS mc-builder + +ARG MC_VERSION=RELEASE.2025-08-13T08-35-41Z +RUN CGO_ENABLED=0 GOBIN=/out go install github.com/minio/mc@${MC_VERSION} + +FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf AS server + +RUN apk upgrade --no-cache && \ + apk add --no-cache ca-certificates wget && \ + addgroup -g 1000 minio && \ + adduser -u 1000 -G minio -s /sbin/nologin -D minio && \ + mkdir -p /data && \ + chown minio:minio /data + +COPY --from=minio-builder /out/minio /usr/local/bin/minio + +USER minio:minio +VOLUME ["/data"] +EXPOSE 9000 + +HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=20 \ + CMD wget -qO- http://127.0.0.1:9000/minio/health/live >/dev/null || exit 1 + +ENTRYPOINT ["/usr/local/bin/minio"] +CMD ["server", "/data", "--address", ":9000"] + +FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf AS client + +RUN apk upgrade --no-cache && \ + apk add --no-cache ca-certificates && \ + addgroup -g 1000 minio && \ + adduser -u 1000 -G minio -s /sbin/nologin -D minio + +COPY --from=mc-builder /out/mc /usr/local/bin/mc + +USER minio:minio +ENTRYPOINT ["/usr/local/bin/mc"] + diff --git a/infrastructure/minio/api-policy.template.json b/infrastructure/minio/api-policy.template.json new file mode 100644 index 0000000..018f222 --- /dev/null +++ b/infrastructure/minio/api-policy.template.json @@ -0,0 +1,20 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": ["s3:GetBucketLocation", "s3:ListBucket"], + "Resource": ["arn:aws:s3:::__BUCKET__"] + }, + { + "Effect": "Allow", + "Action": ["s3:PutObject"], + "Resource": ["arn:aws:s3:::__BUCKET__/staging/*"] + }, + { + "Effect": "Allow", + "Action": ["s3:GetObject"], + "Resource": ["arn:aws:s3:::__BUCKET__/attachments/*"] + } + ] +} diff --git a/infrastructure/minio/worker-policy.template.json b/infrastructure/minio/worker-policy.template.json new file mode 100644 index 0000000..a85d92e --- /dev/null +++ b/infrastructure/minio/worker-policy.template.json @@ -0,0 +1,20 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": ["s3:GetBucketLocation", "s3:ListBucket"], + "Resource": ["arn:aws:s3:::__BUCKET__"] + }, + { + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:DeleteObject"], + "Resource": ["arn:aws:s3:::__BUCKET__/staging/*"] + }, + { + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], + "Resource": ["arn:aws:s3:::__BUCKET__/attachments/*"] + } + ] +} diff --git a/infrastructure/nginx/Dockerfile b/infrastructure/nginx/Dockerfile new file mode 100644 index 0000000..dc1f7cf --- /dev/null +++ b/infrastructure/nginx/Dockerfile @@ -0,0 +1,16 @@ +FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f AS frontend-build + +WORKDIR /frontend +COPY frontend/package.json frontend/package-lock.json ./ +RUN npm ci + +COPY frontend/ ./ +RUN npm test && npm run build + +FROM nginx:1.30.6-alpine@sha256:970364228b1e4f932abc22d321932816782cca8a20b85a77552a7cfe9acfb3b5 + +COPY infrastructure/nginx/nginx.conf /etc/nginx/nginx.conf +COPY --from=frontend-build /frontend/dist /usr/share/nginx/html + +EXPOSE 8080 + diff --git a/infrastructure/nginx/nginx.conf b/infrastructure/nginx/nginx.conf new file mode 100644 index 0000000..2cbe0b3 --- /dev/null +++ b/infrastructure/nginx/nginx.conf @@ -0,0 +1,33 @@ +worker_processes auto; + +events { + worker_connections 512; +} + +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + + server { + listen 8080; + server_name _; + root /usr/share/nginx/html; + index index.html; + + add_header X-Content-Type-Options "nosniff" always; + add_header Referrer-Policy "no-referrer" always; + add_header X-Frame-Options "DENY" always; + add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always; + + location /assets/ { + try_files $uri =404; + expires 1y; + add_header Cache-Control "public, immutable"; + } + + location / { + try_files $uri $uri/ /index.html; + } + } +} + diff --git a/infrastructure/openbao/api-policy.hcl b/infrastructure/openbao/api-policy.hcl new file mode 100644 index 0000000..30b5a18 --- /dev/null +++ b/infrastructure/openbao/api-policy.hcl @@ -0,0 +1,3 @@ +path "secret/data/api" { + capabilities = ["read"] +} diff --git a/infrastructure/openbao/config.hcl b/infrastructure/openbao/config.hcl new file mode 100644 index 0000000..2ea2f77 --- /dev/null +++ b/infrastructure/openbao/config.hcl @@ -0,0 +1,15 @@ +ui = false +disable_mlock = true + +storage "file" { + path = "/openbao/data" +} + +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/run/secrets/openbao_cert" + tls_key_file = "/run/secrets/openbao_key" + tls_min_version = "tls13" +} + +api_addr = "https://openbao:8200" diff --git a/infrastructure/openbao/dispatcher-policy.hcl b/infrastructure/openbao/dispatcher-policy.hcl new file mode 100644 index 0000000..f6f732c --- /dev/null +++ b/infrastructure/openbao/dispatcher-policy.hcl @@ -0,0 +1,3 @@ +path "secret/data/dispatcher" { + capabilities = ["read"] +} diff --git a/infrastructure/openbao/worker-policy.hcl b/infrastructure/openbao/worker-policy.hcl new file mode 100644 index 0000000..977dfae --- /dev/null +++ b/infrastructure/openbao/worker-policy.hcl @@ -0,0 +1,3 @@ +path "secret/data/worker" { + capabilities = ["read"] +} diff --git a/infrastructure/telemetry/grafana/dashboards/lab6-grade3.json b/infrastructure/telemetry/grafana/dashboards/lab6-grade3.json new file mode 100644 index 0000000..f369412 --- /dev/null +++ b/infrastructure/telemetry/grafana/dashboards/lab6-grade3.json @@ -0,0 +1,81 @@ +{ + "annotations": {"list": []}, + "editable": false, + "fiscalYearStartMonth": 0, + "graphTooltip": 1, + "id": null, + "links": [], + "liveNow": false, + "panels": [ + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 0, "y": 0}, + "id": 1, + "options": {"legend": {"displayMode": "table", "placement": "bottom"}}, + "targets": [{"expr": "sum(rate(messenger_http_server_requests_total[1m]))", "legendFormat": "all requests", "refId": "A"}], + "title": "API request rate", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 8, "y": 0}, + "id": 2, + "options": {"legend": {"displayMode": "table", "placement": "bottom"}}, + "targets": [{"expr": "sum by (status_class) (rate(messenger_http_server_requests_total[1m]))", "legendFormat": "{{status_class}}", "refId": "A"}], + "title": "API responses by status class", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 16, "y": 0}, + "id": 3, + "options": {"legend": {"displayMode": "table", "placement": "bottom"}}, + "targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "A"}], + "title": "API duration", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "jobs"}, "overrides": []}, + "gridPos": {"h": 8, "w": 12, "x": 0, "y": 8}, + "id": 4, + "options": {"legend": {"displayMode": "table", "placement": "bottom"}}, + "targets": [{"expr": "sum by (outcome) (increase(messenger_worker_jobs_total[5m]))", "legendFormat": "{{outcome}}", "refId": "A"}], + "title": "Worker jobs by outcome", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}, + "gridPos": {"h": 8, "w": 12, "x": 12, "y": 8}, + "id": 5, + "options": {"legend": {"displayMode": "table", "placement": "bottom"}}, + "targets": [{"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_worker_job_duration_seconds_bucket[5m])))", "legendFormat": "p95 {{outcome}}", "refId": "A"}], + "title": "Worker processing duration", + "type": "timeseries" + }, + { + "datasource": {"type": "loki", "uid": "loki"}, + "gridPos": {"h": 10, "w": 24, "x": 0, "y": 16}, + "id": 6, + "options": {"dedupStrategy": "none", "enableLogDetails": true, "showCommonLabels": false, "showLabels": false, "showTime": true, "sortOrder": "Descending", "wrapLogMessage": true}, + "targets": [{"expr": "{service_name=~\"messenger-(api|worker)\"}", "queryType": "range", "refId": "A"}], + "title": "Correlated structured logs", + "type": "logs" + } + ], + "refresh": "5s", + "schemaVersion": 41, + "tags": ["mtusi", "lab6", "grade3"], + "templating": {"list": []}, + "time": {"from": "now-15m", "to": "now"}, + "timepicker": {}, + "timezone": "browser", + "title": "MTUSI Lab 6 — Grade 3", + "uid": "mtusi-lab7-grade3", + "version": 1 +} + diff --git a/infrastructure/telemetry/grafana/dashboards/lab6-grade4.json b/infrastructure/telemetry/grafana/dashboards/lab6-grade4.json new file mode 100644 index 0000000..7128afa --- /dev/null +++ b/infrastructure/telemetry/grafana/dashboards/lab6-grade4.json @@ -0,0 +1,544 @@ +{ + "annotations": { + "list": [] + }, + "editable": false, + "graphTooltip": 1, + "id": null, + "links": [], + "panels": [ + { + "id": 1, + "title": "API RPS", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 0, + "y": 0 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rate(messenger_http_server_requests_total[1m]))", + "legendFormat": "requests/s" + } + ] + }, + { + "id": 2, + "title": "API 5xx ratio", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 6, + "y": 0 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rate(messenger_http_server_requests_total{status_class=\"5xx\"}[1m])) / clamp_min(sum(rate(messenger_http_server_requests_total[1m])), 0.000001)", + "legendFormat": "5xx / all" + } + ] + }, + { + "id": 3, + "title": "API latency p50/p95/p99", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 0 + }, + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))", + "legendFormat": "p99" + } + ] + }, + { + "id": 4, + "title": "Queue depth / oldest age seconds", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 7 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max(messenger_queue_depth)", + "legendFormat": "depth" + }, + { + "refId": "B", + "expr": "max(messenger_queue_oldest_job_age_seconds)", + "legendFormat": "oldest age s" + } + ] + }, + { + "id": 5, + "title": "Worker saturation", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 8, + "y": 7 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max(messenger_worker_busy) / clamp_min(max(messenger_worker_capacity), 1)", + "legendFormat": "busy / capacity" + } + ] + }, + { + "id": 6, + "title": "Time to ready p50/p95/p99", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 16, + "y": 7 + }, + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[5m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[5m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[5m])))", + "legendFormat": "p99" + } + ] + }, + { + "id": 7, + "title": "PostgreSQL pool used/idle/capacity", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 14 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (service_name, state) (messenger_db_pool_connections)", + "legendFormat": "{{service_name}} {{state}}" + } + ] + }, + { + "id": 8, + "title": "PostgreSQL pool waits", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 8, + "y": 14 + }, + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (service_name) (rate(messenger_db_pool_waits_total[5m]))", + "legendFormat": "{{service_name}} waits/s" + } + ] + }, + { + "id": 9, + "title": "Process CPU", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 16, + "y": 14 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (service_name) (rate(messenger_process_cpu_time_seconds_total[5m]))", + "legendFormat": "{{service_name}}" + } + ] + }, + { + "id": 10, + "title": "Process RSS", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 21 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (service_name) (messenger_process_memory_bytes)", + "legendFormat": "{{service_name}}" + } + ] + }, + { + "id": 11, + "title": "Worker jobs and p95 duration", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 8, + "y": 21 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (outcome) (rate(messenger_worker_jobs_total[5m]))", + "legendFormat": "jobs/s {{outcome}}" + }, + { + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_worker_job_duration_seconds_bucket[5m])))", + "legendFormat": "p95 s {{outcome}}" + } + ] + }, + { + "id": 12, + "title": "Collector bounded queues / drops", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 16, + "y": 21 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "otelcol_exporter_queue_size", + "legendFormat": "queue {{exporter}}" + }, + { + "refId": "B", + "expr": "otelcol_exporter_queue_capacity", + "legendFormat": "capacity {{exporter}}" + }, + { + "refId": "C", + "expr": "(sum(rate(otelcol_exporter_send_failed_log_records[5m])) or vector(0)) + (sum(rate(otelcol_exporter_send_failed_spans[5m])) or vector(0))", + "legendFormat": "drops/s" + } + ] + }, + { + "id": 13, + "title": "Alert state", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 28 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom" + } + }, + "targets": [ + { + "refId": "A", + "expr": "ALERTS{alertname=~\"Messenger(APIHighErrorRate|QueueLagGrowing)\"}", + "legendFormat": "{{alertname}} {{alertstate}}" + } + ] + }, + { + "id": 14, + "title": "Correlated logs", + "type": "logs", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "gridPos": { + "h": 10, + "w": 16, + "x": 8, + "y": 28 + }, + "targets": [ + { + "refId": "A", + "expr": "{service_name=~\"messenger-(api|worker|dispatcher)\"}", + "queryType": "range" + } + ], + "options": { + "dedupStrategy": "none", + "enableLogDetails": true, + "showCommonLabels": false, + "showLabels": false, + "showTime": true, + "sortOrder": "Descending", + "wrapLogMessage": true + } + } + ], + "refresh": "5s", + "schemaVersion": 41, + "tags": [ + "mtusi", + "lab6", + "grade4" + ], + "templating": { + "list": [] + }, + "time": { + "from": "now-30m", + "to": "now" + }, + "timepicker": {}, + "timezone": "browser", + "title": "MTUSI Lab 6 - Grade 4", + "uid": "mtusi-lab7-grade4", + "version": 1 +} + diff --git a/infrastructure/telemetry/grafana/dashboards/lab6-grade5.json b/infrastructure/telemetry/grafana/dashboards/lab6-grade5.json new file mode 100644 index 0000000..b76f767 --- /dev/null +++ b/infrastructure/telemetry/grafana/dashboards/lab6-grade5.json @@ -0,0 +1,70 @@ +{ + "annotations": {"list": []}, + "editable": false, + "graphTooltip": 1, + "id": null, + "panels": [ + { + "id": 1, + "title": "API error ratio by burn window", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 9, "w": 12, "x": 0, "y": 0}, + "fieldConfig": {"defaults": {"unit": "percentunit"}, "overrides": []}, + "targets": [ + {"refId": "A", "expr": "messenger:sli_api_error_ratio_30s", "legendFormat": "30s"}, + {"refId": "B", "expr": "messenger:sli_api_error_ratio_1m", "legendFormat": "1m"}, + {"refId": "C", "expr": "messenger:sli_api_error_ratio_2m", "legendFormat": "2m"}, + {"refId": "D", "expr": "messenger:sli_api_error_ratio_5m", "legendFormat": "5m"} + ] + }, + { + "id": 2, + "title": "Attachment >10s ratio by burn window", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 9, "w": 12, "x": 12, "y": 0}, + "fieldConfig": {"defaults": {"unit": "percentunit"}, "overrides": []}, + "targets": [ + {"refId": "A", "expr": "messenger:sli_attachment_slow_ratio_30s", "legendFormat": "30s"}, + {"refId": "B", "expr": "messenger:sli_attachment_slow_ratio_1m", "legendFormat": "1m"}, + {"refId": "C", "expr": "messenger:sli_attachment_slow_ratio_2m", "legendFormat": "2m"}, + {"refId": "D", "expr": "messenger:sli_attachment_slow_ratio_5m", "legendFormat": "5m"} + ] + }, + { + "id": 3, + "title": "SLO compliance (7d policy window)", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 12, "x": 0, "y": 9}, + "fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []}, + "targets": [ + {"refId": "A", "expr": "messenger:slo_api_success_ratio_7d", "legendFormat": "API success"}, + {"refId": "B", "expr": "messenger:slo_attachment_ready_ratio_7d", "legendFormat": "ready <=10s"}, + {"refId": "C", "expr": "vector(0.99)", "legendFormat": "99% objective"} + ] + }, + { + "id": 4, + "title": "Burn-rate alert states", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "gridPos": {"h": 8, "w": 12, "x": 12, "y": 9}, + "fieldConfig": {"defaults": {"unit": "short"}, "overrides": []}, + "targets": [ + {"refId": "A", "expr": "ALERTS{alertname=~\"Messenger(API|AttachmentReady)BurnRate(Fast|Slow)\"}", "legendFormat": "{{alertname}} {{alertstate}}"} + ] + } + ], + "refresh": "5s", + "schemaVersion": 42, + "tags": ["mtusi", "lab6", "grade5", "slo", "burn-rate"], + "templating": {"list": []}, + "time": {"from": "now-30m", "to": "now"}, + "timezone": "browser", + "title": "MTUSI Lab 6 - Grade 5 SLO", + "uid": "mtusi-lab7-grade5", + "version": 1 +} + diff --git a/infrastructure/telemetry/grafana/provisioning/alerting/.gitkeep b/infrastructure/telemetry/grafana/provisioning/alerting/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/infrastructure/telemetry/grafana/provisioning/alerting/.gitkeep @@ -0,0 +1 @@ + diff --git a/infrastructure/telemetry/grafana/provisioning/dashboards/dashboards.yaml b/infrastructure/telemetry/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 0000000..19ae498 --- /dev/null +++ b/infrastructure/telemetry/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,13 @@ +apiVersion: 1 + +providers: + - name: MTUSI Lab 6 + orgId: 1 + folder: Lab 6 + type: file + disableDeletion: true + editable: false + updateIntervalSeconds: 10 + options: + path: /var/lib/grafana/dashboards + diff --git a/infrastructure/telemetry/grafana/provisioning/datasources/datasources.yaml b/infrastructure/telemetry/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 0000000..e4af8c3 --- /dev/null +++ b/infrastructure/telemetry/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,45 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: https://telemetry-gateway:9090 + isDefault: true + editable: false + + - name: Loki + uid: loki + type: loki + access: proxy + url: https://telemetry-gateway:3100 + editable: false + jsonData: + derivedFields: + - name: TraceID + matcherRegex: '([0-9a-f]{32})' + datasourceUid: tempo + url: '$${__value.raw}' + + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: https://telemetry-gateway:3200 + editable: false + jsonData: + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: -1m + spanEndTimeShift: 1m + tags: + - key: service.name + value: service_name + filterByTraceID: true + filterBySpanID: true + serviceMap: + datasourceUid: prometheus + nodeGraph: + enabled: true + diff --git a/infrastructure/telemetry/grafana/provisioning/plugins/.gitkeep b/infrastructure/telemetry/grafana/provisioning/plugins/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/infrastructure/telemetry/grafana/provisioning/plugins/.gitkeep @@ -0,0 +1 @@ + diff --git a/infrastructure/telemetry/loki/config.yaml b/infrastructure/telemetry/loki/config.yaml new file mode 100644 index 0000000..22fe2fb --- /dev/null +++ b/infrastructure/telemetry/loki/config.yaml @@ -0,0 +1,35 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + +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: 168h + +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem + diff --git a/infrastructure/telemetry/otel-collector/config.yaml b/infrastructure/telemetry/otel-collector/config.yaml new file mode 100644 index 0000000..1409a53 --- /dev/null +++ b/infrastructure/telemetry/otel-collector/config.yaml @@ -0,0 +1,81 @@ +extensions: + health_check: + endpoint: 0.0.0.0:13133 +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 +processors: + memory_limiter: + check_interval: 1s + limit_mib: 192 + spike_limit_mib: 48 + batch: + timeout: 1s + send_batch_size: 256 + send_batch_max_size: 512 +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + resource_constant_labels: + included: [service.name, service.version, service.instance.id, deployment.environment.name] + otlp_http/tempo: + endpoint: https://telemetry-gateway:4319 + tls: + ca_file: /run/secrets/tls_ca + cert_file: /run/secrets/collector_client_cert + key_file: /run/secrets/collector_client_key + timeout: 3s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 256 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 30s + otlp_http/loki: + endpoint: https://telemetry-gateway:3100/otlp + tls: + ca_file: /run/secrets/tls_ca + cert_file: /run/secrets/collector_client_cert + key_file: /run/secrets/collector_client_key + timeout: 3s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 256 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 30s +service: + extensions: [health_check] + pipelines: + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp_http/loki] + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp_http/tempo] + telemetry: + logs: + level: info + metrics: + level: detailed + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 + diff --git a/infrastructure/telemetry/prometheus/prometheus.yaml b/infrastructure/telemetry/prometheus/prometheus.yaml new file mode 100644 index 0000000..c29e51e --- /dev/null +++ b/infrastructure/telemetry/prometheus/prometheus.yaml @@ -0,0 +1,24 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s +rule_files: + - /etc/prometheus/rules/*.yaml +scrape_configs: + - job_name: application-telemetry + scheme: https + tls_config: + ca_file: /run/secrets/tls_ca + server_name: telemetry-gateway + cert_file: /run/secrets/prometheus_client_cert + key_file: /run/secrets/prometheus_client_key + static_configs: + - targets: [telemetry-gateway:8889] + - job_name: collector-internal + scheme: https + tls_config: + ca_file: /run/secrets/tls_ca + server_name: telemetry-gateway + cert_file: /run/secrets/prometheus_client_cert + key_file: /run/secrets/prometheus_client_key + static_configs: + - targets: [telemetry-gateway:8888] diff --git a/infrastructure/telemetry/prometheus/rules/alerts.yaml b/infrastructure/telemetry/prometheus/rules/alerts.yaml new file mode 100644 index 0000000..3a50296 --- /dev/null +++ b/infrastructure/telemetry/prometheus/rules/alerts.yaml @@ -0,0 +1,98 @@ +groups: + - name: messenger-level4 + interval: 5s + rules: + - record: messenger:sli_api_success_ratio_5m + expr: 1 - (sum(rate(messenger_http_server_requests_total{status_class="5xx"}[5m])) / clamp_min(sum(rate(messenger_http_server_requests_total[5m])), 0.000001)) + - alert: MessengerAPIHighErrorRate + expr: (sum(rate(messenger_http_server_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_server_requests_total[1m])), 0.000001)) > 0.01 and sum(rate(messenger_http_server_requests_total[1m])) > 0.05 + for: 10s + labels: + severity: warning + slo: api-availability + annotations: + summary: API 5xx ratio exceeds the 99% availability SLO + description: More than 1% of business HTTP requests were 5xx during the last minute. + runbook: infrastructure/telemetry/runbooks/level4.md#api-high-error-rate + - alert: MessengerQueueLagGrowing + expr: max(messenger_queue_depth) > 0 and max(messenger_queue_oldest_job_age_seconds) > 10 + for: 10s + labels: + severity: warning + slo: attachment-ready + annotations: + summary: Attachment queue lag is growing + description: At least one job has remained queued for more than 10 seconds. + runbook: infrastructure/telemetry/runbooks/level4.md#queue-lag-growing + + - name: messenger-level5-burn-rate + interval: 5s + rules: + - record: messenger:slo_api_success_ratio_7d + expr: (1 - (sum(increase(messenger_http_server_requests_total{status_class="5xx"}[7d])) / clamp_min(sum(increase(messenger_http_server_requests_total[7d])), 1))) and sum(increase(messenger_http_server_requests_total[7d])) > 0 + - record: messenger:slo_attachment_ready_ratio_7d + expr: (sum(increase(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[7d])) / clamp_min(sum(increase(messenger_attachment_ready_duration_seconds_count[7d])), 1)) and sum(increase(messenger_attachment_ready_duration_seconds_count[7d])) > 0 + + - record: messenger:sli_api_error_ratio_30s + expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[30s])) / clamp_min(sum(rate(messenger_http_server_requests_total[30s])), 0.000001) + - record: messenger:sli_api_error_ratio_1m + expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_server_requests_total[1m])), 0.000001) + - record: messenger:sli_api_error_ratio_2m + expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[2m])) / clamp_min(sum(rate(messenger_http_server_requests_total[2m])), 0.000001) + - record: messenger:sli_api_error_ratio_5m + expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[5m])) / clamp_min(sum(rate(messenger_http_server_requests_total[5m])), 0.000001) + + - record: messenger:sli_attachment_slow_ratio_30s + expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[30s])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[30s]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[30s])), 0.000001) + - record: messenger:sli_attachment_slow_ratio_1m + expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[1m])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[1m]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[1m])), 0.000001) + - record: messenger:sli_attachment_slow_ratio_2m + expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[2m])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[2m]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[2m])), 0.000001) + - record: messenger:sli_attachment_slow_ratio_5m + expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[5m])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[5m]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[5m])), 0.000001) + + - alert: MessengerAPIBurnRateFast + expr: messenger:sli_api_error_ratio_30s > (14.4 * 0.01) and messenger:sli_api_error_ratio_2m > (14.4 * 0.01) and sum(rate(messenger_http_server_requests_total[30s])) > 0.1 + for: 10s + labels: + severity: page + slo: api-availability + burn_rate: fast + annotations: + summary: API consumes the 1% error budget at fast burn rate + description: Both 30s and 2m windows exceed 14.4x burn rate. + runbook: infrastructure/telemetry/runbooks/level5.md#api-burn-rate + - alert: MessengerAPIBurnRateSlow + expr: messenger:sli_api_error_ratio_1m > (6 * 0.01) and messenger:sli_api_error_ratio_5m > (6 * 0.01) and sum(rate(messenger_http_server_requests_total[1m])) > 0.05 + for: 20s + labels: + severity: ticket + slo: api-availability + burn_rate: slow + annotations: + summary: API consumes the 1% error budget at sustained burn rate + description: Both 1m and 5m windows exceed 6x burn rate. + runbook: infrastructure/telemetry/runbooks/level5.md#api-burn-rate + - alert: MessengerAttachmentReadyBurnRateFast + expr: messenger:sli_attachment_slow_ratio_30s > (14.4 * 0.01) and messenger:sli_attachment_slow_ratio_2m > (14.4 * 0.01) and sum(rate(messenger_attachment_ready_duration_seconds_count[30s])) > 0 + for: 10s + labels: + severity: page + slo: attachment-ready + burn_rate: fast + annotations: + summary: Attachment ready latency consumes its error budget quickly + description: More than 14.4% of completed attachments exceed 10s in both windows. + runbook: infrastructure/telemetry/runbooks/level5.md#attachment-ready-burn-rate + - alert: MessengerAttachmentReadyBurnRateSlow + expr: messenger:sli_attachment_slow_ratio_1m > (6 * 0.01) and messenger:sli_attachment_slow_ratio_5m > (6 * 0.01) and sum(rate(messenger_attachment_ready_duration_seconds_count[1m])) > 0 + for: 20s + labels: + severity: ticket + slo: attachment-ready + burn_rate: slow + annotations: + summary: Attachment ready latency consumes its error budget persistently + description: More than 6% of completed attachments exceed 10s in both windows. + runbook: infrastructure/telemetry/runbooks/level5.md#attachment-ready-burn-rate + diff --git a/infrastructure/telemetry/runbooks/level4.md b/infrastructure/telemetry/runbooks/level4.md new file mode 100644 index 0000000..76bcdd9 --- /dev/null +++ b/infrastructure/telemetry/runbooks/level4.md @@ -0,0 +1,25 @@ +# Runbook уровня 4 + +## API high error rate + +1. Сравнить error ratio с RPS на dashboard. +2. Найти в Loki `{service_name="messenger-api"} | status_class="5xx"`. +3. Открыть `trace_id` в Tempo. +4. Ошибочный `postgresql.*` client span указывает на БД; медленный server span без медленного DB child — на handler/внешнюю зависимость. +5. Проверить DB pool used/capacity и rate waits. +6. После восстановления создать успешные запросы и дождаться `resolved`. + +## Queue lag growing + +1. Сравнить `messenger_queue_depth` и `messenger_queue_oldest_job_age_seconds`. +2. Проверить worker busy/capacity и `attachment_job_failed` в Loki. +3. Открыть consumer trace и S3/PostgreSQL child spans. +4. Восстановить worker; depth/age должны вернуться к нулю, alert — в `resolved`. + +## Telemetry backend unavailable + +1. Проверить `otelcol_exporter_queue_size`, capacity и failure counters. +2. Memory limiter — 192 MiB при container limit 256 MiB; exporter queues — 256 batches. +3. API/очередь не зависят от Loki/Tempo. После 30 s retry telemetry может отбрасываться — это bounded degradation. +4. После восстановления backend проверить уменьшение очереди и появление новых сигналов. + diff --git a/infrastructure/telemetry/runbooks/level5.md b/infrastructure/telemetry/runbooks/level5.md new file mode 100644 index 0000000..8f4c2d8 --- /dev/null +++ b/infrastructure/telemetry/runbooks/level5.md @@ -0,0 +1,32 @@ +# Runbook уровня 5: SLO burn rate + +## SLO и приоритет + +- Policy window — 7 дней, что совпадает с retention Prometheus. +- API availability SLO: не менее 99% HTTP-запросов без 5xx (`messenger:slo_api_success_ratio_7d`). +- Attachment ready SLO: не менее 99% успешно завершённых attachments переходят в `ready` не позднее 10 секунд после durable acceptance (`messenger:slo_attachment_ready_ratio_7d`). +- `fast` (14.4x, 30s + 2m) — page: бюджет расходуется достаточно быстро для немедленного вмешательства. +- `slow` (6x, 1m + 5m) — ticket: деградация устойчивее, но допускает более спокойную диагностику. +- Оба окна должны нарушаться одновременно. Traffic guard исключает алерт при отсутствии наблюдений. + +## API burn rate + +1. В Prometheus открыть `ALERTS{alertname=~"MessengerAPIBurnRate(Fast|Slow)"}` и записать `activeAt`. +2. Сравнить `messenger:sli_api_error_ratio_30s`, `_1m`, `_2m`, `_5m` и RPS. Одно короткое окно без длинного не считается burn-rate инцидентом. +3. В Loki выполнить `{service_name="messenger-api"} | status_class="5xx"` и взять свежие `request_id`/`trace_id`. +4. Открыть trace в Tempo. `postgresql.acquire` error означает исчерпание/недоступность pool; `postgresql.*` query error — ошибку операции; медленный server span без DB/S3 child указывает на handler. +5. Проверить `messenger_db_pool_connections`, `messenger_db_pool_waits_total`, process RAM/CPU и health зависимостей. +6. Восстановить зависимость, создать контрольные успешные запросы. Зафиксировать момент исчезновения alert и recovery time. + +## Attachment ready burn rate + +1. Сравнить `messenger:sli_attachment_slow_ratio_30s`, `_1m`, `_2m`, `_5m` с queue depth/oldest age. +2. Проверить `messenger_worker_busy / messenger_worker_capacity`; saturation около 1 при растущей очереди означает недостаточную worker capacity. +3. Найти `attachment_job_failed`/`attachment_job_completed` в Loki и перейти по trace ID к producer/consumer spans. +4. Ошибка `s3.*` указывает на object storage; `postgresql.*` — на DB; длинный разрыв между producer и consumer — на queue/worker. +5. Восстановить worker/backend. Убедиться, что новые attachments укладываются в 10 секунд, оба burn-rate alert исчезли, queue age вернулся к нулю. + +## Проверка ложного срабатывания + +`tests/slo_burn_rate.py` сначала создаёт большой успешный baseline, затем короткий ограниченный 5xx burst. В течение observation window ни `Fast`, ни `Slow` не должны перейти в `pending` или `firing`. Далее тот же тест создаёт длительную DB-деградацию и измеряет detection/recovery. Это отделяет чувствительность к реальному расходованию бюджета от реакции на единичную ошибку. + diff --git a/infrastructure/telemetry/tempo/config.yaml b/infrastructure/telemetry/tempo/config.yaml new file mode 100644 index 0000000..c4a6b84 --- /dev/null +++ b/infrastructure/telemetry/tempo/config.yaml @@ -0,0 +1,22 @@ +server: + http_listen_port: 3200 + +distributor: + receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks + +compactor: + compaction: + block_retention: 168h + diff --git a/internal/adapter/broker/rabbitmq.go b/internal/adapter/broker/rabbitmq.go new file mode 100644 index 0000000..6a0670a --- /dev/null +++ b/internal/adapter/broker/rabbitmq.go @@ -0,0 +1,193 @@ +package broker + +import ( + "context" + "encoding/json" + "fmt" + neturl "net/url" + "os" + "sync" + "time" + + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/security" + + amqp "github.com/rabbitmq/amqp091-go" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" +) + +const QueueName = "attachment.process.v1" + +type RabbitMQ struct { + connection *amqp.Connection + channel *amqp.Channel + confirms <-chan amqp.Confirmation + publishMu sync.Mutex +} + +func Open(url string, prefetch int) (*RabbitMQ, error) { + if url == "" { + return nil, fmt.Errorf("broker URL is required") + } + parsedURL, err := neturl.Parse(url) + if err != nil { + return nil, fmt.Errorf("parse broker URL: %w", err) + } + connectionConfig := amqp.Config{Heartbeat: 10 * time.Second, Locale: "en_US"} + if parsedURL.Scheme == "amqps" { + serverName := os.Getenv("BROKER_TLS_SERVER_NAME") + if serverName == "" { + serverName = "dependency-gateway" + } + connectionConfig.TLSClientConfig, err = security.ClientMTLSConfig( + os.Getenv("CLIENT_TLS_CA_FILE"), + os.Getenv("CLIENT_TLS_CERT_FILE"), + os.Getenv("CLIENT_TLS_KEY_FILE"), + serverName, + ) + if err != nil { + return nil, fmt.Errorf("configure broker mTLS: %w", err) + } + } + connection, err := amqp.DialConfig(url, connectionConfig) + if err != nil { + return nil, fmt.Errorf("connect RabbitMQ: %w", err) + } + channel, err := connection.Channel() + if err != nil { + _ = connection.Close() + return nil, fmt.Errorf("open RabbitMQ channel: %w", err) + } + if _, err = channel.QueueDeclare(QueueName, true, false, false, false, nil); err != nil { + _ = channel.Close() + _ = connection.Close() + return nil, fmt.Errorf("declare RabbitMQ queue: %w", err) + } + if prefetch > 0 { + if err = channel.Qos(prefetch, 0, false); err != nil { + _ = channel.Close() + _ = connection.Close() + return nil, fmt.Errorf("set RabbitMQ prefetch: %w", err) + } + } + client := &RabbitMQ{connection: connection, channel: channel} + if err = channel.Confirm(false); err != nil { + client.Close() + return nil, fmt.Errorf("enable RabbitMQ publisher confirms: %w", err) + } + client.confirms = channel.NotifyPublish(make(chan amqp.Confirmation, 1)) + return client, nil +} + +func (client *RabbitMQ) Publish(ctx context.Context, job domain.AttachmentJob) (err error) { + parentCarrier := propagation.MapCarrier{} + if job.TraceParent != "" { + parentCarrier.Set("traceparent", job.TraceParent) + } + if job.TraceState != "" { + parentCarrier.Set("tracestate", job.TraceState) + } + ctx = otel.GetTextMapPropagator().Extract(ctx, parentCarrier) + ctx, span := otel.Tracer("mtusi2026lab7/broker").Start( + ctx, + QueueName+" publish", + trace.WithSpanKind(trace.SpanKindProducer), + trace.WithAttributes( + attribute.String("messaging.system", "rabbitmq"), + attribute.String("messaging.destination.name", QueueName), + attribute.String("messaging.operation.name", "publish"), + attribute.Int("job.attempt", job.Attempt), + ), + ) + defer func() { + if err != nil { + span.SetStatus(codes.Error, "broker publish failed") + } else { + span.SetStatus(codes.Ok, "") + } + span.End() + }() + + body, err := json.Marshal(job.Message()) + if err != nil { + return fmt.Errorf("encode attachment job: %w", err) + } + traceCarrier := propagation.MapCarrier{} + otel.GetTextMapPropagator().Inject(ctx, traceCarrier) + headers := amqp.Table{} + for _, key := range traceCarrier.Keys() { + headers[key] = traceCarrier.Get(key) + } + + client.publishMu.Lock() + defer client.publishMu.Unlock() + if err = client.channel.PublishWithContext(ctx, "", QueueName, false, false, amqp.Publishing{ + DeliveryMode: amqp.Persistent, + ContentType: "application/json", + Type: domain.AttachmentJobType, + MessageId: job.JobID, + Timestamp: time.Now().UTC(), + Headers: headers, + Body: body, + }); err != nil { + return fmt.Errorf("publish attachment job: %w", err) + } + select { + case confirmation, ok := <-client.confirms: + if !ok { + return fmt.Errorf("publisher confirm channel closed") + } + if !confirmation.Ack { + return fmt.Errorf("broker rejected attachment job") + } + return nil + case <-ctx.Done(): + return fmt.Errorf("wait for publisher confirm: %w", ctx.Err()) + } +} + +func ContextFromDelivery(ctx context.Context, delivery amqp.Delivery) context.Context { + carrier := propagation.MapCarrier{} + for key, value := range delivery.Headers { + if text, ok := value.(string); ok { + carrier.Set(key, text) + } + } + return otel.GetTextMapPropagator().Extract(ctx, carrier) +} + +func (client *RabbitMQ) Consume(consumerName string) (<-chan amqp.Delivery, error) { + deliveries, err := client.channel.Consume(QueueName, consumerName, false, false, false, false, nil) + if err != nil { + return nil, fmt.Errorf("consume attachment jobs: %w", err) + } + return deliveries, nil +} + +func Decode(delivery amqp.Delivery) (domain.AttachmentJobMessage, error) { + var message domain.AttachmentJobMessage + if err := json.Unmarshal(delivery.Body, &message); err != nil { + return message, fmt.Errorf("decode attachment job: %w", err) + } + if message.SchemaVersion != 1 || message.Type != domain.AttachmentJobType || message.JobID == "" || message.AttachmentID == "" || message.PipelineVersion < 1 || message.Attempt < 1 { + return message, fmt.Errorf("attachment job has invalid required fields") + } + return message, nil +} + +func (client *RabbitMQ) Close() error { + if client == nil { + return nil + } + if client.channel != nil { + _ = client.channel.Close() + } + if client.connection != nil { + return client.connection.Close() + } + return nil +} diff --git a/internal/adapter/cache/repository.go b/internal/adapter/cache/repository.go new file mode 100644 index 0000000..d1a57a1 --- /dev/null +++ b/internal/adapter/cache/repository.go @@ -0,0 +1,110 @@ +package cache + +import ( + "context" + "errors" + "log" + + "mtusi2026lab7/internal/adapter/redis" + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" +) + +// CachedRepository декорирует основной Repository. Все операции, кроме чтения +// и создания чата, автоматически делегируются встроенному Repository. +type CachedRepository struct { + application.Repository + chatCache redis.ChatCache + logger *log.Logger +} + +func NewCachedRepository( + repository application.Repository, + chatCache redis.ChatCache, + logger *log.Logger, +) *CachedRepository { + if logger == nil { + logger = log.Default() + } + + return &CachedRepository{ + Repository: repository, + chatCache: chatCache, + logger: logger, + } +} + +func (r *CachedRepository) CreateQueuedAttachment( + ctx context.Context, + attachment domain.Attachment, + job domain.AttachmentJob, +) (domain.Attachment, error) { + queueRepository, ok := r.Repository.(application.AttachmentQueueRepository) + if !ok { + return domain.Attachment{}, errors.New("attachment queue repository is not configured") + } + return queueRepository.CreateQueuedAttachment(ctx, attachment, job) +} +func (r *CachedRepository) CreateChat( + ctx context.Context, + title string, + memberIDs []string, +) (domain.Chat, error) { + chat, err := r.Repository.CreateChat(ctx, title, memberIDs) + if err != nil { + return domain.Chat{}, err + } + + // Запись в PostgreSQL уже подтверждена. Ошибка необязательного кэша не + // должна превращать успешную бизнес-операцию в 503. + if err = r.chatCache.Set(ctx, chat); err != nil { + r.logger.Printf("[WARN] Redis chat cache write failed: %v", err) + } + + return chat, nil +} + +func (r *CachedRepository) GetChatByID( + ctx context.Context, + chatID string, + callerID string, +) (domain.Chat, error) { + chat, err := r.chatCache.Get(ctx, chatID) + if err == nil { + if !containsMember(chat.MemberIDs, callerID) { + return domain.Chat{}, domain.ErrNotFound + } + + return chat, nil + } + + shouldFillCache := errors.Is(err, redis.ErrMiss) + if !shouldFillCache { + r.logger.Printf("[WARN] Redis chat cache read failed: %v", err) + } + + chat, err = r.Repository.GetChatByID(ctx, chatID, callerID) + if err != nil { + return domain.Chat{}, err + } + + if shouldFillCache { + if err = r.chatCache.Set(ctx, chat); err != nil { + r.logger.Printf("[WARN] Redis chat cache fill failed: %v", err) + } + } + + return chat, nil +} + +func containsMember(memberIDs []string, callerID string) bool { + for _, memberID := range memberIDs { + if memberID == callerID { + return true + } + } + + return false +} + +var _ application.Repository = (*CachedRepository)(nil) diff --git a/internal/adapter/cache/repository_test.go b/internal/adapter/cache/repository_test.go new file mode 100644 index 0000000..6e558d0 --- /dev/null +++ b/internal/adapter/cache/repository_test.go @@ -0,0 +1,183 @@ +package cache + +import ( + "context" + "errors" + "io" + "log" + "testing" + + "mtusi2026lab7/internal/adapter/memory" + "mtusi2026lab7/internal/adapter/redis" + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" +) + +type fakeChatCache struct { + chats map[string]domain.Chat + getErr error + setErr error + sets int +} + +func (c *fakeChatCache) Get( + _ context.Context, + chatID string, +) (domain.Chat, error) { + if c.getErr != nil { + return domain.Chat{}, c.getErr + } + + chat, exists := c.chats[chatID] + if !exists { + return domain.Chat{}, redis.ErrMiss + } + + return chat, nil +} + +func (c *fakeChatCache) Set( + _ context.Context, + chat domain.Chat, +) error { + c.sets++ + if c.setErr != nil { + return c.setErr + } + c.chats[chat.ID] = chat + + return nil +} + +type countingRepository struct { + application.Repository + getChatCalls int +} + +func (r *countingRepository) GetChatByID( + ctx context.Context, + chatID string, + callerID string, +) (domain.Chat, error) { + r.getChatCalls++ + return r.Repository.GetChatByID(ctx, chatID, callerID) +} + +func cachedRepositoryFixture( + t *testing.T, +) (*countingRepository, *fakeChatCache, domain.User, domain.User, domain.Chat) { + t.Helper() + + legacy := memory.NewMemoryStore() + member, err := legacy.CreateUser("cache_member", "Участник") + if err != nil { + t.Fatalf("create member: %v", err) + } + outsider, err := legacy.CreateUser("cache_outsider", "Посторонний") + if err != nil { + t.Fatalf("create outsider: %v", err) + } + chat, err := legacy.CreateChat("Кешируемый чат", []string{member.ID}) + if err != nil { + t.Fatalf("create chat: %v", err) + } + + repository := &countingRepository{ + Repository: memory.NewMemoryRepository(legacy), + } + chatCache := &fakeChatCache{ + chats: make(map[string]domain.Chat), + } + + return repository, chatCache, member, outsider, chat +} + +func TestCachedRepositoryMissThenHit(t *testing.T) { + repository, chatCache, member, _, expected := cachedRepositoryFixture(t) + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + first, err := cached.GetChatByID(context.Background(), expected.ID, member.ID) + if err != nil { + t.Fatalf("first read: %v", err) + } + second, err := cached.GetChatByID(context.Background(), expected.ID, member.ID) + if err != nil { + t.Fatalf("second read: %v", err) + } + + if repository.getChatCalls != 1 { + t.Fatalf("expected one source read, got %d", repository.getChatCalls) + } + if chatCache.sets != 1 { + t.Fatalf("expected one cache fill, got %d", chatCache.sets) + } + if first.ID != expected.ID || second.ID != expected.ID { + t.Fatal("cache changed chat identity") + } +} + +func TestCachedRepositoryFallsBackWhenCacheUnavailable(t *testing.T) { + repository, chatCache, member, _, expected := cachedRepositoryFixture(t) + chatCache.getErr = errors.New("redis unavailable") + chatCache.setErr = errors.New("redis unavailable") + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + chat, err := cached.GetChatByID(context.Background(), expected.ID, member.ID) + if err != nil { + t.Fatalf("fallback read: %v", err) + } + if chat.ID != expected.ID || repository.getChatCalls != 1 { + t.Fatal("source repository was not used after cache failure") + } + if chatCache.sets != 0 { + t.Fatal("failed cache read must not trigger another cache operation") + } +} + +func TestCachedRepositoryChecksMembershipOnHit(t *testing.T) { + repository, chatCache, _, outsider, expected := cachedRepositoryFixture(t) + chatCache.chats[expected.ID] = expected + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + _, err := cached.GetChatByID(context.Background(), expected.ID, outsider.ID) + if !errors.Is(err, domain.ErrNotFound) { + t.Fatalf("expected ErrNotFound for outsider, got %v", err) + } + if repository.getChatCalls != 0 { + t.Fatal("cache hit unexpectedly queried source repository") + } +} + +func TestCachedRepositoryIgnoresWriteFailure(t *testing.T) { + repository, chatCache, member, _, _ := cachedRepositoryFixture(t) + chatCache.setErr = errors.New("redis unavailable") + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + chat, err := cached.CreateChat( + context.Background(), + "Новый чат", + []string{member.ID}, + ) + if err != nil { + t.Fatalf("create chat with unavailable cache: %v", err) + } + if chat.ID == "" || chatCache.sets != 1 { + t.Fatal("chat was not created before best-effort cache write") + } +} diff --git a/internal/adapter/health/multi.go b/internal/adapter/health/multi.go new file mode 100644 index 0000000..bfb402c --- /dev/null +++ b/internal/adapter/health/multi.go @@ -0,0 +1,33 @@ +package health + +import ( + "context" + "fmt" +) + +type Checker interface { + Ping(ctx context.Context) error +} + +type MultiChecker struct { + checkers []Checker +} + +func NewMultiChecker(checkers ...Checker) *MultiChecker { + filtered := make([]Checker, 0, len(checkers)) + for _, checker := range checkers { + if checker != nil { + filtered = append(filtered, checker) + } + } + return &MultiChecker{checkers: filtered} +} + +func (checker *MultiChecker) Ping(ctx context.Context) error { + for index, dependency := range checker.checkers { + if err := dependency.Ping(ctx); err != nil { + return fmt.Errorf("dependency %d: %w", index, err) + } + } + return nil +} diff --git a/internal/adapter/memory/errors.go b/internal/adapter/memory/errors.go new file mode 100644 index 0000000..0714884 --- /dev/null +++ b/internal/adapter/memory/errors.go @@ -0,0 +1,8 @@ +package memory + +import "mtusi2026lab7/internal/domain" + +var ( + ErrNotFound = domain.ErrNotFound + ErrConflict = domain.ErrConflict +) diff --git a/internal/adapter/memory/repository.go b/internal/adapter/memory/repository.go new file mode 100644 index 0000000..60c703f --- /dev/null +++ b/internal/adapter/memory/repository.go @@ -0,0 +1,401 @@ +package memory + +import ( + "context" + "fmt" + "sync" + "time" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" +) + +type memorySession struct { + userID string + expiresAt time.Time +} + +type memoryIdempotencyScope struct { + actorID string + method string + canonicalPath string + key string +} + +type memoryIdempotencyResult struct { + requestHash [32]byte + message domain.Message + expiresAt time.Time +} + +type MemoryRepository struct { + legacy *MemoryStore + + mu sync.RWMutex + passwordByUserID map[string]string + userIDByUsername map[string]string + sessionsByHashKey map[[32]byte]memorySession + idempotencyByScope map[memoryIdempotencyScope]memoryIdempotencyResult +} + +func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository { + return &MemoryRepository{ + legacy: legacy, + passwordByUserID: make(map[string]string), + userIDByUsername: make(map[string]string), + sessionsByHashKey: make(map[[32]byte]memorySession), + idempotencyByScope: make(map[memoryIdempotencyScope]memoryIdempotencyResult), + } +} + +func (r *MemoryRepository) CreateUser( + ctx context.Context, + username string, + displayName string, + passwordHash string, +) (domain.User, error) { + if err := ctx.Err(); err != nil { + return domain.User{}, err + } + + user, err := r.legacy.CreateUser(username, displayName) + if err != nil { + return domain.User{}, err + } + + r.mu.Lock() + r.passwordByUserID[user.ID] = passwordHash + r.userIDByUsername[user.Username] = user.ID + r.mu.Unlock() + + return user, nil +} + +func (r *MemoryRepository) GetUserByID( + ctx context.Context, + userID string, +) (domain.User, error) { + if err := ctx.Err(); err != nil { + return domain.User{}, err + } + + return r.legacy.GetUserByID(userID) +} + +func (r *MemoryRepository) GetUserByUsername( + ctx context.Context, + username string, +) (domain.User, string, error) { + if err := ctx.Err(); err != nil { + return domain.User{}, "", err + } + + r.mu.RLock() + userID, exists := r.userIDByUsername[username] + passwordHash := r.passwordByUserID[userID] + r.mu.RUnlock() + + if !exists { + return domain.User{}, "", ErrNotFound + } + + user, err := r.legacy.GetUserByID(userID) + if err != nil { + return domain.User{}, "", err + } + + return user, passwordHash, nil +} + +func (r *MemoryRepository) UpdatePasswordHash( + ctx context.Context, + userID string, + previousHash string, + newHash string, +) error { + if err := ctx.Err(); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + if current, exists := r.passwordByUserID[userID]; exists && current == previousHash { + r.passwordByUserID[userID] = newHash + } + return nil +} + +func (r *MemoryRepository) CreateChat( + ctx context.Context, + title string, + memberIDs []string, +) (domain.Chat, error) { + if err := ctx.Err(); err != nil { + return domain.Chat{}, err + } + + return r.legacy.CreateChat(title, memberIDs) +} + +func (r *MemoryRepository) GetChatByID( + ctx context.Context, + chatID string, + callerID string, +) (domain.Chat, error) { + if err := ctx.Err(); err != nil { + return domain.Chat{}, err + } + + return r.legacy.GetChatByID(chatID, callerID) +} + +func (r *MemoryRepository) GetChatsForUser( + ctx context.Context, + userID string, + limit int, + cursor *domain.ChatCursor, +) ([]domain.Chat, bool, error) { + if err := ctx.Err(); err != nil { + return nil, false, err + } + + return r.legacy.GetChatsForUser(userID, limit, cursor) +} + +func (r *MemoryRepository) CreateMessageIdempotently( + ctx context.Context, + write application.IdempotentMessageWrite, +) (domain.Message, error) { + if err := ctx.Err(); err != nil { + return domain.Message{}, err + } + + scope := memoryIdempotencyScope{ + actorID: write.ActorID, + method: write.Method, + canonicalPath: write.CanonicalPath, + key: write.Key, + } + now := time.Now().UTC() + + r.mu.Lock() + defer r.mu.Unlock() + + if _, err := r.legacy.GetChatByID(write.ChatID, write.ActorID); err != nil { + return domain.Message{}, err + } + for _, attachmentID := range write.AttachmentIDs { + attachment, err := r.legacy.GetAttachmentByID(attachmentID) + if err != nil || attachment.ChatID != write.ChatID { + return domain.Message{}, ErrNotFound + } + if attachment.Status != domain.AttachmentStatusReady { + return domain.Message{}, application.ErrAttachmentNotReady + } + } + + if stored, exists := r.idempotencyByScope[scope]; exists { + if stored.expiresAt.After(now) { + if stored.requestHash != write.RequestHash { + return domain.Message{}, application.ErrIdempotencyConflict + } + return stored.message, nil + } + delete(r.idempotencyByScope, scope) + } + + message, err := r.legacy.CreateMessage( + write.ChatID, + write.ActorID, + write.Text, + write.AttachmentIDs, + ) + if err != nil { + return domain.Message{}, err + } + r.idempotencyByScope[scope] = memoryIdempotencyResult{ + requestHash: write.RequestHash, + message: message, + expiresAt: now.Add(write.TTL), + } + return message, nil +} + +func (r *MemoryRepository) GetMessages( + ctx context.Context, + chatID string, + callerID string, + limit int, + cursor *domain.MessageCursor, +) ([]domain.Message, bool, error) { + if err := ctx.Err(); err != nil { + return nil, false, err + } + + return r.legacy.GetMessages( + chatID, + callerID, + limit, + cursor, + ) +} + +func (r *MemoryRepository) CreateSession( + ctx context.Context, + tokenHash []byte, + userID string, + expiresAt time.Time, +) error { + if err := ctx.Err(); err != nil { + return err + } + + key, err := memoryTokenHashKey(tokenHash) + if err != nil { + return err + } + + r.mu.Lock() + r.sessionsByHashKey[key] = memorySession{ + userID: userID, + expiresAt: expiresAt, + } + r.mu.Unlock() + + return nil +} + +func (r *MemoryRepository) GetUserBySession( + ctx context.Context, + tokenHash []byte, +) (domain.User, error) { + if err := ctx.Err(); err != nil { + return domain.User{}, err + } + + key, err := memoryTokenHashKey(tokenHash) + if err != nil { + return domain.User{}, ErrNotFound + } + + r.mu.RLock() + session, exists := r.sessionsByHashKey[key] + r.mu.RUnlock() + + if !exists || !session.expiresAt.After(time.Now().UTC()) { + return domain.User{}, ErrNotFound + } + + return r.legacy.GetUserByID(session.userID) +} + +func (r *MemoryRepository) DeleteSession( + ctx context.Context, + tokenHash []byte, +) error { + if err := ctx.Err(); err != nil { + return err + } + + key, err := memoryTokenHashKey(tokenHash) + if err != nil { + return err + } + + r.mu.Lock() + delete(r.sessionsByHashKey, key) + r.mu.Unlock() + + return nil +} + +func (r *MemoryRepository) CreateQueuedAttachment( + ctx context.Context, + attachment domain.Attachment, + _ domain.AttachmentJob, +) (domain.Attachment, error) { + return r.CreateAttachment(ctx, attachment) +} +func (r *MemoryRepository) CreateAttachment( + ctx context.Context, + attachment domain.Attachment, +) (domain.Attachment, error) { + if err := ctx.Err(); err != nil { + return domain.Attachment{}, err + } + if err := r.legacy.PutAttachment(attachment); err != nil { + return domain.Attachment{}, err + } + return attachment, nil +} + +func (r *MemoryRepository) MarkAttachmentReady( + ctx context.Context, + attachmentID string, + updatedAt time.Time, +) (domain.Attachment, error) { + if err := ctx.Err(); err != nil { + return domain.Attachment{}, err + } + return r.legacy.UpdateAttachmentStatus( + attachmentID, + domain.AttachmentStatusReady, + nil, + updatedAt, + ) +} + +func (r *MemoryRepository) MarkAttachmentFailed( + ctx context.Context, + attachmentID string, + errorCode string, + updatedAt time.Time, +) error { + if err := ctx.Err(); err != nil { + return err + } + _, err := r.legacy.UpdateAttachmentStatus( + attachmentID, + domain.AttachmentStatusFailed, + &errorCode, + updatedAt, + ) + return err +} + +func (r *MemoryRepository) GetAttachment( + ctx context.Context, + attachmentID string, + callerID string, +) (domain.Attachment, error) { + if err := ctx.Err(); err != nil { + return domain.Attachment{}, err + } + attachment, err := r.legacy.GetAttachmentByID(attachmentID) + if err != nil { + return domain.Attachment{}, err + } + if _, err = r.legacy.GetChatByID(attachment.ChatID, callerID); err != nil { + return domain.Attachment{}, err + } + if attachment.Variants == nil { + attachment.Variants = make([]domain.AttachmentVariant, 0) + } + return attachment, nil +} + +func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) { + var key [32]byte + + if len(tokenHash) != len(key) { + return key, fmt.Errorf( + "session token hash must contain %d bytes", + len(key), + ) + } + + copy(key[:], tokenHash) + + return key, nil +} + +var _ application.Repository = (*MemoryRepository)(nil) diff --git a/internal/adapter/memory/store.go b/internal/adapter/memory/store.go new file mode 100644 index 0000000..454a913 --- /dev/null +++ b/internal/adapter/memory/store.go @@ -0,0 +1,371 @@ +package memory + +import ( + "fmt" + "sort" + "sync" + "time" + + "mtusi2026lab7/internal/domain" + + "github.com/google/uuid" +) + +type MemoryStore struct { + mu sync.RWMutex + + usersByID map[string]domain.User //key = user UUID + usersByUsername map[string]string //key = username для быстрой проверки уникальности + + chatsByID map[string]domain.Chat //key = chat UUID + + messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений + + attachmentsByID map[string]domain.Attachment +} + +func NewMemoryStore() *MemoryStore { + return &MemoryStore{ + usersByID: make(map[string]domain.User), + usersByUsername: make(map[string]string), + chatsByID: make(map[string]domain.Chat), + messagesByChatID: make(map[string][]domain.Message), + attachmentsByID: make(map[string]domain.Attachment), + } +} + +// ---пользователи--- + +func (s *MemoryStore) CreateUser(username, displayName string) (domain.User, error) { + s.mu.Lock() + defer s.mu.Unlock() + + // дубликат username -> 409 Conflict + if _, exists := s.usersByUsername[username]; exists { + return domain.User{}, ErrConflict + } + + user := domain.User{ + ID: uuid.NewString(), + Username: username, + DisplayName: displayName, + CreatedAt: time.Now().UTC(), + } + + s.usersByID[user.ID] = user + s.usersByUsername[user.Username] = user.ID + + return user, nil +} + +func (s *MemoryStore) GetUserByID(id string) (domain.User, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + user, exists := s.usersByID[id] + if !exists { + return domain.User{}, ErrNotFound + } + return user, nil +} + +// ---чаты--- + +func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat, error) { + s.mu.Lock() + defer s.mu.Unlock() + + //все участники рил существуют + for _, memberID := range memberIDs { + if _, exists := s.usersByID[memberID]; !exists { + return domain.Chat{}, fmt.Errorf( + "%w: member %s", + ErrNotFound, + memberID, + ) + } + } + + chat := domain.Chat{ + ID: uuid.NewString(), + Title: title, + MemberIDs: append([]string(nil), memberIDs...), //копирую слайс для изоляции + CreatedAt: time.Now().UTC(), + } + + s.chatsByID[chat.ID] = chat + s.messagesByChatID[chat.ID] = make([]domain.Message, 0) + + return chat, nil +} + +func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + chat, exists := s.chatsByID[chatID] + if !exists { + return domain.Chat{}, ErrNotFound + } + + // Требование безопасности: посторонний получает 404, а не 403 + isMember := false + for _, m := range chat.MemberIDs { + if m == callerID { + isMember = true + break + } + } + + if !isMember { + return domain.Chat{}, ErrNotFound + } + + return chat, nil +} + +func (s *MemoryStore) GetChatsForUser( + userID string, + limit int, + cursorData *domain.ChatCursor, +) ([]domain.Chat, bool, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + chats := make([]domain.Chat, 0) + + for _, chat := range s.chatsByID { + for _, memberID := range chat.MemberIDs { + if memberID == userID { + chats = append(chats, chat) + break + } + } + } + + sort.Slice(chats, func(i, j int) bool { + if chats[i].CreatedAt.Equal(chats[j].CreatedAt) { + return chats[i].ID < chats[j].ID + } + + return chats[i].CreatedAt.Before(chats[j].CreatedAt) + }) + + start := 0 + + if cursorData != nil { + start = sort.Search(len(chats), func(index int) bool { + chat := chats[index] + + if chat.CreatedAt.After(cursorData.CreatedAt) { + return true + } + + return chat.CreatedAt.Equal(cursorData.CreatedAt) && + chat.ID > cursorData.ChatID + }) + } + + if start >= len(chats) { + return make([]domain.Chat, 0), false, nil + } + + end := start + limit + if end > len(chats) { + end = len(chats) + } + + items := make([]domain.Chat, end-start) + copy(items, chats[start:end]) + return items, end < len(chats), nil +} + +// PutAttachment stores metadata for adapter and application tests. Binary +// content intentionally does not belong to this in-memory metadata store. +func (s *MemoryStore) PutAttachment(attachment domain.Attachment) error { + s.mu.Lock() + defer s.mu.Unlock() + + if _, exists := s.attachmentsByID[attachment.ID]; exists { + return ErrConflict + } + + chat, exists := s.chatsByID[attachment.ChatID] + if !exists { + return ErrNotFound + } + + ownerIsMember := false + for _, memberID := range chat.MemberIDs { + if memberID == attachment.OwnerID { + ownerIsMember = true + break + } + } + if !ownerIsMember { + return ErrNotFound + } + + s.attachmentsByID[attachment.ID] = attachment + return nil +} + +func (s *MemoryStore) GetAttachmentByID( + attachmentID string, +) (domain.Attachment, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + attachment, exists := s.attachmentsByID[attachmentID] + if !exists { + return domain.Attachment{}, ErrNotFound + } + return attachment, nil +} + +func (s *MemoryStore) UpdateAttachmentStatus( + attachmentID string, + status domain.AttachmentStatus, + errorCode *string, + updatedAt time.Time, +) (domain.Attachment, error) { + s.mu.Lock() + defer s.mu.Unlock() + + attachment, exists := s.attachmentsByID[attachmentID] + if !exists { + return domain.Attachment{}, ErrNotFound + } + if attachment.Status != domain.AttachmentStatusPending { + return domain.Attachment{}, ErrConflict + } + attachment.Status = status + attachment.ErrorCode = errorCode + attachment.UpdatedAt = updatedAt + if attachment.Variants == nil { + attachment.Variants = make([]domain.AttachmentVariant, 0) + } + s.attachmentsByID[attachmentID] = attachment + return attachment, nil +} + +// ---Сообщения--- + +func (s *MemoryStore) CreateMessage( + chatID, senderID, text string, + attachmentLists ...[]string, +) (domain.Message, error) { + messageID := uuid.NewString() + attachmentIDs := make([]string, 0) + if len(attachmentLists) > 0 { + attachmentIDs = append(attachmentIDs, attachmentLists[0]...) + } + + s.mu.Lock() + defer s.mu.Unlock() + + chat, exists := s.chatsByID[chatID] + if !exists { + return domain.Message{}, ErrNotFound + } + + isMember := false + for _, memberID := range chat.MemberIDs { + if memberID == senderID { + isMember = true + break + } + } + if !isMember { + return domain.Message{}, ErrNotFound + } + + createdAt := time.Now().UTC() + + messages := s.messagesByChatID[chatID] + if len(messages) > 0 { + lastCreatedAt := messages[len(messages)-1].CreatedAt + + // Обеспечиваем строго возрастающее время внутри каждого чата. + if !createdAt.After(lastCreatedAt) { + createdAt = lastCreatedAt.Add(time.Nanosecond) + } + } + + message := domain.Message{ + ID: messageID, + ChatID: chatID, + SenderID: senderID, + Text: text, + AttachmentIDs: attachmentIDs, + CreatedAt: createdAt, + } + + s.messagesByChatID[chatID] = append(messages, message) + + return message, nil +} + +func (s *MemoryStore) GetMessages( + chatID, callerID string, + limit int, + cursorData *domain.MessageCursor, +) ([]domain.Message, bool, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + chat, exists := s.chatsByID[chatID] + if !exists { + return nil, false, ErrNotFound + } + + isMember := false + for _, memberID := range chat.MemberIDs { + if memberID == callerID { + isMember = true + break + } + } + if !isMember { + return nil, false, ErrNotFound + } + + messages := s.messagesByChatID[chatID] + + start := 0 + + if cursorData != nil { + // Срез уже упорядочен во время записи, поэтому вместо + // полного прохода используем бинарный поиск. + start = sort.Search(len(messages), func(index int) bool { + message := messages[index] + + if message.CreatedAt.After(cursorData.CreatedAt) { + return true + } + + return message.CreatedAt.Equal(cursorData.CreatedAt) && + message.ID > cursorData.MessageID + }) + } + + if start >= len(messages) { + return make([]domain.Message, 0), false, nil + } + + end := len(messages) + if limit > 0 && end-start > limit { + end = start + limit + } + + // копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез + items := make([]domain.Message, end-start) + for index, message := range messages[start:end] { + message.AttachmentIDs = append( + make([]string, 0, len(message.AttachmentIDs)), + message.AttachmentIDs..., + ) + items[index] = message + } + return items, end < len(messages), nil +} diff --git a/internal/adapter/objectstore/minio.go b/internal/adapter/objectstore/minio.go new file mode 100644 index 0000000..cd68500 --- /dev/null +++ b/internal/adapter/objectstore/minio.go @@ -0,0 +1,226 @@ +package objectstore + +import ( + "bytes" + "context" + "fmt" + "io" + "net/url" + "strings" + "time" + + "mtusi2026lab7/internal/application" + + minio "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/trace" +) + +type MinIOStore struct { + client *minio.Client + bucket string + operationTimeout time.Duration +} + +type StoredObject struct { + Key string + SizeBytes int64 + LastModified time.Time +} + +func NewMinIOStore( + endpoint string, + region string, + bucket string, + accessKeyID string, + secretAccessKey string, + operationTimeout time.Duration, +) (*MinIOStore, error) { + parsedEndpoint, err := url.Parse(endpoint) + if err != nil || parsedEndpoint.Host == "" { + return nil, fmt.Errorf("S3 endpoint must be an absolute HTTP(S) URL") + } + if parsedEndpoint.Scheme != "http" && parsedEndpoint.Scheme != "https" { + return nil, fmt.Errorf("S3 endpoint scheme must be http or https") + } + if parsedEndpoint.Path != "" && parsedEndpoint.Path != "/" { + return nil, fmt.Errorf("S3 endpoint must not contain a path") + } + if parsedEndpoint.RawQuery != "" || parsedEndpoint.Fragment != "" || parsedEndpoint.User != nil { + return nil, fmt.Errorf("S3 endpoint must not contain credentials, query or fragment") + } + if strings.TrimSpace(bucket) == "" || strings.TrimSpace(accessKeyID) == "" || + strings.TrimSpace(secretAccessKey) == "" { + return nil, fmt.Errorf("S3 bucket and credentials are required") + } + if operationTimeout <= 0 { + return nil, fmt.Errorf("S3 operation timeout must be positive") + } + + client, err := minio.New(parsedEndpoint.Host, &minio.Options{ + Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""), + Secure: parsedEndpoint.Scheme == "https", + Region: region, + }) + if err != nil { + return nil, fmt.Errorf("create MinIO client: %w", err) + } + return &MinIOStore{client: client, bucket: bucket, operationTimeout: operationTimeout}, nil +} + +func (store *MinIOStore) Put(ctx context.Context, object application.ObjectPut) error { + ctx, span := startObjectSpan(ctx, "put") + defer span.End() + operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout) + defer cancel() + upload, err := store.client.PutObject( + operationContext, + store.bucket, + object.Key, + object.Body, + object.SizeBytes, + minio.PutObjectOptions{ContentType: object.ContentType}, + ) + if err != nil { + return fmt.Errorf("put MinIO object: %w", err) + } + if upload.Size != object.SizeBytes { + return fmt.Errorf("put MinIO object: stored %d bytes, want %d", upload.Size, object.SizeBytes) + } + return nil +} + +func (store *MinIOStore) Get( + ctx context.Context, + key string, +) (application.ObjectContent, error) { + ctx, span := startObjectSpan(ctx, "get") + defer span.End() + operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout) + stat, err := store.client.StatObject( + operationContext, + store.bucket, + key, + minio.StatObjectOptions{}, + ) + if err != nil { + cancel() + return application.ObjectContent{}, fmt.Errorf("stat MinIO object: %w", err) + } + object, err := store.client.GetObject( + operationContext, + store.bucket, + key, + minio.GetObjectOptions{}, + ) + if err != nil { + cancel() + return application.ObjectContent{}, fmt.Errorf("get MinIO object: %w", err) + } + firstByte := make([]byte, 1) + readCount, readError := object.Read(firstByte) + if readError != nil && readCount == 0 { + _ = object.Close() + cancel() + return application.ObjectContent{}, fmt.Errorf("read MinIO object: %w", readError) + } + if readCount != 1 { + _ = object.Close() + cancel() + return application.ObjectContent{}, fmt.Errorf("read MinIO object: expected non-empty object") + } + return application.ObjectContent{ + Body: &cancelingReadCloser{ + Reader: io.MultiReader(bytes.NewReader(firstByte), object), + Closer: object, + cancel: cancel, + }, + SizeBytes: stat.Size, + }, nil +} + +func (store *MinIOStore) List( + ctx context.Context, + prefix string, +) ([]StoredObject, error) { + ctx, span := startObjectSpan(ctx, "list") + defer span.End() + operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout) + defer cancel() + + objects := make([]StoredObject, 0) + for object := range store.client.ListObjects( + operationContext, + store.bucket, + minio.ListObjectsOptions{Prefix: prefix, Recursive: true}, + ) { + if object.Err != nil { + return nil, fmt.Errorf("list MinIO objects: %w", object.Err) + } + objects = append(objects, StoredObject{ + Key: object.Key, + SizeBytes: object.Size, + LastModified: object.LastModified.UTC(), + }) + } + return objects, nil +} + +func (store *MinIOStore) Delete(ctx context.Context, key string) error { + ctx, span := startObjectSpan(ctx, "delete") + defer span.End() + operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout) + defer cancel() + if err := store.client.RemoveObject( + operationContext, + store.bucket, + key, + minio.RemoveObjectOptions{}, + ); err != nil { + return fmt.Errorf("delete MinIO object: %w", err) + } + return nil +} + +func (store *MinIOStore) Ping(ctx context.Context) error { + ctx, span := startObjectSpan(ctx, "bucket_exists") + defer span.End() + operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout) + defer cancel() + exists, err := store.client.BucketExists(operationContext, store.bucket) + if err != nil { + return fmt.Errorf("check MinIO bucket: %w", err) + } + if !exists { + return fmt.Errorf("MinIO bucket %q does not exist", store.bucket) + } + return nil +} + +func startObjectSpan(ctx context.Context, operation string) (context.Context, trace.Span) { + return otel.Tracer("mtusi2026lab7/s3").Start( + ctx, + "s3."+operation, + trace.WithSpanKind(trace.SpanKindClient), + trace.WithAttributes( + attribute.String("storage.system", "s3"), + attribute.String("storage.operation", operation), + ), + ) +} + +type cancelingReadCloser struct { + io.Reader + io.Closer + cancel context.CancelFunc +} + +func (reader *cancelingReadCloser) Close() error { + err := reader.Closer.Close() + reader.cancel() + return err +} + +var _ application.ObjectStore = (*MinIOStore)(nil) diff --git a/internal/adapter/objectstore/minio_test.go b/internal/adapter/objectstore/minio_test.go new file mode 100644 index 0000000..204debd --- /dev/null +++ b/internal/adapter/objectstore/minio_test.go @@ -0,0 +1,37 @@ +package objectstore + +import ( + "testing" + "time" +) + +func TestNewMinIOStoreValidatesConfiguration(t *testing.T) { + testCases := []struct { + name string + endpoint string + bucket string + accessKey string + secretKey string + timeout time.Duration + wantError bool + }{ + {name: "valid HTTP", endpoint: "http://minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second}, + {name: "valid HTTPS", endpoint: "https://s3.example.test", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second}, + {name: "relative endpoint", endpoint: "minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true}, + {name: "endpoint path", endpoint: "http://minio:9000/path", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true}, + {name: "embedded credentials", endpoint: "http://user:pass@minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true}, + {name: "empty bucket", endpoint: "http://minio:9000", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true}, + {name: "empty credentials", endpoint: "http://minio:9000", bucket: "attachments", timeout: time.Second, wantError: true}, + {name: "invalid timeout", endpoint: "http://minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", wantError: true}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + _, err := NewMinIOStore(testCase.endpoint, "us-east-1", testCase.bucket, + testCase.accessKey, testCase.secretKey, testCase.timeout) + if (err != nil) != testCase.wantError { + t.Fatalf("NewMinIOStore() error = %v, wantError %v", err, testCase.wantError) + } + }) + } +} diff --git a/internal/adapter/postgres/attachment_jobs.go b/internal/adapter/postgres/attachment_jobs.go new file mode 100644 index 0000000..9ee6f55 --- /dev/null +++ b/internal/adapter/postgres/attachment_jobs.go @@ -0,0 +1,906 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "mtusi2026lab7/internal/domain" + + "github.com/jackc/pgx/v5" +) + +const attachmentJobColumns = ` + schema_version, job_id::text, job_type, attachment_id::text, + pipeline_version, attempt, max_attempts, status, error_code, + available_at, lease_until, leased_by, replay_count, created_at, updated_at, + COALESCE(traceparent, ''), COALESCE(tracestate, '') +` + +type scanner interface { + Scan(dest ...any) error +} + +func scanAttachmentJob(row scanner, job *domain.AttachmentJob) error { + return row.Scan( + &job.SchemaVersion, + &job.JobID, + &job.Type, + &job.AttachmentID, + &job.PipelineVersion, + &job.Attempt, + &job.MaxAttempts, + &job.Status, + &job.ErrorCode, + &job.AvailableAt, + &job.LeaseUntil, + &job.LeasedBy, + &job.ReplayCount, + &job.CreatedAt, + &job.UpdatedAt, + &job.TraceParent, + &job.TraceState, + ) +} + +func (s *PostgreSQLStore) CreateQueuedAttachment(ctx context.Context, attachment domain.Attachment, job domain.AttachmentJob) (domain.Attachment, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + tx, err := s.pool.Begin(queryContext) + if err != nil { + return domain.Attachment{}, fmt.Errorf("begin queued attachment transaction: %w", err) + } + defer func() { _ = tx.Rollback(queryContext) }() + + err = tx.QueryRow(queryContext, ` + INSERT INTO attachments ( + id, chat_id, owner_id, object_key, staging_key, filename, content_type, + size_bytes, sha256, width, height, pipeline_version, status, error_code, + created_at, updated_at + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,decode($9,'hex'),$10,$11,$12,$13,NULL,$14,$15) + RETURNING created_at, updated_at + `, attachment.ID, attachment.ChatID, attachment.OwnerID, attachment.ObjectKey, + attachment.StagingKey, attachment.Filename, attachment.ContentType, attachment.SizeBytes, + attachment.SHA256, attachment.Width, attachment.Height, attachment.PipelineVersion, + attachment.Status, attachment.CreatedAt, attachment.UpdatedAt, + ).Scan(&attachment.CreatedAt, &attachment.UpdatedAt) + if err != nil { + return domain.Attachment{}, fmt.Errorf("insert queued attachment: %w", err) + } + if job.AvailableAt.IsZero() { + job.AvailableAt = job.CreatedAt + } + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_jobs ( + job_id, attachment_id, schema_version, job_type, pipeline_version, + attempt, max_attempts, status, available_at, created_at, updated_at, + traceparent, tracestate + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) + `, job.JobID, job.AttachmentID, job.SchemaVersion, job.Type, job.PipelineVersion, + job.Attempt, job.MaxAttempts, job.Status, job.AvailableAt, job.CreatedAt, job.UpdatedAt, + job.TraceParent, job.TraceState) + if err != nil { + return domain.Attachment{}, fmt.Errorf("insert attachment job: %w", err) + } + if err = tx.Commit(queryContext); err != nil { + return domain.Attachment{}, fmt.Errorf("commit queued attachment: %w", err) + } + attachment.Variants = make([]domain.AttachmentVariant, 0) + return attachment, nil +} + +func (s *PostgreSQLStore) ListUnpublishedAttachmentJobs(ctx context.Context, limit int) ([]domain.AttachmentJob, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + rows, err := s.pool.Query(queryContext, ` + SELECT `+attachmentJobColumns+` + FROM attachment_jobs + WHERE status = 'queued' AND published_at IS NULL + AND available_at <= CURRENT_TIMESTAMP + ORDER BY available_at, created_at, job_id + LIMIT $1 + `, limit) + if err != nil { + return nil, fmt.Errorf("list unpublished attachment jobs: %w", err) + } + defer rows.Close() + jobs := make([]domain.AttachmentJob, 0) + for rows.Next() { + var job domain.AttachmentJob + if err = scanAttachmentJob(rows, &job); err != nil { + return nil, fmt.Errorf("scan unpublished attachment job: %w", err) + } + jobs = append(jobs, job) + } + return jobs, rows.Err() +} + +func (s *PostgreSQLStore) MarkAttachmentJobPublished(ctx context.Context, jobID string, attempt int, publishedAt time.Time) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + _, err := s.pool.Exec(queryContext, ` + UPDATE attachment_jobs SET published_at = $3, updated_at = $3 + WHERE job_id = $1 AND attempt = $2 AND status = 'queued' + `, jobID, attempt, publishedAt) + if err != nil { + return fmt.Errorf("mark attachment job published: %w", err) + } + return nil +} + +func (s *PostgreSQLStore) ClaimAttachmentJob( + ctx context.Context, + message domain.AttachmentJobMessage, + workerID string, + leaseUntil time.Time, +) (domain.AttachmentJob, bool, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + tx, err := s.pool.Begin(queryContext) + if err != nil { + return domain.AttachmentJob{}, false, fmt.Errorf("begin claim attachment job: %w", err) + } + defer func() { _ = tx.Rollback(queryContext) }() + + var job domain.AttachmentJob + err = scanAttachmentJob(tx.QueryRow(queryContext, ` + UPDATE attachment_jobs + SET status = 'processing', lease_until = $5, leased_by = $6, + updated_at = CURRENT_TIMESTAMP + WHERE job_id = $1 AND attachment_id = $2 AND pipeline_version = $3 + AND attempt = $4 AND status = 'queued' + AND available_at <= CURRENT_TIMESTAMP + AND EXISTS ( + SELECT 1 FROM attachments a + WHERE a.id = attachment_jobs.attachment_id + AND a.pipeline_version = attachment_jobs.pipeline_version + AND a.status = 'queued' + ) + RETURNING `+attachmentJobColumns+` + `, message.JobID, message.AttachmentID, message.PipelineVersion, message.Attempt, + leaseUntil, workerID), &job) + if errors.Is(err, pgx.ErrNoRows) { + var status domain.AttachmentJobStatus + var attachmentStatus domain.AttachmentStatus + var attempt, activeVersion, jobVersion int + lookupErr := tx.QueryRow(queryContext, ` + SELECT j.status, j.attempt, a.status, a.pipeline_version, j.pipeline_version + FROM attachment_jobs j + JOIN attachments a ON a.id=j.attachment_id + WHERE j.job_id=$1 + FOR UPDATE OF a,j + `, message.JobID).Scan( + &status, + &attempt, + &attachmentStatus, + &activeVersion, + &jobVersion, + ) + if errors.Is(lookupErr, pgx.ErrNoRows) { + return domain.AttachmentJob{}, false, ErrNotFound + } + if lookupErr != nil { + return domain.AttachmentJob{}, false, fmt.Errorf("inspect unclaimed attachment job: %w", lookupErr) + } + err = nil + switch { + case status == domain.AttachmentJobQueued && + activeVersion == jobVersion && + attachmentStatus == domain.AttachmentStatusReady: + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='succeeded', error_code=NULL, published_at=COALESCE(published_at,CURRENT_TIMESTAMP), + lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP + WHERE job_id=$1 + `, message.JobID) + status = domain.AttachmentJobSucceeded + case status == domain.AttachmentJobQueued && activeVersion != jobVersion: + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='superseded', error_code='superseded_pipeline', + lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP + WHERE job_id=$1 + `, message.JobID) + status = domain.AttachmentJobSuperseded + } + if err != nil { + return domain.AttachmentJob{}, false, fmt.Errorf("normalize unclaimed attachment job: %w", err) + } + if err = tx.Commit(queryContext); err != nil { + return domain.AttachmentJob{}, false, fmt.Errorf("commit unclaimed attachment job: %w", err) + } + return domain.AttachmentJob{JobID: message.JobID, Status: status, Attempt: attempt}, false, nil + } + if err != nil { + return domain.AttachmentJob{}, false, fmt.Errorf("claim attachment job: %w", err) + } + _, err = tx.Exec(queryContext, ` + UPDATE attachments SET status = 'processing', updated_at = CURRENT_TIMESTAMP + WHERE id = $1 AND pipeline_version = $2 AND status = 'queued' + `, message.AttachmentID, message.PipelineVersion) + if err != nil { + return domain.AttachmentJob{}, false, fmt.Errorf("mark attachment processing: %w", err) + } + if err = tx.Commit(queryContext); err != nil { + return domain.AttachmentJob{}, false, fmt.Errorf("commit claimed attachment job: %w", err) + } + return job, true, nil +} + +func (s *PostgreSQLStore) GetAttachmentForProcessing(ctx context.Context, attachmentID string) (domain.Attachment, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + var attachment domain.Attachment + var digest []byte + var stagingKey *string + err := s.pool.QueryRow(queryContext, ` + SELECT id::text, chat_id::text, owner_id::text, object_key, staging_key, + filename, content_type, size_bytes, sha256, width, height, + pipeline_version, status, error_code, created_at, updated_at + FROM attachments WHERE id = $1 + `, attachmentID).Scan(&attachment.ID, &attachment.ChatID, &attachment.OwnerID, + &attachment.ObjectKey, &stagingKey, &attachment.Filename, + &attachment.ContentType, &attachment.SizeBytes, &digest, &attachment.Width, + &attachment.Height, &attachment.PipelineVersion, &attachment.Status, + &attachment.ErrorCode, &attachment.CreatedAt, &attachment.UpdatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return domain.Attachment{}, ErrNotFound + } + if err != nil { + return domain.Attachment{}, fmt.Errorf("get attachment for processing: %w", err) + } + attachment.SHA256 = fmt.Sprintf("%x", digest) + if stagingKey != nil { + attachment.StagingKey = *stagingKey + } + return attachment, nil +} + +func (s *PostgreSQLStore) CompleteAttachmentJob( + ctx context.Context, + job domain.AttachmentJob, + variants []domain.AttachmentVariant, + updatedAt time.Time, +) (bool, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + tx, err := s.pool.Begin(queryContext) + if err != nil { + return false, fmt.Errorf("begin complete attachment job: %w", err) + } + defer func() { _ = tx.Rollback(queryContext) }() + + var attachmentStatus domain.AttachmentStatus + var pipelineVersion int + var jobStatus domain.AttachmentJobStatus + err = tx.QueryRow(queryContext, ` + SELECT a.status, a.pipeline_version, j.status + FROM attachments a + JOIN attachment_jobs j ON j.attachment_id = a.id + WHERE a.id = $1 AND j.job_id = $2 + FOR UPDATE OF a, j + `, job.AttachmentID, job.JobID).Scan(&attachmentStatus, &pipelineVersion, &jobStatus) + if err != nil { + return false, fmt.Errorf("lock attachment completion: %w", err) + } + if pipelineVersion != job.PipelineVersion || jobStatus == domain.AttachmentJobSuperseded { + if jobStatus != domain.AttachmentJobSuperseded { + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='superseded', error_code='superseded_pipeline', + lease_until=NULL, leased_by=NULL, updated_at=$2 + WHERE job_id=$1 + `, job.JobID, updatedAt) + if err == nil { + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_job_events + (job_id, event_type, previous_status, new_status, attempt, error_code, created_at) + VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4) + `, job.JobID, jobStatus, job.Attempt, updatedAt) + } + if err != nil { + return false, fmt.Errorf("supersede stale pipeline completion: %w", err) + } + } + if err = tx.Commit(queryContext); err != nil { + return false, fmt.Errorf("commit stale pipeline completion: %w", err) + } + return false, nil + } + if attachmentStatus == domain.AttachmentStatusReady || jobStatus == domain.AttachmentJobSucceeded { + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2 + WHERE job_id=$1 + `, job.JobID, updatedAt) + if err != nil { + return false, fmt.Errorf("normalize completed job: %w", err) + } + if err = tx.Commit(queryContext); err != nil { + return false, err + } + return true, nil + } + if len(variants) != 3 { + return false, fmt.Errorf("complete attachment requires three variants: %w", ErrConflict) + } + for _, variant := range variants { + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_variants ( + attachment_id, pipeline_version, name, object_key, content_type, + size_bytes, width, height, sha256, created_at + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,decode($9,'hex'),$10) + ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET + object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type, + size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, + height = EXCLUDED.height, sha256 = EXCLUDED.sha256 + `, job.AttachmentID, job.PipelineVersion, variant.Name, variant.ObjectKey, + variant.ContentType, variant.SizeBytes, variant.Width, variant.Height, + variant.SHA256, updatedAt) + if err != nil { + return false, fmt.Errorf("upsert attachment variant %s: %w", variant.Name, err) + } + } + tag, err := tx.Exec(queryContext, ` + UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = $3 + WHERE id = $1 AND pipeline_version = $2 AND status IN ('queued','processing') + `, job.AttachmentID, job.PipelineVersion, updatedAt) + if err != nil { + return false, fmt.Errorf("mark attachment ready: %w", err) + } + if tag.RowsAffected() != 1 { + return false, fmt.Errorf("active pipeline changed during completion: %w", ErrConflict) + } + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status = 'succeeded', error_code = NULL, lease_until = NULL, + leased_by = NULL, updated_at = $2 + WHERE job_id = $1 + `, job.JobID, updatedAt) + if err != nil { + return false, fmt.Errorf("mark attachment job succeeded: %w", err) + } + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_job_events + (job_id, event_type, previous_status, new_status, attempt, created_at) + VALUES ($1, 'completed', $2, 'succeeded', $3, $4) + `, job.JobID, jobStatus, job.Attempt, updatedAt) + if err != nil { + return false, fmt.Errorf("record attachment completion: %w", err) + } + if err = tx.Commit(queryContext); err != nil { + return false, fmt.Errorf("commit completed attachment job: %w", err) + } + return true, nil +} + +func (s *PostgreSQLStore) RetryAttachmentJob( + ctx context.Context, + jobID string, + errorCode string, + availableAt time.Time, + updatedAt time.Time, + eventType string, +) (domain.AttachmentJob, bool, error) { + if eventType != "retry_scheduled" && eventType != "lease_recovered" { + return domain.AttachmentJob{}, false, fmt.Errorf("unsupported retry event type") + } + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + tx, err := s.pool.Begin(queryContext) + if err != nil { + return domain.AttachmentJob{}, false, fmt.Errorf("begin retry attachment job: %w", err) + } + defer func() { _ = tx.Rollback(queryContext) }() + + var job domain.AttachmentJob + err = scanAttachmentJob(tx.QueryRow(queryContext, ` + SELECT `+attachmentJobColumns+` + FROM attachment_jobs WHERE job_id = $1 FOR UPDATE + `, jobID), &job) + if err != nil { + return domain.AttachmentJob{}, false, fmt.Errorf("lock attachment job for retry: %w", err) + } + var attachmentStatus domain.AttachmentStatus + var activePipelineVersion int + if err = tx.QueryRow(queryContext, + `SELECT status, pipeline_version FROM attachments WHERE id = $1 FOR UPDATE`, + job.AttachmentID, + ).Scan(&attachmentStatus, &activePipelineVersion); err != nil { + return domain.AttachmentJob{}, false, fmt.Errorf("lock attachment for retry: %w", err) + } + if activePipelineVersion != job.PipelineVersion || job.Status == domain.AttachmentJobSuperseded { + previousStatus := job.Status + if job.Status != domain.AttachmentJobSuperseded { + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='superseded', error_code='superseded_pipeline', + lease_until=NULL, leased_by=NULL, updated_at=$2 + WHERE job_id=$1 + `, jobID, updatedAt) + if err == nil { + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_job_events + (job_id, event_type, previous_status, new_status, attempt, error_code, created_at) + VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4) + `, jobID, previousStatus, job.Attempt, updatedAt) + } + } + if err != nil { + return domain.AttachmentJob{}, false, err + } + if err = tx.Commit(queryContext); err != nil { + return domain.AttachmentJob{}, false, err + } + job.Status = domain.AttachmentJobSuperseded + job.ErrorCode = stringPointer("superseded_pipeline") + job.LeaseUntil = nil + job.LeasedBy = nil + return job, true, nil + } + if attachmentStatus == domain.AttachmentStatusReady || job.Status == domain.AttachmentJobSucceeded { + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2 + WHERE job_id=$1 + `, jobID, updatedAt) + if err != nil { + return domain.AttachmentJob{}, false, err + } + if err = tx.Commit(queryContext); err != nil { + return domain.AttachmentJob{}, false, err + } + job.Status = domain.AttachmentJobSucceeded + return job, true, nil + } + if job.Status != domain.AttachmentJobProcessing { + if err = tx.Commit(queryContext); err != nil { + return domain.AttachmentJob{}, false, err + } + return job, job.Status == domain.AttachmentJobFailed || job.Status == domain.AttachmentJobSuperseded, nil + } + if job.Attempt >= job.MaxAttempts { + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='failed', error_code=$2, lease_until=NULL, leased_by=NULL, updated_at=$3 + WHERE job_id=$1 + `, jobID, errorCode, updatedAt) + if err == nil { + _, err = tx.Exec(queryContext, ` + UPDATE attachments + SET status='failed', error_code='retry_exhausted', updated_at=$3 + WHERE id=$1 AND pipeline_version=$2 AND status <> 'ready' + `, job.AttachmentID, job.PipelineVersion, updatedAt) + } + if err == nil { + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_job_events + (job_id, event_type, previous_status, new_status, attempt, error_code, created_at) + VALUES ($1, 'permanent_failure', 'processing', 'failed', $2, $3, $4) + `, jobID, job.Attempt, errorCode, updatedAt) + } + if err != nil { + return domain.AttachmentJob{}, false, err + } + if err = tx.Commit(queryContext); err != nil { + return domain.AttachmentJob{}, false, err + } + job.Status = domain.AttachmentJobFailed + job.ErrorCode = &errorCode + job.LeaseUntil = nil + job.LeasedBy = nil + return job, true, nil + } + + job.Attempt++ + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET attempt=$2, status='queued', error_code=$3, available_at=$4, + published_at=NULL, lease_until=NULL, leased_by=NULL, updated_at=$5 + WHERE job_id=$1 + `, jobID, job.Attempt, errorCode, availableAt, updatedAt) + if err == nil { + _, err = tx.Exec(queryContext, ` + UPDATE attachments + SET status='queued', error_code=NULL, updated_at=$3 + WHERE id=$1 AND pipeline_version=$2 AND status <> 'ready' + `, job.AttachmentID, job.PipelineVersion, updatedAt) + } + if err == nil { + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_job_events + (job_id, event_type, previous_status, new_status, attempt, error_code, created_at) + VALUES ($1, $2, 'processing', 'queued', $3, $4, $5) + `, jobID, eventType, job.Attempt, errorCode, updatedAt) + } + if err != nil { + return domain.AttachmentJob{}, false, err + } + if err = tx.Commit(queryContext); err != nil { + return domain.AttachmentJob{}, false, err + } + job.Status = domain.AttachmentJobQueued + job.ErrorCode = &errorCode + job.AvailableAt = availableAt + job.LeaseUntil = nil + job.LeasedBy = nil + job.UpdatedAt = updatedAt + return job, false, nil +} + +func (s *PostgreSQLStore) FailAttachmentJob(ctx context.Context, jobID, errorCode string, updatedAt time.Time) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + tx, err := s.pool.Begin(queryContext) + if err != nil { + return err + } + defer func() { _ = tx.Rollback(queryContext) }() + + var attachmentID string + var attachmentStatus domain.AttachmentStatus + var activePipelineVersion, jobPipelineVersion, attempt int + var jobStatus domain.AttachmentJobStatus + err = tx.QueryRow(queryContext, ` + SELECT a.id::text, a.status, a.pipeline_version, j.pipeline_version, j.status, j.attempt + FROM attachment_jobs j + JOIN attachments a ON a.id=j.attachment_id + WHERE j.job_id=$1 FOR UPDATE OF a,j + `, jobID).Scan( + &attachmentID, + &attachmentStatus, + &activePipelineVersion, + &jobPipelineVersion, + &jobStatus, + &attempt, + ) + if err != nil { + return err + } + if activePipelineVersion != jobPipelineVersion || jobStatus == domain.AttachmentJobSuperseded { + if jobStatus != domain.AttachmentJobSuperseded { + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='superseded', error_code='superseded_pipeline', + lease_until=NULL, leased_by=NULL, updated_at=$2 + WHERE job_id=$1 + `, jobID, updatedAt) + if err == nil { + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_job_events + (job_id, event_type, previous_status, new_status, attempt, error_code, created_at) + VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4) + `, jobID, jobStatus, attempt, updatedAt) + } + } + if err != nil { + return err + } + return tx.Commit(queryContext) + } + if attachmentStatus == domain.AttachmentStatusReady || jobStatus == domain.AttachmentJobSucceeded { + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2 + WHERE job_id=$1 + `, jobID, updatedAt) + } else { + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='failed', error_code=$2, lease_until=NULL, leased_by=NULL, updated_at=$3 + WHERE job_id=$1 + `, jobID, errorCode, updatedAt) + if err == nil { + _, err = tx.Exec(queryContext, ` + UPDATE attachments + SET status='failed', error_code=$3, updated_at=$4 + WHERE id=$1 AND pipeline_version=$2 + `, attachmentID, jobPipelineVersion, errorCode, updatedAt) + } + if err == nil { + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_job_events + (job_id, event_type, previous_status, new_status, attempt, error_code, created_at) + VALUES ($1, 'permanent_failure', $2, 'failed', $3, $4, $5) + `, jobID, jobStatus, attempt, errorCode, updatedAt) + } + } + if err != nil { + return err + } + return tx.Commit(queryContext) +} + +func (s *PostgreSQLStore) ListExpiredAttachmentJobs(ctx context.Context, now time.Time, limit int) ([]domain.AttachmentJob, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + rows, err := s.pool.Query(queryContext, ` + SELECT `+attachmentJobColumns+` + FROM attachment_jobs + WHERE status='processing' AND lease_until <= $1 + ORDER BY lease_until, job_id + LIMIT $2 + `, now, limit) + if err != nil { + return nil, fmt.Errorf("list expired attachment jobs: %w", err) + } + defer rows.Close() + jobs := make([]domain.AttachmentJob, 0) + for rows.Next() { + var job domain.AttachmentJob + if err = scanAttachmentJob(rows, &job); err != nil { + return nil, fmt.Errorf("scan expired attachment job: %w", err) + } + jobs = append(jobs, job) + } + return jobs, rows.Err() +} + +func (s *PostgreSQLStore) ReplayFailedAttachmentJob(ctx context.Context, jobID string, replayedAt time.Time) (domain.AttachmentJob, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + tx, err := s.pool.Begin(queryContext) + if err != nil { + return domain.AttachmentJob{}, fmt.Errorf("begin attachment replay: %w", err) + } + defer func() { _ = tx.Rollback(queryContext) }() + + var job domain.AttachmentJob + err = scanAttachmentJob(tx.QueryRow(queryContext, ` + SELECT `+attachmentJobColumns+` + FROM attachment_jobs WHERE job_id=$1 FOR UPDATE + `, jobID), &job) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AttachmentJob{}, ErrNotFound + } + if err != nil { + return domain.AttachmentJob{}, fmt.Errorf("lock failed job for replay: %w", err) + } + var attachmentStatus domain.AttachmentStatus + var activePipelineVersion int + var stagingKey *string + if err = tx.QueryRow(queryContext, ` + SELECT status, staging_key, pipeline_version FROM attachments WHERE id=$1 FOR UPDATE + `, job.AttachmentID).Scan(&attachmentStatus, &stagingKey, &activePipelineVersion); err != nil { + return domain.AttachmentJob{}, err + } + if job.Status != domain.AttachmentJobFailed || + attachmentStatus != domain.AttachmentStatusFailed || + activePipelineVersion != job.PipelineVersion { + return domain.AttachmentJob{}, fmt.Errorf("only the active failed pipeline can be replayed: %w", ErrConflict) + } + if stagingKey == nil || *stagingKey == "" { + return domain.AttachmentJob{}, fmt.Errorf("failed job staging is no longer retained: %w", ErrConflict) + } + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET attempt=1, status='queued', error_code=NULL, available_at=$2, + published_at=NULL, lease_until=NULL, leased_by=NULL, + replay_count=replay_count+1, updated_at=$2 + WHERE job_id=$1 + `, jobID, replayedAt) + if err == nil { + _, err = tx.Exec(queryContext, ` + UPDATE attachments SET status='queued', error_code=NULL, updated_at=$2 WHERE id=$1 + `, job.AttachmentID, replayedAt) + } + if err == nil { + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_job_events + (job_id, event_type, previous_status, new_status, attempt, created_at) + VALUES ($1, 'operator_replay', 'failed', 'queued', 1, $2) + `, jobID, replayedAt) + } + if err != nil { + return domain.AttachmentJob{}, fmt.Errorf("replay failed job: %w", err) + } + if err = tx.Commit(queryContext); err != nil { + return domain.AttachmentJob{}, fmt.Errorf("commit attachment replay: %w", err) + } + job.Attempt = 1 + job.Status = domain.AttachmentJobQueued + job.ErrorCode = nil + job.AvailableAt = replayedAt + job.ReplayCount++ + job.UpdatedAt = replayedAt + return job, nil +} + +func (s *PostgreSQLStore) ListFailedAttachmentJobs(ctx context.Context, limit int) ([]domain.AttachmentJob, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + rows, err := s.pool.Query(queryContext, ` + SELECT `+attachmentJobColumns+` + FROM attachment_jobs + WHERE status='failed' + ORDER BY updated_at, job_id + LIMIT $1 + `, limit) + if err != nil { + return nil, fmt.Errorf("list failed attachment jobs: %w", err) + } + defer rows.Close() + jobs := make([]domain.AttachmentJob, 0) + for rows.Next() { + var job domain.AttachmentJob + if err = scanAttachmentJob(rows, &job); err != nil { + return nil, err + } + jobs = append(jobs, job) + } + return jobs, rows.Err() +} + +func (s *PostgreSQLStore) LookupAttachmentByStagingKey( + ctx context.Context, + stagingKey string, +) (string, domain.AttachmentStatus, time.Time, bool, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + var attachmentID string + var status domain.AttachmentStatus + var updatedAt time.Time + err := s.pool.QueryRow(queryContext, ` + SELECT id::text, status, updated_at FROM attachments WHERE staging_key=$1 + `, stagingKey).Scan(&attachmentID, &status, &updatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return "", "", time.Time{}, false, nil + } + if err != nil { + return "", "", time.Time{}, false, err + } + return attachmentID, status, updatedAt, true, nil +} + +func (s *PostgreSQLStore) ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + _, err := s.pool.Exec(queryContext, ` + UPDATE attachments SET staging_key=NULL + WHERE id=$1 AND staging_key=$2 AND status IN ('ready','failed') + `, attachmentID, stagingKey) + if err != nil { + return fmt.Errorf("clear attachment staging key: %w", err) + } + return nil +} + +func (s *PostgreSQLStore) ListReadyStagingKeys( + ctx context.Context, + limit int, +) (map[string]string, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + rows, err := s.pool.Query(queryContext, ` + SELECT staging_key, id::text + FROM attachments + WHERE status='ready' AND staging_key IS NOT NULL + ORDER BY updated_at, id + LIMIT $1 + `, limit) + if err != nil { + return nil, fmt.Errorf("list ready staging keys: %w", err) + } + defer rows.Close() + keys := make(map[string]string) + for rows.Next() { + var key, attachmentID string + if err = rows.Scan(&key, &attachmentID); err != nil { + return nil, fmt.Errorf("scan ready staging key: %w", err) + } + keys[key] = attachmentID + } + return keys, rows.Err() +} + +func stringPointer(value string) *string { return &value } + +func (s *PostgreSQLStore) GetAttachmentJob(ctx context.Context, jobID string) (domain.AttachmentJob, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + var job domain.AttachmentJob + err := scanAttachmentJob(s.pool.QueryRow(queryContext, ` + SELECT `+attachmentJobColumns+` + FROM attachment_jobs WHERE job_id=$1 + `, jobID), &job) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AttachmentJob{}, ErrNotFound + } + if err != nil { + return domain.AttachmentJob{}, fmt.Errorf("get attachment job: %w", err) + } + return job, nil +} + +func (s *PostgreSQLStore) UpgradeAttachmentPipeline( + ctx context.Context, + attachmentID string, + targetVersion int, + stagingKey string, + job domain.AttachmentJob, + upgradedAt time.Time, +) (domain.AttachmentJob, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + tx, err := s.pool.Begin(queryContext) + if err != nil { + return domain.AttachmentJob{}, fmt.Errorf("begin pipeline upgrade: %w", err) + } + defer func() { _ = tx.Rollback(queryContext) }() + + var status domain.AttachmentStatus + var currentVersion int + err = tx.QueryRow(queryContext, ` + SELECT status, pipeline_version + FROM attachments WHERE id=$1 FOR UPDATE + `, attachmentID).Scan(&status, ¤tVersion) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AttachmentJob{}, ErrNotFound + } + if err != nil { + return domain.AttachmentJob{}, fmt.Errorf("lock attachment for pipeline upgrade: %w", err) + } + if targetVersion != currentVersion+1 || + (status != domain.AttachmentStatusReady && status != domain.AttachmentStatusProcessing) { + return domain.AttachmentJob{}, fmt.Errorf("pipeline upgrade requires ready/processing current version and next target version: %w", ErrConflict) + } + + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_job_events + (job_id, event_type, previous_status, new_status, attempt, error_code, created_at) + SELECT job_id, 'superseded', status, 'superseded', attempt, 'superseded_pipeline', $3 + FROM attachment_jobs + WHERE attachment_id=$1 AND pipeline_version < $2 + AND status IN ('queued','processing') + `, attachmentID, targetVersion, upgradedAt) + if err == nil { + _, err = tx.Exec(queryContext, ` + UPDATE attachment_jobs + SET status='superseded', error_code='superseded_pipeline', + lease_until=NULL, leased_by=NULL, updated_at=$3 + WHERE attachment_id=$1 AND pipeline_version < $2 + AND status IN ('queued','processing') + `, attachmentID, targetVersion, upgradedAt) + } + if err == nil { + _, err = tx.Exec(queryContext, ` + UPDATE attachments + SET pipeline_version=$2, staging_key=$3, status='queued', + error_code=NULL, updated_at=$4 + WHERE id=$1 + `, attachmentID, targetVersion, stagingKey, upgradedAt) + } + if job.AvailableAt.IsZero() { + job.AvailableAt = upgradedAt + } + if err == nil { + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_jobs ( + job_id, attachment_id, schema_version, job_type, pipeline_version, + attempt, max_attempts, status, available_at, created_at, updated_at, + traceparent, tracestate + ) VALUES ($1,$2,$3,$4,$5,$6,$7,'queued',$8,$9,$10,$11,$12) + `, job.JobID, attachmentID, job.SchemaVersion, job.Type, targetVersion, + job.Attempt, job.MaxAttempts, job.AvailableAt, job.CreatedAt, job.UpdatedAt, + job.TraceParent, job.TraceState) + } + if err == nil { + _, err = tx.Exec(queryContext, ` + INSERT INTO attachment_job_events + (job_id, event_type, previous_status, new_status, attempt, created_at) + VALUES ($1, 'version_upgrade', 'queued', 'queued', $2, $3) + `, job.JobID, job.Attempt, upgradedAt) + } + if err != nil { + return domain.AttachmentJob{}, fmt.Errorf("apply pipeline upgrade: %w", err) + } + if err = tx.Commit(queryContext); err != nil { + return domain.AttachmentJob{}, fmt.Errorf("commit pipeline upgrade: %w", err) + } + job.Status = domain.AttachmentJobQueued + job.PipelineVersion = targetVersion + job.AvailableAt = upgradedAt + job.UpdatedAt = upgradedAt + return job, nil +} diff --git a/internal/adapter/postgres/attachments.go b/internal/adapter/postgres/attachments.go new file mode 100644 index 0000000..3286650 --- /dev/null +++ b/internal/adapter/postgres/attachments.go @@ -0,0 +1,372 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/reconcile" + + "github.com/jackc/pgx/v5" +) + +func (s *PostgreSQLStore) CreateAttachment( + ctx context.Context, + attachment domain.Attachment, +) (domain.Attachment, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + err := s.pool.QueryRow( + queryContext, + ` + INSERT INTO attachments ( + id, chat_id, owner_id, object_key, filename, content_type, + size_bytes, sha256, width, height, status, error_code, + created_at, updated_at + ) + VALUES ( + $1, $2, $3, $4, $5, $6, + $7, decode($8, 'hex'), $9, $10, $11, $12, + $13, $14 + ) + RETURNING created_at, updated_at + `, + attachment.ID, + attachment.ChatID, + attachment.OwnerID, + attachment.ObjectKey, + attachment.Filename, + attachment.ContentType, + attachment.SizeBytes, + attachment.SHA256, + attachment.Width, + attachment.Height, + attachment.Status, + attachment.ErrorCode, + attachment.CreatedAt, + attachment.UpdatedAt, + ).Scan(&attachment.CreatedAt, &attachment.UpdatedAt) + if err != nil { + return domain.Attachment{}, fmt.Errorf("insert attachment metadata: %w", err) + } + if attachment.Variants == nil { + attachment.Variants = make([]domain.AttachmentVariant, 0) + } + return attachment, nil +} + +func (s *PostgreSQLStore) MarkAttachmentReady( + ctx context.Context, + attachmentID string, + updatedAt time.Time, +) (domain.Attachment, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var attachment domain.Attachment + var sha256Bytes []byte + err := s.pool.QueryRow( + queryContext, + ` + UPDATE attachments + SET status = 'ready', error_code = NULL, updated_at = $2 + WHERE id = $1 AND status IN ('queued', 'processing') + RETURNING + id::text, chat_id::text, owner_id::text, object_key, + filename, content_type, size_bytes, sha256, width, height, + pipeline_version, status, error_code, created_at, updated_at + `, + attachmentID, + updatedAt, + ).Scan( + &attachment.ID, + &attachment.ChatID, + &attachment.OwnerID, + &attachment.ObjectKey, + &attachment.Filename, + &attachment.ContentType, + &attachment.SizeBytes, + &sha256Bytes, + &attachment.Width, + &attachment.Height, + &attachment.PipelineVersion, + &attachment.Status, + &attachment.ErrorCode, + &attachment.CreatedAt, + &attachment.UpdatedAt, + ) + if errors.Is(err, pgx.ErrNoRows) { + return domain.Attachment{}, ErrConflict + } + if err != nil { + return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", err) + } + attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes) + attachment.Variants, err = s.listAttachmentVariants(queryContext, attachment.ID, attachment.PipelineVersion) + if err != nil { + return domain.Attachment{}, err + } + return attachment, nil +} + +func (s *PostgreSQLStore) MarkAttachmentFailed( + ctx context.Context, + attachmentID string, + errorCode string, + updatedAt time.Time, +) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + commandTag, err := s.pool.Exec( + queryContext, + ` + UPDATE attachments + SET status = 'failed', error_code = $2, updated_at = $3 + WHERE id = $1 AND status IN ('queued', 'processing') + `, + attachmentID, + errorCode, + updatedAt, + ) + if err != nil { + return fmt.Errorf("mark attachment failed: %w", err) + } + if commandTag.RowsAffected() != 1 { + return ErrConflict + } + return nil +} + +func (s *PostgreSQLStore) GetAttachment( + ctx context.Context, + attachmentID string, + callerID string, +) (domain.Attachment, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var attachment domain.Attachment + var sha256Bytes []byte + err := s.pool.QueryRow( + queryContext, + ` + SELECT + a.id::text, a.chat_id::text, a.owner_id::text, a.object_key, + a.filename, a.content_type, a.size_bytes, a.sha256, + a.width, a.height, a.pipeline_version, a.status, a.error_code, + a.created_at, a.updated_at + FROM attachments AS a + JOIN chat_members AS cm + ON cm.chat_id = a.chat_id AND cm.user_id = $2 + WHERE a.id = $1 + `, + attachmentID, + callerID, + ).Scan( + &attachment.ID, + &attachment.ChatID, + &attachment.OwnerID, + &attachment.ObjectKey, + &attachment.Filename, + &attachment.ContentType, + &attachment.SizeBytes, + &sha256Bytes, + &attachment.Width, + &attachment.Height, + &attachment.PipelineVersion, + &attachment.Status, + &attachment.ErrorCode, + &attachment.CreatedAt, + &attachment.UpdatedAt, + ) + if errors.Is(err, pgx.ErrNoRows) { + return domain.Attachment{}, ErrNotFound + } + if err != nil { + return domain.Attachment{}, fmt.Errorf("get attachment metadata: %w", err) + } + attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes) + attachment.Variants, err = s.listAttachmentVariants(queryContext, attachment.ID, attachment.PipelineVersion) + if err != nil { + return domain.Attachment{}, err + } + return attachment, nil +} + +func (s *PostgreSQLStore) ListAttachmentInventory( + ctx context.Context, +) ([]reconcile.AttachmentRecord, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + rows, err := s.pool.Query( + queryContext, + ` + SELECT + a.id::text, + a.object_key, + a.status, + a.updated_at, + EXISTS ( + SELECT 1 + FROM message_attachments AS ma + WHERE ma.attachment_id = a.id + ) AS referenced, + COALESCE(a.staging_key, ''), + COALESCE(av.object_key, '') + FROM attachments AS a + LEFT JOIN attachment_variants AS av ON av.attachment_id = a.id + ORDER BY a.id, av.pipeline_version, av.name + `, + ) + if err != nil { + return nil, fmt.Errorf("query attachment inventory: %w", err) + } + defer rows.Close() + + records := make([]reconcile.AttachmentRecord, 0) + recordIndexes := make(map[string]int) + for rows.Next() { + var record reconcile.AttachmentRecord + var stagingKey string + var variantKey string + if err = rows.Scan( + &record.ID, + &record.ObjectKey, + &record.Status, + &record.UpdatedAt, + &record.Referenced, + &stagingKey, + &variantKey, + ); err != nil { + return nil, fmt.Errorf("scan attachment inventory: %w", err) + } + if recordIndex, exists := recordIndexes[record.ID]; exists { + if variantKey != "" { + records[recordIndex].AdditionalObjectKeys = append( + records[recordIndex].AdditionalObjectKeys, + variantKey, + ) + } + continue + } + if stagingKey != "" { + record.AdditionalObjectKeys = append(record.AdditionalObjectKeys, stagingKey) + } + if variantKey != "" { + record.AdditionalObjectKeys = append(record.AdditionalObjectKeys, variantKey) + } + recordIndexes[record.ID] = len(records) + records = append(records, record) + } + if err = rows.Err(); err != nil { + return nil, fmt.Errorf("iterate attachment inventory: %w", err) + } + return records, nil +} + +func (s *PostgreSQLStore) MarkAttachmentFailedIfUnreferenced( + ctx context.Context, + attachmentID string, + expectedStatus domain.AttachmentStatus, + updatedBefore time.Time, + errorCode string, + updatedAt time.Time, +) (bool, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{}) + if err != nil { + return false, fmt.Errorf("begin attachment reconciliation transaction: %w", err) + } + defer func() { _ = transaction.Rollback(queryContext) }() + + var lockedAttachmentID string + err = transaction.QueryRow( + queryContext, + ` + SELECT id::text + FROM attachments + WHERE id = $1 + FOR UPDATE + `, + attachmentID, + ).Scan(&lockedAttachmentID) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("lock attachment during reconciliation: %w", err) + } + + // This is deliberately a second statement. Under READ COMMITTED it gets a + // fresh snapshot after the row lock was acquired, so a message transaction + // that linked this attachment while we waited is visible to NOT EXISTS. + commandTag, err := transaction.Exec( + queryContext, + ` + UPDATE attachments AS a + SET status = 'failed', error_code = $4, updated_at = $5 + WHERE a.id = $1 + AND a.status = $2 + AND a.updated_at <= $3 + AND NOT EXISTS ( + SELECT 1 + FROM message_attachments AS ma + WHERE ma.attachment_id = a.id + ) + `, + attachmentID, + expectedStatus, + updatedBefore, + errorCode, + updatedAt, + ) + if err != nil { + return false, fmt.Errorf("mark attachment failed during reconciliation: %w", err) + } + if err = transaction.Commit(queryContext); err != nil { + return false, fmt.Errorf("commit attachment reconciliation: %w", err) + } + return commandTag.RowsAffected() == 1, nil +} + +func (s *PostgreSQLStore) listAttachmentVariants( + ctx context.Context, + attachmentID string, + pipelineVersion int, +) ([]domain.AttachmentVariant, error) { + if pipelineVersion < 1 { + pipelineVersion = 1 + } + rows, err := s.pool.Query(ctx, ` + SELECT name, object_key, content_type, size_bytes, width, height, sha256, pipeline_version + FROM attachment_variants + WHERE attachment_id = $1 AND pipeline_version = $2 + ORDER BY name + `, attachmentID, pipelineVersion) + if err != nil { + return nil, fmt.Errorf("query attachment variants: %w", err) + } + defer rows.Close() + variants := make([]domain.AttachmentVariant, 0) + for rows.Next() { + var variant domain.AttachmentVariant + var digest []byte + if err = rows.Scan(&variant.Name, &variant.ObjectKey, &variant.ContentType, &variant.SizeBytes, &variant.Width, &variant.Height, &digest, &variant.PipelineVersion); err != nil { + return nil, fmt.Errorf("scan attachment variant: %w", err) + } + variant.SHA256 = fmt.Sprintf("%x", digest) + variants = append(variants, variant) + } + if err = rows.Err(); err != nil { + return nil, fmt.Errorf("iterate attachment variants: %w", err) + } + return variants, nil +} + +var _ reconcile.MetadataStore = (*PostgreSQLStore)(nil) diff --git a/internal/adapter/postgres/chats.go b/internal/adapter/postgres/chats.go new file mode 100644 index 0000000..6e88102 --- /dev/null +++ b/internal/adapter/postgres/chats.go @@ -0,0 +1,278 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + + "mtusi2026lab7/internal/domain" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +func (s *PostgreSQLStore) CreateChat( + ctx context.Context, + title string, + memberIDs []string, +) (domain.Chat, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + transaction, err := s.pool.Begin(queryContext) + if err != nil { + return domain.Chat{}, fmt.Errorf( + "begin create chat transaction: %w", + err, + ) + } + + defer func() { + _ = transaction.Rollback(queryContext) + }() + + chat := domain.Chat{ + ID: uuid.NewString(), + Title: title, + MemberIDs: append([]string(nil), memberIDs...), + } + + err = transaction.QueryRow( + queryContext, + ` + INSERT INTO chats ( + id, + title + ) + VALUES ($1, $2) + RETURNING created_at + `, + chat.ID, + chat.Title, + ).Scan(&chat.CreatedAt) + if err != nil { + return domain.Chat{}, fmt.Errorf("insert chat: %w", err) + } + + for position, memberID := range memberIDs { + commandTag, insertErr := transaction.Exec( + queryContext, + ` + INSERT INTO chat_members ( + chat_id, + user_id, + position + ) + SELECT + $1, + id, + $3 + FROM users + WHERE id = $2 + `, + chat.ID, + memberID, + position, + ) + if insertErr != nil { + return domain.Chat{}, fmt.Errorf( + "insert chat member %s: %w", + memberID, + insertErr, + ) + } + + // INSERT ... SELECT не вставляет строку, если пользователя нет. + // Возврат из функции активирует deferred Rollback: уже созданные + // chat и предыдущие membership-строки не останутся в базе. + if commandTag.RowsAffected() != 1 { + return domain.Chat{}, fmt.Errorf( + "%w: member %s", + ErrNotFound, + memberID, + ) + } + } + + if err = transaction.Commit(queryContext); err != nil { + return domain.Chat{}, fmt.Errorf( + "commit create chat transaction: %w", + err, + ) + } + + return chat, nil +} + +func (s *PostgreSQLStore) GetChatByID( + ctx context.Context, + chatID string, + callerID string, +) (domain.Chat, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var chat domain.Chat + + err := s.pool.QueryRow( + queryContext, + ` + SELECT + chat.id::text, + chat.title, + chat.created_at, + array_agg( + member.user_id::text + ORDER BY member.position + ) + FROM chats AS chat + JOIN chat_members AS caller + ON caller.chat_id = chat.id + AND caller.user_id = $2 + JOIN chat_members AS member + ON member.chat_id = chat.id + WHERE chat.id = $1 + GROUP BY + chat.id, + chat.title, + chat.created_at + `, + chatID, + callerID, + ).Scan( + &chat.ID, + &chat.Title, + &chat.CreatedAt, + &chat.MemberIDs, + ) + + if errors.Is(err, pgx.ErrNoRows) { + return domain.Chat{}, ErrNotFound + } + if err != nil { + return domain.Chat{}, fmt.Errorf("select chat by id: %w", err) + } + + return chat, nil +} + +func (s *PostgreSQLStore) GetChatsForUser( + ctx context.Context, + userID string, + limit int, + cursor *domain.ChatCursor, +) ([]domain.Chat, bool, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var ( + rows pgx.Rows + err error + ) + + if cursor == nil { + rows, err = s.pool.Query( + queryContext, + ` + SELECT + chat.id::text, + chat.title, + chat.created_at, + array_agg( + member.user_id::text + ORDER BY member.position + ) + FROM chat_members AS own_membership + JOIN chats AS chat + ON chat.id = own_membership.chat_id + JOIN chat_members AS member + ON member.chat_id = chat.id + WHERE own_membership.user_id = $1 + GROUP BY + chat.id, + chat.title, + chat.created_at + ORDER BY + chat.created_at, + chat.id + LIMIT $2 + `, + userID, + limit+1, + ) + } else { + rows, err = s.pool.Query( + queryContext, + ` + SELECT + chat.id::text, + chat.title, + chat.created_at, + array_agg( + member.user_id::text + ORDER BY member.position + ) + FROM chat_members AS own_membership + JOIN chats AS chat + ON chat.id = own_membership.chat_id + JOIN chat_members AS member + ON member.chat_id = chat.id + WHERE own_membership.user_id = $1 + AND (chat.created_at, chat.id) > ($2, $3) + GROUP BY + chat.id, + chat.title, + chat.created_at + ORDER BY + chat.created_at, + chat.id + LIMIT $4 + `, + userID, + cursor.CreatedAt, + cursor.ChatID, + limit+1, + ) + } + + if err != nil { + return nil, false, fmt.Errorf( + "query chats for user: %w", + err, + ) + } + defer rows.Close() + + items := make([]domain.Chat, 0, limit+1) + + for rows.Next() { + var chat domain.Chat + + if err := rows.Scan( + &chat.ID, + &chat.Title, + &chat.CreatedAt, + &chat.MemberIDs, + ); err != nil { + return nil, false, fmt.Errorf( + "scan chat page: %w", + err, + ) + } + + items = append(items, chat) + } + + if err := rows.Err(); err != nil { + return nil, false, fmt.Errorf( + "iterate chat page: %w", + err, + ) + } + + hasMore := len(items) > limit + if hasMore { + items = items[:limit] + } + return items, hasMore, nil +} diff --git a/internal/adapter/postgres/contract.go b/internal/adapter/postgres/contract.go new file mode 100644 index 0000000..4aab020 --- /dev/null +++ b/internal/adapter/postgres/contract.go @@ -0,0 +1,5 @@ +package postgres + +import "mtusi2026lab7/internal/application" + +var _ application.Repository = (*PostgreSQLStore)(nil) diff --git a/internal/adapter/postgres/errors.go b/internal/adapter/postgres/errors.go new file mode 100644 index 0000000..dd4e55b --- /dev/null +++ b/internal/adapter/postgres/errors.go @@ -0,0 +1,8 @@ +package postgres + +import "mtusi2026lab7/internal/domain" + +var ( + ErrNotFound = domain.ErrNotFound + ErrConflict = domain.ErrConflict +) diff --git a/internal/adapter/postgres/login_rate_limit.go b/internal/adapter/postgres/login_rate_limit.go new file mode 100644 index 0000000..ed86701 --- /dev/null +++ b/internal/adapter/postgres/login_rate_limit.go @@ -0,0 +1,75 @@ +package postgres + +import ( + "context" + "fmt" + "time" +) + +func (s *PostgreSQLStore) AllowLoginAttempt( + ctx context.Context, + identifierHash [32]byte, + now time.Time, + window time.Duration, + limit int, +) (bool, time.Duration, error) { + if err := s.maybePruneExpiredState(ctx, now); err != nil { + return false, 0, err + } + if err := s.maybePruneExpiredLoginRateState(ctx, now, window); err != nil { + return false, 0, err + } + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var attempts int + var windowStartedAt time.Time + err := s.pool.QueryRow(queryContext, ` + INSERT INTO login_rate_limits ( + identifier_hash, window_started_at, attempts + ) + VALUES ($1, $2, 1) + ON CONFLICT (identifier_hash) DO UPDATE + SET + window_started_at = CASE + WHEN login_rate_limits.window_started_at <= $3 + THEN EXCLUDED.window_started_at + ELSE login_rate_limits.window_started_at + END, + attempts = CASE + WHEN login_rate_limits.window_started_at <= $3 THEN 1 + ELSE login_rate_limits.attempts + 1 + END + RETURNING attempts, window_started_at + `, identifierHash[:], now.UTC(), now.UTC().Add(-window)).Scan( + &attempts, + &windowStartedAt, + ) + if err != nil { + return false, 0, fmt.Errorf("update login rate limit: %w", err) + } + if attempts <= limit { + return true, 0, nil + } + retryAfter := windowStartedAt.Add(window).Sub(now.UTC()) + if retryAfter < time.Second { + retryAfter = time.Second + } + return false, retryAfter, nil +} + +func (s *PostgreSQLStore) ResetLoginAttempts( + ctx context.Context, + identifierHash [32]byte, +) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + if _, err := s.pool.Exec( + queryContext, + `DELETE FROM login_rate_limits WHERE identifier_hash = $1`, + identifierHash[:], + ); err != nil { + return fmt.Errorf("reset login rate limit: %w", err) + } + return nil +} diff --git a/internal/adapter/postgres/maintenance.go b/internal/adapter/postgres/maintenance.go new file mode 100644 index 0000000..ac35a31 --- /dev/null +++ b/internal/adapter/postgres/maintenance.go @@ -0,0 +1,99 @@ +package postgres + +import ( + "context" + "fmt" + "time" +) + +const ( + expiredStatePruneEvery = 128 + expiredStatePruneBatch = 256 +) + +// maybePruneExpiredState bounds session/idempotency table growth without adding +// a cleanup round trip to every request. The first operation after process +// start prunes immediately; later operations amortize one bounded indexed +// delete per expiredStatePruneEvery writes. +func (s *PostgreSQLStore) maybePruneExpiredState(ctx context.Context, now time.Time) error { + iteration := s.expiredStatePruneCounter.Add(1) + if iteration != 1 && iteration%expiredStatePruneEvery != 0 { + return nil + } + + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + _, err := s.pool.Exec(queryContext, ` + WITH stale_sessions AS ( + SELECT token_hash + FROM sessions + WHERE expires_at <= $1 + ORDER BY expires_at + LIMIT $2 + FOR UPDATE SKIP LOCKED + ), deleted_sessions AS ( + DELETE FROM sessions AS target + USING stale_sessions AS stale + WHERE target.token_hash = stale.token_hash + RETURNING 1 + ), stale_idempotency AS ( + SELECT user_id, method, canonical_path, idempotency_key + FROM message_idempotency + WHERE expires_at <= $1 + ORDER BY expires_at + LIMIT $2 + FOR UPDATE SKIP LOCKED + ), deleted_idempotency AS ( + DELETE FROM message_idempotency AS target + USING stale_idempotency AS stale + WHERE target.user_id = stale.user_id + AND target.method = stale.method + AND target.canonical_path = stale.canonical_path + AND target.idempotency_key = stale.idempotency_key + RETURNING 1 + ) + SELECT + (SELECT count(*) FROM deleted_sessions), + (SELECT count(*) FROM deleted_idempotency) + `, now.UTC(), expiredStatePruneBatch) + if err != nil { + return fmt.Errorf("prune expired auth state: %w", err) + } + return nil +} + +// maybePruneExpiredLoginRateState uses the configured limiter window as the +// cutoff. Comparing with now directly would delete active windows and weaken +// the limiter whenever maintenance runs. +func (s *PostgreSQLStore) maybePruneExpiredLoginRateState( + ctx context.Context, + now time.Time, + window time.Duration, +) error { + iteration := s.loginRatePruneCounter.Add(1) + if iteration != 1 && iteration%expiredStatePruneEvery != 0 { + return nil + } + + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + _, err := s.pool.Exec(queryContext, ` + WITH stale_login_limits AS ( + SELECT identifier_hash + FROM login_rate_limits + WHERE window_started_at <= $1 + ORDER BY window_started_at + LIMIT $2 + FOR UPDATE SKIP LOCKED + ) + DELETE FROM login_rate_limits AS target + USING stale_login_limits AS stale + WHERE target.identifier_hash = stale.identifier_hash + `, now.UTC().Add(-window), expiredStatePruneBatch) + if err != nil { + return fmt.Errorf("prune expired login rate state: %w", err) + } + return nil +} diff --git a/internal/adapter/postgres/messages.go b/internal/adapter/postgres/messages.go new file mode 100644 index 0000000..6a5bb4f --- /dev/null +++ b/internal/adapter/postgres/messages.go @@ -0,0 +1,426 @@ +package postgres + +import ( + "bytes" + "context" + "errors" + "fmt" + "time" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +func (s *PostgreSQLStore) CreateMessageIdempotently( + ctx context.Context, + write application.IdempotentMessageWrite, +) (domain.Message, error) { + if err := s.maybePruneExpiredState(ctx, time.Now()); err != nil { + return domain.Message{}, err + } + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{}) + if err != nil { + return domain.Message{}, fmt.Errorf("begin idempotent message transaction: %w", err) + } + defer func() { _ = transaction.Rollback(queryContext) }() + + var isMember bool + err = transaction.QueryRow( + queryContext, + ` + SELECT EXISTS ( + SELECT 1 + FROM chat_members + WHERE chat_id = $1 + AND user_id = $2 + ) + `, + write.ChatID, + write.ActorID, + ).Scan(&isMember) + if err != nil { + return domain.Message{}, fmt.Errorf("check chat membership: %w", err) + } + if !isMember { + return domain.Message{}, ErrNotFound + } + + attachmentUUIDs := make([]uuid.UUID, len(write.AttachmentIDs)) + for index, attachmentID := range write.AttachmentIDs { + parsedID, parseErr := uuid.Parse(attachmentID) + if parseErr != nil { + return domain.Message{}, fmt.Errorf("parse validated attachment id: %w", parseErr) + } + attachmentUUIDs[index] = parsedID + } + + if len(attachmentUUIDs) > 0 { + rows, queryError := transaction.Query( + queryContext, + ` + SELECT id::text, status + FROM attachments + WHERE chat_id = $1 + AND id = ANY($2::uuid[]) + ORDER BY id + FOR UPDATE + `, + write.ChatID, + attachmentUUIDs, + ) + if queryError != nil { + return domain.Message{}, fmt.Errorf("lock message attachments: %w", queryError) + } + availableCount := 0 + eligibleCount := 0 + for rows.Next() { + var attachmentID string + var status domain.AttachmentStatus + if queryError = rows.Scan(&attachmentID, &status); queryError != nil { + rows.Close() + return domain.Message{}, fmt.Errorf("scan locked message attachment: %w", queryError) + } + availableCount++ + if status != domain.AttachmentStatusFailed { + eligibleCount++ + } + } + queryError = rows.Err() + rows.Close() + if queryError != nil { + return domain.Message{}, fmt.Errorf("iterate locked message attachments: %w", queryError) + } + if availableCount != len(attachmentUUIDs) { + return domain.Message{}, ErrNotFound + } + if eligibleCount != len(attachmentUUIDs) { + return domain.Message{}, application.ErrAttachmentNotReady + } + } + + _, err = transaction.Exec( + queryContext, + ` + DELETE FROM message_idempotency + WHERE user_id = $1 + AND method = $2 + AND canonical_path = $3 + AND idempotency_key = $4 + AND expires_at <= CURRENT_TIMESTAMP + `, + write.ActorID, + write.Method, + write.CanonicalPath, + write.Key, + ) + if err != nil { + return domain.Message{}, fmt.Errorf("delete expired idempotency key: %w", err) + } + + message := domain.Message{ + ID: uuid.NewString(), + ChatID: write.ChatID, + SenderID: write.ActorID, + Text: write.Text, + AttachmentIDs: append([]string(nil), write.AttachmentIDs...), + } + + var storedHash []byte + var storedMessageID string + err = transaction.QueryRow( + queryContext, + ` + INSERT INTO message_idempotency ( + user_id, + method, + canonical_path, + idempotency_key, + request_hash, + message_id, + expires_at + ) + VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + CURRENT_TIMESTAMP + $7 * INTERVAL '1 second' + ) + ON CONFLICT DO NOTHING + RETURNING request_hash, message_id::text + `, + write.ActorID, + write.Method, + write.CanonicalPath, + write.Key, + write.RequestHash[:], + message.ID, + int64(write.TTL/time.Second), + ).Scan(&storedHash, &storedMessageID) + + if errors.Is(err, pgx.ErrNoRows) { + err = transaction.QueryRow( + queryContext, + ` + SELECT request_hash, message_id::text + FROM message_idempotency + WHERE user_id = $1 + AND method = $2 + AND canonical_path = $3 + AND idempotency_key = $4 + `, + write.ActorID, + write.Method, + write.CanonicalPath, + write.Key, + ).Scan(&storedHash, &storedMessageID) + if err != nil { + return domain.Message{}, fmt.Errorf("read idempotency result: %w", err) + } + + if !bytes.Equal(storedHash, write.RequestHash[:]) { + return domain.Message{}, application.ErrIdempotencyConflict + } + + err = transaction.QueryRow( + queryContext, + ` + SELECT + id::text, + chat_id::text, + sender_id::text, + text, + created_at, + COALESCE( + ARRAY( + SELECT attachment_id::text + FROM message_attachments + WHERE message_id = messages.id + ORDER BY position + ), ARRAY[]::text[] + ) + FROM messages + WHERE id = $1 + `, + storedMessageID, + ).Scan( + &message.ID, + &message.ChatID, + &message.SenderID, + &message.Text, + &message.CreatedAt, + &message.AttachmentIDs, + ) + if err != nil { + return domain.Message{}, fmt.Errorf("read idempotent message: %w", err) + } + + if err = transaction.Commit(queryContext); err != nil { + return domain.Message{}, fmt.Errorf("commit idempotency replay: %w", err) + } + return message, nil + } + if err != nil { + return domain.Message{}, fmt.Errorf("claim idempotency key: %w", err) + } + + err = transaction.QueryRow( + queryContext, + ` + INSERT INTO messages ( + id, + chat_id, + sender_id, + text + ) + VALUES ($1, $2, $3, $4) + RETURNING created_at + `, + message.ID, + message.ChatID, + message.SenderID, + message.Text, + ).Scan(&message.CreatedAt) + if err != nil { + return domain.Message{}, fmt.Errorf("insert message: %w", err) + } + + if len(attachmentUUIDs) > 0 { + _, err = transaction.Exec( + queryContext, + ` + INSERT INTO message_attachments ( + message_id, + chat_id, + attachment_id, + position + ) + SELECT $1, $2, attachment_id, (ordinality - 1)::smallint + FROM unnest($3::uuid[]) WITH ORDINALITY AS input(attachment_id, ordinality) + `, + message.ID, + message.ChatID, + attachmentUUIDs, + ) + if err != nil { + return domain.Message{}, fmt.Errorf("link message attachments: %w", err) + } + } + + if err = transaction.Commit(queryContext); err != nil { + return domain.Message{}, fmt.Errorf("commit idempotent message: %w", err) + } + + return message, nil +} + +func (s *PostgreSQLStore) GetMessages( + ctx context.Context, + chatID string, + callerID string, + limit int, + cursor *domain.MessageCursor, +) ([]domain.Message, bool, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var isMember bool + + err := s.pool.QueryRow( + queryContext, + ` + SELECT EXISTS ( + SELECT 1 + FROM chat_members + WHERE chat_id = $1 + AND user_id = $2 + ) + `, + chatID, + callerID, + ).Scan(&isMember) + if err != nil { + return nil, false, fmt.Errorf( + "check chat membership: %w", + err, + ) + } + + if !isMember { + return nil, false, ErrNotFound + } + + var rows pgx.Rows + + if cursor == nil { + rows, err = s.pool.Query( + queryContext, + ` + SELECT + id::text, + chat_id::text, + sender_id::text, + text, + created_at, + COALESCE( + ARRAY( + SELECT attachment_id::text + FROM message_attachments + WHERE message_id = messages.id + ORDER BY position + ), ARRAY[]::text[] + ) + FROM messages + WHERE chat_id = $1 + ORDER BY + created_at, + id + LIMIT $2 + `, + chatID, + limit+1, + ) + } else { + rows, err = s.pool.Query( + queryContext, + ` + SELECT + id::text, + chat_id::text, + sender_id::text, + text, + created_at, + COALESCE( + ARRAY( + SELECT attachment_id::text + FROM message_attachments + WHERE message_id = messages.id + ORDER BY position + ), ARRAY[]::text[] + ) + FROM messages + WHERE chat_id = $1 + AND (created_at, id) > ($2, $3) + ORDER BY + created_at, + id + LIMIT $4 + `, + chatID, + cursor.CreatedAt, + cursor.MessageID, + limit+1, + ) + } + + if err != nil { + return nil, false, fmt.Errorf( + "query messages: %w", + err, + ) + } + defer rows.Close() + + items := make([]domain.Message, 0, limit+1) + + for rows.Next() { + var message domain.Message + + if err := rows.Scan( + &message.ID, + &message.ChatID, + &message.SenderID, + &message.Text, + &message.CreatedAt, + &message.AttachmentIDs, + ); err != nil { + return nil, false, fmt.Errorf( + "scan message page: %w", + err, + ) + } + + items = append(items, message) + } + + if err := rows.Err(); err != nil { + return nil, false, fmt.Errorf( + "iterate message page: %w", + err, + ) + } + + hasMore := len(items) > limit + if hasMore { + items = items[:limit] + } + return items, hasMore, nil +} diff --git a/internal/adapter/postgres/queue_stats.go b/internal/adapter/postgres/queue_stats.go new file mode 100644 index 0000000..81f7c86 --- /dev/null +++ b/internal/adapter/postgres/queue_stats.go @@ -0,0 +1,31 @@ +package postgres + +import ( + "context" + "fmt" + "time" +) + +func (s *PostgreSQLStore) AttachmentQueueStats( + ctx context.Context, + now time.Time, +) (int64, float64, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + var depth int64 + var oldestAge float64 + err := s.pool.QueryRow(queryContext, ` + SELECT + COUNT(*), + COALESCE(EXTRACT(EPOCH FROM ($1::timestamptz - MIN(created_at))), 0) + FROM attachment_jobs + WHERE status = 'queued' + `, now).Scan(&depth, &oldestAge) + if err != nil { + return 0, 0, fmt.Errorf("read attachment queue stats: %w", err) + } + if oldestAge < 0 { + oldestAge = 0 + } + return depth, oldestAge, nil +} diff --git a/internal/adapter/postgres/sessions.go b/internal/adapter/postgres/sessions.go new file mode 100644 index 0000000..5b526cd --- /dev/null +++ b/internal/adapter/postgres/sessions.go @@ -0,0 +1,111 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "mtusi2026lab7/internal/domain" + + "github.com/jackc/pgx/v5" +) + +func (s *PostgreSQLStore) CreateSession( + ctx context.Context, + tokenHash []byte, + userID string, + expiresAt time.Time, +) error { + if err := s.maybePruneExpiredState(ctx, time.Now()); err != nil { + return err + } + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + _, err := s.pool.Exec( + queryContext, + ` + INSERT INTO sessions ( + token_hash, + user_id, + expires_at + ) + VALUES ($1, $2, $3) + `, + tokenHash, + userID, + expiresAt, + ) + if err != nil { + return fmt.Errorf("insert session: %w", err) + } + + return nil +} + +func (s *PostgreSQLStore) GetUserBySession( + ctx context.Context, + tokenHash []byte, +) (domain.User, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var user domain.User + + err := s.pool.QueryRow( + queryContext, + ` + SELECT + app_user.id::text, + app_user.username, + app_user.display_name, + app_user.created_at + FROM sessions AS session + JOIN users AS app_user + ON app_user.id = session.user_id + WHERE session.token_hash = $1 + AND session.expires_at > CURRENT_TIMESTAMP + `, + tokenHash, + ).Scan( + &user.ID, + &user.Username, + &user.DisplayName, + &user.CreatedAt, + ) + + if errors.Is(err, pgx.ErrNoRows) { + return domain.User{}, ErrNotFound + } + if err != nil { + return domain.User{}, fmt.Errorf( + "select user by session: %w", + err, + ) + } + + return user, nil +} + +func (s *PostgreSQLStore) DeleteSession( + ctx context.Context, + tokenHash []byte, +) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + _, err := s.pool.Exec( + queryContext, + ` + DELETE FROM sessions + WHERE token_hash = $1 + `, + tokenHash, + ) + if err != nil { + return fmt.Errorf("delete session: %w", err) + } + + return nil +} diff --git a/internal/adapter/postgres/store.go b/internal/adapter/postgres/store.go new file mode 100644 index 0000000..19cf441 --- /dev/null +++ b/internal/adapter/postgres/store.go @@ -0,0 +1,43 @@ +package postgres + +import ( + "context" + "sync/atomic" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +type PostgreSQLStore struct { + pool *pgxpool.Pool + queryTimeout time.Duration + expiredStatePruneCounter atomic.Uint64 + loginRatePruneCounter atomic.Uint64 +} + +func NewPostgreSQLStore( + pool *pgxpool.Pool, + queryTimeout time.Duration, +) *PostgreSQLStore { + return &PostgreSQLStore{ + pool: pool, + queryTimeout: queryTimeout, + } +} + +func (s *PostgreSQLStore) Ping(ctx context.Context) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + return s.pool.Ping(queryContext) +} + +func (s *PostgreSQLStore) Close() { + s.pool.Close() +} + +func (s *PostgreSQLStore) withTimeout( + ctx context.Context, +) (context.Context, context.CancelFunc) { + return context.WithTimeout(ctx, s.queryTimeout) +} diff --git a/internal/adapter/postgres/users.go b/internal/adapter/postgres/users.go new file mode 100644 index 0000000..f6c7305 --- /dev/null +++ b/internal/adapter/postgres/users.go @@ -0,0 +1,165 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + + "mtusi2026lab7/internal/domain" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +func (s *PostgreSQLStore) CreateUser( + ctx context.Context, + username string, + displayName string, + passwordHash string, +) (domain.User, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + user := domain.User{ + ID: uuid.NewString(), + Username: username, + DisplayName: displayName, + } + + err := s.pool.QueryRow( + queryContext, + ` + INSERT INTO users ( + id, + username, + display_name, + password_hash + ) + VALUES ($1, $2, $3, $4) + RETURNING created_at + `, + user.ID, + user.Username, + user.DisplayName, + passwordHash, + ).Scan(&user.CreatedAt) + + if err == nil { + return user, nil + } + + var postgresError *pgconn.PgError + if errors.As(err, &postgresError) && + postgresError.Code == "23505" && + postgresError.ConstraintName == "users_username_unique" { + return domain.User{}, ErrConflict + } + + return domain.User{}, fmt.Errorf("insert user: %w", err) +} + +func (s *PostgreSQLStore) GetUserByID( + ctx context.Context, + userID string, +) (domain.User, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var user domain.User + + err := s.pool.QueryRow( + queryContext, + ` + SELECT + id::text, + username, + display_name, + created_at + FROM users + WHERE id = $1 + `, + userID, + ).Scan( + &user.ID, + &user.Username, + &user.DisplayName, + &user.CreatedAt, + ) + + if errors.Is(err, pgx.ErrNoRows) { + return domain.User{}, ErrNotFound + } + if err != nil { + return domain.User{}, fmt.Errorf("select user by id: %w", err) + } + + return user, nil +} + +func (s *PostgreSQLStore) GetUserByUsername( + ctx context.Context, + username string, +) (domain.User, string, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var ( + user domain.User + passwordHash string + ) + + err := s.pool.QueryRow( + queryContext, + ` + SELECT + id::text, + username, + display_name, + created_at, + password_hash + FROM users + WHERE username = $1 + `, + username, + ).Scan( + &user.ID, + &user.Username, + &user.DisplayName, + &user.CreatedAt, + &passwordHash, + ) + + if errors.Is(err, pgx.ErrNoRows) { + return domain.User{}, "", ErrNotFound + } + if err != nil { + return domain.User{}, "", fmt.Errorf( + "select user by username: %w", + err, + ) + } + + return user, passwordHash, nil +} + +func (s *PostgreSQLStore) UpdatePasswordHash( + ctx context.Context, + userID string, + previousHash string, + newHash string, +) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + _, err := s.pool.Exec( + queryContext, + `UPDATE users SET password_hash = $1 WHERE id = $2 AND password_hash = $3`, + newHash, + userID, + previousHash, + ) + if err != nil { + return fmt.Errorf("update password hash: %w", err) + } + return nil +} diff --git a/internal/adapter/redis/chat_cache.go b/internal/adapter/redis/chat_cache.go new file mode 100644 index 0000000..82a9720 --- /dev/null +++ b/internal/adapter/redis/chat_cache.go @@ -0,0 +1,175 @@ +package redis + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "mtusi2026lab7/internal/domain" + + "github.com/google/uuid" + goredis "github.com/redis/go-redis/v9" +) + +const chatKeyPrefix = "chat:v2:" + +var ErrMiss = errors.New("cache miss") + +// ChatCache хранит только производную копию неизменяемых данных чата. +// PostgreSQL остаётся источником истины. +type ChatCache interface { + Get(ctx context.Context, chatID string) (domain.Chat, error) + Set(ctx context.Context, chat domain.Chat) error +} + +type RedisChatCache struct { + client *goredis.Client + ttl time.Duration + operationTimeout time.Duration +} + +func NewRedisChatCache( + redisURL string, + ttl time.Duration, + operationTimeout time.Duration, + poolSize int, +) (*RedisChatCache, error) { + options, err := goredis.ParseURL(strings.TrimSpace(redisURL)) + if err != nil { + return nil, fmt.Errorf("parse Redis URL: %w", err) + } + + options.DialTimeout = operationTimeout + options.ReadTimeout = operationTimeout + options.WriteTimeout = operationTimeout + options.PoolTimeout = operationTimeout + options.PoolSize = poolSize + options.MaxRetries = -1 + + return &RedisChatCache{ + client: goredis.NewClient(options), + ttl: ttl, + operationTimeout: operationTimeout, + }, nil +} + +func (c *RedisChatCache) Ping(ctx context.Context) error { + operationContext, cancel := c.withTimeout(ctx) + defer cancel() + + if err := c.client.Ping(operationContext).Err(); err != nil { + return fmt.Errorf("ping Redis: %w", err) + } + + return nil +} + +func (c *RedisChatCache) Close() error { + return c.client.Close() +} + +func (c *RedisChatCache) Get( + ctx context.Context, + chatID string, +) (domain.Chat, error) { + operationContext, cancel := c.withTimeout(ctx) + defer cancel() + + payload, err := c.client.Get( + operationContext, + chatKey(chatID), + ).Bytes() + if errors.Is(err, goredis.Nil) { + return domain.Chat{}, ErrMiss + } + if err != nil { + return domain.Chat{}, fmt.Errorf("get cached chat: %w", err) + } + + var chat domain.Chat + if err = json.Unmarshal(payload, &chat); err != nil { + c.deleteInvalidValue(operationContext, chatID) + return domain.Chat{}, fmt.Errorf("decode cached chat: %w", err) + } + + if err = validateCachedChat(chat, chatID); err != nil { + c.deleteInvalidValue(operationContext, chatID) + return domain.Chat{}, err + } + + return chat, nil +} + +func (c *RedisChatCache) Set( + ctx context.Context, + chat domain.Chat, +) error { + payload, err := json.Marshal(chat) + if err != nil { + return fmt.Errorf("encode chat for cache: %w", err) + } + + operationContext, cancel := c.withTimeout(ctx) + defer cancel() + + if err = c.client.Set( + operationContext, + chatKey(chat.ID), + payload, + c.ttl, + ).Err(); err != nil { + return fmt.Errorf("cache chat: %w", err) + } + + return nil +} + +func (c *RedisChatCache) withTimeout( + ctx context.Context, +) (context.Context, context.CancelFunc) { + return context.WithTimeout(ctx, c.operationTimeout) +} + +func (c *RedisChatCache) deleteInvalidValue( + ctx context.Context, + chatID string, +) { + _ = c.client.Del(ctx, chatKey(chatID)).Err() +} + +func chatKey(chatID string) string { + return chatKeyPrefix + chatID +} + +func validateCachedChat(chat domain.Chat, expectedID string) error { + if chat.ID != expectedID { + return errors.New("cached chat id does not match cache key") + } + if _, err := uuid.Parse(chat.ID); err != nil { + return errors.New("cached chat contains invalid id") + } + if strings.TrimSpace(chat.Title) == "" || chat.CreatedAt.IsZero() { + return errors.New("cached chat is incomplete") + } + if len(chat.MemberIDs) == 0 { + return errors.New("cached chat has no members") + } + + seenMembers := make(map[string]struct{}, len(chat.MemberIDs)) + for _, memberID := range chat.MemberIDs { + if _, err := uuid.Parse(memberID); err != nil { + return errors.New("cached chat contains invalid member id") + } + if _, exists := seenMembers[memberID]; exists { + return errors.New("cached chat contains duplicate member id") + } + seenMembers[memberID] = struct{}{} + } + + return nil +} + +var _ ChatCache = (*RedisChatCache)(nil) diff --git a/internal/application/attachment_queries.go b/internal/application/attachment_queries.go new file mode 100644 index 0000000..d7aea9e --- /dev/null +++ b/internal/application/attachment_queries.go @@ -0,0 +1,67 @@ +package application + +import ( + "context" + "fmt" + "io" + + "mtusi2026lab7/internal/domain" +) + +type AttachmentDownload struct { + Body io.ReadCloser + ContentType string + Filename string + SizeBytes int64 +} + +func (s *Service) GetAttachment(ctx context.Context, attachmentID, actorID string) (domain.Attachment, error) { + return s.repository.GetAttachment(ctx, attachmentID, actorID) +} + +func (s *Service) DownloadAttachment(ctx context.Context, attachmentID, actorID, variantName string) (AttachmentDownload, error) { + attachment, err := s.repository.GetAttachment(ctx, attachmentID, actorID) + if err != nil { + return AttachmentDownload{}, err + } + if attachment.Status != domain.AttachmentStatusReady { + return AttachmentDownload{}, ErrAttachmentNotReady + } + if s.objectStore == nil { + return AttachmentDownload{}, ErrStorageUnavailable + } + if variantName == "" { + variantName = "original" + } + key := attachment.ObjectKey + contentType := attachment.ContentType + sizeBytes := attachment.SizeBytes + filename := attachment.Filename + if variantName != "original" { + found := false + for _, variant := range attachment.Variants { + if variant.Name == variantName { + key = variant.ObjectKey + contentType = variant.ContentType + sizeBytes = variant.SizeBytes + filename = variant.Name + ".jpg" + found = true + break + } + } + if !found { + return AttachmentDownload{}, domain.ErrNotFound + } + } + object, err := s.objectStore.Get(ctx, key) + if err != nil { + return AttachmentDownload{}, fmt.Errorf("%w: get object", ErrStorageUnavailable) + } + if object.Body == nil || object.SizeBytes != sizeBytes { + if object.Body != nil { + _ = object.Body.Close() + } + return AttachmentDownload{}, fmt.Errorf("%w: object metadata mismatch", ErrStorageUnavailable) + } + return AttachmentDownload{Body: object.Body, ContentType: contentType, Filename: filename, SizeBytes: sizeBytes}, nil +} diff --git a/internal/application/attachments.go b/internal/application/attachments.go new file mode 100644 index 0000000..5b6dd21 --- /dev/null +++ b/internal/application/attachments.go @@ -0,0 +1,182 @@ +package application + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "image" + _ "image/jpeg" + _ "image/png" + "io" + "os" + + "mtusi2026lab7/internal/domain" + + "github.com/google/uuid" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/propagation" +) + +const currentAttachmentPipelineVersion = 1 + +func (s *Service) UploadAttachment(ctx context.Context, command UploadAttachmentCommand) (domain.Attachment, error) { + if s.objectStore == nil { + return domain.Attachment{}, ErrStorageUnavailable + } + queueRepository, ok := s.repository.(AttachmentQueueRepository) + if !ok { + return domain.Attachment{}, fmt.Errorf("attachment queue repository is not configured") + } + if command.Body == nil { + return domain.Attachment{}, fmt.Errorf("%w: attachment body is required", ErrInvalidInput) + } + if err := domain.ValidateAttachmentFilename(command.Filename); err != nil { + return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + if err := domain.ValidateAttachmentContentType(command.DeclaredContentType); err != nil { + return domain.Attachment{}, fmt.Errorf("%w: %v", ErrUnsupportedMediaType, err) + } + if _, err := s.repository.GetChatByID(ctx, command.ChatID, command.ActorID); err != nil { + return domain.Attachment{}, err + } + if err := acquireAttachmentSlot(ctx, s.attachmentUploadSlots); err != nil { + return domain.Attachment{}, fmt.Errorf("%w: wait for upload capacity", ErrStorageUnavailable) + } + defer releaseAttachmentSlot(s.attachmentUploadSlots) + + stagedFile, err := os.CreateTemp("", "mtusi-attachment-*") + if err != nil { + return domain.Attachment{}, fmt.Errorf("create bounded upload staging file: %w", err) + } + stagedPath := stagedFile.Name() + defer func() { + _ = stagedFile.Close() + _ = os.Remove(stagedPath) + }() + + hasher := sha256.New() + sizeBytes, err := io.Copy(io.MultiWriter(stagedFile, hasher), io.LimitReader(command.Body, domain.MaxAttachmentSizeBytes+1)) + if err != nil { + return domain.Attachment{}, fmt.Errorf("%w: read attachment body", ErrInvalidInput) + } + if sizeBytes > domain.MaxAttachmentSizeBytes { + return domain.Attachment{}, ErrPayloadTooLarge + } + if _, err = stagedFile.Seek(0, io.SeekStart); err != nil { + return domain.Attachment{}, fmt.Errorf("rewind staged attachment: %w", err) + } + imageConfig, format, err := image.DecodeConfig(stagedFile) + if err != nil { + return domain.Attachment{}, fmt.Errorf("%w: decode image header", ErrInvalidImage) + } + actualContentType, supported := contentTypeForImageFormat(format) + if !supported || actualContentType != command.DeclaredContentType { + return domain.Attachment{}, ErrUnsupportedMediaType + } + if imageConfig.Width < 1 || imageConfig.Height < 1 { + return domain.Attachment{}, ErrInvalidImage + } + if int64(imageConfig.Width) > int64(domain.MaxAttachmentPixels)/int64(imageConfig.Height) { + return domain.Attachment{}, ErrPayloadTooLarge + } + sha256Hex := hex.EncodeToString(hasher.Sum(nil)) + if err = domain.ValidateReadyAttachmentMetadata(command.Filename, actualContentType, sizeBytes, sha256Hex, imageConfig.Width, imageConfig.Height); err != nil { + return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidImage, err) + } + if _, err = stagedFile.Seek(0, io.SeekStart); err != nil { + return domain.Attachment{}, fmt.Errorf("rewind staged attachment for validation: %w", err) + } + if err = s.validateCompleteImage(ctx, stagedFile); err != nil { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return domain.Attachment{}, fmt.Errorf("%w: wait for image decoder", ErrStorageUnavailable) + } + return domain.Attachment{}, fmt.Errorf("%w: decode complete image", ErrInvalidImage) + } + + now := s.now().UTC() + attachmentID := uuid.NewString() + attachment := domain.Attachment{ + ID: attachmentID, + ChatID: command.ChatID, + OwnerID: command.ActorID, + Filename: command.Filename, + ObjectKey: "attachments/" + command.ChatID + "/" + attachmentID + "/original", + StagingKey: "staging/" + attachmentID + "/original", + ContentType: actualContentType, + SizeBytes: sizeBytes, + SHA256: sha256Hex, + Width: imageConfig.Width, + Height: imageConfig.Height, + PipelineVersion: currentAttachmentPipelineVersion, + Status: domain.AttachmentStatusQueued, + Variants: make([]domain.AttachmentVariant, 0), + CreatedAt: now, + UpdatedAt: now, + } + if _, err = stagedFile.Seek(0, io.SeekStart); err != nil { + return domain.Attachment{}, fmt.Errorf("rewind staged attachment for storage: %w", err) + } + if err = s.objectStore.Put(ctx, ObjectPut{Key: attachment.StagingKey, ContentType: attachment.ContentType, SizeBytes: attachment.SizeBytes, Body: stagedFile}); err != nil { + return domain.Attachment{}, fmt.Errorf("%w: put durable staging object", ErrStorageUnavailable) + } + traceCarrier := propagation.MapCarrier{} + otel.GetTextMapPropagator().Inject(ctx, traceCarrier) + job := domain.AttachmentJob{ + SchemaVersion: 1, + JobID: uuid.NewString(), + Type: domain.AttachmentJobType, + AttachmentID: attachment.ID, + PipelineVersion: attachment.PipelineVersion, + Attempt: 1, + MaxAttempts: s.jobMaxAttempts, + Status: domain.AttachmentJobQueued, + AvailableAt: now, + CreatedAt: now, + UpdatedAt: now, + TraceParent: traceCarrier.Get("traceparent"), + TraceState: traceCarrier.Get("tracestate"), + } + attachment, err = queueRepository.CreateQueuedAttachment(ctx, attachment, job) + if err != nil { + // A failed COMMIT response is ambiguous. Preserve staging so a committed + // job can still finish and an uncommitted orphan can be retained/cleaned. + return domain.Attachment{}, fmt.Errorf("persist queued attachment: %w", err) + } + if attachment.Variants == nil { + attachment.Variants = make([]domain.AttachmentVariant, 0) + } + return attachment, nil +} + +func acquireAttachmentSlot(ctx context.Context, slots chan struct{}) error { + select { + case slots <- struct{}{}: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func releaseAttachmentSlot(slots chan struct{}) { <-slots } + +func (s *Service) validateCompleteImage(ctx context.Context, body io.Reader) error { + if err := acquireAttachmentSlot(ctx, s.attachmentDecodeSlots); err != nil { + return err + } + defer releaseAttachmentSlot(s.attachmentDecodeSlots) + _, _, err := image.Decode(body) + return err +} + +func contentTypeForImageFormat(format string) (string, bool) { + switch format { + case "png": + return "image/png", true + case "jpeg": + return "image/jpeg", true + default: + return "", false + } +} diff --git a/internal/application/attachments_test.go b/internal/application/attachments_test.go new file mode 100644 index 0000000..4f67f07 --- /dev/null +++ b/internal/application/attachments_test.go @@ -0,0 +1,155 @@ +package application_test + +import ( + "bytes" + "context" + "errors" + "image" + "image/color" + "image/png" + "io" + "sync" + "testing" + "time" + + "mtusi2026lab7/internal/adapter/memory" + . "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" +) + +type fakeObjectStore struct { + mu sync.Mutex + objects map[string][]byte + putError error +} + +func newFakeObjectStore() *fakeObjectStore { return &fakeObjectStore{objects: make(map[string][]byte)} } +func (store *fakeObjectStore) Put(_ context.Context, object ObjectPut) error { + if store.putError != nil { + return store.putError + } + payload, err := io.ReadAll(object.Body) + if err != nil { + return err + } + store.mu.Lock() + store.objects[object.Key] = payload + store.mu.Unlock() + return nil +} +func (store *fakeObjectStore) Get(_ context.Context, key string) (ObjectContent, error) { + store.mu.Lock() + defer store.mu.Unlock() + payload, ok := store.objects[key] + if !ok { + return ObjectContent{}, errors.New("not found") + } + return ObjectContent{Body: io.NopCloser(bytes.NewReader(payload)), SizeBytes: int64(len(payload))}, nil +} +func (store *fakeObjectStore) Delete(_ context.Context, key string) error { + store.mu.Lock() + delete(store.objects, key) + store.mu.Unlock() + return nil +} + +type interruptedReader struct{} + +func (interruptedReader) Read([]byte) (int, error) { return 0, errors.New("injected read failure") } + +func newAttachmentService(t *testing.T, objects ObjectStore) (*Service, string, string) { + t.Helper() + legacy := memory.NewMemoryStore() + repository := memory.NewMemoryRepository(legacy) + user, err := repository.CreateUser(context.Background(), "uploader", "Uploader", "hash") + if err != nil { + t.Fatal(err) + } + chat, err := repository.CreateChat(context.Background(), "Images", []string{user.ID}) + if err != nil { + t.Fatal(err) + } + codec, err := NewCursorCodec("attachment-test-key-with-more-than-thirty-two-bytes") + if err != nil { + t.Fatal(err) + } + service, err := NewService(repository, codec, time.Hour, WithObjectStore(objects), WithJobMaxAttempts(5)) + if err != nil { + t.Fatal(err) + } + return service, user.ID, chat.ID +} + +func testPNG(t *testing.T) []byte { + t.Helper() + var payload bytes.Buffer + img := image.NewRGBA(image.Rect(0, 0, 320, 200)) + img.Set(0, 0, color.RGBA{R: 255, A: 255}) + if err := png.Encode(&payload, img); err != nil { + t.Fatal(err) + } + return payload.Bytes() +} + +func TestUploadAttachmentDurablyQueuesStagingObject(t *testing.T) { + objects := newFakeObjectStore() + service, actorID, chatID := newAttachmentService(t, objects) + payload := testPNG(t) + attachment, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{ + ActorID: actorID, ChatID: chatID, Filename: "photo.png", + DeclaredContentType: "image/png", Body: bytes.NewReader(payload), + }) + if err != nil { + t.Fatal(err) + } + if attachment.Status != domain.AttachmentStatusQueued { + t.Fatalf("status=%s, want queued", attachment.Status) + } + if attachment.StagingKey == "" || attachment.ObjectKey == attachment.StagingKey { + t.Fatalf("staging/final keys are not separated: %+v", attachment) + } + objects.mu.Lock() + staged := append([]byte(nil), objects.objects[attachment.StagingKey]...) + objects.mu.Unlock() + if !bytes.Equal(staged, payload) { + t.Fatal("durable staging bytes differ") + } +} + +func TestUploadAttachmentRejectsInvalidInputBeforeStaging(t *testing.T) { + objects := newFakeObjectStore() + service, actorID, chatID := newAttachmentService(t, objects) + cases := []struct { + name string + command UploadAttachmentCommand + target error + }{ + {"unsafe filename", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "../x.png", DeclaredContentType: "image/png", Body: bytes.NewReader(testPNG(t))}, ErrInvalidInput}, + {"mime", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/jpeg", Body: bytes.NewReader(testPNG(t))}, ErrUnsupportedMediaType}, + {"corrupt", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: bytes.NewReader([]byte("broken"))}, ErrInvalidImage}, + {"interrupted", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: interruptedReader{}}, ErrInvalidInput}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if _, err := service.UploadAttachment(context.Background(), tc.command); !errors.Is(err, tc.target) { + t.Fatalf("error=%v, want %v", err, tc.target) + } + }) + } + objects.mu.Lock() + count := len(objects.objects) + objects.mu.Unlock() + if count != 0 { + t.Fatalf("invalid requests staged %d objects", count) + } +} + +func TestUploadAttachmentStorageFailureDoesNotCreateQueuedMetadata(t *testing.T) { + objects := newFakeObjectStore() + objects.putError = errors.New("storage down") + service, actorID, chatID := newAttachmentService(t, objects) + _, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: bytes.NewReader(testPNG(t))}) + if !errors.Is(err, ErrStorageUnavailable) { + t.Fatalf("error=%v, want storage unavailable", err) + } +} diff --git a/internal/application/chats.go b/internal/application/chats.go new file mode 100644 index 0000000..7d8cea7 --- /dev/null +++ b/internal/application/chats.go @@ -0,0 +1,55 @@ +package application + +import ( + "context" + "fmt" + + "mtusi2026lab7/internal/domain" +) + +func (s *Service) CreateChat(ctx context.Context, command CreateChatCommand) (domain.Chat, error) { + if err := domain.ValidateChatInput(command.Title, command.MemberIDs, command.ActorID); err != nil { + return domain.Chat{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + return s.repository.CreateChat(ctx, command.Title, command.MemberIDs) +} + +func (s *Service) GetChat(ctx context.Context, actorID, chatID string) (domain.Chat, error) { + return s.repository.GetChatByID(ctx, chatID, actorID) +} + +func (s *Service) ListChats( + ctx context.Context, + actorID string, + limit int, + cursorToken string, +) (domain.ChatPage, error) { + var cursor *domain.ChatCursor + if cursorToken != "" { + decoded, err := s.cursors.DecodeChat(cursorToken, actorID) + if err != nil { + return domain.ChatPage{}, ErrInvalidCursor + } + cursor = decoded + } + + items, hasMore, err := s.repository.GetChatsForUser(ctx, actorID, limit, cursor) + if err != nil { + return domain.ChatPage{}, err + } + page := domain.ChatPage{Items: items} + if page.Items == nil { + page.Items = make([]domain.Chat, 0) + } + if hasMore { + last := page.Items[len(page.Items)-1] + next, encodeErr := s.cursors.EncodeChat(domain.ChatCursor{ + CreatedAt: last.CreatedAt, ChatID: last.ID, UserID: actorID, + }) + if encodeErr != nil { + return domain.ChatPage{}, encodeErr + } + page.NextCursor = &next + } + return page, nil +} diff --git a/internal/application/commands.go b/internal/application/commands.go new file mode 100644 index 0000000..c33b5c1 --- /dev/null +++ b/internal/application/commands.go @@ -0,0 +1,38 @@ +package application + +import "io" + +type CreateUserCommand struct { + Username string + DisplayName string + Password string +} + +type CreateSessionCommand struct { + Username string + Password string +} + +type CreateChatCommand struct { + ActorID string + Title string + MemberIDs []string +} + +type SendMessageCommand struct { + ActorID string + ChatID string + Text string + AttachmentIDs []string + Method string + CanonicalPath string + IdempotencyKey string +} + +type UploadAttachmentCommand struct { + ActorID string + ChatID string + Filename string + DeclaredContentType string + Body io.Reader +} diff --git a/internal/application/cursor.go b/internal/application/cursor.go new file mode 100644 index 0000000..6a5e842 --- /dev/null +++ b/internal/application/cursor.go @@ -0,0 +1,121 @@ +package application + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "strings" + "time" + + "mtusi2026lab7/internal/domain" + + "github.com/google/uuid" +) + +const cursorVersion = 1 + +type CursorCodec struct { + key []byte +} + +type cursorPayload struct { + Version int `json:"v"` + Kind string `json:"kind"` + CreatedAt string `json:"created_at"` + ID string `json:"id"` + ScopeID string `json:"scope_id"` +} + +func NewCursorCodec(key string) (*CursorCodec, error) { + if len(key) < 32 { + return nil, fmt.Errorf("cursor signing key must contain at least 32 bytes") + } + return &CursorCodec{key: []byte(key)}, nil +} + +func (c *CursorCodec) EncodeChat(cursor domain.ChatCursor) (string, error) { + return c.encode(cursorPayload{ + Version: cursorVersion, Kind: "chat", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano), + ID: cursor.ChatID, ScopeID: cursor.UserID, + }) +} + +func (c *CursorCodec) DecodeChat(token, expectedUserID string) (*domain.ChatCursor, error) { + payload, err := c.decode(token, "chat", expectedUserID) + if err != nil { + return nil, err + } + return &domain.ChatCursor{CreatedAt: payload.createdAt, ChatID: payload.id, UserID: payload.scopeID}, nil +} + +func (c *CursorCodec) EncodeMessage(cursor domain.MessageCursor) (string, error) { + return c.encode(cursorPayload{ + Version: cursorVersion, Kind: "message", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano), + ID: cursor.MessageID, ScopeID: cursor.ChatID, + }) +} + +func (c *CursorCodec) DecodeMessage(token, expectedChatID string) (*domain.MessageCursor, error) { + payload, err := c.decode(token, "message", expectedChatID) + if err != nil { + return nil, err + } + return &domain.MessageCursor{CreatedAt: payload.createdAt, MessageID: payload.id, ChatID: payload.scopeID}, nil +} + +func (c *CursorCodec) encode(payload cursorPayload) (string, error) { + encodedPayload, err := json.Marshal(payload) + if err != nil { + return "", fmt.Errorf("encode cursor payload: %w", err) + } + mac := hmac.New(sha256.New, c.key) + _, _ = mac.Write(encodedPayload) + return base64.RawURLEncoding.EncodeToString(encodedPayload) + "." + + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil +} + +type decodedCursor struct { + createdAt time.Time + id string + scopeID string +} + +func (c *CursorCodec) decode(token, expectedKind, expectedScopeID string) (decodedCursor, error) { + parts := strings.Split(token, ".") + if len(parts) != 2 { + return decodedCursor{}, ErrInvalidCursor + } + payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0]) + if err != nil { + return decodedCursor{}, ErrInvalidCursor + } + signature, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + return decodedCursor{}, ErrInvalidCursor + } + mac := hmac.New(sha256.New, c.key) + _, _ = mac.Write(payloadBytes) + if !hmac.Equal(signature, mac.Sum(nil)) { + return decodedCursor{}, ErrInvalidCursor + } + + var payload cursorPayload + if err = json.Unmarshal(payloadBytes, &payload); err != nil || + payload.Version != cursorVersion || payload.Kind != expectedKind || + payload.ScopeID != expectedScopeID { + return decodedCursor{}, ErrInvalidCursor + } + createdAt, err := time.Parse(time.RFC3339Nano, payload.CreatedAt) + if err != nil { + return decodedCursor{}, ErrInvalidCursor + } + if _, err = uuid.Parse(payload.ID); err != nil { + return decodedCursor{}, ErrInvalidCursor + } + if _, err = uuid.Parse(payload.ScopeID); err != nil { + return decodedCursor{}, ErrInvalidCursor + } + return decodedCursor{createdAt: createdAt.UTC(), id: payload.ID, scopeID: payload.ScopeID}, nil +} diff --git a/internal/application/cursor_test.go b/internal/application/cursor_test.go new file mode 100644 index 0000000..77b401e --- /dev/null +++ b/internal/application/cursor_test.go @@ -0,0 +1,96 @@ +package application + +import ( + "encoding/base64" + "errors" + "strings" + "testing" + "time" + + "mtusi2026lab7/internal/domain" +) + +const cursorTestKey = "cursor-test-key-with-more-than-thirty-two-bytes" + +func TestCursorCodecRoundTrip(t *testing.T) { + codec, err := NewCursorCodec(cursorTestKey) + if err != nil { + t.Fatal(err) + } + expected := domain.MessageCursor{ + CreatedAt: time.Date(2026, 10, 18, 12, 30, 0, 123, time.UTC), + MessageID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf", + ChatID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf", + } + token, err := codec.EncodeMessage(expected) + if err != nil { + t.Fatal(err) + } + actual, err := codec.DecodeMessage(token, expected.ChatID) + if err != nil { + t.Fatal(err) + } + if *actual != expected { + t.Fatalf("cursor changed after round trip: got %#v, want %#v", *actual, expected) + } +} + +func TestCursorCodecRejectsTamperingAndWrongScope(t *testing.T) { + codec, err := NewCursorCodec(cursorTestKey) + if err != nil { + t.Fatal(err) + } + token, err := codec.EncodeChat(domain.ChatCursor{ + CreatedAt: time.Now().UTC(), + ChatID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf", + UserID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf", + }) + if err != nil { + t.Fatal(err) + } + + parts := strings.Split(token, ".") + signature, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + t.Fatal(err) + } + signature[0] ^= 1 + tampered := parts[0] + "." + base64.RawURLEncoding.EncodeToString(signature) + if _, err = codec.DecodeChat(tampered, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) { + t.Fatalf("tampered cursor: got %v, want ErrInvalidCursor", err) + } + if _, err = codec.DecodeChat(token, "e6ca4af0-69ed-4784-8ce0-ee035299fe08"); !errors.Is(err, ErrInvalidCursor) { + t.Fatalf("wrong scope: got %v, want ErrInvalidCursor", err) + } + if _, err = codec.DecodeMessage(token, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) { + t.Fatalf("wrong cursor kind: got %v, want ErrInvalidCursor", err) + } +} + +func TestCursorCodecRequiresStrongSharedKey(t *testing.T) { + if _, err := NewCursorCodec("too-short"); err == nil { + t.Fatal("expected short cursor signing key to be rejected") + } +} + +func TestCursorCodecRejectsSignedInvalidFieldTypesBeforeSQL(t *testing.T) { + codec, err := NewCursorCodec(cursorTestKey) + if err != nil { + t.Fatal(err) + } + chatID := "9fa3f49c-e62e-4209-8414-d6d5f69805bf" + validMessageID := "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf" + testCases := []cursorPayload{ + {Version: cursorVersion, Kind: "message", CreatedAt: "not-a-time", ID: validMessageID, ScopeID: chatID}, + {Version: cursorVersion, Kind: "message", CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), ID: "not-a-uuid", ScopeID: chatID}, + } + for _, payload := range testCases { + token, encodeErr := codec.encode(payload) + if encodeErr != nil { + t.Fatal(encodeErr) + } + if _, decodeErr := codec.DecodeMessage(token, chatID); !errors.Is(decodeErr, ErrInvalidCursor) { + t.Fatalf("invalid signed cursor returned %v, want ErrInvalidCursor", decodeErr) + } + } +} diff --git a/internal/application/errors.go b/internal/application/errors.go new file mode 100644 index 0000000..336f54b --- /dev/null +++ b/internal/application/errors.go @@ -0,0 +1,16 @@ +package application + +import "errors" + +var ( + ErrInvalidCursor = errors.New("invalid cursor") + ErrInvalidCredentials = errors.New("invalid credentials") + ErrInvalidInput = errors.New("invalid input") + ErrCredentialState = errors.New("invalid stored credential state") + ErrIdempotencyConflict = errors.New("idempotency key is already used for another request") + ErrAttachmentNotReady = errors.New("attachment is not ready") + ErrPayloadTooLarge = errors.New("payload too large") + ErrUnsupportedMediaType = errors.New("unsupported media type") + ErrInvalidImage = errors.New("invalid image") + ErrStorageUnavailable = errors.New("object storage unavailable") +) diff --git a/internal/application/messages.go b/internal/application/messages.go new file mode 100644 index 0000000..4b22b14 --- /dev/null +++ b/internal/application/messages.go @@ -0,0 +1,88 @@ +package application + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + + "mtusi2026lab7/internal/domain" + + "github.com/google/uuid" +) + +type canonicalMessageRequest struct { + Text string `json:"text"` + AttachmentIDs []string `json:"attachment_ids"` +} + +func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) { + attachmentIDs := append([]string(nil), command.AttachmentIDs...) + if attachmentIDs == nil { + attachmentIDs = make([]string, 0) + } + + if err := domain.ValidateMessageInput(command.Text, attachmentIDs); err != nil { + return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + for index, attachmentID := range attachmentIDs { + attachmentIDs[index] = uuid.MustParse(attachmentID).String() + } + + canonicalBody, err := json.Marshal(canonicalMessageRequest{ + Text: command.Text, + AttachmentIDs: attachmentIDs, + }) + if err != nil { + return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err) + } + + return s.repository.CreateMessageIdempotently(ctx, IdempotentMessageWrite{ + ActorID: command.ActorID, + ChatID: command.ChatID, + Text: command.Text, + AttachmentIDs: attachmentIDs, + Method: command.Method, + CanonicalPath: command.CanonicalPath, + Key: command.IdempotencyKey, + RequestHash: sha256.Sum256(canonicalBody), + TTL: s.idempotencyTTL, + }) +} + +func (s *Service) ListMessages( + ctx context.Context, + actorID string, + chatID string, + limit int, + cursorToken string, +) (domain.MessagePage, error) { + var cursor *domain.MessageCursor + if cursorToken != "" { + decoded, err := s.cursors.DecodeMessage(cursorToken, chatID) + if err != nil { + return domain.MessagePage{}, ErrInvalidCursor + } + cursor = decoded + } + + items, hasMore, err := s.repository.GetMessages(ctx, chatID, actorID, limit, cursor) + if err != nil { + return domain.MessagePage{}, err + } + page := domain.MessagePage{Items: items} + if page.Items == nil { + page.Items = make([]domain.Message, 0) + } + if hasMore { + last := page.Items[len(page.Items)-1] + next, encodeErr := s.cursors.EncodeMessage(domain.MessageCursor{ + CreatedAt: last.CreatedAt, MessageID: last.ID, ChatID: chatID, + }) + if encodeErr != nil { + return domain.MessagePage{}, encodeErr + } + page.NextCursor = &next + } + return page, nil +} diff --git a/internal/application/ports.go b/internal/application/ports.go new file mode 100644 index 0000000..d149d2b --- /dev/null +++ b/internal/application/ports.go @@ -0,0 +1,81 @@ +package application + +import ( + "context" + "io" + "time" + + "mtusi2026lab7/internal/domain" +) + +type UserRepository interface { + CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error) + GetUserByUsername(ctx context.Context, username string) (domain.User, string, error) + UpdatePasswordHash(ctx context.Context, userID, previousHash, newHash string) error +} + +type SessionRepository interface { + CreateSession(ctx context.Context, tokenHash []byte, userID string, expiresAt time.Time) error + GetUserBySession(ctx context.Context, tokenHash []byte) (domain.User, error) + DeleteSession(ctx context.Context, tokenHash []byte) error +} + +type ChatRepository interface { + CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error) + GetChatByID(ctx context.Context, chatID, callerID string) (domain.Chat, error) + GetChatsForUser(ctx context.Context, userID string, limit int, cursor *domain.ChatCursor) ([]domain.Chat, bool, error) +} + +type IdempotentMessageWrite struct { + ActorID string + ChatID string + Text string + AttachmentIDs []string + Method string + CanonicalPath string + Key string + RequestHash [32]byte + TTL time.Duration +} + +type MessageRepository interface { + CreateMessageIdempotently(ctx context.Context, write IdempotentMessageWrite) (domain.Message, error) + GetMessages(ctx context.Context, chatID, callerID string, limit int, cursor *domain.MessageCursor) ([]domain.Message, bool, error) +} + +type AttachmentRepository interface { + CreateAttachment(ctx context.Context, attachment domain.Attachment) (domain.Attachment, error) + MarkAttachmentReady(ctx context.Context, attachmentID string, updatedAt time.Time) (domain.Attachment, error) + MarkAttachmentFailed(ctx context.Context, attachmentID, errorCode string, updatedAt time.Time) error + GetAttachment(ctx context.Context, attachmentID, callerID string) (domain.Attachment, error) +} + +type AttachmentQueueRepository interface { + CreateQueuedAttachment(ctx context.Context, attachment domain.Attachment, job domain.AttachmentJob) (domain.Attachment, error) +} + +type Repository interface { + UserRepository + SessionRepository + ChatRepository + MessageRepository + AttachmentRepository +} + +type ObjectPut struct { + Key string + ContentType string + SizeBytes int64 + Body io.Reader +} + +type ObjectContent struct { + Body io.ReadCloser + SizeBytes int64 +} + +type ObjectStore interface { + Put(ctx context.Context, object ObjectPut) error + Get(ctx context.Context, key string) (ObjectContent, error) + Delete(ctx context.Context, key string) error +} diff --git a/internal/application/service.go b/internal/application/service.go new file mode 100644 index 0000000..78b79c5 --- /dev/null +++ b/internal/application/service.go @@ -0,0 +1,86 @@ +package application + +import ( + "fmt" + "time" +) + +const MinimumIdempotencyTTL = 24 * time.Hour +const defaultAttachmentCleanupTimeout = time.Second +const defaultAttachmentUploadConcurrency = 4 +const defaultAttachmentDecodeConcurrency = 1 +const defaultJobMaxAttempts = 5 + +type ServiceOption func(*Service) error + +type Service struct { + repository Repository + cursors *CursorCodec + sessionTTL time.Duration + idempotencyTTL time.Duration + now func() time.Time + objectStore ObjectStore + attachmentCleanupTimeout time.Duration + attachmentUploadSlots chan struct{} + attachmentDecodeSlots chan struct{} + jobMaxAttempts int +} + +func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) { + if repository == nil { + return nil, fmt.Errorf("repository is required") + } + if cursors == nil { + return nil, fmt.Errorf("cursor codec is required") + } + if sessionTTL <= 0 { + return nil, fmt.Errorf("session TTL must be positive") + } + service := &Service{ + repository: repository, + cursors: cursors, + sessionTTL: sessionTTL, + idempotencyTTL: MinimumIdempotencyTTL, + now: func() time.Time { return time.Now().UTC() }, + attachmentCleanupTimeout: defaultAttachmentCleanupTimeout, + attachmentUploadSlots: make(chan struct{}, defaultAttachmentUploadConcurrency), + attachmentDecodeSlots: make(chan struct{}, defaultAttachmentDecodeConcurrency), + jobMaxAttempts: defaultJobMaxAttempts, + } + for _, option := range options { + if err := option(service); err != nil { + return nil, err + } + } + return service, nil +} + +func WithIdempotencyTTL(ttl time.Duration) ServiceOption { + return func(service *Service) error { + if ttl < MinimumIdempotencyTTL { + return fmt.Errorf("idempotency TTL must be at least %s", MinimumIdempotencyTTL) + } + service.idempotencyTTL = ttl + return nil + } +} + +func WithObjectStore(objectStore ObjectStore) ServiceOption { + return func(service *Service) error { + if objectStore == nil { + return fmt.Errorf("object store is required") + } + service.objectStore = objectStore + return nil + } +} + +func WithJobMaxAttempts(attempts int) ServiceOption { + return func(service *Service) error { + if attempts < 1 { + return fmt.Errorf("job max attempts must be positive") + } + service.jobMaxAttempts = attempts + return nil + } +} diff --git a/internal/application/sessions.go b/internal/application/sessions.go new file mode 100644 index 0000000..cb7eb64 --- /dev/null +++ b/internal/application/sessions.go @@ -0,0 +1,70 @@ +package application + +import ( + "context" + "errors" + "fmt" + + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/security" +) + +const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" + + "AAAAAAAAAAAAAAAAAAAAAA$" + + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + +func (s *Service) CreateSession(ctx context.Context, command CreateSessionCommand) (domain.Session, error) { + user, passwordHash, err := s.repository.GetUserByUsername(ctx, command.Username) + userNotFound := errors.Is(err, domain.ErrNotFound) + if userNotFound { + passwordHash = dummyPasswordHash + } else if err != nil { + return domain.Session{}, err + } + + passwordMatches, verifyErr := security.VerifyPassword(command.Password, passwordHash) + if verifyErr != nil { + return domain.Session{}, fmt.Errorf("%w: %v", ErrCredentialState, verifyErr) + } + if userNotFound || !passwordMatches { + return domain.Session{}, ErrInvalidCredentials + } + needsRehash, rehashErr := security.NeedsPasswordRehash(passwordHash) + if rehashErr != nil { + return domain.Session{}, fmt.Errorf("%w: password hash policy", ErrCredentialState) + } + if needsRehash { + newHash, hashErr := security.HashPassword(command.Password) + if hashErr != nil { + return domain.Session{}, fmt.Errorf("%w: password rehash", ErrCredentialState) + } + if updateErr := s.repository.UpdatePasswordHash(ctx, user.ID, passwordHash, newHash); updateErr != nil { + return domain.Session{}, fmt.Errorf("%w: password rehash update", ErrCredentialState) + } + } + + token, tokenHash, err := security.GenerateSessionToken() + if err != nil { + return domain.Session{}, fmt.Errorf("generate session token: %w", err) + } + expiresAt := s.now().Add(s.sessionTTL) + if err = s.repository.CreateSession(ctx, tokenHash, user.ID, expiresAt); err != nil { + return domain.Session{}, err + } + return domain.Session{ + Token: token, TokenType: "Bearer", ExpiresAt: expiresAt, User: user, + }, nil +} + +func (s *Service) Authenticate(ctx context.Context, token string) (domain.User, []byte, error) { + tokenHash := security.HashSessionToken(token) + user, err := s.repository.GetUserBySession(ctx, tokenHash) + if err != nil { + return domain.User{}, nil, err + } + return user, tokenHash, nil +} + +func (s *Service) DeleteSession(ctx context.Context, tokenHash []byte) error { + return s.repository.DeleteSession(ctx, tokenHash) +} diff --git a/internal/application/users.go b/internal/application/users.go new file mode 100644 index 0000000..b831a9b --- /dev/null +++ b/internal/application/users.go @@ -0,0 +1,29 @@ +package application + +import ( + "context" + "fmt" + + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/security" +) + +func (s *Service) CreateUser(ctx context.Context, command CreateUserCommand) (domain.User, error) { + if err := domain.ValidateUser(command.Username, command.DisplayName); err != nil { + return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + if err := security.ValidatePassword(command.Password); err != nil { + return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + + passwordHash, err := security.HashPassword(command.Password) + if err != nil { + return domain.User{}, fmt.Errorf("hash password: %w", err) + } + return s.repository.CreateUser( + ctx, + command.Username, + command.DisplayName, + passwordHash, + ) +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..b31dfb7 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,554 @@ +package config + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "net" + "os" + "regexp" + "strconv" + "strings" + "time" +) + +type Config struct { + HTTPHost string + HTTPPort string + InstanceID string + + SessionTTL time.Duration + IdempotencyTTL time.Duration + SessionCookieSecure bool + CursorSigningKey string + LoginRateLimit int + LoginRateWindow time.Duration + + DatabaseURL string + DatabaseMaxConns int32 + DatabaseMinConns int32 + DatabaseMaxConnLifetime time.Duration + DatabaseMaxConnIdleTime time.Duration + DatabaseHealthCheckPeriod time.Duration + DatabaseConnectTimeout time.Duration + DatabaseQueryTimeout time.Duration + + RedisURL string + RedisCacheTTL time.Duration + RedisOperationTimeout time.Duration + RedisPoolSize int + + S3Endpoint string + S3Region string + S3Bucket string + S3AccessKeyID string + S3SecretAccessKey string + S3OperationTimeout time.Duration + + BrokerURL string + WorkerConcurrency int + JobMaxAttempts int + JobTimeout time.Duration + JobRetryBase time.Duration + JobRetryMax time.Duration + JobLease time.Duration + StagingRetention time.Duration + StagingCleanupInterval time.Duration + + ReadinessTimeout time.Duration + ShutdownDrainDelay time.Duration + ShutdownTimeout time.Duration +} + +func Load() (Config, error) { return load(true, true) } + +func LoadWorker() (Config, error) { return load(false, true) } + +func LoadDispatcher() (Config, error) { return load(false, false) } + +func load(requireCursor, requireS3 bool) (Config, error) { + instanceID, err := instanceIDFromEnv() + if err != nil { + return Config{}, err + } + + sessionTTL, err := secondsDurationFromEnv( + "SESSION_TTL_SECONDS", + 3600, + ) + if err != nil { + return Config{}, err + } + + idempotencyTTL, err := secondsDurationFromEnv( + "IDEMPOTENCY_TTL_SECONDS", + 86400, + ) + if err != nil { + return Config{}, err + } + loginRateLimit, err := int32FromEnv("LOGIN_RATE_LIMIT", 5, 1) + if err != nil { + return Config{}, err + } + loginRateWindow, err := secondsDurationFromEnv("LOGIN_RATE_WINDOW_SECONDS", 60) + if err != nil { + return Config{}, err + } + + sessionCookieSecure, err := boolFromEnv("SESSION_COOKIE_SECURE", false) + if err != nil { + return Config{}, err + } + databaseURL, err := requiredValueOrFile( + "DATABASE_URL", + "DATABASE_URL_FILE", + ) + if err != nil { + return Config{}, err + } + + cursorSigningKey, err := roleValueOrFile(requireCursor, + "CURSOR_SIGNING_KEY", + "CURSOR_SIGNING_KEY_FILE", + ) + if err != nil { + return Config{}, err + } + + s3AccessKeyID, err := roleValueOrFile(requireS3, + "S3_ACCESS_KEY_ID", + "S3_ACCESS_KEY_ID_FILE", + ) + if err != nil { + return Config{}, err + } + s3SecretAccessKey, err := roleValueOrFile(requireS3, + "S3_SECRET_ACCESS_KEY", + "S3_SECRET_ACCESS_KEY_FILE", + ) + if err != nil { + return Config{}, err + } + s3OperationTimeout, err := durationFromEnv("S3_OPERATION_TIMEOUT", 5*time.Second) + if err != nil { + return Config{}, err + } + brokerURL, err := optionalValueOrFile("BROKER_URL", "BROKER_URL_FILE") + if err != nil { + return Config{}, err + } + workerConcurrency, err := int32FromEnv("WORKER_CONCURRENCY", 2, 1) + if err != nil { + return Config{}, err + } + jobMaxAttempts, err := int32FromEnv("JOB_MAX_ATTEMPTS", 5, 1) + if err != nil { + return Config{}, err + } + jobTimeout, err := secondsDurationFromEnv("JOB_TIMEOUT_SECONDS", 60) + if err != nil { + return Config{}, err + } + jobRetryBase, err := durationFromEnv("JOB_RETRY_BASE", 250*time.Millisecond) + if err != nil { + return Config{}, err + } + jobRetryMax, err := durationFromEnv("JOB_RETRY_MAX", 4*time.Second) + if err != nil { + return Config{}, err + } + jobLease, err := secondsDurationFromEnv("JOB_LEASE_SECONDS", 75) + if err != nil { + return Config{}, err + } + stagingRetention, err := secondsDurationFromEnv("STAGING_RETENTION_SECONDS", 86400) + if err != nil { + return Config{}, err + } + stagingCleanupInterval, err := secondsDurationFromEnv("STAGING_CLEANUP_INTERVAL_SECONDS", 30) + if err != nil { + return Config{}, err + } + databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1) + if err != nil { + return Config{}, err + } + + databaseMinConns, err := int32FromEnv("DB_MIN_CONNS", 2, 0) + if err != nil { + return Config{}, err + } + + databaseMaxConnLifetime, err := durationFromEnv( + "DB_MAX_CONN_LIFETIME", + 30*time.Minute, + ) + if err != nil { + return Config{}, err + } + + databaseMaxConnIdleTime, err := durationFromEnv( + "DB_MAX_CONN_IDLE_TIME", + 5*time.Minute, + ) + if err != nil { + return Config{}, err + } + + databaseHealthCheckPeriod, err := durationFromEnv( + "DB_HEALTH_CHECK_PERIOD", + 30*time.Second, + ) + if err != nil { + return Config{}, err + } + + databaseConnectTimeout, err := durationFromEnv( + "DB_CONNECT_TIMEOUT", + 5*time.Second, + ) + if err != nil { + return Config{}, err + } + + databaseQueryTimeout, err := durationFromEnv( + "DB_QUERY_TIMEOUT", + 3*time.Second, + ) + if err != nil { + return Config{}, err + } + + redisURL, err := optionalValueOrFile("CACHE_URL", "CACHE_URL_FILE") + if err != nil { + return Config{}, err + } + + redisCacheTTL, err := durationFromEnv( + "CACHE_TTL", + 5*time.Minute, + ) + if err != nil { + return Config{}, err + } + + redisOperationTimeout, err := durationFromEnv( + "CACHE_OPERATION_TIMEOUT", + 250*time.Millisecond, + ) + if err != nil { + return Config{}, err + } + + redisPoolSize, err := int32FromEnv("CACHE_POOL_SIZE", 10, 1) + if err != nil { + return Config{}, err + } + + readinessTimeout, err := durationFromEnv( + "READINESS_TIMEOUT", + 2*time.Second, + ) + if err != nil { + return Config{}, err + } + + shutdownDrainDelay, err := durationFromEnv( + "SHUTDOWN_DRAIN_DELAY", + 2*time.Second, + ) + if err != nil { + return Config{}, err + } + + shutdownTimeout, err := durationFromEnv( + "SHUTDOWN_TIMEOUT", + 10*time.Second, + ) + if err != nil { + return Config{}, err + } + + if databaseMinConns > databaseMaxConns { + return Config{}, errors.New( + "DB_MIN_CONNS must not be greater than DB_MAX_CONNS", + ) + } + + if idempotencyTTL < 24*time.Hour { + return Config{}, errors.New( + "IDEMPOTENCY_TTL_SECONDS must be at least 86400", + ) + } + + if shutdownDrainDelay >= shutdownTimeout { + return Config{}, errors.New( + "SHUTDOWN_DRAIN_DELAY must be less than SHUTDOWN_TIMEOUT", + ) + } + + if jobRetryMax < jobRetryBase { + return Config{}, errors.New("JOB_RETRY_MAX must not be less than JOB_RETRY_BASE") + } + if jobLease <= jobTimeout { + return Config{}, errors.New("JOB_LEASE_SECONDS must be greater than JOB_TIMEOUT_SECONDS") + } + + return Config{ + HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"), + HTTPPort: envOrDefault("APP_PORT", "8080"), + InstanceID: instanceID, + SessionTTL: sessionTTL, + IdempotencyTTL: idempotencyTTL, + SessionCookieSecure: sessionCookieSecure, + CursorSigningKey: cursorSigningKey, + LoginRateLimit: int(loginRateLimit), + LoginRateWindow: loginRateWindow, + + DatabaseURL: databaseURL, + DatabaseMaxConns: databaseMaxConns, + DatabaseMinConns: databaseMinConns, + DatabaseMaxConnLifetime: databaseMaxConnLifetime, + DatabaseMaxConnIdleTime: databaseMaxConnIdleTime, + DatabaseHealthCheckPeriod: databaseHealthCheckPeriod, + DatabaseConnectTimeout: databaseConnectTimeout, + DatabaseQueryTimeout: databaseQueryTimeout, + + RedisURL: redisURL, + RedisCacheTTL: redisCacheTTL, + RedisOperationTimeout: redisOperationTimeout, + RedisPoolSize: int(redisPoolSize), + + S3Endpoint: envOrDefault("S3_ENDPOINT", "http://minio:9000"), + S3Region: envOrDefault("S3_REGION", "us-east-1"), + S3Bucket: envOrDefault("S3_BUCKET", "messenger-attachments"), + S3AccessKeyID: s3AccessKeyID, + S3SecretAccessKey: s3SecretAccessKey, + S3OperationTimeout: s3OperationTimeout, + + BrokerURL: brokerURL, + WorkerConcurrency: int(workerConcurrency), + JobMaxAttempts: int(jobMaxAttempts), + JobTimeout: jobTimeout, + JobRetryBase: jobRetryBase, + JobRetryMax: jobRetryMax, + JobLease: jobLease, + StagingRetention: stagingRetention, + StagingCleanupInterval: stagingCleanupInterval, + ReadinessTimeout: readinessTimeout, + ShutdownDrainDelay: shutdownDrainDelay, + ShutdownTimeout: shutdownTimeout, + }, nil +} + +var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`) + +func instanceIDFromEnv() (string, error) { + instanceID := strings.TrimSpace(os.Getenv("INSTANCE_ID")) + if instanceID == "" { + randomBytes := make([]byte, 6) + if _, err := rand.Read(randomBytes); err != nil { + return "", fmt.Errorf("generate opaque instance id: %w", err) + } + instanceID = "api-" + hex.EncodeToString(randomBytes) + } + + if !instanceIDPattern.MatchString(instanceID) { + return "", errors.New( + "INSTANCE_ID or hostname must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}", + ) + } + + return instanceID, nil +} + +func (c Config) HTTPAddress() string { + return net.JoinHostPort(c.HTTPHost, c.HTTPPort) +} + +func roleValueOrFile(required bool, valueEnv, fileEnv string) (string, error) { + if required { + return requiredValueOrFile(valueEnv, fileEnv) + } + return optionalValueOrFile(valueEnv, fileEnv) +} +func requiredValueOrFile(valueEnv, fileEnv string) (string, error) { + value, valueExists := os.LookupEnv(valueEnv) + filePath, fileExists := os.LookupEnv(fileEnv) + + if valueExists && fileExists { + return "", fmt.Errorf( + "%s and %s must not be set at the same time", + valueEnv, + fileEnv, + ) + } + + if valueExists { + value = strings.TrimSpace(value) + if value == "" { + return "", fmt.Errorf("%s must not be empty", valueEnv) + } + + return value, nil + } + + if fileExists { + filePath = strings.TrimSpace(filePath) + if filePath == "" { + return "", fmt.Errorf("%s must not be empty", fileEnv) + } + + data, err := os.ReadFile(filePath) + if err != nil { + return "", fmt.Errorf("read %s: %w", fileEnv, err) + } + + value = strings.TrimSpace(string(data)) + if value == "" { + return "", fmt.Errorf("file from %s must not be empty", fileEnv) + } + + return value, nil + } + + return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv) +} + +func optionalValueOrFile(valueEnv, fileEnv string) (string, error) { + value, valueExists := os.LookupEnv(valueEnv) + filePath, fileExists := os.LookupEnv(fileEnv) + + if valueExists && fileExists { + return "", fmt.Errorf( + "%s and %s must not be set at the same time", + valueEnv, + fileEnv, + ) + } + + if valueExists { + value = strings.TrimSpace(value) + if value == "" { + return "", fmt.Errorf("%s must not be empty", valueEnv) + } + + return value, nil + } + + if fileExists { + filePath = strings.TrimSpace(filePath) + if filePath == "" { + return "", fmt.Errorf("%s must not be empty", fileEnv) + } + + data, err := os.ReadFile(filePath) + if err != nil { + return "", fmt.Errorf("read %s: %w", fileEnv, err) + } + + value = strings.TrimSpace(string(data)) + if value == "" { + return "", fmt.Errorf("file from %s must not be empty", fileEnv) + } + + return value, nil + } + + return "", nil +} + +func envOrDefault(name, fallback string) string { + value := strings.TrimSpace(os.Getenv(name)) + if value == "" { + return fallback + } + + return value +} + +func int32FromEnv(name string, fallback, minimum int32) (int32, error) { + raw := strings.TrimSpace(os.Getenv(name)) + if raw == "" { + return fallback, nil + } + + value, err := strconv.ParseInt(raw, 10, 32) + if err != nil { + return 0, fmt.Errorf("%s must be an integer: %w", name, err) + } + + if value < int64(minimum) { + return 0, fmt.Errorf("%s must be at least %d", name, minimum) + } + + return int32(value), nil +} + +func boolFromEnv(name string, fallback bool) (bool, error) { + raw := strings.TrimSpace(os.Getenv(name)) + if raw == "" { + return fallback, nil + } + + value, err := strconv.ParseBool(raw) + if err != nil { + return false, fmt.Errorf("%s must be true or false: %w", name, err) + } + + return value, nil +} + +func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) { + raw := strings.TrimSpace(os.Getenv(name)) + if raw == "" { + return fallback, nil + } + + value, err := time.ParseDuration(raw) + if err != nil { + return 0, fmt.Errorf( + "%s must be a Go duration such as 3s or 5m: %w", + name, + err, + ) + } + + if value <= 0 { + return 0, fmt.Errorf("%s must be positive", name) + } + + return value, nil +} + +func secondsDurationFromEnv( + name string, + fallbackSeconds int64, +) (time.Duration, error) { + raw := strings.TrimSpace(os.Getenv(name)) + if raw == "" { + raw = strconv.FormatInt(fallbackSeconds, 10) + } + + seconds, err := strconv.ParseInt(raw, 10, 64) + if err != nil { + return 0, fmt.Errorf( + "%s must be an integer number of seconds: %w", + name, + err, + ) + } + + if seconds <= 0 { + return 0, fmt.Errorf("%s must be positive", name) + } + + duration, err := time.ParseDuration(raw + "s") + if err != nil { + return 0, fmt.Errorf("%s is too large: %w", name, err) + } + + return duration, nil +} diff --git a/internal/config/instance_id_test.go b/internal/config/instance_id_test.go new file mode 100644 index 0000000..0b61b4b --- /dev/null +++ b/internal/config/instance_id_test.go @@ -0,0 +1,35 @@ +package config + +import "testing" + +func TestInstanceIDFromEnvironment(t *testing.T) { + t.Setenv("INSTANCE_ID", "api-replica_01") + + instanceID, err := instanceIDFromEnv() + if err != nil { + t.Fatal(err) + } + if instanceID != "api-replica_01" { + t.Fatalf("got %q, want api-replica_01", instanceID) + } +} + +func TestInstanceIDRejectsUnsafeHeaderValue(t *testing.T) { + t.Setenv("INSTANCE_ID", "api-1\r\nX-Forged: true") + + if _, err := instanceIDFromEnv(); err == nil { + t.Fatal("expected unsafe instance ID to be rejected") + } +} + +func TestInstanceIDGeneratesOpaqueAlias(t *testing.T) { + t.Setenv("INSTANCE_ID", "") + + instanceID, err := instanceIDFromEnv() + if err != nil { + t.Fatal(err) + } + if instanceID == "" { + t.Fatal("random alias returned an empty instance ID") + } +} diff --git a/internal/config/session_cookie_test.go b/internal/config/session_cookie_test.go new file mode 100644 index 0000000..05dff00 --- /dev/null +++ b/internal/config/session_cookie_test.go @@ -0,0 +1,29 @@ +package config + +import "testing" + +func TestBoolFromEnv(t *testing.T) { + t.Run("fallback", func(t *testing.T) { + t.Setenv("TEST_BOOL", "") + value, err := boolFromEnv("TEST_BOOL", true) + if err != nil || !value { + t.Fatalf("boolFromEnv() = %v, %v; want true, nil", value, err) + } + }) + + t.Run("explicit false", func(t *testing.T) { + t.Setenv("TEST_BOOL", "false") + value, err := boolFromEnv("TEST_BOOL", true) + if err != nil || value { + t.Fatalf("boolFromEnv() = %v, %v; want false, nil", value, err) + } + }) + + t.Run("invalid", func(t *testing.T) { + t.Setenv("TEST_BOOL", "sometimes") + _, err := boolFromEnv("TEST_BOOL", false) + if err == nil { + t.Fatal("boolFromEnv() error = nil, want validation error") + } + }) +} diff --git a/internal/database/postgres.go b/internal/database/postgres.go new file mode 100644 index 0000000..65b9e27 --- /dev/null +++ b/internal/database/postgres.go @@ -0,0 +1,41 @@ +package database + +import ( + "context" + "fmt" + + "mtusi2026lab7/internal/config" + + "github.com/jackc/pgx/v5/pgxpool" +) + +func Open( + ctx context.Context, + cfg config.Config, +) (*pgxpool.Pool, error) { + poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL) + if err != nil { + return nil, fmt.Errorf("parse PostgreSQL configuration: %w", err) + } + + poolConfig.MaxConns = cfg.DatabaseMaxConns + poolConfig.MinConns = cfg.DatabaseMinConns + poolConfig.MaxConnLifetime = cfg.DatabaseMaxConnLifetime + poolConfig.MaxConnIdleTime = cfg.DatabaseMaxConnIdleTime + poolConfig.HealthCheckPeriod = cfg.DatabaseHealthCheckPeriod + poolConfig.ConnConfig.Tracer = pgxQueryTracer{} + + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + return nil, fmt.Errorf("create PostgreSQL pool: %w", err) + } + + // NewWithConfig создаёт структуру пула, но не гарантирует, + // что PostgreSQL уже доступен. Ping обеспечивает fail-fast. + if err := pool.Ping(ctx); err != nil { + pool.Close() + return nil, fmt.Errorf("ping PostgreSQL: %w", err) + } + + return pool, nil +} diff --git a/internal/database/tracing.go b/internal/database/tracing.go new file mode 100644 index 0000000..968a75f --- /dev/null +++ b/internal/database/tracing.go @@ -0,0 +1,92 @@ +package database + +import ( + "context" + "strings" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/trace" +) + +type pgxQueryTracer struct{} + +func (pgxQueryTracer) TraceAcquireStart( + ctx context.Context, + _ *pgxpool.Pool, + _ pgxpool.TraceAcquireStartData, +) context.Context { + ctx, _ = otel.Tracer("mtusi2026lab7/postgresql").Start( + ctx, + "postgresql.acquire", + trace.WithSpanKind(trace.SpanKindClient), + trace.WithAttributes( + attribute.String("db.system.name", "postgresql"), + attribute.String("db.operation.name", "ACQUIRE"), + ), + ) + return ctx +} + +func (pgxQueryTracer) TraceAcquireEnd( + ctx context.Context, + _ *pgxpool.Pool, + data pgxpool.TraceAcquireEndData, +) { + span := trace.SpanFromContext(ctx) + if data.Err != nil { + span.SetStatus(codes.Error, "database connection acquisition failed") + } else { + span.SetStatus(codes.Ok, "") + } + span.End() +} + +func (pgxQueryTracer) TraceQueryStart( + ctx context.Context, + _ *pgx.Conn, + data pgx.TraceQueryStartData, +) context.Context { + operation := databaseOperation(data.SQL) + ctx, _ = otel.Tracer("mtusi2026lab7/postgresql").Start( + ctx, + "postgresql."+strings.ToLower(operation), + trace.WithSpanKind(trace.SpanKindClient), + trace.WithAttributes( + attribute.String("db.system.name", "postgresql"), + attribute.String("db.operation.name", operation), + ), + ) + return ctx +} + +func (pgxQueryTracer) TraceQueryEnd( + ctx context.Context, + _ *pgx.Conn, + data pgx.TraceQueryEndData, +) { + span := trace.SpanFromContext(ctx) + if data.Err != nil { + span.SetStatus(codes.Error, "database operation failed") + } else { + span.SetStatus(codes.Ok, "") + } + span.End() +} + +func databaseOperation(sql string) string { + fields := strings.Fields(sql) + if len(fields) == 0 { + return "QUERY" + } + operation := strings.ToUpper(fields[0]) + switch operation { + case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK": + return operation + default: + return "QUERY" + } +} diff --git a/internal/domain/attachment.go b/internal/domain/attachment.go new file mode 100644 index 0000000..119eda9 --- /dev/null +++ b/internal/domain/attachment.go @@ -0,0 +1,126 @@ +package domain + +import ( + "encoding/hex" + "fmt" + "strings" + "time" + "unicode" + "unicode/utf8" +) + +const ( + MaxAttachmentFilenameCodePoints = 255 + MaxAttachmentSizeBytes = 10 * 1024 * 1024 + MaxAttachmentPixels = 40_000_000 +) + +type AttachmentVariant struct { + Name string + ContentType string + SizeBytes int64 + Width int + Height int + SHA256 string + ObjectKey string + PipelineVersion int +} + +type AttachmentStatus string + +const ( + AttachmentStatusQueued AttachmentStatus = "queued" + AttachmentStatusProcessing AttachmentStatus = "processing" + AttachmentStatusReady AttachmentStatus = "ready" + AttachmentStatusFailed AttachmentStatus = "failed" + // Source-compatible alias for the lab4 reconciliation code. + AttachmentStatusPending = AttachmentStatusQueued +) + +// Attachment contains metadata only. ObjectKey points to bytes in the +// private object store and must never be derived from Filename. +type Attachment struct { + ID string + ChatID string + OwnerID string + Filename string + ObjectKey string + ContentType string + SizeBytes int64 + SHA256 string + Width int + Height int + StagingKey string + PipelineVersion int + Status AttachmentStatus + Variants []AttachmentVariant + ErrorCode *string + CreatedAt time.Time + UpdatedAt time.Time +} + +func ValidateAttachmentFilename(filename string) error { + if !utf8.ValidString(filename) { + return fmt.Errorf("filename must be valid UTF-8") + } + filenameLength := utf8.RuneCountInString(filename) + if filenameLength < 1 || filenameLength > MaxAttachmentFilenameCodePoints { + return fmt.Errorf("filename length must be between 1 and %d code points", MaxAttachmentFilenameCodePoints) + } + if strings.TrimSpace(filename) == "" || filename == "." || filename == ".." { + return fmt.Errorf("filename is unsafe") + } + if strings.ContainsAny(filename, `/\\`) { + return fmt.Errorf("filename must not contain path separators") + } + for _, character := range filename { + if unicode.IsControl(character) { + return fmt.Errorf("filename must not contain control characters") + } + } + return nil +} + +func ValidateAttachmentContentType(contentType string) error { + if contentType != "image/png" && contentType != "image/jpeg" { + return fmt.Errorf("content type must be image/png or image/jpeg") + } + return nil +} + +// ValidateReadyAttachmentMetadata checks the bounded metadata produced after +// the upload stream has been identified, decoded and hashed. It deliberately +// does not trust an HTTP Content-Type header. +func ValidateReadyAttachmentMetadata( + filename string, + contentType string, + sizeBytes int64, + sha256Hex string, + width int, + height int, +) error { + if err := ValidateAttachmentFilename(filename); err != nil { + return err + } + if err := ValidateAttachmentContentType(contentType); err != nil { + return err + } + if sizeBytes < 1 || sizeBytes > MaxAttachmentSizeBytes { + return fmt.Errorf("attachment size must be between 1 and %d bytes", MaxAttachmentSizeBytes) + } + if width < 1 || height < 1 { + return fmt.Errorf("image dimensions must be positive and contain at most %d pixels", MaxAttachmentPixels) + } + if int64(width) > int64(MaxAttachmentPixels)/int64(height) { + return fmt.Errorf("image dimensions must be positive and contain at most %d pixels", MaxAttachmentPixels) + } + if len(sha256Hex) != 64 || sha256Hex != strings.ToLower(sha256Hex) { + return fmt.Errorf("sha256 must contain 64 lowercase hexadecimal characters") + } + decodedHash, err := hex.DecodeString(sha256Hex) + if err != nil || len(decodedHash) != 32 { + return fmt.Errorf("sha256 must contain 64 lowercase hexadecimal characters") + } + + return nil +} diff --git a/internal/domain/attachment_job.go b/internal/domain/attachment_job.go new file mode 100644 index 0000000..67e63e8 --- /dev/null +++ b/internal/domain/attachment_job.go @@ -0,0 +1,57 @@ +package domain + +import "time" + +const AttachmentJobType = "attachment.process.v1" + +type AttachmentJobStatus string + +const ( + AttachmentJobQueued AttachmentJobStatus = "queued" + AttachmentJobProcessing AttachmentJobStatus = "processing" + AttachmentJobSucceeded AttachmentJobStatus = "succeeded" + AttachmentJobFailed AttachmentJobStatus = "failed" + AttachmentJobSuperseded AttachmentJobStatus = "superseded" +) + +type AttachmentJob struct { + SchemaVersion int + JobID string + Type string + AttachmentID string + PipelineVersion int + Attempt int + MaxAttempts int + Status AttachmentJobStatus + ErrorCode *string + AvailableAt time.Time + LeaseUntil *time.Time + LeasedBy *string + ReplayCount int + CreatedAt time.Time + UpdatedAt time.Time + TraceParent string + TraceState string +} + +type AttachmentJobMessage struct { + SchemaVersion int `json:"schema_version"` + JobID string `json:"job_id"` + Type string `json:"type"` + AttachmentID string `json:"attachment_id"` + PipelineVersion int `json:"pipeline_version"` + Attempt int `json:"attempt"` + CreatedAt time.Time `json:"created_at"` +} + +func (job AttachmentJob) Message() AttachmentJobMessage { + return AttachmentJobMessage{ + SchemaVersion: job.SchemaVersion, + JobID: job.JobID, + Type: job.Type, + AttachmentID: job.AttachmentID, + PipelineVersion: job.PipelineVersion, + Attempt: job.Attempt, + CreatedAt: job.CreatedAt.UTC(), + } +} diff --git a/internal/domain/attachment_test.go b/internal/domain/attachment_test.go new file mode 100644 index 0000000..ec7c101 --- /dev/null +++ b/internal/domain/attachment_test.go @@ -0,0 +1,59 @@ +package domain + +import ( + "math" + "strings" + "testing" +) + +func TestValidateReadyAttachmentMetadata(t *testing.T) { + validHash := strings.Repeat("ab", 32) + + testCases := []struct { + name string + filename string + contentType string + sizeBytes int64 + sha256 string + width int + height int + wantError bool + }{ + {name: "png", filename: "кот.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1}, + {name: "jpeg at limits", filename: strings.Repeat("界", 255), contentType: "image/jpeg", sizeBytes: MaxAttachmentSizeBytes, sha256: validHash, width: 8_000, height: 5_000}, + {name: "empty filename", filename: "", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "blank filename", filename: " ", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "dot segment", filename: "..", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "forward slash", filename: "folder/image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "backslash", filename: `folder\\image.png`, contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "control character", filename: "image\n.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "C1 control character", filename: "image\u0085.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "invalid UTF-8", filename: string([]byte{'x', 0xff, '.', 'p', 'n', 'g'}), contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "filename too long", filename: strings.Repeat("a", 256), contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "unsupported MIME", filename: "image.gif", contentType: "image/gif", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "empty file", filename: "image.png", contentType: "image/png", sizeBytes: 0, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "file too large", filename: "image.png", contentType: "image/png", sizeBytes: MaxAttachmentSizeBytes + 1, sha256: validHash, width: 1, height: 1, wantError: true}, + {name: "zero width", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 0, height: 1, wantError: true}, + {name: "too many pixels", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 8_001, height: 5_000, wantError: true}, + {name: "dimension multiplication cannot overflow", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: math.MaxInt, height: math.MaxInt, wantError: true}, + {name: "short hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: "ab", width: 1, height: 1, wantError: true}, + {name: "uppercase hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: strings.ToUpper(validHash), width: 1, height: 1, wantError: true}, + {name: "non-hex hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: strings.Repeat("zz", 32), width: 1, height: 1, wantError: true}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + err := ValidateReadyAttachmentMetadata( + testCase.filename, + testCase.contentType, + testCase.sizeBytes, + testCase.sha256, + testCase.width, + testCase.height, + ) + if (err != nil) != testCase.wantError { + t.Fatalf("ValidateReadyAttachmentMetadata() error = %v, wantError %v", err, testCase.wantError) + } + }) + } +} diff --git a/internal/domain/chat.go b/internal/domain/chat.go new file mode 100644 index 0000000..fe0c594 --- /dev/null +++ b/internal/domain/chat.go @@ -0,0 +1,21 @@ +package domain + +import "time" + +type Chat struct { + ID string + Title string + MemberIDs []string + CreatedAt time.Time +} + +type ChatCursor struct { + CreatedAt time.Time + ChatID string + UserID string +} + +type ChatPage struct { + Items []Chat + NextCursor *string +} diff --git a/internal/domain/errors.go b/internal/domain/errors.go new file mode 100644 index 0000000..38a7599 --- /dev/null +++ b/internal/domain/errors.go @@ -0,0 +1,8 @@ +package domain + +import "errors" + +var ( + ErrNotFound = errors.New("not found") + ErrConflict = errors.New("conflict") +) diff --git a/internal/domain/message.go b/internal/domain/message.go new file mode 100644 index 0000000..b661222 --- /dev/null +++ b/internal/domain/message.go @@ -0,0 +1,23 @@ +package domain + +import "time" + +type Message struct { + ID string + ChatID string + SenderID string + Text string + AttachmentIDs []string + CreatedAt time.Time +} + +type MessageCursor struct { + CreatedAt time.Time + MessageID string + ChatID string +} + +type MessagePage struct { + Items []Message + NextCursor *string +} diff --git a/internal/domain/message_test.go b/internal/domain/message_test.go new file mode 100644 index 0000000..3516a5e --- /dev/null +++ b/internal/domain/message_test.go @@ -0,0 +1,70 @@ +package domain + +import ( + "strings" + "testing" +) + +func TestValidateMessageInput(t *testing.T) { + validAttachment := "11111111-1111-4111-8111-111111111111" + + testCases := []struct { + name string + text string + attachmentIDs []string + wantError bool + }{ + {name: "text only", text: "hello"}, + {name: "attachment only", attachmentIDs: []string{validAttachment}}, + {name: "whitespace with attachment", text: " ", attachmentIDs: []string{validAttachment}}, + {name: "empty", wantError: true}, + {name: "whitespace only", text: " ", wantError: true}, + {name: "text too long", text: strings.Repeat("界", 4001), wantError: true}, + {name: "invalid attachment uuid", text: "hello", attachmentIDs: []string{"not-a-uuid"}, wantError: true}, + { + name: "duplicate attachment uuid ignores case", + text: "hello", + attachmentIDs: []string{ + "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + }, + wantError: true, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + err := ValidateMessageInput(testCase.text, testCase.attachmentIDs) + if (err != nil) != testCase.wantError { + t.Fatalf("ValidateMessageInput() error = %v, wantError %v", err, testCase.wantError) + } + }) + } +} + +func TestValidateMessageInputAttachmentLimit(t *testing.T) { + attachmentIDs := []string{ + "00000000-0000-4000-8000-000000000001", + "00000000-0000-4000-8000-000000000002", + "00000000-0000-4000-8000-000000000003", + "00000000-0000-4000-8000-000000000004", + "00000000-0000-4000-8000-000000000005", + "00000000-0000-4000-8000-000000000006", + "00000000-0000-4000-8000-000000000007", + "00000000-0000-4000-8000-000000000008", + "00000000-0000-4000-8000-000000000009", + "00000000-0000-4000-8000-000000000010", + } + + if err := ValidateMessageInput("", attachmentIDs); err != nil { + t.Fatalf("10 attachments must be accepted: %v", err) + } + + attachmentIDs = append( + attachmentIDs, + "00000000-0000-4000-8000-000000000011", + ) + if err := ValidateMessageInput("hello", attachmentIDs); err == nil { + t.Fatal("11 attachments must be rejected") + } +} diff --git a/internal/domain/session.go b/internal/domain/session.go new file mode 100644 index 0000000..420c04b --- /dev/null +++ b/internal/domain/session.go @@ -0,0 +1,10 @@ +package domain + +import "time" + +type Session struct { + Token string + TokenType string + ExpiresAt time.Time + User User +} diff --git a/internal/domain/user.go b/internal/domain/user.go new file mode 100644 index 0000000..090c349 --- /dev/null +++ b/internal/domain/user.go @@ -0,0 +1,11 @@ +package domain + +import "time" + +// User is the transport-independent representation of a messenger user. +type User struct { + ID string + Username string + DisplayName string + CreatedAt time.Time +} diff --git a/internal/domain/validation.go b/internal/domain/validation.go new file mode 100644 index 0000000..5d00b65 --- /dev/null +++ b/internal/domain/validation.go @@ -0,0 +1,101 @@ +package domain + +import ( + "fmt" + "regexp" + "strings" + "unicode/utf8" + + "github.com/google/uuid" +) + +const MaxMessageAttachments = 10 + +var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +func ValidateUser(username, displayName string) error { + if !usernameRegex.MatchString(username) { + return fmt.Errorf("username must match [a-z0-9_]{3,32}") + } + + nameRunes := utf8.RuneCountInString(displayName) + if nameRunes < 1 || nameRunes > 100 { + return fmt.Errorf("display_name length must be between 1 and 100 code points") + } + if strings.TrimSpace(displayName) == "" { + return fmt.Errorf("display_name cannot be only whitespace") + } + + return nil +} + +// Validate remains as a compatibility convenience for existing callers. +func (u User) Validate() error { + return ValidateUser(u.Username, u.DisplayName) +} + +func ValidateChatInput(title string, memberIDs []string, callerID string) error { + titleRunes := utf8.RuneCountInString(title) + if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" { + return fmt.Errorf("invalid chat title") + } + if len(memberIDs) == 0 { + return fmt.Errorf("member_ids cannot be empty") + } + if len(memberIDs) > 100 { + return fmt.Errorf("member_ids must contain at most 100 users") + } + + hasCaller := false + seen := make(map[string]struct{}, len(memberIDs)) + for _, id := range memberIDs { + if _, err := uuid.Parse(id); err != nil { + return fmt.Errorf("invalid member uuid: %s", id) + } + if _, exists := seen[id]; exists { + return fmt.Errorf("duplicate member_id: %s", id) + } + seen[id] = struct{}{} + if id == callerID { + hasCaller = true + } + } + + if !hasCaller { + return fmt.Errorf("caller must be in member_ids") + } + return nil +} + +func ValidateMessageInput(text string, attachmentIDs []string) error { + textRunes := utf8.RuneCountInString(text) + if textRunes > 4000 { + return fmt.Errorf("message text length must be at most 4000 code points") + } + if len(attachmentIDs) > MaxMessageAttachments { + return fmt.Errorf("attachment_ids must contain at most %d items", MaxMessageAttachments) + } + + seen := make(map[string]struct{}, len(attachmentIDs)) + for _, attachmentID := range attachmentIDs { + parsedID, err := uuid.Parse(attachmentID) + if err != nil { + return fmt.Errorf("invalid attachment uuid: %s", attachmentID) + } + canonicalID := parsedID.String() + if _, exists := seen[canonicalID]; exists { + return fmt.Errorf("duplicate attachment_id: %s", attachmentID) + } + seen[canonicalID] = struct{}{} + } + + if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 { + return fmt.Errorf("message must contain non-blank text or at least one attachment") + } + return nil +} + +// ValidateMessageText remains for callers that create text-only messages. +func ValidateMessageText(text string) error { + return ValidateMessageInput(text, nil) +} diff --git a/internal/reconcile/reconciler.go b/internal/reconcile/reconciler.go new file mode 100644 index 0000000..abfbb29 --- /dev/null +++ b/internal/reconcile/reconciler.go @@ -0,0 +1,203 @@ +package reconcile + +import ( + "context" + "fmt" + "sort" + "time" + + "mtusi2026lab7/internal/adapter/objectstore" + "mtusi2026lab7/internal/domain" +) + +const ( + IssueOrphanObject = "orphan_object" + IssueMissingObject = "missing_object" + IssueFailedObject = "failed_object" + IssueReferencedMissing = "referenced_missing_object" +) + +type AttachmentRecord struct { + ID string + ObjectKey string + AdditionalObjectKeys []string + Status domain.AttachmentStatus + UpdatedAt time.Time + Referenced bool +} + +type MetadataStore interface { + ListAttachmentInventory(ctx context.Context) ([]AttachmentRecord, error) + MarkAttachmentFailedIfUnreferenced( + ctx context.Context, + attachmentID string, + expectedStatus domain.AttachmentStatus, + updatedBefore time.Time, + errorCode string, + updatedAt time.Time, + ) (bool, error) +} + +type ObjectInventory interface { + List(ctx context.Context, prefix string) ([]objectstore.StoredObject, error) + Delete(ctx context.Context, key string) error +} + +type Issue struct { + Kind string `json:"kind"` + AttachmentID string `json:"attachment_id,omitempty"` + ObjectKey string `json:"object_key"` + Protected bool `json:"protected,omitempty"` + Action string `json:"action"` +} + +type Result struct { + DryRun bool `json:"dry_run"` + GracePeriod time.Duration `json:"-"` + GracePeriodSeconds int64 `json:"grace_period_seconds"` + ScannedAttachments int `json:"scanned_attachments"` + ScannedObjects int `json:"scanned_objects"` + Issues []Issue `json:"issues"` + DeletedObjects int `json:"deleted_objects"` + FailedAttachments int `json:"failed_attachments"` + Duration time.Duration `json:"-"` + DurationMillis int64 `json:"duration_ms"` +} + +type Reconciler struct { + metadata MetadataStore + objects ObjectInventory + now func() time.Time +} + +func New(metadata MetadataStore, objects ObjectInventory) (*Reconciler, error) { + if metadata == nil || objects == nil { + return nil, fmt.Errorf("metadata and object stores are required") + } + return &Reconciler{ + metadata: metadata, + objects: objects, + now: func() time.Time { return time.Now().UTC() }, + }, nil +} + +func (r *Reconciler) Run( + ctx context.Context, + gracePeriod time.Duration, + apply bool, +) (Result, error) { + if gracePeriod <= 0 { + return Result{}, fmt.Errorf("grace period must be positive") + } + startedAt := r.now().UTC() + cutoff := startedAt.Add(-gracePeriod) + result := Result{ + DryRun: !apply, + GracePeriod: gracePeriod, + GracePeriodSeconds: int64(gracePeriod / time.Second), + Issues: make([]Issue, 0), + } + + attachments, err := r.metadata.ListAttachmentInventory(ctx) + if err != nil { + return Result{}, fmt.Errorf("list attachment metadata: %w", err) + } + objects, err := r.objects.List(ctx, "attachments/") + if err != nil { + return Result{}, fmt.Errorf("list attachment objects: %w", err) + } + result.ScannedAttachments = len(attachments) + result.ScannedObjects = len(objects) + + attachmentsByKey := make(map[string]AttachmentRecord, len(attachments)) + for _, attachment := range attachments { + attachmentsByKey[attachment.ObjectKey] = attachment + for _, objectKey := range attachment.AdditionalObjectKeys { + if objectKey != "" { + attachmentsByKey[objectKey] = attachment + } + } + } + objectsByKey := make(map[string]objectstore.StoredObject, len(objects)) + for _, object := range objects { + objectsByKey[object.Key] = object + if _, exists := attachmentsByKey[object.Key]; exists { + continue + } + if object.LastModified.IsZero() || object.LastModified.After(cutoff) { + continue + } + issue := Issue{Kind: IssueOrphanObject, ObjectKey: object.Key, Action: "would_delete"} + if apply { + if err = r.objects.Delete(ctx, object.Key); err != nil { + return result, fmt.Errorf("delete orphan object %q: %w", object.Key, err) + } + issue.Action = "deleted" + result.DeletedObjects++ + } + result.Issues = append(result.Issues, issue) + } + + for _, attachment := range attachments { + if attachment.UpdatedAt.After(cutoff) { + continue + } + _, objectExists := objectsByKey[attachment.ObjectKey] + switch { + case attachment.Status == domain.AttachmentStatusReady && !objectExists: + issue := Issue{ + Kind: IssueMissingObject, + AttachmentID: attachment.ID, + ObjectKey: attachment.ObjectKey, + Protected: attachment.Referenced, + Action: "would_mark_failed", + } + if attachment.Referenced { + issue.Kind = IssueReferencedMissing + issue.Action = "manual_repair_required" + } else if apply { + changed, markError := r.metadata.MarkAttachmentFailedIfUnreferenced( + ctx, attachment.ID, attachment.Status, cutoff, + "reconciler_missing_object", startedAt, + ) + if markError != nil { + return result, fmt.Errorf("mark missing attachment %q failed: %w", attachment.ID, markError) + } + if changed { + issue.Action = "marked_failed" + result.FailedAttachments++ + } else { + issue.Action = "skipped_concurrent_change" + } + } + result.Issues = append(result.Issues, issue) + + case attachment.Status == domain.AttachmentStatusFailed && objectExists: + issue := Issue{ + Kind: IssueFailedObject, AttachmentID: attachment.ID, + ObjectKey: attachment.ObjectKey, Protected: attachment.Referenced, + Action: "would_delete", + } + if attachment.Referenced { + issue.Action = "manual_repair_required" + } else if apply { + if err = r.objects.Delete(ctx, attachment.ObjectKey); err != nil { + return result, fmt.Errorf("delete failed attachment object %q: %w", attachment.ObjectKey, err) + } + issue.Action = "deleted" + result.DeletedObjects++ + } + result.Issues = append(result.Issues, issue) + } + } + + sort.Slice(result.Issues, func(i, j int) bool { + if result.Issues[i].ObjectKey == result.Issues[j].ObjectKey { + return result.Issues[i].Kind < result.Issues[j].Kind + } + return result.Issues[i].ObjectKey < result.Issues[j].ObjectKey + }) + result.Duration = r.now().UTC().Sub(startedAt) + result.DurationMillis = result.Duration.Milliseconds() + return result, nil +} diff --git a/internal/reconcile/reconciler_test.go b/internal/reconcile/reconciler_test.go new file mode 100644 index 0000000..fa03e17 --- /dev/null +++ b/internal/reconcile/reconciler_test.go @@ -0,0 +1,228 @@ +package reconcile + +import ( + "context" + "errors" + "testing" + "time" + + "mtusi2026lab7/internal/adapter/objectstore" + "mtusi2026lab7/internal/domain" +) + +type fakeMetadataStore struct { + records []AttachmentRecord + markError error + skipMark bool +} + +func (store *fakeMetadataStore) ListAttachmentInventory( + context.Context, +) ([]AttachmentRecord, error) { + return append([]AttachmentRecord(nil), store.records...), nil +} + +func (store *fakeMetadataStore) MarkAttachmentFailedIfUnreferenced( + _ context.Context, + attachmentID string, + expectedStatus domain.AttachmentStatus, + updatedBefore time.Time, + errorCode string, + updatedAt time.Time, +) (bool, error) { + if store.markError != nil { + return false, store.markError + } + if store.skipMark { + return false, nil + } + for index := range store.records { + record := &store.records[index] + if record.ID != attachmentID || record.Status != expectedStatus || + record.UpdatedAt.After(updatedBefore) || record.Referenced { + continue + } + record.Status = domain.AttachmentStatusFailed + record.UpdatedAt = updatedAt + _ = errorCode + return true, nil + } + return false, nil +} + +func TestReconcilerDoesNotTouchActiveAttachments(t *testing.T) { + old := time.Now().UTC().Add(-2 * time.Hour) + metadata := &fakeMetadataStore{ + records: []AttachmentRecord{ + { + ID: "queued-old", ObjectKey: "attachments/queued-old", + AdditionalObjectKeys: []string{"attachments/queued-old-staging"}, + Status: domain.AttachmentStatusQueued, UpdatedAt: old, + }, + { + ID: "processing-old", ObjectKey: "attachments/processing-old", + Status: domain.AttachmentStatusProcessing, UpdatedAt: old, + }, + }, + } + objects := &fakeObjectInventory{objects: map[string]objectstore.StoredObject{ + "attachments/queued-old": {Key: "attachments/queued-old", LastModified: old}, + "attachments/queued-old-staging": {Key: "attachments/queued-old-staging", LastModified: old}, + "attachments/processing-old": {Key: "attachments/processing-old", LastModified: old}, + }} + reconciler, err := New(metadata, objects) + if err != nil { + t.Fatal(err) + } + + result, err := reconciler.Run(context.Background(), time.Hour, true) + if err != nil { + t.Fatal(err) + } + if result.DeletedObjects != 0 || result.FailedAttachments != 0 { + t.Fatalf("active attachments must not be reconciled as stale: %+v", result) + } + if len(result.Issues) != 0 { + t.Fatalf("active attachments must not produce reconciliation issues: %+v", result.Issues) + } + if len(objects.objects) != 3 { + t.Fatal("reconciler deleted an object belonging to an active attachment") + } +} + +type fakeObjectInventory struct { + objects map[string]objectstore.StoredObject + deleteError error +} + +func (store *fakeObjectInventory) List( + context.Context, + string, +) ([]objectstore.StoredObject, error) { + objects := make([]objectstore.StoredObject, 0, len(store.objects)) + for _, object := range store.objects { + objects = append(objects, object) + } + return objects, nil +} + +func (store *fakeObjectInventory) Delete(_ context.Context, key string) error { + if store.deleteError != nil { + return store.deleteError + } + delete(store.objects, key) + return nil +} + +func TestReconcilerDryRunApplyAndRepeat(t *testing.T) { + now := time.Now().UTC() + old := now.Add(-2 * time.Hour) + fresh := now.Add(-5 * time.Minute) + metadata := &fakeMetadataStore{records: []AttachmentRecord{ + { + ID: "ready-present", ObjectKey: "attachments/ready-present", + AdditionalObjectKeys: []string{"attachments/ready-present-thumbnail"}, + Status: domain.AttachmentStatusReady, UpdatedAt: old, + }, + {ID: "ready-missing", ObjectKey: "attachments/ready-missing", Status: domain.AttachmentStatusReady, UpdatedAt: old}, + {ID: "ready-used-missing", ObjectKey: "attachments/ready-used-missing", Status: domain.AttachmentStatusReady, UpdatedAt: old, Referenced: true}, + {ID: "queued-old", ObjectKey: "attachments/queued-old", Status: domain.AttachmentStatusQueued, UpdatedAt: old}, + {ID: "failed-old", ObjectKey: "attachments/failed-old", Status: domain.AttachmentStatusFailed, UpdatedAt: old}, + {ID: "queued-fresh", ObjectKey: "attachments/queued-fresh", Status: domain.AttachmentStatusQueued, UpdatedAt: fresh}, + }} + objects := &fakeObjectInventory{objects: map[string]objectstore.StoredObject{ + "attachments/ready-present": {Key: "attachments/ready-present", LastModified: old}, + "attachments/ready-present-thumbnail": {Key: "attachments/ready-present-thumbnail", LastModified: old}, + "attachments/queued-old": {Key: "attachments/queued-old", LastModified: old}, + "attachments/failed-old": {Key: "attachments/failed-old", LastModified: old}, + "attachments/orphan-old": {Key: "attachments/orphan-old", LastModified: old}, + "attachments/orphan-fresh": {Key: "attachments/orphan-fresh", LastModified: fresh}, + }} + reconciler, err := New(metadata, objects) + if err != nil { + t.Fatal(err) + } + + dryRun, err := reconciler.Run(context.Background(), time.Hour, false) + if err != nil { + t.Fatal(err) + } + if !dryRun.DryRun || len(dryRun.Issues) != 4 || + dryRun.DeletedObjects != 0 || dryRun.FailedAttachments != 0 { + t.Fatalf("unexpected dry-run result: %+v", dryRun) + } + if len(objects.objects) != 6 { + t.Fatal("dry-run changed object storage") + } + for _, record := range metadata.records { + if record.ID == "ready-missing" && record.Status != domain.AttachmentStatusReady { + t.Fatal("dry-run changed metadata") + } + } + + applied, err := reconciler.Run(context.Background(), time.Hour, true) + if err != nil { + t.Fatal(err) + } + if applied.DeletedObjects != 2 || applied.FailedAttachments != 1 { + t.Fatalf("unexpected apply result: %+v", applied) + } + if _, exists := objects.objects["attachments/orphan-old"]; exists { + t.Fatal("old orphan was not deleted") + } + if _, exists := objects.objects["attachments/orphan-fresh"]; !exists { + t.Fatal("fresh orphan must be protected by grace period") + } + if _, exists := objects.objects["attachments/ready-present"]; !exists { + t.Fatal("healthy object was deleted") + } + if _, exists := objects.objects["attachments/ready-present-thumbnail"]; !exists { + t.Fatal("managed variant object was deleted as an orphan") + } + if _, exists := objects.objects["attachments/queued-old"]; !exists { + t.Fatal("active queued attachment object was deleted") + } + for _, issue := range applied.Issues { + if issue.AttachmentID == "ready-used-missing" && + (!issue.Protected || issue.Action != "manual_repair_required") { + t.Fatalf("referenced attachment was not protected: %+v", issue) + } + } + + repeated, err := reconciler.Run(context.Background(), time.Hour, true) + if err != nil { + t.Fatal(err) + } + if repeated.DeletedObjects != 0 || repeated.FailedAttachments != 0 { + t.Fatalf("repeat must be mutation-idempotent: %+v", repeated) + } + if len(repeated.Issues) != 1 || !repeated.Issues[0].Protected { + t.Fatalf("repeat should retain only protected manual issue: %+v", repeated) + } +} + +func TestReconcilerReportsMutationFailures(t *testing.T) { + old := time.Now().UTC().Add(-2 * time.Hour) + metadata := &fakeMetadataStore{records: []AttachmentRecord{ + {ID: "missing", ObjectKey: "attachments/missing", Status: domain.AttachmentStatusReady, UpdatedAt: old}, + }} + metadata.markError = errors.New("injected database failure") + objects := &fakeObjectInventory{objects: make(map[string]objectstore.StoredObject)} + reconciler, err := New(metadata, objects) + if err != nil { + t.Fatal(err) + } + if _, err = reconciler.Run(context.Background(), time.Hour, true); err == nil { + t.Fatal("injected database mutation failure was hidden") + } + + metadata.records = nil + metadata.markError = nil + objects.objects["attachments/orphan"] = objectstore.StoredObject{ + Key: "attachments/orphan", LastModified: old, + } + objects.deleteError = errors.New("injected object-store failure") + if _, err = reconciler.Run(context.Background(), time.Hour, true); err == nil { + t.Fatal("injected object-store mutation failure was hidden") + } +} diff --git a/internal/security/client_mtls.go b/internal/security/client_mtls.go new file mode 100644 index 0000000..21838d4 --- /dev/null +++ b/internal/security/client_mtls.go @@ -0,0 +1,43 @@ +package security + +import ( + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "os" + "strings" +) + +// ClientMTLSConfig builds a TLS 1.3 client configuration with an explicit +// workload certificate. The service name is verified against the server +// certificate; neither InsecureSkipVerify nor the host trust store is used. +func ClientMTLSConfig(caFile, certFile, keyFile, serverName string) (*tls.Config, error) { + caFile = strings.TrimSpace(caFile) + certFile = strings.TrimSpace(certFile) + keyFile = strings.TrimSpace(keyFile) + serverName = strings.TrimSpace(serverName) + if caFile == "" || certFile == "" || keyFile == "" || serverName == "" { + return nil, errors.New("client CA, certificate, key, and server name are required") + } + + caPEM, err := os.ReadFile(caFile) + if err != nil { + return nil, fmt.Errorf("read client TLS CA: %w", err) + } + roots := x509.NewCertPool() + if !roots.AppendCertsFromPEM(caPEM) { + return nil, errors.New("client TLS CA file contains no certificate") + } + certificate, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return nil, fmt.Errorf("load client TLS identity: %w", err) + } + + return &tls.Config{ + MinVersion: tls.VersionTLS13, + RootCAs: roots, + Certificates: []tls.Certificate{certificate}, + ServerName: serverName, + }, nil +} diff --git a/internal/security/mtls.go b/internal/security/mtls.go new file mode 100644 index 0000000..402fa0b --- /dev/null +++ b/internal/security/mtls.go @@ -0,0 +1,64 @@ +package security + +import ( + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "os" + "strings" +) + +func ServerMTLSConfig(clientCAFile string, allowedClientURI string, allowedClientURIFile string) (*tls.Config, error) { + clientCAFile = strings.TrimSpace(clientCAFile) + allowedClientURI = strings.TrimSpace(allowedClientURI) + allowedClientURIFile = strings.TrimSpace(allowedClientURIFile) + if clientCAFile == "" || (allowedClientURI == "" && allowedClientURIFile == "") { + return nil, errors.New("TLS_CLIENT_CA_FILE and an allowed client URI source are required") + } + allowedClientURIs := make(map[string]struct{}) + if allowedClientURI != "" { + allowedClientURIs[allowedClientURI] = struct{}{} + } + if allowedClientURIFile != "" { + allowedPEM, readErr := os.ReadFile(allowedClientURIFile) + if readErr != nil { + return nil, fmt.Errorf("read allowed client URI file: %w", readErr) + } + for _, line := range strings.Split(string(allowedPEM), "\n") { + line = strings.TrimSpace(line) + if line != "" && !strings.HasPrefix(line, "#") { + allowedClientURIs[line] = struct{}{} + } + } + } + if len(allowedClientURIs) == 0 { + return nil, errors.New("allowed client URI set is empty") + } + caPEM, err := os.ReadFile(clientCAFile) + if err != nil { + return nil, fmt.Errorf("read client CA: %w", err) + } + clientRoots := x509.NewCertPool() + if !clientRoots.AppendCertsFromPEM(caPEM) { + return nil, errors.New("client CA file contains no certificate") + } + return &tls.Config{ + MinVersion: tls.VersionTLS13, + ClientAuth: tls.RequireAndVerifyClientCert, + ClientCAs: clientRoots, + NextProtos: []string{"h2", "http/1.1"}, + VerifyConnection: func(state tls.ConnectionState) error { + if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 { + return errors.New("verified client certificate is required") + } + leaf := state.PeerCertificates[0] + for _, identity := range leaf.URIs { + if _, allowed := allowedClientURIs[identity.String()]; allowed { + return nil + } + } + return fmt.Errorf("client certificate URI SAN is not allowed") + }, + }, nil +} diff --git a/internal/security/password.go b/internal/security/password.go new file mode 100644 index 0000000..42d3cf1 --- /dev/null +++ b/internal/security/password.go @@ -0,0 +1,225 @@ +package security + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "os" + "strconv" + "strings" + "unicode/utf8" + + "golang.org/x/crypto/argon2" +) + +const ( + defaultArgonMemory uint32 = 19 * 1024 + defaultArgonIterations uint32 = 2 + defaultArgonParallelism uint8 = 1 + argonSaltLength = 16 + argonKeyLength uint32 = 32 + + minPasswordLength = 12 + maxPasswordLength = 128 +) + +var ErrInvalidPasswordHash = errors.New("invalid password hash") + +func ValidatePassword(password string) error { + if !utf8.ValidString(password) { + return errors.New("password must be valid UTF-8") + } + + length := utf8.RuneCountInString(password) + if length < minPasswordLength || length > maxPasswordLength { + return fmt.Errorf( + "password length must be between %d and %d code points", + minPasswordLength, + maxPasswordLength, + ) + } + + return nil +} + +func HashPassword(password string) (string, error) { + if err := ValidatePassword(password); err != nil { + return "", err + } + parameters, err := passwordParametersFromEnvironment() + if err != nil { + return "", err + } + + salt := make([]byte, argonSaltLength) + if _, err = rand.Read(salt); err != nil { + return "", fmt.Errorf("generate password salt: %w", err) + } + + hash := argon2.IDKey( + []byte(password), + salt, + parameters.iterations, + parameters.memory, + parameters.parallelism, + argonKeyLength, + ) + + encodedSalt := base64.RawStdEncoding.EncodeToString(salt) + encodedHash := base64.RawStdEncoding.EncodeToString(hash) + + encoded := fmt.Sprintf( + "$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, + parameters.memory, + parameters.iterations, + parameters.parallelism, + encodedSalt, + encodedHash, + ) + + return encoded, nil +} + +func VerifyPassword( + password string, + encodedHash string, +) (bool, error) { + parameters, salt, expectedHash, err := decodePasswordHash(encodedHash) + if err != nil { + return false, err + } + + actualHash := argon2.IDKey( + []byte(password), + salt, + parameters.iterations, + parameters.memory, + parameters.parallelism, + uint32(len(expectedHash)), + ) + + matches := subtle.ConstantTimeCompare( + actualHash, + expectedHash, + ) == 1 + + return matches, nil +} + +// NeedsPasswordRehash reports whether a verified stored hash must be upgraded +// to the active Argon2id policy. Callers must verify the password first. +func NeedsPasswordRehash(encodedHash string) (bool, error) { + stored, salt, hash, err := decodePasswordHash(encodedHash) + if err != nil { + return false, err + } + active, err := passwordParametersFromEnvironment() + if err != nil { + return false, err + } + return stored != active || len(salt) != argonSaltLength || uint32(len(hash)) != argonKeyLength, nil +} + +type argonParameters struct { + memory uint32 + iterations uint32 + parallelism uint8 +} + +func passwordParametersFromEnvironment() (argonParameters, error) { + memory, err := boundedUint32Environment( + "ARGON2_MEMORY_KIB", defaultArgonMemory, defaultArgonMemory, 256*1024, + ) + if err != nil { + return argonParameters{}, err + } + iterations, err := boundedUint32Environment( + "ARGON2_ITERATIONS", defaultArgonIterations, defaultArgonIterations, 10, + ) + if err != nil { + return argonParameters{}, err + } + parallelism, err := boundedUint32Environment( + "ARGON2_PARALLELISM", uint32(defaultArgonParallelism), 1, 8, + ) + if err != nil { + return argonParameters{}, err + } + return argonParameters{ + memory: memory, iterations: iterations, parallelism: uint8(parallelism), + }, nil +} + +func boundedUint32Environment( + name string, + fallback uint32, + minimum uint32, + maximum uint32, +) (uint32, error) { + raw := strings.TrimSpace(os.Getenv(name)) + if raw == "" { + return fallback, nil + } + value, err := strconv.ParseUint(raw, 10, 32) + if err != nil || value < uint64(minimum) || value > uint64(maximum) { + return 0, fmt.Errorf("%s must be an integer from %d to %d", name, minimum, maximum) + } + return uint32(value), nil +} + +func decodePasswordHash( + encodedHash string, +) (argonParameters, []byte, []byte, error) { + parts := strings.Split(encodedHash, "$") + if len(parts) != 6 || + parts[0] != "" || + parts[1] != "argon2id" { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + var version int + if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + if version != argon2.Version { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + var parameters argonParameters + if _, err := fmt.Sscanf( + parts[3], + "m=%d,t=%d,p=%d", + ¶meters.memory, + ¶meters.iterations, + ¶meters.parallelism, + ); err != nil { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + // Ограничения не позволяют повреждённой строке из БД запросить + // гигантский объём памяти или процессорного времени. + if parameters.memory < 8*1024 || + parameters.memory > 256*1024 || + parameters.iterations < 1 || + parameters.iterations > 10 || + parameters.parallelism < 1 || + parameters.parallelism > 8 { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + salt, err := base64.RawStdEncoding.DecodeString(parts[4]) + if err != nil || len(salt) < 16 || len(salt) > 64 { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + hash, err := base64.RawStdEncoding.DecodeString(parts[5]) + if err != nil || len(hash) < 16 || len(hash) > 64 { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + return parameters, salt, hash, nil +} diff --git a/internal/security/password_test.go b/internal/security/password_test.go new file mode 100644 index 0000000..5df3d5a --- /dev/null +++ b/internal/security/password_test.go @@ -0,0 +1,159 @@ +package security + +import ( + "strings" + "testing" +) + +func BenchmarkHashPasswordGrade3(b *testing.B) { + const password = "benchmark-password-123" + for index := 0; index < b.N; index++ { + if _, err := HashPassword(password); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkVerifyPasswordGrade4(b *testing.B) { + const password = "benchmark-password-123" + encodedHash, err := HashPassword(password) + if err != nil { + b.Fatal(err) + } + b.ResetTimer() + for index := 0; index < b.N; index++ { + matches, verifyErr := VerifyPassword(password, encodedHash) + if verifyErr != nil || !matches { + b.Fatalf("verify failed: matches=%v err=%v", matches, verifyErr) + } + } +} + +func TestHashPasswordRejectsWeakConfiguredCost(t *testing.T) { + t.Setenv("ARGON2_MEMORY_KIB", "8192") + if _, err := HashPassword("valid-password-123"); err == nil { + t.Fatal("HashPassword accepted memory below the lab7 minimum") + } +} + +func TestPasswordHashAndVerify(t *testing.T) { + password := "Correct-password-123" + + encodedHash, err := HashPassword(password) + if err != nil { + t.Fatalf("HashPassword returned error: %v", err) + } + + if strings.Contains(encodedHash, password) { + t.Fatal("encoded hash contains plaintext password") + } + + matches, err := VerifyPassword(password, encodedHash) + if err != nil { + t.Fatalf("VerifyPassword returned error: %v", err) + } + if !matches { + t.Fatal("correct password did not match") + } + + matches, err = VerifyPassword("Wrong-password-123", encodedHash) + if err != nil { + t.Fatalf("VerifyPassword returned error: %v", err) + } + if matches { + t.Fatal("wrong password matched") + } +} + +func TestPasswordHashesUseDifferentSalts(t *testing.T) { + password := "Correct-password-123" + + firstHash, err := HashPassword(password) + if err != nil { + t.Fatalf("first HashPassword returned error: %v", err) + } + + secondHash, err := HashPassword(password) + if err != nil { + t.Fatalf("second HashPassword returned error: %v", err) + } + + if firstHash == secondHash { + t.Fatal("equal passwords produced equal encoded hashes") + } +} + +func TestPasswordValidation(t *testing.T) { + testCases := []struct { + name string + password string + wantErr bool + }{ + { + name: "minimum length", + password: "123456789012", + wantErr: false, + }, + { + name: "unicode", + password: "пароль-проверка-123", + wantErr: false, + }, + { + name: "colon is allowed", + password: "password:with:colon", + wantErr: false, + }, + { + name: "too short", + password: "short", + wantErr: true, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + err := ValidatePassword(testCase.password) + + if testCase.wantErr && err == nil { + t.Fatal("expected validation error") + } + if !testCase.wantErr && err != nil { + t.Fatalf("unexpected validation error: %v", err) + } + }) + } +} + +func TestMalformedPasswordHash(t *testing.T) { + _, err := VerifyPassword( + "Correct-password-123", + "not-an-argon2-hash", + ) + if err == nil { + t.Fatal("expected malformed hash error") + } +} + +func TestNeedsPasswordRehash(t *testing.T) { + currentHash, err := HashPassword("Correct-password-123") + if err != nil { + t.Fatal(err) + } + needsRehash, err := NeedsPasswordRehash(currentHash) + if err != nil { + t.Fatal(err) + } + if needsRehash { + t.Fatal("current policy hash unexpectedly requires rehash") + } + + legacyHash := strings.Replace(currentHash, "m=19456,t=2,p=1", "m=8192,t=2,p=1", 1) + needsRehash, err = NeedsPasswordRehash(legacyHash) + if err != nil { + t.Fatal(err) + } + if !needsRehash { + t.Fatal("legacy policy hash was not marked for rehash") + } +} diff --git a/internal/security/token.go b/internal/security/token.go new file mode 100644 index 0000000..aae7300 --- /dev/null +++ b/internal/security/token.go @@ -0,0 +1,32 @@ +package security + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "fmt" +) + +const sessionTokenBytes = 32 + +func GenerateSessionToken() (string, []byte, error) { + randomBytes := make([]byte, sessionTokenBytes) + + if _, err := rand.Read(randomBytes); err != nil { + return "", nil, fmt.Errorf("generate session token: %w", err) + } + + token := base64.RawURLEncoding.EncodeToString(randomBytes) + tokenHash := HashSessionToken(token) + + return token, tokenHash, nil +} + +func HashSessionToken(token string) []byte { + digest := sha256.Sum256([]byte(token)) + + hash := make([]byte, len(digest)) + copy(hash, digest[:]) + + return hash +} diff --git a/internal/security/token_test.go b/internal/security/token_test.go new file mode 100644 index 0000000..14e2ecf --- /dev/null +++ b/internal/security/token_test.go @@ -0,0 +1,35 @@ +package security + +import ( + "bytes" + "testing" +) + +func TestGenerateSessionToken(t *testing.T) { + firstToken, firstHash, err := GenerateSessionToken() + if err != nil { + t.Fatalf("GenerateSessionToken returned error: %v", err) + } + + secondToken, secondHash, err := GenerateSessionToken() + if err != nil { + t.Fatalf("GenerateSessionToken returned error: %v", err) + } + + if firstToken == secondToken { + t.Fatal("generated session tokens are equal") + } + + if bytes.Equal(firstHash, secondHash) { + t.Fatal("generated session token hashes are equal") + } + + if len(firstHash) != 32 { + t.Fatalf("expected 32-byte token hash, got %d", len(firstHash)) + } + + recalculatedHash := HashSessionToken(firstToken) + if !bytes.Equal(firstHash, recalculatedHash) { + t.Fatal("token hash is not reproducible") + } +} diff --git a/internal/telemetry/jobs.go b/internal/telemetry/jobs.go new file mode 100644 index 0000000..99b8084 --- /dev/null +++ b/internal/telemetry/jobs.go @@ -0,0 +1,173 @@ +package telemetry + +import ( + "context" + "fmt" + "sync/atomic" + "time" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/trace" +) + +type JobRecorder struct { + runtime *Runtime + processed metric.Int64Counter + duration metric.Float64Histogram + readyDuration metric.Float64Histogram + busy atomic.Int64 + capacity int64 +} + +type JobAttempt struct { + recorder *JobRecorder + ctx context.Context + span trace.Span + started time.Time + createdAt time.Time + jobType string + attempt int + ended atomic.Bool +} + +func NewJobRecorder(runtime *Runtime, capacity int) (*JobRecorder, error) { + if capacity < 1 { + return nil, fmt.Errorf("worker capacity must be positive") + } + processed, err := runtime.Meter.Int64Counter( + "messenger.worker.jobs", + metric.WithDescription("Number of completed worker processing attempts"), + metric.WithUnit("{job}"), + ) + if err != nil { + return nil, fmt.Errorf("create worker jobs counter: %w", err) + } + duration, err := runtime.Meter.Float64Histogram( + "messenger.worker.job.duration", + metric.WithDescription("Worker processing attempt duration"), + metric.WithUnit("s"), + ) + if err != nil { + return nil, fmt.Errorf("create worker duration histogram: %w", err) + } + readyDuration, err := runtime.Meter.Float64Histogram( + "messenger.attachment.ready.duration", + metric.WithDescription("Time from durable acceptance until attachment ready"), + metric.WithUnit("s"), + ) + if err != nil { + return nil, fmt.Errorf("create attachment ready duration histogram: %w", err) + } + busy, err := runtime.Meter.Int64ObservableGauge( + "messenger.worker.busy", + metric.WithDescription("Number of workers processing jobs"), + ) + if err != nil { + return nil, fmt.Errorf("create worker busy metric: %w", err) + } + workerCapacity, err := runtime.Meter.Int64ObservableGauge( + "messenger.worker.capacity", + metric.WithDescription("Configured worker processing capacity"), + ) + if err != nil { + return nil, fmt.Errorf("create worker capacity metric: %w", err) + } + recorder := &JobRecorder{ + runtime: runtime, + processed: processed, + duration: duration, + readyDuration: readyDuration, + capacity: int64(capacity), + } + _, err = runtime.Meter.RegisterCallback( + func(ctx context.Context, observer metric.Observer) error { + observer.ObserveInt64(busy, recorder.busy.Load()) + observer.ObserveInt64(workerCapacity, recorder.capacity) + return nil + }, + busy, + workerCapacity, + ) + if err != nil { + return nil, fmt.Errorf("register worker saturation metrics: %w", err) + } + return recorder, nil +} + +func (recorder *JobRecorder) Start( + ctx context.Context, + jobType string, + destination string, + attempt int, + createdAt time.Time, +) (context.Context, *JobAttempt) { + ctx, span := recorder.runtime.Tracer.Start( + ctx, + "attachment.process", + trace.WithSpanKind(trace.SpanKindConsumer), + trace.WithAttributes( + attribute.String("messaging.system", "rabbitmq"), + attribute.String("messaging.destination.name", destination), + attribute.String("messaging.operation.name", "process"), + attribute.String("job.type", jobType), + attribute.Int("job.attempt", attempt), + ), + ) + recorder.busy.Add(1) + return ctx, &JobAttempt{ + recorder: recorder, + ctx: ctx, + span: span, + started: time.Now(), + createdAt: createdAt, + jobType: jobType, + attempt: attempt, + } +} + +func (attempt *JobAttempt) End(processErr error) { + if !attempt.ended.CompareAndSwap(false, true) { + return + } + defer attempt.recorder.busy.Add(-1) + elapsed := time.Since(attempt.started) + outcome := "succeeded" + event := "attachment_job_completed" + if processErr != nil { + outcome = "failed" + event = "attachment_job_failed" + attempt.span.SetStatus(codes.Error, "job processing failed") + } else { + attempt.span.SetStatus(codes.Ok, "") + } + labels := metric.WithAttributes( + attribute.String("job_type", attempt.jobType), + attribute.String("outcome", outcome), + ) + attempt.recorder.processed.Add(attempt.ctx, 1, labels) + attempt.recorder.duration.Record(attempt.ctx, elapsed.Seconds(), labels) + if processErr == nil && !attempt.createdAt.IsZero() { + readySeconds := time.Since(attempt.createdAt).Seconds() + if readySeconds >= 0 { + attempt.recorder.readyDuration.Record( + attempt.ctx, + readySeconds, + metric.WithAttributes(attribute.String("job_type", attempt.jobType)), + ) + } + } + fields := Fields{ + "job_type": attempt.jobType, + "outcome": outcome, + "attempt": attempt.attempt, + "duration_ms": float64(elapsed.Microseconds()) / 1000, + } + if processErr != nil { + attempt.recorder.runtime.Logger.Warn(attempt.ctx, event, fields) + } else { + attempt.recorder.runtime.Logger.Info(attempt.ctx, event, fields) + } + attempt.span.End() +} diff --git a/internal/telemetry/logger.go b/internal/telemetry/logger.go new file mode 100644 index 0000000..7c693f7 --- /dev/null +++ b/internal/telemetry/logger.go @@ -0,0 +1,109 @@ +package telemetry + +import ( + "context" + "encoding/json" + "fmt" + "os" + "sync" + "time" + + "go.opentelemetry.io/otel/attribute" + otellog "go.opentelemetry.io/otel/log" + "go.opentelemetry.io/otel/trace" +) + +type Fields map[string]any + +type Logger struct { + logger otellog.Logger + serviceName string + instanceID string +} + +var stdoutMu sync.Mutex + +func NewLogger(logger otellog.Logger, serviceName, instanceID string) *Logger { + return &Logger{logger: logger, serviceName: serviceName, instanceID: instanceID} +} + +func (logger *Logger) Info(ctx context.Context, event string, fields Fields) { + logger.emit(ctx, otellog.SeverityInfo, "INFO", event, fields) +} + +func (logger *Logger) Warn(ctx context.Context, event string, fields Fields) { + logger.emit(ctx, otellog.SeverityWarn, "WARN", event, fields) +} + +func (logger *Logger) emit( + ctx context.Context, + severity otellog.Severity, + severityText string, + event string, + fields Fields, +) { + now := time.Now().UTC() + spanContext := trace.SpanContextFromContext(ctx) + traceID := "" + spanID := "" + if spanContext.IsValid() { + traceID = spanContext.TraceID().String() + spanID = spanContext.SpanID().String() + } + + line := map[string]any{ + "timestamp": now.Format(time.RFC3339Nano), + "severity": severityText, + "service.name": logger.serviceName, + "service.instance.id": logger.instanceID, + "event": event, + "trace_id": traceID, + "span_id": spanID, + } + attributes := []attribute.KeyValue{ + attribute.String("event", event), + attribute.String("trace_id", traceID), + attribute.String("span_id", spanID), + } + for key, value := range fields { + if _, protected := line[key]; protected { + continue + } + line[key] = value + attributes = append(attributes, logAttribute(key, value)) + } + + encoded, err := json.Marshal(line) + if err == nil { + stdoutMu.Lock() + _, _ = fmt.Fprintln(os.Stdout, string(encoded)) + stdoutMu.Unlock() + } + + var record otellog.Record + record.SetTimestamp(now) + record.SetObservedTimestamp(now) + record.SetSeverity(severity) + record.SetSeverityText(severityText) + record.SetEventName(event) + record.SetBody(attribute.StringValue(event)) + record.AddAttributes(attributes...) + logger.logger.Emit(ctx, record) +} + +func logAttribute(key string, value any) attribute.KeyValue { + switch typed := value.(type) { + case string: + return attribute.String(key, typed) + case int: + return attribute.Int(key, typed) + case int64: + return attribute.Int64(key, typed) + case float64: + return attribute.Float64(key, typed) + case bool: + return attribute.Bool(key, typed) + default: + return attribute.String(key, fmt.Sprint(value)) + } +} diff --git a/internal/telemetry/metrics.go b/internal/telemetry/metrics.go new file mode 100644 index 0000000..2cf059e --- /dev/null +++ b/internal/telemetry/metrics.go @@ -0,0 +1,156 @@ +package telemetry + +import ( + "context" + "fmt" + "os" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/pgxpool" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" +) + +func registerProcessMetrics(meter metric.Meter) error { + cpu, err := meter.Float64ObservableCounter( + "messenger.process.cpu.time", + metric.WithDescription("CPU time consumed by the process"), + metric.WithUnit("s"), + ) + if err != nil { + return fmt.Errorf("create process CPU metric: %w", err) + } + memory, err := meter.Int64ObservableGauge( + "messenger.process.memory", + metric.WithDescription("Resident memory used by the process"), + metric.WithUnit("By"), + ) + if err != nil { + return fmt.Errorf("create process memory metric: %w", err) + } + _, err = meter.RegisterCallback( + func(ctx context.Context, observer metric.Observer) error { + if seconds, readErr := processCPUSeconds(); readErr == nil { + observer.ObserveFloat64(cpu, seconds) + } + if bytes, readErr := processResidentBytes(); readErr == nil { + observer.ObserveInt64(memory, bytes) + } + return nil + }, + cpu, + memory, + ) + if err != nil { + return fmt.Errorf("register process metrics: %w", err) + } + return nil +} + +func processCPUSeconds() (float64, error) { + data, err := os.ReadFile("/proc/self/schedstat") + if err != nil { + return 0, err + } + fields := strings.Fields(string(data)) + if len(fields) < 1 { + return 0, fmt.Errorf("invalid /proc/self/schedstat") + } + nanoseconds, err := strconv.ParseUint(fields[0], 10, 64) + if err != nil { + return 0, err + } + return float64(nanoseconds) / 1_000_000_000, nil +} + +func processResidentBytes() (int64, error) { + data, err := os.ReadFile("/proc/self/statm") + if err != nil { + return 0, err + } + fields := strings.Fields(string(data)) + if len(fields) < 2 { + return 0, fmt.Errorf("invalid /proc/self/statm") + } + pages, err := strconv.ParseInt(fields[1], 10, 64) + if err != nil { + return 0, err + } + return pages * int64(os.Getpagesize()), nil +} + +func RegisterDBPool(runtime *Runtime, pool *pgxpool.Pool) error { + connections, err := runtime.Meter.Int64ObservableGauge( + "messenger.db.pool.connections", + metric.WithDescription("PostgreSQL pool connections by state"), + ) + if err != nil { + return fmt.Errorf("create DB pool connection metric: %w", err) + } + waits, err := runtime.Meter.Int64ObservableCounter( + "messenger.db.pool.waits", + metric.WithDescription("Number of acquisitions that waited for a PostgreSQL connection"), + ) + if err != nil { + return fmt.Errorf("create DB pool wait metric: %w", err) + } + _, err = runtime.Meter.RegisterCallback( + func(ctx context.Context, observer metric.Observer) error { + stats := pool.Stat() + observer.ObserveInt64( + connections, + int64(stats.AcquiredConns()), + metric.WithAttributes(attribute.String("state", "used")), + ) + observer.ObserveInt64( + connections, + int64(stats.IdleConns()), + metric.WithAttributes(attribute.String("state", "idle")), + ) + observer.ObserveInt64( + connections, + int64(stats.MaxConns()), + metric.WithAttributes(attribute.String("state", "capacity")), + ) + observer.ObserveInt64(waits, stats.EmptyAcquireCount()) + return nil + }, + connections, + waits, + ) + if err != nil { + return fmt.Errorf("register DB pool metrics: %w", err) + } + return nil +} + +type QueueRecorder struct { + depth metric.Int64Gauge + age metric.Float64Gauge +} + +func NewQueueRecorder(runtime *Runtime) (*QueueRecorder, error) { + depth, err := runtime.Meter.Int64Gauge( + "messenger.queue.depth", + metric.WithDescription("Number of queued attachment jobs"), + ) + if err != nil { + return nil, fmt.Errorf("create queue depth metric: %w", err) + } + age, err := runtime.Meter.Float64Gauge( + "messenger.queue.oldest_job_age", + metric.WithDescription("Age of the oldest queued attachment job"), + metric.WithUnit("s"), + ) + if err != nil { + return nil, fmt.Errorf("create queue age metric: %w", err) + } + return &QueueRecorder{depth: depth, age: age}, nil +} + +func (recorder *QueueRecorder) Record(ctx context.Context, depth int64, ageSeconds float64) { + labels := metric.WithAttributes(attribute.String("queue", "attachment.process.v1")) + recorder.depth.Record(ctx, depth, labels) + recorder.age.Record(ctx, ageSeconds, labels) +} diff --git a/internal/telemetry/runtime.go b/internal/telemetry/runtime.go new file mode 100644 index 0000000..3e0cf66 --- /dev/null +++ b/internal/telemetry/runtime.go @@ -0,0 +1,183 @@ +package telemetry + +import ( + "context" + "errors" + "fmt" + "os" + "time" + + "mtusi2026lab7/internal/security" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp" + "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" + otellogglobal "go.opentelemetry.io/otel/log/global" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/propagation" + sdklog "go.opentelemetry.io/otel/sdk/log" + sdkmetric "go.opentelemetry.io/otel/sdk/metric" + "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" +) + +const ( + ServiceVersion = "6.0.0" + instrumentationScope = "mtusi2026lab7" +) + +type Runtime struct { + Tracer trace.Tracer + Meter metric.Meter + Logger *Logger + + tracerProvider *sdktrace.TracerProvider + meterProvider *sdkmetric.MeterProvider + loggerProvider *sdklog.LoggerProvider +} + +func Start( + ctx context.Context, + serviceName string, + instanceID string, + deploymentEnvironment string, +) (*Runtime, error) { + serverName := os.Getenv("OTEL_TLS_SERVER_NAME") + if serverName == "" { + serverName = "telemetry-gateway" + } + clientTLS, err := security.ClientMTLSConfig( + os.Getenv("CLIENT_TLS_CA_FILE"), + os.Getenv("CLIENT_TLS_CERT_FILE"), + os.Getenv("CLIENT_TLS_KEY_FILE"), + serverName, + ) + if err != nil { + return nil, fmt.Errorf("configure OpenTelemetry mTLS: %w", err) + } + + res, err := resource.New(ctx, resource.WithAttributes( + attribute.String("service.name", serviceName), + attribute.String("service.version", ServiceVersion), + attribute.String("service.instance.id", instanceID), + attribute.String("deployment.environment.name", deploymentEnvironment), + )) + if err != nil { + return nil, fmt.Errorf("create OpenTelemetry resource: %w", err) + } + + traceExporter, err := otlptracehttp.New(ctx, + otlptracehttp.WithTimeout(3*time.Second), + otlptracehttp.WithTLSClientConfig(clientTLS.Clone()), + ) + if err != nil { + return nil, fmt.Errorf("create OTLP trace exporter: %w", err) + } + tracerProvider := sdktrace.NewTracerProvider( + sdktrace.WithResource(res), + sdktrace.WithBatcher( + traceExporter, + sdktrace.WithBatchTimeout(time.Second), + sdktrace.WithExportTimeout(3*time.Second), + sdktrace.WithMaxQueueSize(2048), + sdktrace.WithMaxExportBatchSize(256), + ), + ) + + metricExporter, err := otlpmetrichttp.New(ctx, + otlpmetrichttp.WithTimeout(3*time.Second), + otlpmetrichttp.WithTLSClientConfig(clientTLS.Clone()), + ) + if err != nil { + _ = tracerProvider.Shutdown(context.Background()) + return nil, fmt.Errorf("create OTLP metric exporter: %w", err) + } + metricReader := sdkmetric.NewPeriodicReader( + metricExporter, + sdkmetric.WithInterval(5*time.Second), + sdkmetric.WithTimeout(3*time.Second), + ) + meterProvider := sdkmetric.NewMeterProvider( + sdkmetric.WithResource(res), + sdkmetric.WithReader(metricReader), + sdkmetric.WithView(durationHistogramView( + "messenger.http.server.duration", + []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}, + )), + sdkmetric.WithView(durationHistogramView( + "messenger.worker.job.duration", + []float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60}, + )), + sdkmetric.WithView(durationHistogramView( + "messenger.attachment.ready.duration", + []float64{0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120}, + )), + ) + + logExporter, err := otlploghttp.New(ctx, + otlploghttp.WithTimeout(3*time.Second), + otlploghttp.WithTLSClientConfig(clientTLS.Clone()), + ) + if err != nil { + _ = meterProvider.Shutdown(context.Background()) + _ = tracerProvider.Shutdown(context.Background()) + return nil, fmt.Errorf("create OTLP log exporter: %w", err) + } + loggerProvider := sdklog.NewLoggerProvider( + sdklog.WithResource(res), + sdklog.WithAttributeCountLimit(32), + sdklog.WithAttributeValueLengthLimit(1024), + sdklog.WithProcessor(sdklog.NewBatchProcessor( + logExporter, + sdklog.WithMaxQueueSize(2048), + sdklog.WithExportMaxBatchSize(256), + sdklog.WithExportInterval(time.Second), + sdklog.WithExportTimeout(3*time.Second), + )), + ) + + otel.SetTracerProvider(tracerProvider) + otel.SetMeterProvider(meterProvider) + otellogglobal.SetLoggerProvider(loggerProvider) + otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator( + propagation.TraceContext{}, + propagation.Baggage{}, + )) + + runtime := &Runtime{ + Tracer: tracerProvider.Tracer(instrumentationScope), + Meter: meterProvider.Meter(instrumentationScope), + Logger: NewLogger(otellogglobal.Logger(instrumentationScope), serviceName, instanceID), + tracerProvider: tracerProvider, + meterProvider: meterProvider, + loggerProvider: loggerProvider, + } + if err = registerProcessMetrics(runtime.Meter); err != nil { + _ = runtime.Shutdown(context.Background()) + return nil, err + } + return runtime, nil +} + +func durationHistogramView(name string, boundaries []float64) sdkmetric.View { + return sdkmetric.NewView( + sdkmetric.Instrument{Name: name, Kind: sdkmetric.InstrumentKindHistogram}, + sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{ + Boundaries: boundaries, + }}, + ) +} + +func (runtime *Runtime) Shutdown(ctx context.Context) error { + if runtime == nil { + return nil + } + return errors.Join( + runtime.loggerProvider.Shutdown(ctx), + runtime.meterProvider.Shutdown(ctx), + runtime.tracerProvider.Shutdown(ctx), + ) +} diff --git a/internal/transport/http/dto/attachment.go b/internal/transport/http/dto/attachment.go new file mode 100644 index 0000000..7830900 --- /dev/null +++ b/internal/transport/http/dto/attachment.go @@ -0,0 +1,59 @@ +package dto + +import ( + "time" + + "mtusi2026lab7/internal/domain" +) + +type AttachmentVariantResponse struct { + Name string `json:"name"` + ContentType string `json:"content_type"` + SizeBytes int64 `json:"size_bytes"` + Width int `json:"width"` + Height int `json:"height"` + SHA256 string `json:"sha256"` +} + +type AttachmentResponse struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + OwnerID string `json:"owner_id"` + Filename string `json:"filename"` + ContentType string `json:"content_type"` + SizeBytes int64 `json:"size_bytes"` + SHA256 string `json:"sha256"` + Status domain.AttachmentStatus `json:"status"` + Variants []AttachmentVariantResponse `json:"variants"` + ErrorCode *string `json:"error_code"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +func AttachmentFromDomain(attachment domain.Attachment) AttachmentResponse { + variants := make([]AttachmentVariantResponse, 0, len(attachment.Variants)) + for _, variant := range attachment.Variants { + variants = append(variants, AttachmentVariantResponse{ + Name: variant.Name, + ContentType: variant.ContentType, + SizeBytes: variant.SizeBytes, + Width: variant.Width, + Height: variant.Height, + SHA256: variant.SHA256, + }) + } + return AttachmentResponse{ + ID: attachment.ID, + ChatID: attachment.ChatID, + OwnerID: attachment.OwnerID, + Filename: attachment.Filename, + ContentType: attachment.ContentType, + SizeBytes: attachment.SizeBytes, + SHA256: attachment.SHA256, + Status: attachment.Status, + Variants: variants, + ErrorCode: attachment.ErrorCode, + CreatedAt: attachment.CreatedAt, + UpdatedAt: attachment.UpdatedAt, + } +} diff --git a/internal/transport/http/dto/chat.go b/internal/transport/http/dto/chat.go new file mode 100644 index 0000000..dc44bc8 --- /dev/null +++ b/internal/transport/http/dto/chat.go @@ -0,0 +1,38 @@ +package dto + +import ( + "time" + + "mtusi2026lab7/internal/domain" +) + +type CreateChatRequest struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` +} + +type ChatResponse struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type ChatPageResponse struct { + Items []ChatResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func ChatFromDomain(chat domain.Chat) ChatResponse { + return ChatResponse{ + ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt, + } +} + +func ChatPageFromDomain(page domain.ChatPage) ChatPageResponse { + items := make([]ChatResponse, len(page.Items)) + for index, chat := range page.Items { + items[index] = ChatFromDomain(chat) + } + return ChatPageResponse{Items: items, NextCursor: page.NextCursor} +} diff --git a/internal/transport/http/dto/message.go b/internal/transport/http/dto/message.go new file mode 100644 index 0000000..742b4fa --- /dev/null +++ b/internal/transport/http/dto/message.go @@ -0,0 +1,46 @@ +package dto + +import ( + "time" + + "mtusi2026lab7/internal/domain" +) + +type CreateMessageRequest struct { + Text string `json:"text"` + AttachmentIDs []string `json:"attachment_ids"` +} + +type MessageResponse struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + AttachmentIDs []string `json:"attachment_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type MessagePageResponse struct { + Items []MessageResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func MessageFromDomain(message domain.Message) MessageResponse { + attachmentIDs := append([]string(nil), message.AttachmentIDs...) + if attachmentIDs == nil { + attachmentIDs = make([]string, 0) + } + + return MessageResponse{ + ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID, + Text: message.Text, AttachmentIDs: attachmentIDs, CreatedAt: message.CreatedAt, + } +} + +func MessagePageFromDomain(page domain.MessagePage) MessagePageResponse { + items := make([]MessageResponse, len(page.Items)) + for index, message := range page.Items { + items[index] = MessageFromDomain(message) + } + return MessagePageResponse{Items: items, NextCursor: page.NextCursor} +} diff --git a/internal/transport/http/dto/session.go b/internal/transport/http/dto/session.go new file mode 100644 index 0000000..589386c --- /dev/null +++ b/internal/transport/http/dto/session.go @@ -0,0 +1,21 @@ +package dto + +import ( + "time" + + "mtusi2026lab7/internal/domain" +) + +type SessionResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User UserResponse `json:"user"` +} + +func SessionFromDomain(session domain.Session) SessionResponse { + return SessionResponse{ + Token: session.Token, TokenType: session.TokenType, ExpiresAt: session.ExpiresAt, + User: UserFromDomain(session.User), + } +} diff --git a/internal/transport/http/dto/user.go b/internal/transport/http/dto/user.go new file mode 100644 index 0000000..99daa95 --- /dev/null +++ b/internal/transport/http/dto/user.go @@ -0,0 +1,26 @@ +package dto + +import ( + "time" + + "mtusi2026lab7/internal/domain" +) + +type CreateUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` +} + +type UserResponse struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +func UserFromDomain(user domain.User) UserResponse { + return UserResponse{ + ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: user.CreatedAt, + } +} diff --git a/internal/transport/http/handlers/create_chat.go b/internal/transport/http/handlers/create_chat.go new file mode 100644 index 0000000..03429ab --- /dev/null +++ b/internal/transport/http/handlers/create_chat.go @@ -0,0 +1,44 @@ +package handlers + +import ( + "errors" + "net/http" + "strings" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" +) + +func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + var request dto.CreateChatRequest + if err := decodeJSON(r, &request); err != nil { + writeDecodeJSONError(w, requestID, err) + return + } + + chat, err := h.service.CreateChat(r.Context(), application.CreateChatCommand{ + ActorID: currentUser.ID, Title: request.Title, MemberIDs: request.MemberIDs, + }) + if errors.Is(err, application.ErrInvalidInput) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID) + return + } + if errors.Is(err, domain.ErrNotFound) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "one or more members do not exist", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusCreated, dto.ChatFromDomain(chat), requestID) +} diff --git a/internal/transport/http/handlers/create_message.go b/internal/transport/http/handlers/create_message.go new file mode 100644 index 0000000..b050cba --- /dev/null +++ b/internal/transport/http/handlers/create_message.go @@ -0,0 +1,77 @@ +package handlers + +import ( + "errors" + "net/http" + "regexp" + "strings" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" + + "github.com/google/uuid" +) + +var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + parsedChatID, err := uuid.Parse(r.PathValue("chat_id")) + if err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "invalid chat_id uuid", requestID) + return + } + chatID := parsedChatID.String() + + idempotencyKey := r.Header.Get("Idempotency-Key") + if !idempotencyKeyPattern.MatchString(idempotencyKey) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "Idempotency-Key must match [A-Za-z0-9._:-]{1,128}", requestID) + return + } + + var request dto.CreateMessageRequest + if err := decodeJSON(r, &request); err != nil { + writeDecodeJSONError(w, requestID, err) + return + } + message, err := h.service.SendMessage(r.Context(), application.SendMessageCommand{ + ActorID: currentUser.ID, + ChatID: chatID, + Text: request.Text, + AttachmentIDs: request.AttachmentIDs, + Method: http.MethodPost, + CanonicalPath: "/api/v1/chats/" + chatID + "/messages", + IdempotencyKey: idempotencyKey, + }) + if errors.Is(err, application.ErrIdempotencyConflict) { + response.WriteError(w, http.StatusConflict, response.CodeConflict, + "Idempotency-Key is already used for another request", requestID) + return + } + if errors.Is(err, application.ErrAttachmentNotReady) { + response.WriteError(w, http.StatusConflict, response.CodeConflict, + "attachment is not ready", requestID) + return + } + if errors.Is(err, application.ErrInvalidInput) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID) + return + } + if errors.Is(err, domain.ErrNotFound) { + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusCreated, dto.MessageFromDomain(message), requestID) +} diff --git a/internal/transport/http/handlers/delete_session.go b/internal/transport/http/handlers/delete_session.go new file mode 100644 index 0000000..b8e8379 --- /dev/null +++ b/internal/transport/http/handlers/delete_session.go @@ -0,0 +1,20 @@ +package handlers + +import ( + "net/http" + + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" +) + +func (h *Handler) DeleteCurrentSession(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + tokenHash := middleware.GetCurrentSessionTokenHash(r.Context()) + if err := h.service.DeleteSession(r.Context(), tokenHash); err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + h.clearSessionCookie(w) + response.WriteJSON(w, http.StatusNoContent, nil, requestID) +} diff --git a/internal/transport/http/handlers/get_attachment.go b/internal/transport/http/handlers/get_attachment.go new file mode 100644 index 0000000..cd9b436 --- /dev/null +++ b/internal/transport/http/handlers/get_attachment.go @@ -0,0 +1,94 @@ +package handlers + +import ( + "errors" + "io" + "mime" + "net/http" + "strconv" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" + + "github.com/google/uuid" +) + +func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + attachmentID, ok := parseAttachmentID(w, r, requestID) + if !ok { + return + } + + attachment, err := h.service.GetAttachment(r.Context(), attachmentID, currentUser.ID) + if errors.Is(err, domain.ErrNotFound) { + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, + "attachment not found", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusOK, dto.AttachmentFromDomain(attachment), requestID) +} + +func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + attachmentID, ok := parseAttachmentID(w, r, requestID) + if !ok { + return + } + + download, err := h.service.DownloadAttachment( + r.Context(), attachmentID, currentUser.ID, r.URL.Query().Get("variant"), + ) + switch { + case errors.Is(err, domain.ErrNotFound): + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, + "attachment or variant not found", requestID) + return + case errors.Is(err, application.ErrAttachmentNotReady): + response.WriteError(w, http.StatusConflict, response.CodeConflict, + "attachment is not ready", requestID) + return + case errors.Is(err, application.ErrStorageUnavailable): + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "object storage is temporarily unavailable", requestID) + return + case err != nil: + response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, + "unexpected internal error", requestID) + return + } + defer download.Body.Close() + + w.Header().Set("Content-Type", download.ContentType) + w.Header().Set("Content-Length", strconv.FormatInt(download.SizeBytes, 10)) + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Content-Disposition", mime.FormatMediaType( + "attachment", map[string]string{"filename": download.Filename}, + )) + w.WriteHeader(http.StatusOK) + _, _ = io.Copy(w, download.Body) +} + +func parseAttachmentID( + w http.ResponseWriter, + r *http.Request, + requestID string, +) (string, bool) { + parsedID, err := uuid.Parse(r.PathValue("attachment_id")) + if err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "invalid attachment_id uuid", requestID) + return "", false + } + return parsedID.String(), true +} diff --git a/internal/transport/http/handlers/get_chat.go b/internal/transport/http/handlers/get_chat.go new file mode 100644 index 0000000..4478827 --- /dev/null +++ b/internal/transport/http/handlers/get_chat.go @@ -0,0 +1,36 @@ +package handlers + +import ( + "errors" + "net/http" + + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" + + "github.com/google/uuid" +) + +func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "invalid chat_id uuid", requestID) + return + } + + chat, err := h.service.GetChat(r.Context(), currentUser.ID, chatID) + if errors.Is(err, domain.ErrNotFound) { + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusOK, dto.ChatFromDomain(chat), requestID) +} diff --git a/internal/transport/http/handlers/get_me.go b/internal/transport/http/handlers/get_me.go new file mode 100644 index 0000000..63ae2a6 --- /dev/null +++ b/internal/transport/http/handlers/get_me.go @@ -0,0 +1,15 @@ +package handlers + +import ( + "net/http" + + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" +) + +func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + response.WriteJSON(w, http.StatusOK, dto.UserFromDomain(currentUser), requestID) +} diff --git a/internal/transport/http/handlers/handler.go b/internal/transport/http/handlers/handler.go new file mode 100644 index 0000000..576271f --- /dev/null +++ b/internal/transport/http/handlers/handler.go @@ -0,0 +1,170 @@ +package handlers + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "mime" + "net/http" + "strings" + "time" + "unicode/utf8" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/transport/http/response" +) + +const maxJSONBodyBytes = 1 << 20 + +var ( + errUnsupportedMediaType = errors.New("unsupported media type") + errJSONBodyTooLarge = errors.New("JSON body exceeds 1 MiB") +) + +type ReadinessChecker interface { + Ping(ctx context.Context) error +} + +type LoginRateLimiter interface { + AllowLoginAttempt(context.Context, [32]byte, time.Time, time.Duration, int) (bool, time.Duration, error) + ResetLoginAttempts(context.Context, [32]byte) error +} + +type Option func(*Handler) + +type Handler struct { + service *application.Service + readinessChecker ReadinessChecker + readinessTimeout time.Duration + sessionCookieSecure bool + loginRateLimiter LoginRateLimiter + loginRateLimit int + loginRateWindow time.Duration +} + +func NewHandler( + service *application.Service, + options ...Option, +) *Handler { + handler := &Handler{ + service: service, + readinessTimeout: 2 * time.Second, + loginRateLimit: 5, + loginRateWindow: time.Minute, + } + + for _, option := range options { + option(handler) + } + + return handler +} + +func WithLoginRateLimit( + limiter LoginRateLimiter, + limit int, + window time.Duration, +) Option { + return func(handler *Handler) { + handler.loginRateLimiter = limiter + handler.loginRateLimit = limit + handler.loginRateWindow = window + } +} + +func WithReadiness( + checker ReadinessChecker, + timeout time.Duration, +) Option { + return func(handler *Handler) { + handler.readinessChecker = checker + handler.readinessTimeout = timeout + } +} + +func WithSessionCookieSecure(secure bool) Option { + return func(handler *Handler) { + handler.sessionCookieSecure = secure + } +} + +func decodeJSON(r *http.Request, destination any) error { + mediaType, parameters, err := mime.ParseMediaType( + r.Header.Get("Content-Type"), + ) + if err != nil || mediaType != "application/json" { + return errUnsupportedMediaType + } + if charset, exists := parameters["charset"]; exists && + !strings.EqualFold(charset, "utf-8") { + return errUnsupportedMediaType + } + + if r.Body == nil { + return errors.New("request body is empty") + } + defer r.Body.Close() + + payload, err := io.ReadAll(io.LimitReader( + r.Body, + maxJSONBodyBytes+1, + )) + if err != nil { + return errors.New("read request body") + } + if len(payload) > maxJSONBodyBytes { + return errJSONBodyTooLarge + } + if !utf8.Valid(payload) { + return errors.New("request body must be valid UTF-8") + } + + decoder := json.NewDecoder(bytes.NewReader(payload)) + decoder.DisallowUnknownFields() + + if err := decoder.Decode(destination); err != nil { + return err + } + + var extra json.RawMessage + if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { + return errors.New("extra data after JSON") + } + + return nil +} + +func writeDecodeJSONError( + w http.ResponseWriter, + requestID string, + err error, +) { + switch { + case errors.Is(err, errUnsupportedMediaType): + response.WriteError( + w, + http.StatusUnsupportedMediaType, + response.CodeUnsupportedMediaType, + "Content-Type must be application/json", + requestID, + ) + case errors.Is(err, errJSONBodyTooLarge): + response.WriteError( + w, + http.StatusRequestEntityTooLarge, + response.CodePayloadTooLarge, + err.Error(), + requestID, + ) + default: + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + "malformed or invalid JSON: "+err.Error(), + requestID, + ) + } +} diff --git a/internal/transport/http/handlers/handler_test.go b/internal/transport/http/handlers/handler_test.go new file mode 100644 index 0000000..36565d8 --- /dev/null +++ b/internal/transport/http/handlers/handler_test.go @@ -0,0 +1,23 @@ +package handlers + +import ( + "errors" + "net/http/httptest" + "strings" + "testing" +) + +func TestDecodeJSONRejectsBodyAboveOneMiB(t *testing.T) { + request := httptest.NewRequest( + "POST", + "/api/v1/users", + strings.NewReader(strings.Repeat(" ", maxJSONBodyBytes+1)), + ) + request.Header.Set("Content-Type", "application/json") + + var destination map[string]any + err := decodeJSON(request, &destination) + if !errors.Is(err, errJSONBodyTooLarge) { + t.Fatalf("expected errJSONBodyTooLarge, got %v", err) + } +} diff --git a/internal/transport/http/handlers/health.go b/internal/transport/http/handlers/health.go new file mode 100644 index 0000000..25d2603 --- /dev/null +++ b/internal/transport/http/handlers/health.go @@ -0,0 +1,62 @@ +package handlers + +import ( + "context" + "net/http" + + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" +) + +// HealthLive проверяет только то, что HTTP-процесс работает. +func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + response.WriteJSON( + w, + http.StatusOK, + map[string]string{"status": "ok"}, + requestID, + ) +} + +// HealthReady проверяет зависимости, без которых API не может обслуживать трафик. +func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + // Этот вариант сохраняет работоспособность изолированных unit-тестов, + // в которых PostgreSQL намеренно не создаётся. + if h.readinessChecker == nil { + response.WriteJSON( + w, + http.StatusOK, + map[string]string{"status": "ok"}, + requestID, + ) + return + } + + ctx, cancel := context.WithTimeout( + r.Context(), + h.readinessTimeout, + ) + defer cancel() + + if err := h.readinessChecker.Ping(ctx); err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is not ready", + requestID, + ) + return + } + + response.WriteJSON( + w, + http.StatusOK, + map[string]string{"status": "ok"}, + requestID, + ) +} diff --git a/internal/transport/http/handlers/list_chats.go b/internal/transport/http/handlers/list_chats.go new file mode 100644 index 0000000..f0fb7d7 --- /dev/null +++ b/internal/transport/http/handlers/list_chats.go @@ -0,0 +1,32 @@ +package handlers + +import ( + "errors" + "net/http" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" +) + +func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + limit, cursor, ok := parsePagination(w, r, requestID) + if !ok { + return + } + + page, err := h.service.ListChats(r.Context(), currentUser.ID, limit, cursor) + if errors.Is(err, application.ErrInvalidCursor) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid cursor", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusOK, dto.ChatPageFromDomain(page), requestID) +} diff --git a/internal/transport/http/handlers/list_messages.go b/internal/transport/http/handlers/list_messages.go new file mode 100644 index 0000000..38a381a --- /dev/null +++ b/internal/transport/http/handlers/list_messages.go @@ -0,0 +1,45 @@ +package handlers + +import ( + "errors" + "net/http" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" + + "github.com/google/uuid" +) + +func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "invalid chat_id uuid", requestID) + return + } + limit, cursor, ok := parsePagination(w, r, requestID) + if !ok { + return + } + + page, err := h.service.ListMessages(r.Context(), currentUser.ID, chatID, limit, cursor) + if errors.Is(err, domain.ErrNotFound) { + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID) + return + } + if errors.Is(err, application.ErrInvalidCursor) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid cursor", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusOK, dto.MessagePageFromDomain(page), requestID) +} diff --git a/internal/transport/http/handlers/pagination.go b/internal/transport/http/handlers/pagination.go new file mode 100644 index 0000000..6234996 --- /dev/null +++ b/internal/transport/http/handlers/pagination.go @@ -0,0 +1,29 @@ +package handlers + +import ( + "net/http" + "strconv" + + "mtusi2026lab7/internal/transport/http/response" +) + +func parsePagination(w http.ResponseWriter, r *http.Request, requestID string) (int, string, bool) { + query := r.URL.Query() + limit := 50 + if query.Has("limit") { + parsed, err := strconv.Atoi(query.Get("limit")) + if err != nil || parsed < 1 || parsed > 100 { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "limit must be an integer between 1 and 100", requestID) + return 0, "", false + } + limit = parsed + } + cursor := query.Get("cursor") + if query.Has("cursor") && cursor == "" { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "cursor must not be empty", requestID) + return 0, "", false + } + return limit, cursor, true +} diff --git a/internal/transport/http/handlers/session_cookie.go b/internal/transport/http/handlers/session_cookie.go new file mode 100644 index 0000000..78792fe --- /dev/null +++ b/internal/transport/http/handlers/session_cookie.go @@ -0,0 +1,39 @@ +package handlers + +import ( + "net/http" + "time" +) + +const sessionCookieName = "mtusi_session" + +func (h *Handler) setSessionCookie( + w http.ResponseWriter, + token string, + expiresAt time.Time, +) { + maxAge := int(time.Until(expiresAt).Seconds()) + if maxAge < 1 { + maxAge = 1 + } + + h.writeSessionCookie(w, token, expiresAt, maxAge) +} + +func (h *Handler) clearSessionCookie(w http.ResponseWriter) { + h.writeSessionCookie(w, "", time.Unix(1, 0).UTC(), -1) +} + +func (h *Handler) writeSessionCookie( + w http.ResponseWriter, + value string, + expiresAt time.Time, + maxAge int, +) { + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, Value: value, Path: "/", + Expires: expiresAt, MaxAge: maxAge, + HttpOnly: true, Secure: h.sessionCookieSecure, + SameSite: http.SameSiteStrictMode, + }) +} diff --git a/internal/transport/http/handlers/session_cookie_test.go b/internal/transport/http/handlers/session_cookie_test.go new file mode 100644 index 0000000..4ac601f --- /dev/null +++ b/internal/transport/http/handlers/session_cookie_test.go @@ -0,0 +1,61 @@ +package handlers + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestSessionCookieIsHardened(t *testing.T) { + handler := &Handler{sessionCookieSecure: true} + recorder := httptest.NewRecorder() + + handler.setSessionCookie( + recorder, + "secret-token", + time.Now().Add(time.Hour), + ) + + cookies := recorder.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("cookie count = %d, want 1", len(cookies)) + } + + cookie := cookies[0] + if cookie.Name != sessionCookieName || cookie.Value != "secret-token" { + t.Fatalf("unexpected cookie: %#v", cookie) + } + if cookie.Path != "/" || cookie.Domain != "" { + t.Fatalf("cookie scope = path %q domain %q", cookie.Path, cookie.Domain) + } + if !cookie.HttpOnly || !cookie.Secure { + t.Fatalf("cookie flags: HttpOnly=%v Secure=%v", cookie.HttpOnly, cookie.Secure) + } + if cookie.SameSite != http.SameSiteStrictMode { + t.Fatalf("SameSite = %v, want Strict", cookie.SameSite) + } + if cookie.MaxAge < 1 { + t.Fatalf("MaxAge = %d, want positive", cookie.MaxAge) + } +} + +func TestClearSessionCookieExpiresIt(t *testing.T) { + handler := &Handler{} + recorder := httptest.NewRecorder() + + handler.clearSessionCookie(recorder) + + cookies := recorder.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("cookie count = %d, want 1", len(cookies)) + } + + cookie := cookies[0] + if cookie.Value != "" || cookie.MaxAge != -1 { + t.Fatalf("clear cookie = value %q MaxAge %d", cookie.Value, cookie.MaxAge) + } + if !cookie.Expires.Before(time.Now()) { + t.Fatalf("clear cookie expiry %v is not in the past", cookie.Expires) + } +} diff --git a/internal/transport/http/handlers/sessions.go b/internal/transport/http/handlers/sessions.go new file mode 100644 index 0000000..4b88b28 --- /dev/null +++ b/internal/transport/http/handlers/sessions.go @@ -0,0 +1,113 @@ +package handlers + +import ( + "crypto/sha256" + "errors" + "math" + "net/http" + "strconv" + "strings" + "time" + "unicode/utf8" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" +) + +const basicChallenge = `Basic realm="messenger", charset="UTF-8"` + +func (h *Handler) CreateSession( + w http.ResponseWriter, + r *http.Request, +) { + requestID := middleware.GetRequestID(r.Context()) + + username, password, ok := r.BasicAuth() + if !ok || username == "" || + !utf8.ValidString(username) || !utf8.ValidString(password) { + writeBasicUnauthorized(w, requestID) + return + } + identifierHash := sha256.Sum256([]byte(strings.ToLower(username))) + if h.loginRateLimiter != nil { + allowed, retryAfter, err := h.loginRateLimiter.AllowLoginAttempt( + r.Context(), identifierHash, time.Now().UTC(), h.loginRateWindow, h.loginRateLimit, + ) + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + if !allowed { + seconds := int(math.Ceil(retryAfter.Seconds())) + if seconds < 1 { + seconds = 1 + } + w.Header().Set("Retry-After", strconv.Itoa(seconds)) + response.WriteError(w, http.StatusTooManyRequests, response.CodeRateLimited, + "too many login attempts", requestID) + return + } + } + + session, err := h.service.CreateSession(r.Context(), application.CreateSessionCommand{ + Username: username, + Password: password, + }) + if errors.Is(err, application.ErrCredentialState) { + response.WriteError( + w, + http.StatusInternalServerError, + response.CodeInternalError, + "service is temporarily unavailable", + requestID, + ) + return + } + if errors.Is(err, application.ErrInvalidCredentials) { + writeBasicUnauthorized(w, requestID) + return + } + if err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + requestID, + ) + return + } + if h.loginRateLimiter != nil { + if err = h.loginRateLimiter.ResetLoginAttempts(r.Context(), identifierHash); err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + } + + h.setSessionCookie(w, session.Token, session.ExpiresAt) + + response.WriteJSON( + w, + http.StatusCreated, + dto.SessionFromDomain(session), + requestID, + ) +} +func writeBasicUnauthorized( + w http.ResponseWriter, + requestID string, +) { + w.Header().Set("WWW-Authenticate", basicChallenge) + + response.WriteError( + w, + http.StatusUnauthorized, + response.CodeUnauthorized, + "invalid username or password", + requestID, + ) +} diff --git a/internal/transport/http/handlers/upload_attachment.go b/internal/transport/http/handlers/upload_attachment.go new file mode 100644 index 0000000..b5b078e --- /dev/null +++ b/internal/transport/http/handlers/upload_attachment.go @@ -0,0 +1,97 @@ +package handlers + +import ( + "errors" + "mime" + "net/http" + "strings" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" + + "github.com/google/uuid" +) + +func (h *Handler) UploadAttachment(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + parsedChatID, err := uuid.Parse(r.PathValue("chat_id")) + if err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "invalid chat_id uuid", requestID) + return + } + filename := r.URL.Query().Get("filename") + if filename == "" { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "filename query parameter is required", requestID) + return + } + + contentType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || len(parameters) != 0 || + (contentType != "image/png" && contentType != "image/jpeg") { + response.WriteError(w, http.StatusUnsupportedMediaType, + response.CodeUnsupportedMediaType, + "Content-Type must be image/png or image/jpeg", requestID) + return + } + if r.ContentLength > domain.MaxAttachmentSizeBytes { + response.WriteError(w, http.StatusRequestEntityTooLarge, + response.CodePayloadTooLarge, + "attachment exceeds 10 MiB", requestID) + return + } + if r.Body == nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "attachment body is required", requestID) + return + } + defer r.Body.Close() + + attachment, err := h.service.UploadAttachment( + r.Context(), + application.UploadAttachmentCommand{ + ActorID: currentUser.ID, + ChatID: parsedChatID.String(), + Filename: filename, + DeclaredContentType: contentType, + Body: r.Body, + }, + ) + switch { + case errors.Is(err, application.ErrPayloadTooLarge): + response.WriteError(w, http.StatusRequestEntityTooLarge, + response.CodePayloadTooLarge, + "attachment exceeds 10 MiB or 40 million pixels", requestID) + return + case errors.Is(err, application.ErrUnsupportedMediaType), errors.Is(err, application.ErrInvalidImage): + response.WriteError(w, http.StatusUnsupportedMediaType, + response.CodeUnsupportedMediaType, + "body is not a valid PNG/JPEG matching the declared Content-Type", requestID) + return + case errors.Is(err, application.ErrInvalidInput): + message := strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": ") + response.WriteError(w, http.StatusBadRequest, + response.CodeInvalidRequest, message, requestID) + return + case errors.Is(err, domain.ErrNotFound): + response.WriteError(w, http.StatusNotFound, + response.CodeNotFound, "chat not found", requestID) + return + case errors.Is(err, application.ErrStorageUnavailable): + response.WriteError(w, http.StatusServiceUnavailable, + response.CodeUnavailable, "object storage is temporarily unavailable", requestID) + return + case err != nil: + response.WriteError(w, http.StatusServiceUnavailable, + response.CodeUnavailable, "service is temporarily unavailable", requestID) + return + } + + response.WriteJSON(w, http.StatusAccepted, dto.AttachmentFromDomain(attachment), requestID) +} diff --git a/internal/transport/http/handlers/users.go b/internal/transport/http/handlers/users.go new file mode 100644 index 0000000..93500c0 --- /dev/null +++ b/internal/transport/http/handlers/users.go @@ -0,0 +1,65 @@ +package handlers + +import ( + "errors" + "net/http" + "strings" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/middleware" + "mtusi2026lab7/internal/transport/http/response" +) + +func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + var request dto.CreateUserRequest + if err := decodeJSON(r, &request); err != nil { + writeDecodeJSONError(w, requestID, err) + return + } + + createdUser, err := h.service.CreateUser(r.Context(), application.CreateUserCommand{ + Username: request.Username, DisplayName: request.DisplayName, Password: request.Password, + }) + if errors.Is(err, application.ErrInvalidInput) { + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), + requestID, + ) + return + } + + if errors.Is(err, domain.ErrConflict) { + response.WriteError( + w, + http.StatusConflict, + response.CodeConflict, + "username already exists", + requestID, + ) + return + } + if err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + requestID, + ) + return + } + + response.WriteJSON( + w, + http.StatusCreated, + dto.UserFromDomain(createdUser), + requestID, + ) +} diff --git a/internal/transport/http/middleware/auth.go b/internal/transport/http/middleware/auth.go new file mode 100644 index 0000000..23d0d66 --- /dev/null +++ b/internal/transport/http/middleware/auth.go @@ -0,0 +1,113 @@ +package middleware + +import ( + "context" + "errors" + "net/http" + "strings" + + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/response" +) + +const bearerChallenge = `Bearer realm="messenger"` + +const ( + UserContextKey contextKey = "current_user" + sessionTokenHashKey contextKey = "session_token_hash" +) + +type SessionAuthenticator interface { + Authenticate( + ctx context.Context, + token string, + ) (domain.User, []byte, error) +} + +func RequireAuth( + authenticator SessionAuthenticator, + next http.HandlerFunc, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := GetRequestID(r.Context()) + + token, ok := bearerToken(r.Header.Get("Authorization")) + if !ok { + writeBearerUnauthorized(w, requestID) + return + } + + user, tokenHash, err := authenticator.Authenticate( + r.Context(), + token, + ) + if errors.Is(err, domain.ErrNotFound) { + writeBearerUnauthorized(w, requestID) + return + } + if err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + requestID, + ) + return + } + + ctx := context.WithValue( + r.Context(), + UserContextKey, + user, + ) + ctx = context.WithValue( + ctx, + sessionTokenHashKey, + tokenHash, + ) + + next(w, r.WithContext(ctx)) + } +} + +func GetCurrentUser(ctx context.Context) domain.User { + user, _ := ctx.Value(UserContextKey).(domain.User) + return user +} + +func GetCurrentSessionTokenHash(ctx context.Context) []byte { + tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte) + + result := make([]byte, len(tokenHash)) + copy(result, tokenHash) + + return result +} + +func bearerToken(authorization string) (string, bool) { + parts := strings.Fields(authorization) + + if len(parts) != 2 || + !strings.EqualFold(parts[0], "Bearer") || + parts[1] == "" { + return "", false + } + + return parts[1], true +} + +func writeBearerUnauthorized( + w http.ResponseWriter, + requestID string, +) { + w.Header().Set("WWW-Authenticate", bearerChallenge) + + response.WriteError( + w, + http.StatusUnauthorized, + response.CodeUnauthorized, + "invalid or expired bearer token", + requestID, + ) +} diff --git a/internal/transport/http/middleware/availability.go b/internal/transport/http/middleware/availability.go new file mode 100644 index 0000000..fc18e72 --- /dev/null +++ b/internal/transport/http/middleware/availability.go @@ -0,0 +1,48 @@ +package middleware + +import ( + "net/http" + "sync/atomic" + + "mtusi2026lab7/internal/transport/http/response" +) + +// AvailabilityGate lets a process reject new work before its HTTP listener is +// closed. Existing requests are still drained by http.Server.Shutdown. +type AvailabilityGate struct { + accepting atomic.Bool +} + +func NewAvailabilityGate() *AvailabilityGate { + gate := &AvailabilityGate{} + gate.accepting.Store(true) + + return gate +} + +func (g *AvailabilityGate) BeginDrain() { + g.accepting.Store(false) +} + +func (g *AvailabilityGate) IsAccepting() bool { + return g.accepting.Load() +} + +func (g *AvailabilityGate) Middleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Liveness deliberately stays available while the process drains. The + // readiness endpoint and all business traffic receive 503 immediately. + if g.IsAccepting() || r.URL.Path == "/health/live" { + next.ServeHTTP(w, r) + return + } + + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is draining", + GetRequestID(r.Context()), + ) + }) +} diff --git a/internal/transport/http/middleware/availability_test.go b/internal/transport/http/middleware/availability_test.go new file mode 100644 index 0000000..18f1097 --- /dev/null +++ b/internal/transport/http/middleware/availability_test.go @@ -0,0 +1,38 @@ +package middleware + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestAvailabilityGateRejectsNewWorkWhileKeepingLiveness(t *testing.T) { + gate := NewAvailabilityGate() + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + }) + handler := RequestID(gate.Middleware(next)) + + before := httptest.NewRecorder() + handler.ServeHTTP(before, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)) + if before.Code != http.StatusNoContent { + t.Fatalf("before drain status = %d, want %d", before.Code, http.StatusNoContent) + } + + gate.BeginDrain() + + draining := httptest.NewRecorder() + handler.ServeHTTP(draining, httptest.NewRequest(http.MethodGet, "/health/ready", nil)) + if draining.Code != http.StatusServiceUnavailable { + t.Fatalf("ready while draining status = %d, want %d", draining.Code, http.StatusServiceUnavailable) + } + if draining.Header().Get("X-Request-Id") == "" { + t.Fatal("draining response is missing X-Request-Id") + } + + live := httptest.NewRecorder() + handler.ServeHTTP(live, httptest.NewRequest(http.MethodGet, "/health/live", nil)) + if live.Code != http.StatusNoContent { + t.Fatalf("live while draining status = %d, want %d", live.Code, http.StatusNoContent) + } +} diff --git a/internal/transport/http/middleware/instance_id.go b/internal/transport/http/middleware/instance_id.go new file mode 100644 index 0000000..0688487 --- /dev/null +++ b/internal/transport/http/middleware/instance_id.go @@ -0,0 +1,15 @@ +package middleware + +import "net/http" + +const InstanceIDHeader = "X-Instance-Id" + +// InstanceID identifies the process that actually produced the response. +// It must wrap recovery and routing so even errors, health checks and 404/405 +// responses carry the same stable process identifier. +func InstanceID(instanceID string, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(InstanceIDHeader, instanceID) + next.ServeHTTP(w, r) + }) +} diff --git a/internal/transport/http/middleware/instance_id_test.go b/internal/transport/http/middleware/instance_id_test.go new file mode 100644 index 0000000..5ec5827 --- /dev/null +++ b/internal/transport/http/middleware/instance_id_test.go @@ -0,0 +1,50 @@ +package middleware + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestInstanceIDOnSuccessfulAndNotFoundResponses(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /ok", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + }) + handler := InstanceID("api-01", mux) + + for _, test := range []struct { + path string + wantStatus int + }{ + {path: "/ok", wantStatus: http.StatusNoContent}, + {path: "/missing", wantStatus: http.StatusNotFound}, + } { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil)) + + if recorder.Code != test.wantStatus { + t.Fatalf("%s: got status %d, want %d", test.path, recorder.Code, test.wantStatus) + } + if got := recorder.Header().Get(InstanceIDHeader); got != "api-01" { + t.Fatalf("%s: got instance ID %q, want api-01", test.path, got) + } + } +} + +func TestInstanceIDSurvivesRecoveredPanic(t *testing.T) { + panicking := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + panic("test panic") + }) + handler := InstanceID("api-panic", Recovery(panicking)) + recorder := httptest.NewRecorder() + + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/panic", nil)) + + if recorder.Code != http.StatusInternalServerError { + t.Fatalf("got status %d, want 500", recorder.Code) + } + if got := recorder.Header().Get(InstanceIDHeader); got != "api-panic" { + t.Fatalf("got instance ID %q, want api-panic", got) + } +} diff --git a/internal/transport/http/middleware/logger.go b/internal/transport/http/middleware/logger.go new file mode 100644 index 0000000..085c786 --- /dev/null +++ b/internal/transport/http/middleware/logger.go @@ -0,0 +1,106 @@ +package middleware + +import ( + "fmt" + "net/http" + "strconv" + "strings" + "time" + + apptelemetry "mtusi2026lab7/internal/telemetry" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" +) + +type responseWriterInterceptor struct { + http.ResponseWriter + statusCode int +} + +func (w *responseWriterInterceptor) WriteHeader(code int) { + w.statusCode = code + w.ResponseWriter.WriteHeader(code) +} + +func Observability(runtime *apptelemetry.Runtime, next http.Handler) (http.Handler, error) { + requests, err := runtime.Meter.Int64Counter( + "messenger.http.server.requests", + metric.WithDescription("Number of completed HTTP requests"), + metric.WithUnit("{request}"), + ) + if err != nil { + return nil, fmt.Errorf("create HTTP request counter: %w", err) + } + duration, err := runtime.Meter.Float64Histogram( + "messenger.http.server.duration", + metric.WithDescription("HTTP server request duration"), + metric.WithUnit("s"), + ) + if err != nil { + return nil, fmt.Errorf("create HTTP duration histogram: %w", err) + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/health/") { + next.ServeHTTP(w, r) + return + } + start := time.Now() + parent := otel.GetTextMapPropagator().Extract( + r.Context(), + propagation.HeaderCarrier(r.Header), + ) + ctx, span := runtime.Tracer.Start( + parent, + r.Method+" HTTP request", + trace.WithSpanKind(trace.SpanKindServer), + trace.WithAttributes(attribute.String("http.request.method", r.Method)), + ) + defer span.End() + interceptor := &responseWriterInterceptor{ + ResponseWriter: w, + statusCode: http.StatusOK, + } + observedRequest := r.WithContext(ctx) + next.ServeHTTP(interceptor, observedRequest) + + route := observedRequest.Pattern + if route == "" { + route = "unmatched" + } + statusClass := strconv.Itoa(interceptor.statusCode/100) + "xx" + elapsed := time.Since(start) + labels := metric.WithAttributes( + attribute.String("method", r.Method), + attribute.String("route", route), + attribute.String("status_class", statusClass), + ) + requests.Add(ctx, 1, labels) + duration.Record(ctx, elapsed.Seconds(), labels) + + span.SetName(r.Method + " " + route) + span.SetAttributes( + attribute.String("http.route", route), + attribute.Int("http.response.status_code", interceptor.statusCode), + ) + if interceptor.statusCode >= http.StatusInternalServerError { + span.SetStatus(codes.Error, "server error") + } else { + span.SetStatus(codes.Ok, "") + } + + runtime.Logger.Info(ctx, "http_request_completed", apptelemetry.Fields{ + "method": r.Method, + "route": route, + "status_code": interceptor.statusCode, + "status_class": statusClass, + "duration_ms": float64(elapsed.Microseconds()) / 1000, + "request_id": GetRequestID(ctx), + }) + }), nil +} diff --git a/internal/transport/http/middleware/recovery.go b/internal/transport/http/middleware/recovery.go new file mode 100644 index 0000000..49ea195 --- /dev/null +++ b/internal/transport/http/middleware/recovery.go @@ -0,0 +1,28 @@ +package middleware + +import ( + "net/http" + + "mtusi2026lab7/internal/transport/http/response" +) + +// Recovery перехватывает панику и возвращает клиенту валидный JSON 500 +func Recovery(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if err := recover(); err != nil { + reqID := GetRequestID(r.Context()) + //из контракта: не раскрывать stack trace и внутренности + response.WriteError( + w, + http.StatusInternalServerError, + response.CodeInternalError, + "internal server error", + reqID, + ) + } + }() + + next.ServeHTTP(w, r) + }) +} diff --git a/internal/transport/http/middleware/request_id.go b/internal/transport/http/middleware/request_id.go new file mode 100644 index 0000000..228a77a --- /dev/null +++ b/internal/transport/http/middleware/request_id.go @@ -0,0 +1,35 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/google/uuid" +) + +type contextKey string + +const RequestIDKey contextKey = "request_id" + +// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа +func RequestID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reqID := r.Header.Get("X-Request-Id") + if reqID == "" { + reqID = uuid.NewString() + } + + w.Header().Set("X-Request-Id", reqID) + + ctx := context.WithValue(r.Context(), RequestIDKey, reqID) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +// GetRequestID достает ID запроса из контекста +func GetRequestID(ctx context.Context) string { + if val, ok := ctx.Value(RequestIDKey).(string); ok { + return val + } + return uuid.NewString() +} diff --git a/internal/transport/http/response/response.go b/internal/transport/http/response/response.go new file mode 100644 index 0000000..4e480c8 --- /dev/null +++ b/internal/transport/http/response/response.go @@ -0,0 +1,64 @@ +package response + +import ( + "encoding/json" + "net/http" +) + +// коды ошибок по контракту +const ( + CodeInvalidRequest = "invalid_request" + CodePayloadTooLarge = "payload_too_large" + CodeUnsupportedMediaType = "unsupported_media_type" + CodeUnauthorized = "unauthorized" + CodeNotFound = "not_found" + CodeConflict = "conflict" + CodeRateLimited = "rate_limited" + CodeUnavailable = "unavailable" + CodeInternalError = "internal_error" +) + +type ErrorPayload struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +// ErrorResponse — строгое тело ответа при любой ошибке +type ErrorResponse struct { + Error ErrorPayload `json:"error"` +} + +// WriteJSON отправляет любой успешный ответ с правильными заголовками +func WriteJSON(w http.ResponseWriter, statusCode int, data any, requestID string) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + if requestID != "" { + w.Header().Set("X-Request-Id", requestID) + } + + w.WriteHeader(statusCode) + + if data != nil { + _ = json.NewEncoder(w).Encode(data) + } +} + +// WriteError формирует стандартизированную ошибку с совпадением request_id в теле и заголовке +func WriteError(w http.ResponseWriter, statusCode int, code string, message string, requestID string) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + if requestID != "" { + w.Header().Set("X-Request-Id", requestID) + } + + w.WriteHeader(statusCode) + + resp := ErrorResponse{ + Error: ErrorPayload{ + Code: code, + Message: message, + RequestID: requestID, + }, + } + + _ = json.NewEncoder(w).Encode(resp) +} diff --git a/internal/worker/backoff.go b/internal/worker/backoff.go new file mode 100644 index 0000000..5fe434a --- /dev/null +++ b/internal/worker/backoff.go @@ -0,0 +1,45 @@ +package worker + +import ( + "crypto/sha256" + "encoding/binary" + "strconv" + "time" +) + +// RetryDelay returns exponential backoff with deterministic per-job jitter in +// [0.5, 1.5). Determinism makes retries reproducible while still avoiding a +// synchronized retry wave across different jobs. +func RetryDelay(jobID string, nextAttempt int, base, maximum time.Duration) time.Duration { + if base <= 0 { + base = time.Millisecond + } + if maximum < base { + maximum = base + } + exponent := nextAttempt - 2 + if exponent < 0 { + exponent = 0 + } + delay := base + for index := 0; index < exponent && delay < maximum; index++ { + if delay > maximum/2 { + delay = maximum + break + } + delay *= 2 + } + if delay > maximum { + delay = maximum + } + sum := sha256.Sum256([]byte(jobID + ":" + strconv.Itoa(nextAttempt))) + fraction := float64(binary.BigEndian.Uint64(sum[:8])) / float64(^uint64(0)) + jittered := time.Duration(float64(delay) * (0.5 + fraction)) + if jittered > maximum { + return maximum + } + if jittered < time.Millisecond { + return time.Millisecond + } + return jittered +} diff --git a/internal/worker/backoff_test.go b/internal/worker/backoff_test.go new file mode 100644 index 0000000..933a297 --- /dev/null +++ b/internal/worker/backoff_test.go @@ -0,0 +1,36 @@ +package worker + +import ( + "testing" + "time" +) + +func TestRetryDelayUsesBoundedExponentialJitter(t *testing.T) { + base := 200 * time.Millisecond + maximum := 2 * time.Second + previousCeiling := time.Duration(0) + for attempt := 2; attempt <= 8; attempt++ { + delay := RetryDelay("job-a", attempt, base, maximum) + if delay < time.Millisecond || delay > maximum { + t.Fatalf("attempt %d delay out of bounds: %v", attempt, delay) + } + ceiling := base << (attempt - 2) + if ceiling > maximum { + ceiling = maximum + } + upper := ceiling + ceiling/2 + if upper > maximum { + upper = maximum + } + if delay < ceiling/2 || delay > upper { + t.Fatalf("attempt %d delay %v outside jitter range [%v,%v]", attempt, delay, ceiling/2, upper) + } + if ceiling < previousCeiling { + t.Fatalf("backoff ceiling decreased") + } + previousCeiling = ceiling + } + if first, second := RetryDelay("job-a", 3, base, maximum), RetryDelay("job-a", 3, base, maximum); first != second { + t.Fatalf("jitter must be reproducible: %v != %v", first, second) + } +} diff --git a/internal/worker/cleaner.go b/internal/worker/cleaner.go new file mode 100644 index 0000000..b320424 --- /dev/null +++ b/internal/worker/cleaner.go @@ -0,0 +1,113 @@ +package worker + +import ( + "context" + "fmt" + "time" + + "mtusi2026lab7/internal/adapter/objectstore" + "mtusi2026lab7/internal/domain" +) + +type StagingCleanupStore interface { + LookupAttachmentByStagingKey(ctx context.Context, stagingKey string) ( + attachmentID string, + status domain.AttachmentStatus, + updatedAt time.Time, + found bool, + err error, + ) + ListReadyStagingKeys(ctx context.Context, limit int) (map[string]string, error) + ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error +} + +type StagingObjectStore interface { + List(ctx context.Context, prefix string) ([]objectstore.StoredObject, error) + Delete(ctx context.Context, key string) error +} + +type StagingCleaner struct { + store StagingCleanupStore + objects StagingObjectStore + retention time.Duration +} + +func NewStagingCleaner( + store StagingCleanupStore, + objects StagingObjectStore, + retention time.Duration, +) (*StagingCleaner, error) { + if store == nil || objects == nil { + return nil, fmt.Errorf("cleanup store and object store are required") + } + if retention <= 0 { + return nil, fmt.Errorf("staging retention must be positive") + } + return &StagingCleaner{store: store, objects: objects, retention: retention}, nil +} + +func (cleaner *StagingCleaner) RunOnce(ctx context.Context, now time.Time) (int, error) { + objects, err := cleaner.objects.List(ctx, "staging/") + if err != nil { + return 0, err + } + present := make(map[string]struct{}, len(objects)) + for _, object := range objects { + present[object.Key] = struct{}{} + } + + // A previous worker may have deleted the object and crashed before clearing + // metadata. Once the result is ready, clearing such a stale pointer is safe. + readyKeys, err := cleaner.store.ListReadyStagingKeys(ctx, 1000) + if err != nil { + return 0, err + } + for key, attachmentID := range readyKeys { + if _, exists := present[key]; exists { + continue + } + if err = cleaner.store.ClearAttachmentStagingKey(ctx, attachmentID, key); err != nil { + return 0, err + } + } + + cutoff := now.UTC().Add(-cleaner.retention) + deleted := 0 + for _, object := range objects { + attachmentID, status, updatedAt, found, lookupErr := + cleaner.store.LookupAttachmentByStagingKey(ctx, object.Key) + if lookupErr != nil { + return deleted, lookupErr + } + safeToDelete := false + switch { + case found && status == domain.AttachmentStatusReady: + // Result metadata is already committed, so staging is redundant. + safeToDelete = true + case found && status == domain.AttachmentStatusFailed && + !updatedAt.After(cutoff) && !object.LastModified.After(cutoff): + safeToDelete = true + case !found && !object.LastModified.After(cutoff): + // An old object without DB metadata is an orphan from a failed or + // ambiguous upload transaction. + safeToDelete = true + } + if !safeToDelete { + continue + } + if err = cleaner.objects.Delete(ctx, object.Key); err != nil { + return deleted, err + } + if found { + if err = cleaner.store.ClearAttachmentStagingKey( + ctx, + attachmentID, + object.Key, + ); err != nil { + return deleted, err + } + } + deleted++ + } + return deleted, nil +} diff --git a/internal/worker/cleaner_test.go b/internal/worker/cleaner_test.go new file mode 100644 index 0000000..372bb32 --- /dev/null +++ b/internal/worker/cleaner_test.go @@ -0,0 +1,122 @@ +package worker + +import ( + "context" + "testing" + "time" + + "mtusi2026lab7/internal/adapter/objectstore" + "mtusi2026lab7/internal/domain" +) + +type cleanupReference struct { + id string + status domain.AttachmentStatus + updatedAt time.Time +} + +type cleanupStoreFake struct { + references map[string]cleanupReference + cleared map[string]bool +} + +func (store *cleanupStoreFake) LookupAttachmentByStagingKey( + _ context.Context, + key string, +) (string, domain.AttachmentStatus, time.Time, bool, error) { + reference, found := store.references[key] + return reference.id, reference.status, reference.updatedAt, found, nil +} + +func (store *cleanupStoreFake) ListReadyStagingKeys( + _ context.Context, + _ int, +) (map[string]string, error) { + keys := make(map[string]string) + for key, reference := range store.references { + if reference.status == domain.AttachmentStatusReady { + keys[key] = reference.id + } + } + return keys, nil +} +func (store *cleanupStoreFake) ClearAttachmentStagingKey( + _ context.Context, + _ string, + key string, +) error { + store.cleared[key] = true + return nil +} + +type cleanupObjectsFake struct { + objects []objectstore.StoredObject + deleted map[string]bool +} + +func (objects *cleanupObjectsFake) List( + context.Context, + string, +) ([]objectstore.StoredObject, error) { + return objects.objects, nil +} + +func (objects *cleanupObjectsFake) Delete(_ context.Context, key string) error { + objects.deleted[key] = true + return nil +} + +func TestStagingCleanerPreservesActiveWorkAndAppliesRetention(t *testing.T) { + now := time.Date(2026, time.November, 5, 12, 0, 0, 0, time.UTC) + old := now.Add(-25 * time.Hour) + recent := now.Add(-time.Hour) + store := &cleanupStoreFake{ + references: map[string]cleanupReference{ + "staging/ready": {id: "ready", status: domain.AttachmentStatusReady, updatedAt: recent}, + "staging/ready-missing": {id: "ready-missing", status: domain.AttachmentStatusReady, updatedAt: recent}, + "staging/failed-old": {id: "failed-old", status: domain.AttachmentStatusFailed, updatedAt: old}, + "staging/failed-recent": {id: "failed-recent", status: domain.AttachmentStatusFailed, updatedAt: recent}, + "staging/queued-old": {id: "queued-old", status: domain.AttachmentStatusQueued, updatedAt: old}, + }, + cleared: make(map[string]bool), + } + objects := &cleanupObjectsFake{ + objects: []objectstore.StoredObject{ + {Key: "staging/ready", LastModified: recent}, + {Key: "staging/failed-old", LastModified: old}, + {Key: "staging/failed-recent", LastModified: recent}, + {Key: "staging/queued-old", LastModified: old}, + {Key: "staging/orphan-old", LastModified: old}, + {Key: "staging/orphan-recent", LastModified: recent}, + }, + deleted: make(map[string]bool), + } + cleaner, err := NewStagingCleaner(store, objects, 24*time.Hour) + if err != nil { + t.Fatal(err) + } + deleted, err := cleaner.RunOnce(context.Background(), now) + if err != nil { + t.Fatal(err) + } + if deleted != 3 { + t.Fatalf("deleted %d objects, want 3", deleted) + } + for _, key := range []string{"staging/ready", "staging/failed-old", "staging/orphan-old"} { + if !objects.deleted[key] { + t.Errorf("expected %s to be deleted", key) + } + } + for _, key := range []string{"staging/failed-recent", "staging/queued-old", "staging/orphan-recent"} { + if objects.deleted[key] { + t.Errorf("active/recent %s was deleted", key) + } + } + if !store.cleared["staging/ready"] || !store.cleared["staging/ready-missing"] || + !store.cleared["staging/failed-old"] { + t.Fatal("deleted referenced staging keys were not cleared") + } + if store.cleared["staging/orphan-old"] { + t.Fatal("orphan must not clear nonexistent metadata") + } +} diff --git a/internal/worker/processor.go b/internal/worker/processor.go new file mode 100644 index 0000000..5ed49b6 --- /dev/null +++ b/internal/worker/processor.go @@ -0,0 +1,319 @@ +package worker + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "image" + "image/color" + "image/draw" + "image/jpeg" + "io" + "math" + "os" + "strings" + "time" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" + + "github.com/disintegration/imaging" + webp "github.com/mayahiro/go-webp" +) + +type pipelineProfile struct { + thumbnailJPEGQuality int + cropJPEGQuality int + optimizedWebPQuality int +} + +func profileForPipeline(version int) (pipelineProfile, bool) { + switch version { + case 1: + return pipelineProfile{thumbnailJPEGQuality: 85, cropJPEGQuality: 85, optimizedWebPQuality: 80}, true + case 2: + return pipelineProfile{thumbnailJPEGQuality: 90, cropJPEGQuality: 90, optimizedWebPQuality: 85}, true + default: + return pipelineProfile{}, false + } +} + +type JobStore interface { + GetAttachmentForProcessing(ctx context.Context, attachmentID string) (domain.Attachment, error) + CompleteAttachmentJob( + ctx context.Context, + job domain.AttachmentJob, + variants []domain.AttachmentVariant, + updatedAt time.Time, + ) (bool, error) + ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error +} + +type FaultHook func(job domain.AttachmentJob) error + +type ProcessorHooks struct { + BeforeObjects FaultHook + AfterObjects FaultHook +} + +type Processor struct { + store JobStore + objects application.ObjectStore + now func() time.Time + beforeObjects FaultHook + afterObjects FaultHook +} + +type PermanentError struct { + Code string + Err error +} + +func (err *PermanentError) Error() string { return err.Code + ": " + err.Err.Error() } +func (err *PermanentError) Unwrap() error { return err.Err } + +func NewProcessor( + store JobStore, + objects application.ObjectStore, + hooks ...ProcessorHooks, +) (*Processor, error) { + if store == nil || objects == nil { + return nil, fmt.Errorf("job store and object store are required") + } + var configured ProcessorHooks + if len(hooks) > 0 { + configured = hooks[0] + } + return &Processor{ + store: store, + objects: objects, + now: func() time.Time { return time.Now().UTC() }, + beforeObjects: configured.BeforeObjects, + afterObjects: configured.AfterObjects, + }, nil +} + +func (processor *Processor) Process(ctx context.Context, job domain.AttachmentJob) error { + attachment, err := processor.store.GetAttachmentForProcessing(ctx, job.AttachmentID) + if err != nil { + return fmt.Errorf("load attachment metadata: %w", err) + } + if attachment.PipelineVersion != job.PipelineVersion { + return &PermanentError{Code: "stale_pipeline", Err: fmt.Errorf("pipeline version mismatch")} + } + profile, supported := profileForPipeline(job.PipelineVersion) + if !supported { + return &PermanentError{Code: "unsupported_pipeline", Err: fmt.Errorf("pipeline version %d is not supported", job.PipelineVersion)} + } + if attachment.StagingKey == "" { + return &PermanentError{Code: "staging_expired", Err: fmt.Errorf("staging object is no longer retained")} + } + + object, err := processor.objects.Get(ctx, attachment.StagingKey) + if err != nil { + return fmt.Errorf("read staging object: %w", err) + } + defer object.Body.Close() + + staged, err := os.CreateTemp("", "mtusi-worker-original-*") + if err != nil { + return fmt.Errorf("create worker staging file: %w", err) + } + stagedPath := staged.Name() + defer func() { + _ = staged.Close() + _ = os.Remove(stagedPath) + }() + + hasher := sha256.New() + copied, err := io.Copy( + io.MultiWriter(staged, hasher), + io.LimitReader(object.Body, domain.MaxAttachmentSizeBytes+1), + ) + if err != nil { + return fmt.Errorf("copy staging object: %w", err) + } + if copied != attachment.SizeBytes || + object.SizeBytes != attachment.SizeBytes || + hex.EncodeToString(hasher.Sum(nil)) != attachment.SHA256 { + return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("staging object integrity mismatch")} + } + if err = ctx.Err(); err != nil { + return err + } + if _, err = staged.Seek(0, io.SeekStart); err != nil { + return fmt.Errorf("rewind staged image: %w", err) + } + config, _, err := image.DecodeConfig(staged) + if err != nil { + return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("decode staged image config: %w", err)} + } + if config.Width < 1 || config.Height < 1 || + int64(config.Width) > int64(domain.MaxAttachmentPixels)/int64(config.Height) { + return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("decoded image dimensions are unsafe")} + } + if _, err = staged.Seek(0, io.SeekStart); err != nil { + return fmt.Errorf("rewind staged image: %w", err) + } + decoded, err := imaging.Decode(staged, imaging.AutoOrientation(true)) + if err != nil { + return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("decode staged image: %w", err)} + } + if err = ctx.Err(); err != nil { + return err + } + bounds := decoded.Bounds() + width, height := bounds.Dx(), bounds.Dy() + if width < 1 || height < 1 || + int64(width) > int64(domain.MaxAttachmentPixels)/int64(height) { + return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("oriented image dimensions are unsafe")} + } + + opaque := image.NewRGBA(image.Rect(0, 0, width, height)) + draw.Draw(opaque, opaque.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src) + draw.Draw(opaque, opaque.Bounds(), decoded, bounds.Min, draw.Over) + + thumbnailWidth, thumbnailHeight := fitDimensions(width, height, 256) + thumbnail := imaging.Resize(opaque, thumbnailWidth, thumbnailHeight, imaging.Lanczos) + thumbnailBytes, err := encodeJPEG(thumbnail, profile.thumbnailJPEGQuality) + if err != nil { + return fmt.Errorf("encode thumbnail: %w", err) + } + + cropSide := width + if height < cropSide { + cropSide = height + } + cropped := imaging.CropCenter(opaque, cropSide, cropSide) + cropped = imaging.Resize(cropped, 128, 128, imaging.Lanczos) + cropBytes, err := encodeJPEG(cropped, profile.cropJPEGQuality) + if err != nil { + return fmt.Errorf("encode crop: %w", err) + } + + optimizedWidth, optimizedHeight := fitDimensions(width, height, 1280) + optimized := decoded + if optimizedWidth != width || optimizedHeight != height { + optimized = imaging.Resize(decoded, optimizedWidth, optimizedHeight, imaging.Lanczos) + } + var optimizedBuffer bytes.Buffer + if err = webp.EncodeContext(ctx, &optimizedBuffer, optimized, &webp.Options{ + Compression: webp.CompressionLossy, + Quality: profile.optimizedWebPQuality, + }); err != nil { + return fmt.Errorf("encode optimized WebP: %w", err) + } + optimizedBytes := optimizedBuffer.Bytes() + + baseKey := strings.TrimSuffix(attachment.ObjectKey, "/original") + + fmt.Sprintf("/v%d/", job.PipelineVersion) + variants := []domain.AttachmentVariant{ + newVariant("thumbnail", "image/jpeg", baseKey+"thumbnail.jpg", + thumbnailBytes, thumbnailWidth, thumbnailHeight, job.PipelineVersion), + newVariant("crop", "image/jpeg", baseKey+"crop.jpg", + cropBytes, 128, 128, job.PipelineVersion), + newVariant("optimized", "image/webp", baseKey+"optimized.webp", + optimizedBytes, optimizedWidth, optimizedHeight, job.PipelineVersion), + } + + if processor.beforeObjects != nil { + if err = processor.beforeObjects(job); err != nil { + return err + } + } + if _, err = staged.Seek(0, io.SeekStart); err != nil { + return fmt.Errorf("rewind original for publication: %w", err) + } + if err = processor.objects.Put(ctx, application.ObjectPut{ + Key: attachment.ObjectKey, + ContentType: attachment.ContentType, + SizeBytes: attachment.SizeBytes, + Body: staged, + }); err != nil { + return fmt.Errorf("publish original: %w", err) + } + variantBodies := [][]byte{thumbnailBytes, cropBytes, optimizedBytes} + for index, variant := range variants { + if err = processor.objects.Put(ctx, application.ObjectPut{ + Key: variant.ObjectKey, + ContentType: variant.ContentType, + SizeBytes: variant.SizeBytes, + Body: bytes.NewReader(variantBodies[index]), + }); err != nil { + return fmt.Errorf("publish %s: %w", variant.Name, err) + } + } + if processor.afterObjects != nil { + if err = processor.afterObjects(job); err != nil { + return err + } + } + applied, err := processor.store.CompleteAttachmentJob( + ctx, + job, + variants, + processor.now(), + ) + if err != nil { + return fmt.Errorf("commit attachment result: %w", err) + } + if !applied { + return nil + } + + cleanupContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) + defer cancel() + if err = processor.objects.Delete(cleanupContext, attachment.StagingKey); err == nil { + _ = processor.store.ClearAttachmentStagingKey( + cleanupContext, + attachment.ID, + attachment.StagingKey, + ) + } + return nil +} + +func fitDimensions(width, height, maximum int) (int, int) { + scale := math.Min(1, math.Min(float64(maximum)/float64(width), float64(maximum)/float64(height))) + resultWidth := int(math.Floor(float64(width) * scale)) + resultHeight := int(math.Floor(float64(height) * scale)) + if resultWidth < 1 { + resultWidth = 1 + } + if resultHeight < 1 { + resultHeight = 1 + } + return resultWidth, resultHeight +} + +func encodeJPEG(source image.Image, quality int) ([]byte, error) { + var encoded bytes.Buffer + if err := jpeg.Encode(&encoded, source, &jpeg.Options{Quality: quality}); err != nil { + return nil, err + } + return encoded.Bytes(), nil +} + +func newVariant( + name string, + contentType string, + objectKey string, + body []byte, + width int, + height int, + pipelineVersion int, +) domain.AttachmentVariant { + digest := sha256.Sum256(body) + return domain.AttachmentVariant{ + Name: name, + ContentType: contentType, + SizeBytes: int64(len(body)), + Width: width, + Height: height, + SHA256: hex.EncodeToString(digest[:]), + ObjectKey: objectKey, + PipelineVersion: pipelineVersion, + } +} diff --git a/internal/worker/processor_test.go b/internal/worker/processor_test.go new file mode 100644 index 0000000..c179eb8 --- /dev/null +++ b/internal/worker/processor_test.go @@ -0,0 +1,256 @@ +package worker + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "image" + "image/color" + "image/jpeg" + "image/png" + "io" + "testing" + "time" + + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" + + xwebp "golang.org/x/image/webp" +) + +type processorStoreFake struct { + attachment domain.Attachment + variants []domain.AttachmentVariant + cleared bool +} + +func (store *processorStoreFake) GetAttachmentForProcessing( + context.Context, + string, +) (domain.Attachment, error) { + return store.attachment, nil +} + +func (store *processorStoreFake) CompleteAttachmentJob( + _ context.Context, + _ domain.AttachmentJob, + variants []domain.AttachmentVariant, + _ time.Time, +) (bool, error) { + store.variants = append([]domain.AttachmentVariant(nil), variants...) + return true, nil +} + +func (store *processorStoreFake) ClearAttachmentStagingKey( + context.Context, + string, + string, +) error { + store.cleared = true + return nil +} + +type objectStoreFake struct { + objects map[string][]byte +} + +func (store *objectStoreFake) Put(_ context.Context, object application.ObjectPut) error { + body, err := io.ReadAll(object.Body) + if err != nil { + return err + } + store.objects[object.Key] = body + return nil +} + +func (store *objectStoreFake) Get( + _ context.Context, + key string, +) (application.ObjectContent, error) { + body := store.objects[key] + return application.ObjectContent{ + Body: io.NopCloser(bytes.NewReader(body)), + SizeBytes: int64(len(body)), + }, nil +} + +func (store *objectStoreFake) Delete(_ context.Context, key string) error { + delete(store.objects, key) + return nil +} + +func TestProcessorCompositesAlphaAndStripsMetadata(t *testing.T) { + source := image.NewNRGBA(image.Rect(0, 0, 32, 16)) + for y := 0; y < 16; y++ { + for x := 0; x < 32; x++ { + if x < 16 { + source.SetNRGBA(x, y, color.NRGBA{R: 255, A: 0}) + } else { + source.SetNRGBA(x, y, color.NRGBA{A: 255}) + } + } + } + var encoded bytes.Buffer + if err := png.Encode(&encoded, source); err != nil { + t.Fatal(err) + } + store, objects, processor, job := processorFixture(t, encoded.Bytes(), "image/png", 32, 16) + if err := processor.Process(context.Background(), job); err != nil { + t.Fatalf("process transparent PNG: %v", err) + } + + thumbnail := decodeJPEG(t, objects.objects[variantKey(store.variants, "thumbnail")]) + if got := thumbnail.Bounds().Size(); got.X != 32 || got.Y != 16 { + t.Fatalf("thumbnail size = %v, want 32x16 without upscale", got) + } + white := color.RGBAModel.Convert(thumbnail.At(2, 8)).(color.RGBA) + black := color.RGBAModel.Convert(thumbnail.At(29, 8)).(color.RGBA) + if white.R < 220 || white.G < 220 || white.B < 220 { + t.Fatalf("transparent pixel was not composited on white: %#v", white) + } + if black.R > 40 || black.G > 40 || black.B > 40 { + t.Fatalf("opaque black pixel changed unexpectedly: %#v", black) + } + + optimizedBytes := objects.objects[variantKey(store.variants, "optimized")] + optimized, err := xwebp.Decode(bytes.NewReader(optimizedBytes)) + if err != nil { + t.Fatalf("decode optimized WebP: %v", err) + } + if got := optimized.Bounds().Size(); got.X != 32 || got.Y != 16 { + t.Fatalf("optimized size = %v, want 32x16 without upscale", got) + } + _, _, _, alpha := optimized.At(2, 8).RGBA() + if alpha > 0x0800 { + t.Fatalf("optimized WebP did not preserve transparent alpha: %d", alpha) + } + for _, metadataChunk := range [][]byte{[]byte("EXIF"), []byte("XMP "), []byte("ICCP")} { + if bytes.Contains(optimizedBytes, metadataChunk) { + t.Fatalf("optimized WebP unexpectedly contains metadata chunk %q", metadataChunk) + } + } + if !store.cleared { + t.Fatal("successful processing did not clear staging metadata") + } + if _, exists := objects.objects[store.attachment.StagingKey]; exists { + t.Fatal("successful processing did not delete staging object") + } +} + +func TestProcessorAppliesEXIFOrientation(t *testing.T) { + source := image.NewRGBA(image.Rect(0, 0, 40, 20)) + var raw bytes.Buffer + if err := jpeg.Encode(&raw, source, &jpeg.Options{Quality: 90}); err != nil { + t.Fatal(err) + } + oriented := injectEXIFOrientation(t, raw.Bytes(), 6) + store, objects, processor, job := processorFixture(t, oriented, "image/jpeg", 40, 20) + if err := processor.Process(context.Background(), job); err != nil { + t.Fatalf("process oriented JPEG: %v", err) + } + thumbnail := decodeJPEG(t, objects.objects[variantKey(store.variants, "thumbnail")]) + if got := thumbnail.Bounds().Size(); got.X != 20 || got.Y != 40 { + t.Fatalf("thumbnail size after orientation = %v, want 20x40", got) + } + optimized, err := xwebp.Decode(bytes.NewReader( + objects.objects[variantKey(store.variants, "optimized")], + )) + if err != nil { + t.Fatalf("decode optimized WebP: %v", err) + } + if got := optimized.Bounds().Size(); got.X != 20 || got.Y != 40 { + t.Fatalf("optimized size after orientation = %v, want 20x40", got) + } + crop := decodeJPEG(t, objects.objects[variantKey(store.variants, "crop")]) + if got := crop.Bounds().Size(); got.X != 128 || got.Y != 128 { + t.Fatalf("crop size = %v, want 128x128", got) + } +} + +func processorFixture( + t *testing.T, + body []byte, + contentType string, + width int, + height int, +) (*processorStoreFake, *objectStoreFake, *Processor, domain.AttachmentJob) { + t.Helper() + digest := sha256.Sum256(body) + attachment := domain.Attachment{ + ID: "attachment", + ChatID: "chat", + OwnerID: "owner", + ObjectKey: "attachments/chat/attachment/original", + StagingKey: "staging/attachment/original", + ContentType: contentType, + SizeBytes: int64(len(body)), + SHA256: hex.EncodeToString(digest[:]), + Width: width, + Height: height, + PipelineVersion: 1, + Status: domain.AttachmentStatusProcessing, + } + store := &processorStoreFake{attachment: attachment} + objects := &objectStoreFake{objects: map[string][]byte{attachment.StagingKey: body}} + processor, err := NewProcessor(store, objects) + if err != nil { + t.Fatal(err) + } + return store, objects, processor, domain.AttachmentJob{ + JobID: "job", + AttachmentID: attachment.ID, + PipelineVersion: 1, + Attempt: 1, + MaxAttempts: 5, + Status: domain.AttachmentJobProcessing, + } +} + +func variantKey(variants []domain.AttachmentVariant, name string) string { + for _, variant := range variants { + if variant.Name == name { + return variant.ObjectKey + } + } + return "" +} + +func decodeJPEG(t *testing.T, body []byte) image.Image { + t.Helper() + decoded, err := jpeg.Decode(bytes.NewReader(body)) + if err != nil { + t.Fatalf("decode JPEG: %v", err) + } + return decoded +} + +func injectEXIFOrientation(t *testing.T, source []byte, orientation uint16) []byte { + t.Helper() + if len(source) < 2 || source[0] != 0xFF || source[1] != 0xD8 { + t.Fatal("source is not JPEG") + } + var tiff bytes.Buffer + tiff.WriteString("II") + _ = binary.Write(&tiff, binary.LittleEndian, uint16(42)) + _ = binary.Write(&tiff, binary.LittleEndian, uint32(8)) + _ = binary.Write(&tiff, binary.LittleEndian, uint16(1)) + _ = binary.Write(&tiff, binary.LittleEndian, uint16(0x0112)) + _ = binary.Write(&tiff, binary.LittleEndian, uint16(3)) + _ = binary.Write(&tiff, binary.LittleEndian, uint32(1)) + _ = binary.Write(&tiff, binary.LittleEndian, orientation) + _ = binary.Write(&tiff, binary.LittleEndian, uint16(0)) + _ = binary.Write(&tiff, binary.LittleEndian, uint32(0)) + payload := append([]byte("Exif\x00\x00"), tiff.Bytes()...) + var segment bytes.Buffer + segment.Write([]byte{0xFF, 0xE1}) + if err := binary.Write(&segment, binary.BigEndian, uint16(len(payload)+2)); err != nil { + t.Fatal(err) + } + segment.Write(payload) + result := append([]byte(nil), source[:2]...) + result = append(result, segment.Bytes()...) + result = append(result, source[2:]...) + return result +} diff --git a/migrations/000001_initial.down.sql b/migrations/000001_initial.down.sql new file mode 100644 index 0000000..1fca29b --- /dev/null +++ b/migrations/000001_initial.down.sql @@ -0,0 +1,10 @@ +BEGIN; + +DROP TABLE sessions; +DROP TABLE messages; +DROP TABLE chat_members; +DROP TABLE chats; +DROP TABLE users; + +COMMIT; + diff --git a/migrations/000001_initial.up.sql b/migrations/000001_initial.up.sql new file mode 100644 index 0000000..3b03064 --- /dev/null +++ b/migrations/000001_initial.up.sql @@ -0,0 +1,113 @@ +BEGIN; + +CREATE TABLE users ( + id UUID PRIMARY KEY, + username VARCHAR(32) NOT NULL, + display_name TEXT NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT users_username_unique + UNIQUE (username), + + CONSTRAINT users_username_format + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + + CONSTRAINT users_display_name_length + CHECK (char_length(display_name) BETWEEN 1 AND 100), + + CONSTRAINT users_display_name_not_blank + CHECK (btrim(display_name) <> ''), + + CONSTRAINT users_password_hash_not_blank + CHECK (btrim(password_hash) <> '') +); + +CREATE TABLE chats ( + id UUID PRIMARY KEY, + title TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT chats_title_length + CHECK (char_length(title) BETWEEN 1 AND 100), + + CONSTRAINT chats_title_not_blank + CHECK (btrim(title) <> '') +); + +CREATE INDEX chats_created_at_id_idx + ON chats (created_at, id); + +CREATE TABLE chat_members ( + chat_id UUID NOT NULL, + user_id UUID NOT NULL, + position SMALLINT NOT NULL, + + CONSTRAINT chat_members_primary_key + PRIMARY KEY (chat_id, user_id), + + CONSTRAINT chat_members_position_unique + UNIQUE (chat_id, position), + + CONSTRAINT chat_members_position_range + CHECK (position BETWEEN 0 AND 99), + + CONSTRAINT chat_members_chat_foreign_key + FOREIGN KEY (chat_id) + REFERENCES chats (id) + ON DELETE RESTRICT, + + CONSTRAINT chat_members_user_foreign_key + FOREIGN KEY (user_id) + REFERENCES users (id) + ON DELETE RESTRICT +); + +CREATE INDEX chat_members_user_chat_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 TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT messages_text_length + CHECK (char_length(text) BETWEEN 1 AND 4000), + + CONSTRAINT messages_text_not_blank + CHECK (btrim(text) <> ''), + + CONSTRAINT messages_sender_membership_foreign_key + FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members (chat_id, user_id) + ON DELETE RESTRICT +); + +CREATE INDEX messages_chat_created_at_id_idx + ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + token_hash BYTEA PRIMARY KEY, + user_id UUID NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at TIMESTAMPTZ NOT NULL, + + CONSTRAINT sessions_user_foreign_key + FOREIGN KEY (user_id) + REFERENCES users (id) + ON DELETE RESTRICT, + + CONSTRAINT sessions_token_hash_length + CHECK (octet_length(token_hash) = 32), + + CONSTRAINT sessions_expiry_after_creation + CHECK (expires_at > created_at) +); + +CREATE INDEX sessions_expires_at_idx + ON sessions (expires_at); + +COMMIT; + diff --git a/migrations/000002_message_idempotency.down.sql b/migrations/000002_message_idempotency.down.sql new file mode 100644 index 0000000..7443675 --- /dev/null +++ b/migrations/000002_message_idempotency.down.sql @@ -0,0 +1,6 @@ +BEGIN; + +DROP TABLE IF EXISTS message_idempotency; + +COMMIT; + diff --git a/migrations/000002_message_idempotency.up.sql b/migrations/000002_message_idempotency.up.sql new file mode 100644 index 0000000..86e0b9c --- /dev/null +++ b/migrations/000002_message_idempotency.up.sql @@ -0,0 +1,55 @@ +BEGIN; + +CREATE TABLE message_idempotency ( + user_id UUID NOT NULL, + method VARCHAR(8) NOT NULL, + canonical_path TEXT NOT NULL, + idempotency_key VARCHAR(128) NOT NULL, + request_hash BYTEA NOT NULL, + message_id UUID NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at TIMESTAMPTZ NOT NULL, + + CONSTRAINT message_idempotency_primary_key + PRIMARY KEY ( + user_id, + method, + canonical_path, + idempotency_key + ), + + CONSTRAINT message_idempotency_user_foreign_key + FOREIGN KEY (user_id) + REFERENCES users (id) + ON DELETE RESTRICT, + + CONSTRAINT message_idempotency_message_foreign_key + FOREIGN KEY (message_id) + REFERENCES messages (id) + ON DELETE RESTRICT + DEFERRABLE INITIALLY DEFERRED, + + CONSTRAINT message_idempotency_message_unique + UNIQUE (message_id), + + CONSTRAINT message_idempotency_method_format + CHECK (method = 'POST'), + + CONSTRAINT message_idempotency_key_format + CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + + CONSTRAINT message_idempotency_path_not_blank + CHECK (btrim(canonical_path) <> ''), + + CONSTRAINT message_idempotency_request_hash_length + CHECK (octet_length(request_hash) = 32), + + CONSTRAINT message_idempotency_expiry_after_creation + CHECK (expires_at >= created_at + INTERVAL '24 hours') +); + +CREATE INDEX message_idempotency_expires_at_idx + ON message_idempotency (expires_at); + +COMMIT; + diff --git a/migrations/000003_attachments.down.sql b/migrations/000003_attachments.down.sql new file mode 100644 index 0000000..f100460 --- /dev/null +++ b/migrations/000003_attachments.down.sql @@ -0,0 +1,37 @@ +BEGIN; + +-- Downgrading would destroy the only content of attachment-only messages. +-- Refuse instead of silently losing valid lab4 data. +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM messages + WHERE btrim(text) = '' + ) THEN + RAISE EXCEPTION + 'cannot downgrade while attachment-only messages exist'; + END IF; +END; +$$; + +DROP TRIGGER message_attachments_payload_check ON message_attachments; +DROP TRIGGER messages_payload_check ON messages; +DROP FUNCTION enforce_message_payload_from_link(); +DROP FUNCTION enforce_message_payload_from_message(); + +DROP TABLE message_attachments; +DROP TABLE attachments; + +ALTER TABLE messages + DROP CONSTRAINT messages_id_chat_unique, + DROP CONSTRAINT messages_text_length; + +ALTER TABLE messages + ADD CONSTRAINT messages_text_length + CHECK (char_length(text) BETWEEN 1 AND 4000), + ADD CONSTRAINT messages_text_not_blank + CHECK (btrim(text) <> ''); + +COMMIT; + diff --git a/migrations/000003_attachments.up.sql b/migrations/000003_attachments.up.sql new file mode 100644 index 0000000..84c0a9a --- /dev/null +++ b/migrations/000003_attachments.up.sql @@ -0,0 +1,192 @@ +BEGIN; + +-- Text may be empty only when the same transaction links at least one +-- attachment. A deferred constraint trigger below enforces that invariant. +ALTER TABLE messages + DROP CONSTRAINT messages_text_length, + DROP CONSTRAINT messages_text_not_blank; + +ALTER TABLE messages + ADD CONSTRAINT messages_text_length + CHECK (char_length(text) BETWEEN 0 AND 4000), + ADD CONSTRAINT messages_id_chat_unique + UNIQUE (id, chat_id); + +CREATE TABLE attachments ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL, + owner_id UUID NOT NULL, + object_key TEXT NOT NULL, + filename TEXT NOT NULL, + content_type VARCHAR(32) NOT NULL, + size_bytes BIGINT NOT NULL, + sha256 BYTEA NOT NULL, + width INTEGER NOT NULL, + height INTEGER NOT NULL, + status VARCHAR(16) NOT NULL, + error_code TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT attachments_id_chat_unique + UNIQUE (id, chat_id), + + CONSTRAINT attachments_object_key_unique + UNIQUE (object_key), + + CONSTRAINT attachments_owner_membership_foreign_key + FOREIGN KEY (chat_id, owner_id) + REFERENCES chat_members (chat_id, user_id) + ON DELETE RESTRICT, + + CONSTRAINT attachments_object_key_not_blank + CHECK (btrim(object_key) <> ''), + + CONSTRAINT attachments_filename_length + CHECK (char_length(filename) BETWEEN 1 AND 255), + + CONSTRAINT attachments_filename_safe + CHECK ( + btrim(filename) <> '' + AND filename NOT IN ('.', '..') + AND position('/' in filename) = 0 + AND position(chr(92) in filename) = 0 + AND filename !~ '[[:cntrl:]]' + ), + + CONSTRAINT attachments_content_type_supported + CHECK (content_type IN ('image/png', 'image/jpeg')), + + CONSTRAINT attachments_size_range + CHECK (size_bytes BETWEEN 1 AND 10485760), + + CONSTRAINT attachments_sha256_length + CHECK (octet_length(sha256) = 32), + + CONSTRAINT attachments_dimensions_positive + CHECK (width > 0 AND height > 0), + + CONSTRAINT attachments_pixel_limit + CHECK (width::BIGINT * height::BIGINT <= 40000000), + + CONSTRAINT attachments_status_supported + CHECK (status IN ('pending', 'ready', 'failed')), + + CONSTRAINT attachments_status_error_consistency + CHECK ( + (status = 'failed' AND error_code IS NOT NULL AND btrim(error_code) <> '') + OR + (status IN ('pending', 'ready') AND error_code IS NULL) + ), + + CONSTRAINT attachments_updated_after_creation + CHECK (updated_at >= created_at) +); + +CREATE INDEX attachments_chat_created_at_id_idx + ON attachments (chat_id, created_at, id); + +CREATE INDEX attachments_status_updated_at_idx + ON attachments (status, updated_at, id); + +CREATE TABLE message_attachments ( + message_id UUID NOT NULL, + chat_id UUID NOT NULL, + attachment_id UUID NOT NULL, + position SMALLINT NOT NULL, + + CONSTRAINT message_attachments_primary_key + PRIMARY KEY (message_id, attachment_id), + + CONSTRAINT message_attachments_position_unique + UNIQUE (message_id, position), + + CONSTRAINT message_attachments_position_range + CHECK (position BETWEEN 0 AND 9), + + CONSTRAINT message_attachments_message_foreign_key + FOREIGN KEY (message_id, chat_id) + REFERENCES messages (id, chat_id) + ON DELETE CASCADE, + + CONSTRAINT message_attachments_attachment_foreign_key + FOREIGN KEY (attachment_id, chat_id) + REFERENCES attachments (id, chat_id) + ON DELETE RESTRICT +); + +CREATE INDEX message_attachments_attachment_id_idx + ON message_attachments (attachment_id, message_id); + +CREATE FUNCTION enforce_message_payload_from_message() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM messages AS message + WHERE message.id = NEW.id + AND btrim(message.text) = '' + AND NOT EXISTS ( + SELECT 1 + FROM message_attachments AS link + WHERE link.message_id = message.id + ) + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', + CONSTRAINT = 'messages_content_required', + MESSAGE = 'message must contain non-blank text or an attachment'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION enforce_message_payload_from_link() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + affected_message_id UUID; +BEGIN + IF TG_OP = 'DELETE' THEN + affected_message_id := OLD.message_id; + ELSE + affected_message_id := NEW.message_id; + END IF; + + IF EXISTS ( + SELECT 1 + FROM messages AS message + WHERE message.id = affected_message_id + AND btrim(message.text) = '' + AND NOT EXISTS ( + SELECT 1 + FROM message_attachments AS link + WHERE link.message_id = message.id + ) + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', + CONSTRAINT = 'messages_content_required', + MESSAGE = 'message must contain non-blank text or an attachment'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER messages_payload_check +AFTER INSERT OR UPDATE ON messages +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW +EXECUTE FUNCTION enforce_message_payload_from_message(); + +CREATE CONSTRAINT TRIGGER message_attachments_payload_check +AFTER INSERT OR UPDATE OR DELETE ON message_attachments +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW +EXECUTE FUNCTION enforce_message_payload_from_link(); + +COMMIT; + diff --git a/migrations/000004_async_attachments.down.sql b/migrations/000004_async_attachments.down.sql new file mode 100644 index 0000000..d9ad494 --- /dev/null +++ b/migrations/000004_async_attachments.down.sql @@ -0,0 +1,25 @@ +BEGIN; + +DROP TABLE IF EXISTS attachment_jobs; +DROP TABLE IF EXISTS attachment_variants; + +ALTER TABLE attachments + DROP CONSTRAINT attachments_status_supported, + DROP CONSTRAINT attachments_status_error_consistency, + DROP CONSTRAINT attachments_staging_key_not_blank, + DROP CONSTRAINT attachments_staging_key_unique, + DROP CONSTRAINT attachments_pipeline_version_positive, + DROP COLUMN pipeline_version, + DROP COLUMN staging_key; + +UPDATE attachments SET status = 'pending' WHERE status IN ('queued', 'processing'); + +ALTER TABLE attachments + ADD CONSTRAINT attachments_status_supported CHECK (status IN ('pending', 'ready', 'failed')), + ADD CONSTRAINT attachments_status_error_consistency CHECK ( + (status = 'failed' AND error_code IS NOT NULL AND btrim(error_code) <> '') + OR (status IN ('pending', 'ready') AND error_code IS NULL) + ); + +COMMIT; + diff --git a/migrations/000004_async_attachments.up.sql b/migrations/000004_async_attachments.up.sql new file mode 100644 index 0000000..c8d1ddc --- /dev/null +++ b/migrations/000004_async_attachments.up.sql @@ -0,0 +1,67 @@ +BEGIN; + +ALTER TABLE attachments + DROP CONSTRAINT attachments_status_supported, + DROP CONSTRAINT attachments_status_error_consistency; + +UPDATE attachments SET status = 'queued' WHERE status = 'pending'; + +ALTER TABLE attachments + ADD COLUMN staging_key TEXT, + ADD COLUMN pipeline_version INTEGER NOT NULL DEFAULT 1, + ADD CONSTRAINT attachments_staging_key_unique UNIQUE (staging_key), + ADD CONSTRAINT attachments_staging_key_not_blank CHECK (staging_key IS NULL OR btrim(staging_key) <> ''), + ADD CONSTRAINT attachments_pipeline_version_positive CHECK (pipeline_version > 0), + ADD CONSTRAINT attachments_status_supported CHECK (status IN ('queued', 'processing', 'ready', 'failed')), + ADD CONSTRAINT attachments_status_error_consistency CHECK ( + (status = 'failed' AND error_code IS NOT NULL AND btrim(error_code) <> '') + OR (status IN ('queued', 'processing', 'ready') AND error_code IS NULL) + ); + +CREATE TABLE attachment_variants ( + attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, + pipeline_version INTEGER NOT NULL, + name VARCHAR(32) NOT NULL, + object_key TEXT NOT NULL UNIQUE, + content_type VARCHAR(32) NOT NULL, + size_bytes BIGINT NOT NULL, + width INTEGER NOT NULL, + height INTEGER NOT NULL, + sha256 BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (attachment_id, pipeline_version, name), + CONSTRAINT attachment_variants_name_supported CHECK (name IN ('thumbnail', 'crop', 'optimized')), + CONSTRAINT attachment_variants_content_type_supported CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')), + CONSTRAINT attachment_variants_values_valid CHECK ( + pipeline_version > 0 AND btrim(object_key) <> '' AND size_bytes > 0 + AND width > 0 AND height > 0 AND octet_length(sha256) = 32 + ) +); + +CREATE TABLE attachment_jobs ( + job_id UUID PRIMARY KEY, + attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, + schema_version INTEGER NOT NULL DEFAULT 1, + job_type TEXT NOT NULL DEFAULT 'attachment.process.v1', + pipeline_version INTEGER NOT NULL, + attempt INTEGER NOT NULL DEFAULT 1, + max_attempts INTEGER NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'queued', + error_code TEXT, + published_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (attachment_id, pipeline_version), + CONSTRAINT attachment_jobs_schema_supported CHECK (schema_version = 1 AND job_type = 'attachment.process.v1'), + CONSTRAINT attachment_jobs_attempts_valid CHECK (attempt BETWEEN 1 AND max_attempts AND max_attempts > 0), + CONSTRAINT attachment_jobs_status_supported CHECK (status IN ('queued', 'processing', 'succeeded', 'failed')), + CONSTRAINT attachment_jobs_error_consistency CHECK ( + (status = 'failed' AND error_code IS NOT NULL AND btrim(error_code) <> '') OR status <> 'failed' + ) +); + +CREATE INDEX attachment_jobs_dispatch_idx ON attachment_jobs (created_at, job_id) + WHERE status = 'queued' AND published_at IS NULL; + +COMMIT; + diff --git a/migrations/000005_level4_jobs.down.sql b/migrations/000005_level4_jobs.down.sql new file mode 100644 index 0000000..77ed7d5 --- /dev/null +++ b/migrations/000005_level4_jobs.down.sql @@ -0,0 +1,20 @@ +BEGIN; + +DROP TABLE IF EXISTS attachment_job_events; +DROP INDEX IF EXISTS attachment_jobs_lease_idx; +DROP INDEX IF EXISTS attachment_jobs_dispatch_idx; + +ALTER TABLE attachment_jobs + DROP CONSTRAINT IF EXISTS attachment_jobs_replay_count_nonnegative, + DROP CONSTRAINT IF EXISTS attachment_jobs_lease_consistency, + DROP COLUMN IF EXISTS replay_count, + DROP COLUMN IF EXISTS leased_by, + DROP COLUMN IF EXISTS lease_until, + DROP COLUMN IF EXISTS available_at; + +CREATE INDEX attachment_jobs_dispatch_idx + ON attachment_jobs (created_at, job_id) + WHERE status = 'queued' AND published_at IS NULL; + +COMMIT; + diff --git a/migrations/000005_level4_jobs.up.sql b/migrations/000005_level4_jobs.up.sql new file mode 100644 index 0000000..2677203 --- /dev/null +++ b/migrations/000005_level4_jobs.up.sql @@ -0,0 +1,52 @@ +BEGIN; + +ALTER TABLE attachment_jobs + ADD COLUMN available_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + ADD COLUMN lease_until TIMESTAMPTZ, + ADD COLUMN leased_by TEXT, + ADD COLUMN replay_count INTEGER NOT NULL DEFAULT 0; + +-- An upgrade can encounter a job left in processing by an older worker that +-- had no lease support. Requeue it through the outbox instead of inventing an +-- unbounded lease. +UPDATE attachment_jobs +SET status = 'queued', published_at = NULL, available_at = CURRENT_TIMESTAMP, + updated_at = CURRENT_TIMESTAMP +WHERE status = 'processing'; + +ALTER TABLE attachment_jobs + ADD CONSTRAINT attachment_jobs_lease_consistency CHECK ( + (status = 'processing' AND lease_until IS NOT NULL AND leased_by IS NOT NULL AND btrim(leased_by) <> '') + OR (status <> 'processing' AND lease_until IS NULL AND leased_by IS NULL) + ), + ADD CONSTRAINT attachment_jobs_replay_count_nonnegative CHECK (replay_count >= 0); + +DROP INDEX attachment_jobs_dispatch_idx; +CREATE INDEX attachment_jobs_dispatch_idx + ON attachment_jobs (available_at, created_at, job_id) + WHERE status = 'queued' AND published_at IS NULL; + +CREATE INDEX attachment_jobs_lease_idx + ON attachment_jobs (lease_until, job_id) + WHERE status = 'processing'; + +CREATE TABLE attachment_job_events ( + event_id BIGSERIAL PRIMARY KEY, + job_id UUID NOT NULL REFERENCES attachment_jobs(job_id) ON DELETE CASCADE, + event_type VARCHAR(32) NOT NULL, + previous_status VARCHAR(16) NOT NULL, + new_status VARCHAR(16) NOT NULL, + attempt INTEGER NOT NULL, + error_code TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT attachment_job_events_type_supported CHECK ( + event_type IN ('retry_scheduled', 'lease_recovered', 'operator_replay', 'permanent_failure', 'completed') + ), + CONSTRAINT attachment_job_events_attempt_positive CHECK (attempt > 0) +); + +CREATE INDEX attachment_job_events_job_idx + ON attachment_job_events (job_id, created_at, event_id); + +COMMIT; + diff --git a/migrations/000006_versioned_pipeline.down.sql b/migrations/000006_versioned_pipeline.down.sql new file mode 100644 index 0000000..0d8f70c --- /dev/null +++ b/migrations/000006_versioned_pipeline.down.sql @@ -0,0 +1,21 @@ +BEGIN; + +DELETE FROM attachment_job_events WHERE event_type IN ('version_upgrade', 'superseded'); +UPDATE attachment_jobs +SET status='failed', error_code='superseded_pipeline', + lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP +WHERE status='superseded'; + +ALTER TABLE attachment_job_events + DROP CONSTRAINT attachment_job_events_type_supported, + ADD CONSTRAINT attachment_job_events_type_supported CHECK ( + event_type IN ('retry_scheduled', 'lease_recovered', 'operator_replay', 'permanent_failure', 'completed') + ); + +ALTER TABLE attachment_jobs + DROP CONSTRAINT attachment_jobs_status_supported, + ADD CONSTRAINT attachment_jobs_status_supported + CHECK (status IN ('queued', 'processing', 'succeeded', 'failed')); + +COMMIT; + diff --git a/migrations/000006_versioned_pipeline.up.sql b/migrations/000006_versioned_pipeline.up.sql new file mode 100644 index 0000000..d6d92a9 --- /dev/null +++ b/migrations/000006_versioned_pipeline.up.sql @@ -0,0 +1,16 @@ +BEGIN; + +ALTER TABLE attachment_jobs + DROP CONSTRAINT attachment_jobs_status_supported, + ADD CONSTRAINT attachment_jobs_status_supported + CHECK (status IN ('queued', 'processing', 'succeeded', 'failed', 'superseded')); + +ALTER TABLE attachment_job_events + DROP CONSTRAINT attachment_job_events_type_supported, + ADD CONSTRAINT attachment_job_events_type_supported CHECK ( + event_type IN ('retry_scheduled', 'lease_recovered', 'operator_replay', + 'permanent_failure', 'completed', 'version_upgrade', 'superseded') + ); + +COMMIT; + diff --git a/migrations/000007_trace_context.down.sql b/migrations/000007_trace_context.down.sql new file mode 100644 index 0000000..ff3f936 --- /dev/null +++ b/migrations/000007_trace_context.down.sql @@ -0,0 +1,4 @@ +ALTER TABLE attachment_jobs + DROP COLUMN IF EXISTS tracestate, + DROP COLUMN IF EXISTS traceparent; + diff --git a/migrations/000007_trace_context.up.sql b/migrations/000007_trace_context.up.sql new file mode 100644 index 0000000..1f41aa3 --- /dev/null +++ b/migrations/000007_trace_context.up.sql @@ -0,0 +1,4 @@ +ALTER TABLE attachment_jobs + ADD COLUMN traceparent varchar(55), + ADD COLUMN tracestate varchar(512); + diff --git a/migrations/000008_login_rate_limits.down.sql b/migrations/000008_login_rate_limits.down.sql new file mode 100644 index 0000000..6d383df --- /dev/null +++ b/migrations/000008_login_rate_limits.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS login_rate_limits; diff --git a/migrations/000008_login_rate_limits.up.sql b/migrations/000008_login_rate_limits.up.sql new file mode 100644 index 0000000..b61811c --- /dev/null +++ b/migrations/000008_login_rate_limits.up.sql @@ -0,0 +1,17 @@ +BEGIN; + +CREATE TABLE login_rate_limits ( + identifier_hash BYTEA PRIMARY KEY, + window_started_at TIMESTAMPTZ NOT NULL, + attempts INTEGER NOT NULL, + + CONSTRAINT login_rate_limits_hash_length + CHECK (octet_length(identifier_hash) = 32), + CONSTRAINT login_rate_limits_attempts_positive + CHECK (attempts > 0) +); + +CREATE INDEX login_rate_limits_window_started_at_idx + ON login_rate_limits (window_started_at); + +COMMIT; diff --git a/scripts/bootstrap-dependencies.sh b/scripts/bootstrap-dependencies.sh new file mode 100755 index 0000000..663152f --- /dev/null +++ b/scripts/bootstrap-dependencies.sh @@ -0,0 +1,55 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +docker compose up -d postgres redis minio broker dependency-gateway + +wait_for() { + service=$1 + shift + attempts=0 + until docker compose exec -T "$service" "$@" >/dev/null 2>&1; do + attempts=$((attempts + 1)) + if [ "$attempts" -ge 60 ]; then + printf '%s\n' "Timed out waiting for $service" >&2 + exit 1 + fi + sleep 2 + done +} + +wait_for postgres pg_isready -U lab7_admin -d messenger +wait_for redis redis-cli -u redis://api:$(cat secrets/redis_api_password.txt)@127.0.0.1:6379 ping +wait_for broker rabbitmq-diagnostics -q ping + +docker compose run --rm migrate +docker compose exec -T postgres sh -ec ' + export PGPASSWORD=$(cat /run/secrets/postgres_admin_password) + exec psql -v ON_ERROR_STOP=1 -U lab7_admin -d messenger -f /run/secrets/postgres_roles +' + +docker compose run --rm minio-bootstrap + +docker compose exec -T broker sh -ec ' + dispatcher_password=$(cat /run/secrets/broker_dispatcher_password) + worker_password=$(cat /run/secrets/broker_worker_password) + if rabbitmqctl list_users -q | cut -f1 | grep -qx dispatcher; then + rabbitmqctl change_password dispatcher "$dispatcher_password" >/dev/null + else + rabbitmqctl add_user dispatcher "$dispatcher_password" >/dev/null + fi + if rabbitmqctl list_users -q | cut -f1 | grep -qx worker; then + rabbitmqctl change_password worker "$worker_password" >/dev/null + else + rabbitmqctl add_user worker "$worker_password" >/dev/null + fi + rabbitmqctl set_permissions -p / dispatcher "^attachment[.]process[.]v1$" "^amq[.]default$" "^$" >/dev/null + rabbitmqctl set_permissions -p / worker "^attachment[.]process[.]v1$" "^$" "^attachment[.]process[.]v1$" >/dev/null + if rabbitmqctl list_users -q | cut -f1 | grep -qx guest; then + rabbitmqctl delete_user guest >/dev/null + fi +' + +printf '%s\n' "PostgreSQL roles, Redis ACL, MinIO policies and RabbitMQ identities are configured." diff --git a/scripts/bootstrap-openbao.sh b/scripts/bootstrap-openbao.sh new file mode 100755 index 0000000..c22f0df --- /dev/null +++ b/scripts/bootstrap-openbao.sh @@ -0,0 +1,81 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +operator_dir="$project_root/.operator" +state_file="$operator_dir/openbao-init.json" +cd "$project_root" + +command -v python3 >/dev/null 2>&1 || { + printf '%s\n' "Python 3 is required for OpenBao operator bootstrap" >&2 + exit 1 +} + +json_field() { + python3 -c 'import json, sys +value = json.load(sys.stdin) +for part in sys.argv[1].split("."): + value = value[int(part)] if isinstance(value, list) else value[part] +print(str(value).lower() if isinstance(value, bool) else value)' "$1" +} + +umask 077 +mkdir -p "$operator_dir" "$project_root/secrets/openbao" +chmod 700 "$operator_dir" +docker compose up -d openbao + +attempts=0 +until status_json=$(docker compose exec -T openbao bao status -format=json 2>/dev/null) || [ -n "${status_json:-}" ]; do + attempts=$((attempts + 1)) + if [ "$attempts" -ge 60 ]; then + printf '%s\n' "Timed out waiting for OpenBao" >&2 + exit 1 + fi + sleep 2 +done + +initialized=$(printf '%s' "$status_json" | json_field initialized) +if [ "$initialized" != true ]; then + init_json=$(docker compose exec -T openbao bao operator init -format=json -key-shares=1 -key-threshold=1) + printf '%s\n' "$init_json" > "$state_file" + chmod 600 "$state_file" +fi + +if [ ! -s "$state_file" ]; then + printf '%s\n' "OpenBao is initialized but .operator/openbao-init.json is unavailable; an operator must provide unseal material" >&2 + exit 1 +fi + +unseal_key=$(json_field unseal_keys_b64.0 < "$state_file") +root_token=$(json_field root_token < "$state_file") +sealed=$(docker compose exec -T openbao bao status -format=json 2>/dev/null | json_field sealed) +if [ "$sealed" = true ]; then + docker compose exec -T openbao bao operator unseal "$unseal_key" >/dev/null +fi + +bao_root() { + docker compose exec -T -e BAO_TOKEN="$root_token" openbao bao "$@" +} + +if ! bao_root secrets list -format=json | grep -q '"secret/"'; then + bao_root secrets enable -path=secret kv-v2 >/dev/null +fi +if ! bao_root auth list -format=json | grep -q '"approle/"'; then + bao_root auth enable approle >/dev/null +fi + +for role in api worker dispatcher; do + bao_root policy write "$role" "/policies/$role-policy.hcl" >/dev/null + bao_root kv put "secret/$role" "@/bootstrap/$role.json" >/dev/null + bao_root write "auth/approle/role/$role" \ + "token_policies=$role" token_ttl=15m token_max_ttl=30m \ + secret_id_ttl=168h secret_id_num_uses=0 >/dev/null + bao_root read -field=role_id "auth/approle/role/$role/role-id" \ + > "$project_root/secrets/openbao/${role}_role_id.txt" + bao_root write -f -field=secret_id "auth/approle/role/$role/secret-id" \ + > "$project_root/secrets/openbao/${role}_secret_id.txt" + chmod 600 "$project_root/secrets/openbao/${role}_role_id.txt" \ + "$project_root/secrets/openbao/${role}_secret_id.txt" +done + +printf '%s\n' "OpenBao is unsealed and scoped AppRoles are configured; root/unseal material remains under .operator only." diff --git a/scripts/cleanup-lab.sh b/scripts/cleanup-lab.sh new file mode 100755 index 0000000..b094ebc --- /dev/null +++ b/scripts/cleanup-lab.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env sh +set -eu + +cd "$(dirname "$0")/.." + +# Keep named volumes (business data and telemetry history) intact. Only this +# Compose project's containers/networks and the four images built by lab7 are +# removed. Pulled third-party images and resources from other labs are never +# selected by this script. +docker compose down --remove-orphans + +for image in \ + mtusi2026lab7-app:latest \ + mtusi2026lab7-ingress:latest \ + mtusi2026lab7-minio:RELEASE.2025-10-15T17-29-55Z \ + mtusi2026lab7-mc:RELEASE.2025-08-13T08-35-41Z +do + if docker image inspect "$image" >/dev/null 2>&1; then + docker image rm "$image" + fi +done + +echo "lab7 containers are stopped; local lab7 images removed; named volumes preserved" + diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100755 index 0000000..c48af9e --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,275 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +secrets_dir="$project_root/secrets" +pki_dir="$secrets_dir/pki" +openbao_dir="$secrets_dir/openbao" +openbao_data_dir="$project_root/volumes/openbao" + +command -v openssl >/dev/null 2>&1 || { + printf '%s\n' "openssl is required" >&2 + exit 1 +} + +umask 077 +mkdir -p "$secrets_dir" "$pki_dir" "$openbao_dir" "$openbao_data_dir" +chmod 700 "$secrets_dir" "$pki_dir" "$openbao_dir" "$openbao_data_dir" + +write_if_missing() { + destination=$1 + value=$2 + if [ ! -e "$destination" ]; then + printf '%s' "$value" > "$destination" + fi + chmod 600 "$destination" +} + +random_hex() { + openssl rand -hex "$1" +} + +write_if_missing "$secrets_dir/postgres_admin_password.txt" "$(random_hex 24)" +write_if_missing "$secrets_dir/postgres_api_password.txt" "$(random_hex 24)" +write_if_missing "$secrets_dir/postgres_worker_password.txt" "$(random_hex 24)" +write_if_missing "$secrets_dir/postgres_dispatcher_password.txt" "$(random_hex 24)" +write_if_missing "$secrets_dir/cursor_signing_key.txt" "$(random_hex 32)" +write_if_missing "$secrets_dir/minio_root_user.txt" "lab7-root" +write_if_missing "$secrets_dir/minio_root_password.txt" "$(random_hex 24)" +write_if_missing "$secrets_dir/s3_api_access_key.txt" "lab7-api" +write_if_missing "$secrets_dir/s3_api_secret_key.txt" "$(random_hex 24)" +write_if_missing "$secrets_dir/s3_worker_access_key.txt" "lab7-worker" +write_if_missing "$secrets_dir/s3_worker_secret_key.txt" "$(random_hex 24)" +write_if_missing "$secrets_dir/broker_dispatcher_password.txt" "$(random_hex 24)" +write_if_missing "$secrets_dir/broker_worker_password.txt" "$(random_hex 24)" +write_if_missing "$secrets_dir/redis_api_password.txt" "$(random_hex 24)" +write_if_missing "$secrets_dir/grafana_admin_password.txt" "$(random_hex 24)" + +if [ ! -e "$pki_dir/ca.key" ]; then + openssl req -x509 -newkey rsa:3072 -sha256 -nodes -days 3650 \ + -subj '/CN=MTUSI lab7 local root CA' \ + -addext 'basicConstraints=critical,CA:TRUE,pathlen:0' \ + -addext 'keyUsage=critical,keyCertSign,cRLSign' \ + -addext 'subjectKeyIdentifier=hash' \ + -keyout "$pki_dir/ca.key" -out "$pki_dir/ca.crt" +fi + +generate_leaf() { + name=$1 + common_name=$2 + subject_alt_name=$3 + extended_usage=$4 + if [ -e "$pki_dir/$name.crt" ] && [ -e "$pki_dir/$name.key" ]; then + return + fi + ext_file="$pki_dir/$name.ext" + csr_file="$pki_dir/$name.csr" + { + printf 'subjectAltName=%s\n' "$subject_alt_name" + printf 'extendedKeyUsage=%s\n' "$extended_usage" + printf 'keyUsage=digitalSignature,keyEncipherment\n' + } > "$ext_file" + openssl req -new -newkey rsa:2048 -sha256 -nodes \ + -subj "/CN=$common_name" \ + -keyout "$pki_dir/$name.key" -out "$csr_file" + openssl x509 -req -sha256 -days 365 \ + -in "$csr_file" -CA "$pki_dir/ca.crt" -CAkey "$pki_dir/ca.key" \ + -CAcreateserial -extfile "$ext_file" -out "$pki_dir/$name.crt" + rm -f "$csr_file" "$ext_file" +} + +generate_leaf ingress localhost 'DNS:localhost,IP:127.0.0.1' serverAuth +generate_leaf api api 'DNS:api,URI:spiffe://mtusi/lab7/api' serverAuth +generate_leaf lb-client load-balancer 'URI:spiffe://mtusi/lab7/lb' clientAuth +generate_leaf wrong-client intruder 'URI:spiffe://mtusi/lab7/intruder' clientAuth +generate_leaf api-client api 'URI:spiffe://mtusi/lab7/api' clientAuth +generate_leaf worker-client worker 'URI:spiffe://mtusi/lab7/worker' clientAuth +generate_leaf dispatcher-client dispatcher 'URI:spiffe://mtusi/lab7/dispatcher' clientAuth +generate_leaf dependency-gateway dependency-gateway 'DNS:dependency-gateway' serverAuth +generate_leaf telemetry-gateway telemetry-gateway 'DNS:telemetry-gateway,DNS:localhost,IP:127.0.0.1' serverAuth +generate_leaf postgres postgres 'DNS:postgres' serverAuth +generate_leaf openbao openbao 'DNS:openbao,DNS:localhost,IP:127.0.0.1' serverAuth +generate_leaf collector-client otel-collector 'URI:spiffe://mtusi/lab7/collector' clientAuth +generate_leaf prometheus-client prometheus 'URI:spiffe://mtusi/lab7/prometheus' clientAuth +generate_leaf grafana-client grafana 'URI:spiffe://mtusi/lab7/grafana' clientAuth + +if [ ! -e "$pki_dir/foreign-ca.key" ]; then + openssl req -x509 -newkey rsa:2048 -sha256 -nodes -days 365 \ + -subj '/CN=Untrusted lab7 CA' \ + -addext 'basicConstraints=critical,CA:TRUE,pathlen:0' \ + -addext 'keyUsage=critical,keyCertSign,cRLSign' \ + -addext 'subjectKeyIdentifier=hash' \ + -keyout "$pki_dir/foreign-ca.key" -out "$pki_dir/foreign-ca.crt" + openssl req -new -newkey rsa:2048 -sha256 -nodes \ + -subj '/CN=foreign-client' \ + -addext 'subjectAltName=URI:spiffe://mtusi/lab7/lb' \ + -keyout "$pki_dir/foreign-client.key" -out "$pki_dir/foreign-client.csr" + printf '%s\n' 'subjectAltName=URI:spiffe://mtusi/lab7/lb' 'extendedKeyUsage=clientAuth' > "$pki_dir/foreign-client.ext" + openssl x509 -req -sha256 -days 365 \ + -in "$pki_dir/foreign-client.csr" \ + -CA "$pki_dir/foreign-ca.crt" -CAkey "$pki_dir/foreign-ca.key" \ + -CAcreateserial -extfile "$pki_dir/foreign-client.ext" \ + -out "$pki_dir/foreign-client.crt" + rm -f "$pki_dir/foreign-client.csr" "$pki_dir/foreign-client.ext" +fi + +for name in ingress lb-client wrong-client dependency-gateway telemetry-gateway foreign-client; do + cat "$pki_dir/$name.crt" "$pki_dir/$name.key" > "$pki_dir/$name.pem" +done +chmod 600 "$pki_dir"/*.key "$pki_dir"/*.pem +chmod 644 "$pki_dir"/*.crt +# Collector and Prometheus images use their own non-root UIDs. The additional +# in-container GID below can read only these client keys; host access remains +# limited to the local operator group. +chmod 640 "$pki_dir/collector-client.key" "$pki_dir/prometheus-client.key" + +write_if_missing "$pki_dir/api-client-uris.txt" 'spiffe://mtusi/lab7/lb' + +write_grafana_tls() { + sed 's/^/ /' "$1" +} + +{ + cat <<'EOF' +apiVersion: 1 + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: https://telemetry-gateway:9090 + isDefault: true + editable: false + jsonData: + tlsAuth: true + secureJsonData: + tlsClientCert: | +EOF + write_grafana_tls "$pki_dir/grafana-client.crt" + printf '%s\n' ' tlsClientKey: |' + write_grafana_tls "$pki_dir/grafana-client.key" + cat <<'EOF' + + - name: Loki + uid: loki + type: loki + access: proxy + url: https://telemetry-gateway:3100 + editable: false + jsonData: + tlsAuth: true + derivedFields: + - name: TraceID + matcherRegex: '([0-9a-f]{32})' + datasourceUid: tempo + url: '$${__value.raw}' + secureJsonData: + tlsClientCert: | +EOF + write_grafana_tls "$pki_dir/grafana-client.crt" + printf '%s\n' ' tlsClientKey: |' + write_grafana_tls "$pki_dir/grafana-client.key" + cat <<'EOF' + + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: https://telemetry-gateway:3200 + editable: false + jsonData: + tlsAuth: true + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: -1m + spanEndTimeShift: 1m + tags: + - key: service.name + value: service_name + filterByTraceID: true + filterBySpanID: true + serviceMap: + datasourceUid: prometheus + nodeGraph: + enabled: true + secureJsonData: + tlsClientCert: | +EOF + write_grafana_tls "$pki_dir/grafana-client.crt" + printf '%s\n' ' tlsClientKey: |' + write_grafana_tls "$pki_dir/grafana-client.key" +} > "$secrets_dir/grafana-datasources.yaml" +chmod 600 "$secrets_dir/grafana-datasources.yaml" + +postgres_api_password=$(cat "$secrets_dir/postgres_api_password.txt") +postgres_worker_password=$(cat "$secrets_dir/postgres_worker_password.txt") +postgres_dispatcher_password=$(cat "$secrets_dir/postgres_dispatcher_password.txt") +redis_api_password=$(cat "$secrets_dir/redis_api_password.txt") +s3_api_access_key=$(cat "$secrets_dir/s3_api_access_key.txt") +s3_api_secret_key=$(cat "$secrets_dir/s3_api_secret_key.txt") +s3_worker_access_key=$(cat "$secrets_dir/s3_worker_access_key.txt") +s3_worker_secret_key=$(cat "$secrets_dir/s3_worker_secret_key.txt") +broker_dispatcher_password=$(cat "$secrets_dir/broker_dispatcher_password.txt") +broker_worker_password=$(cat "$secrets_dir/broker_worker_password.txt") +cursor_signing_key=$(cat "$secrets_dir/cursor_signing_key.txt") + +cat > "$openbao_dir/api.json" < "$openbao_dir/worker.json" < "$openbao_dir/dispatcher.json" < "$secrets_dir/redis.conf" <${redis_api_password} ~chat:v2:* +get +set +del +ping +EOF + +cat > "$secrets_dir/postgres-roles.sql" </dev/null +./scripts/bootstrap-openbao.sh >/dev/null + +# Recreate services so refreshed AppRole SecretID files are mounted. Business +# data, sessions, object data, broker state and telemetry volumes are untouched. +docker compose up -d --build --force-recreate api worker dispatcher ingress telemetry-gateway + +attempts=0 +until curl --silent --fail --cacert secrets/pki/ca.crt https://127.0.0.1:${HTTPS_PORT:-8443}/health/ready >/dev/null; do + attempts=$((attempts + 1)) + if [ "$attempts" -ge 60 ]; then + printf '%s\n' "HTTPS readiness did not recover after restart" >&2 + exit 1 + fi + sleep 2 +done diff --git a/scripts/rotate-leaf-grade4.sh b/scripts/rotate-leaf-grade4.sh new file mode 100755 index 0000000..22c16cd --- /dev/null +++ b/scripts/rotate-leaf-grade4.sh @@ -0,0 +1,109 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +pki_dir="$project_root/secrets/pki" +cd "$project_root" + +temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/mtusi-lab7-leaf.XXXXXX") +case "$temp_dir" in + "${TMPDIR:-/tmp}"/mtusi-lab7-leaf.*) ;; + *) printf '%s\n' "Unexpected temporary directory" >&2; exit 1 ;; +esac + +old_uri=$(sed -n '1p' "$pki_dir/api-client-uris.txt") +cp "$pki_dir/lb-client.crt" "$temp_dir/old.crt" +cp "$pki_dir/lb-client.key" "$temp_dir/old.key" +cp "$pki_dir/lb-client.pem" "$temp_dir/old.pem" +app_image_before=$(docker image inspect -f '{{.Id}}' mtusi2026lab7-app:latest) +ingress_image_before=$(docker image inspect -f '{{.Id}}' mtusi2026lab7-ingress:latest) +new_uri="spiffe://mtusi/lab7/lb-$(openssl rand -hex 8)" +completed=false + +recreate_edge() { + docker compose up -d --no-deps --no-build --force-recreate api ingress >/dev/null 2>&1 +} + +restore_old_leaf() { + install -m 600 "$temp_dir/old.key" "$pki_dir/lb-client.key" + install -m 644 "$temp_dir/old.crt" "$pki_dir/lb-client.crt" + install -m 600 "$temp_dir/old.pem" "$pki_dir/lb-client.pem" + printf '%s' "$old_uri" > "$pki_dir/api-client-uris.txt" + chmod 600 "$pki_dir/api-client-uris.txt" + recreate_edge || true +} + +cleanup() { + if [ "$completed" != true ]; then + restore_old_leaf + fi + rm -f "$temp_dir/old.crt" "$temp_dir/old.key" "$temp_dir/old.pem" \ + "$temp_dir/new.crt" "$temp_dir/new.key" "$temp_dir/new.csr" "$temp_dir/new.ext" \ + "$temp_dir/expired.crt" "$temp_dir/expired.key" "$temp_dir/expired.csr" "$temp_dir/expired.ext" + rmdir "$temp_dir" 2>/dev/null || true +} +trap cleanup EXIT HUP INT TERM + +cat > "$temp_dir/new.ext" </dev/null 2>&1 +openssl x509 -req -sha256 -days 365 -in "$temp_dir/new.csr" \ + -CA "$pki_dir/ca.crt" -CAkey "$pki_dir/ca.key" -CAserial "$pki_dir/ca.srl" \ + -extfile "$temp_dir/new.ext" -out "$temp_dir/new.crt" >/dev/null 2>&1 +install -m 600 "$temp_dir/new.key" "$pki_dir/lb-client.key" +install -m 644 "$temp_dir/new.crt" "$pki_dir/lb-client.crt" +cat "$temp_dir/new.crt" "$temp_dir/new.key" > "$pki_dir/lb-client.pem" +chmod 600 "$pki_dir/lb-client.pem" +printf '%s' "$new_uri" > "$pki_dir/api-client-uris.txt" +chmod 600 "$pki_dir/api-client-uris.txt" + +recreate_edge +attempts=0 +until curl --silent --show-error --fail --cacert "$pki_dir/ca.crt" https://127.0.0.1:8443/health/live >/dev/null 2>&1; do + attempts=$((attempts + 1)) + [ "$attempts" -lt 40 ] || { printf '%s\n' "Rotated edge did not become ready" >&2; exit 1; } + sleep 1 +done + +if docker compose --profile tests run --rm --no-deps -v "$temp_dir:/rotation-old:ro" \ + --entrypoint curl security-test --silent --show-error --fail --cacert /run/secrets/ca.crt \ + --cert /rotation-old/old.crt --key /rotation-old/old.key https://api:8444/health/live >/dev/null 2>&1; then + printf '%s\n' "Old leaf identity is still accepted" >&2 + exit 1 +fi +docker compose --profile tests run --rm --no-deps --entrypoint curl security-test \ + --silent --show-error --fail --cacert /run/secrets/ca.crt \ + --cert /run/secrets/lb-client.crt --key /run/secrets/lb-client.key \ + https://api:8444/health/live >/dev/null + +cat > "$temp_dir/expired.ext" </dev/null 2>&1 +openssl x509 -req -sha256 -days 0 -in "$temp_dir/expired.csr" \ + -CA "$pki_dir/ca.crt" -CAkey "$pki_dir/ca.key" -CAserial "$pki_dir/ca.srl" \ + -extfile "$temp_dir/expired.ext" -out "$temp_dir/expired.crt" >/dev/null 2>&1 +sleep 2 +if docker compose --profile tests run --rm --no-deps -v "$temp_dir:/expired:ro" \ + --entrypoint curl security-test --silent --show-error --fail --cacert /run/secrets/ca.crt \ + --cert /expired/expired.crt --key /expired/expired.key https://api:8444/health/live >/dev/null 2>&1; then + printf '%s\n' "Expired leaf certificate is accepted" >&2 + exit 1 +fi + +app_image_after=$(docker image inspect -f '{{.Id}}' mtusi2026lab7-app:latest) +ingress_image_after=$(docker image inspect -f '{{.Id}}' mtusi2026lab7-ingress:latest) +[ "$app_image_before" = "$app_image_after" ] && [ "$ingress_image_before" = "$ingress_image_after" ] || { + printf '%s\n' "Image changed during leaf rotation" >&2 + exit 1 +} + +completed=true +printf '%s\n' "PASS: LB leaf rotated without rebuild; old identity and expired leaf rejected" diff --git a/scripts/rotate-secret-grade4.sh b/scripts/rotate-secret-grade4.sh new file mode 100755 index 0000000..bed4d04 --- /dev/null +++ b/scripts/rotate-secret-grade4.sh @@ -0,0 +1,61 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +state_file="$project_root/.operator/openbao-init.json" +password_file="$project_root/secrets/broker_worker_password.txt" +[ -s "$state_file" ] || { printf '%s\n' "OpenBao operator state is required" >&2; exit 1; } +[ -s "$password_file" ] || { printf '%s\n' "Broker worker password is required" >&2; exit 1; } + +old_password=$(cat "$password_file") +new_password=$(openssl rand -hex 24) +root_token=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1], encoding="utf-8"))["root_token"])' "$state_file") +app_image_before=$(docker image inspect -f '{{.Id}}' mtusi2026lab7-app:latest) +completed=false + +restore_old_secret() { + printf '%s' "$old_password" > "$password_file" + chmod 600 "$password_file" + ./scripts/init-secrets.sh >/dev/null + docker compose exec -T -e BAO_TOKEN="$root_token" openbao \ + bao kv put secret/worker @/bootstrap/worker.json >/dev/null 2>&1 || true + docker compose exec -T broker rabbitmqctl change_password worker "$old_password" >/dev/null 2>&1 || true + docker compose up -d --no-deps --no-build --force-recreate worker >/dev/null 2>&1 || true +} + +cleanup() { + if [ "$completed" != true ]; then + restore_old_secret + fi +} +trap cleanup EXIT HUP INT TERM + +printf '%s' "$new_password" > "$password_file" +chmod 600 "$password_file" +./scripts/init-secrets.sh >/dev/null +docker compose exec -T -e BAO_TOKEN="$root_token" openbao \ + bao kv put secret/worker @/bootstrap/worker.json >/dev/null +docker compose exec -T broker rabbitmqctl change_password worker "$new_password" >/dev/null + +if docker compose exec -T broker rabbitmqctl authenticate_user worker "$old_password" >/dev/null 2>&1; then + printf '%s\n' "Old broker secret is still accepted" >&2 + exit 1 +fi +docker compose exec -T broker rabbitmqctl authenticate_user worker "$new_password" >/dev/null + +docker compose up -d --no-deps --no-build --force-recreate worker >/dev/null +sleep 4 +[ -n "$(docker compose ps --status running -q worker)" ] || { + printf '%s\n' "Worker did not restart with the rotated secret" >&2 + exit 1 +} +app_image_after=$(docker image inspect -f '{{.Id}}' mtusi2026lab7-app:latest) +[ "$app_image_before" = "$app_image_after" ] || { + printf '%s\n' "Application image changed during secret rotation" >&2 + exit 1 +} + +completed=true +printf '%s\n' "PASS: worker broker secret rotated, old credential revoked, image unchanged" diff --git a/scripts/scan-grade4.sh b/scripts/scan-grade4.sh new file mode 100755 index 0000000..f247aeb --- /dev/null +++ b/scripts/scan-grade4.sh @@ -0,0 +1,44 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +trivy_version=0.76.2 +trivy_image="ghcr.io/aquasecurity/trivy:${trivy_version}@sha256:8f6bb947dbc528902e11f2f5be52f7b519f6a39d5d148f41166f2040499768fb" +trivy_cache="$project_root/.cache/trivy" +mkdir -p "$trivy_cache" + +docker pull "$trivy_image" >/dev/null + +printf '%s\n' "== Go reachable-vulnerability scan ==" +go run golang.org/x/vuln/cmd/govulncheck@v1.10.0 ./... + +for image in \ + mtusi2026lab7-app:latest \ + mtusi2026lab7-ingress:latest; do + printf '%s\n' "== Strict Trivy gate $trivy_version: $image ==" + docker run --rm --read-only --security-opt no-new-privileges:true --cap-drop ALL \ + --tmpfs /tmp:rw,nosuid,nodev,noexec \ + -v /var/run/docker.sock:/var/run/docker.sock:ro \ + -v "$trivy_cache:/root/.cache/trivy" \ + "$trivy_image" image --scanners vuln --severity HIGH,CRITICAL \ + --ignore-unfixed --no-progress --exit-code 1 "$image" +done + +printf '%s\n' \ + "== Informational vendor scan: findings are triaged in security/SCAN_TRIAGE.md ==" +for image in \ + mtusi2026lab7-minio:RELEASE.2025-10-15T17-29-55Z \ + mtusi2026lab7-mc:RELEASE.2025-08-13T08-35-41Z; do + printf '%s\n' "== Informational Trivy scan $trivy_version: $image ==" + docker run --rm --read-only --security-opt no-new-privileges:true --cap-drop ALL \ + --tmpfs /tmp:rw,nosuid,nodev,noexec \ + -v /var/run/docker.sock:/var/run/docker.sock:ro \ + -v "$trivy_cache:/root/.cache/trivy" \ + "$trivy_image" image --scanners vuln --severity HIGH,CRITICAL \ + --ignore-unfixed --no-progress --exit-code 0 "$image" +done + +printf '%s\n' \ + "PASS: authored images passed the strict gate; vendor residual risk is documented" diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 0000000..dad9b5b --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,41 @@ +#!/bin/sh +set -eu + +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +env_file=${ENV_FILE:-.env} +matched_container= + +compose() { + if [ -f "$env_file" ]; then + docker compose --env-file "$env_file" "$@" + else + docker compose "$@" + fi +} + +for container_id in $(compose ps -a -q api); do + instance_id=$(docker exec "$container_id" cat /tmp/instance-id 2>/dev/null || true) + if [ "$instance_id" = "$TARGET_INSTANCE_ID" ]; then + if [ -n "$matched_container" ]; then + printf '%s\n' "multiple API containers match instance $TARGET_INSTANCE_ID" >&2 + exit 1 + fi + matched_container=$container_id + fi +done + +if [ -z "$matched_container" ]; then + printf '%s\n' "API instance not found: $TARGET_INSTANCE_ID" >&2 + exit 1 +fi + +# A manual docker stop suppresses the container restart policy until the next +# explicit start, so the selected replica remains down for the whole test. +docker stop --time 5 "$matched_container" >/dev/null + +printf '%s\n' "stopped API instance $TARGET_INSTANCE_ID" + diff --git a/security/SCAN_TRIAGE.md b/security/SCAN_TRIAGE.md new file mode 100644 index 0000000..5366478 --- /dev/null +++ b/security/SCAN_TRIAGE.md @@ -0,0 +1,48 @@ +# Triage dependency/image scan + +Дата проверки: 2026-11-22. Команда: `make scan-grade4`. + +## Политика проверки + +`govulncheck v1.10.0` проверяет reachable vulnerabilities во всём собственном Go-коде. Trivy 0.76.2 запускается из закреплённого digest и проверяет четыре локально собранных image по исправляемым `HIGH,CRITICAL` (`--ignore-unfixed`): + +- `app` и `ingress` — строгий gate с `--exit-code 1`; +- MinIO и `mc` — обязательный информационный scan с `--exit-code 0` и triage ниже. + +Разделение не скрывает vendor findings: полный вывод остаётся в логе команды. Оно не позволяет неизменяемому архивированному upstream навсегда блокировать воспроизводимую учебную сборку, но оставляет нулевой допуск к исправляемым HIGH/CRITICAL в коде и runtime, которыми управляет проект. Scanner container имеет read-only rootfs, `no-new-privileges`, drop всех capabilities и отдельный tmpfs; read-only Docker socket используется только для operator-owned scan, а не сервисом Compose. + +## Исправленные findings собственного scope + +Первичный scan нашёл HIGH в Go 1.27.1 и Alpine `musl`/`zlib`. Эти компоненты реально присутствовали в TLS/HTTP binaries и runtime, поэтому findings не списывались по одной только недостижимости. + +Builder обновлён до закреплённого Go 1.27.3, runtime — до закреплённого Alpine 3.24 с `apk upgrade --no-cache`. После пересборки: + +- `govulncheck`: `No vulnerabilities found`; +- `mtusi2026lab7-app:latest`: 0 исправляемых HIGH/CRITICAL; +- `mtusi2026lab7-ingress:latest`: 0 исправляемых HIGH/CRITICAL. + +Повторное появление finding в этих двух images завершит target с ненулевым кодом. + +## Остаточный риск MinIO и mc + +MinIO собран из последнего официального server release `RELEASE.2025-10-15T17-29-55Z`, `mc` — из `RELEASE.2025-08-13T08-35-41Z`; их builder/runtime также обновлены до Go 1.27.3 и Alpine 3.24. Это устранило findings базового образа и standard library, но не уязвимые версии зависимостей, закреплённые самим upstream: + +| Image | HIGH | CRITICAL | Основные пакеты | +| --- | ---: | ---: | --- | +| MinIO | 40 | 4 | `x/crypto`, `x/net`, `amqp091-go`, `grpc`, `thrift`, `go-jose`, `compress`, Prometheus/OTel | +| `mc` | 26 | 1 | `x/crypto`, `x/net`, `grpc`, `compress`, Prometheus | + +Проверка более нового module snapshot не дала безопасного официального upgrade path: те же версии зависимостей остаются в upstream `go.mod`. Официальные репозитории [MinIO](https://github.com/minio/minio) и [`mc`](https://github.com/minio/mc) архивированы и больше не поддерживаются, поэтому ожидать исправленного tagged release нельзя. + +Применимость и компенсирующие меры: + +- AMQP notifications, LDAP/KMS, federation и иные необязательные MinIO integrations в стенде не настроены; соответствующие пути не доступны через конфигурацию. +- MinIO не имеет host port и доступен только API/worker/bootstrap в закрытых сетях через TLS gateway; anonymous access запрещён, API/worker policies минимальны. +- root credentials монтируются только в одноразовый bootstrap container. `mc` не является daemon, не слушает сеть и завершается после идемпотентного создания bucket/users/policies. +- generic HTTP/crypto/compression dependencies MinIO потенциально достижимы. Их findings нельзя честно объявить ложными положительными; это принятый остаточный риск только учебного single-host стенда. + +Для production этот риск является блокирующим: нужно заменить MinIO поддерживаемым S3-compatible storage/maintained fork либо отдельно сопровождать проверенный fork с обновлёнными зависимостями и regression suite. Перевод vendor scan в строгий gate выполняется после такой замены; простое подавление CVE или непроверенный массовый `go get -u` не считается исправлением. + +## Итог + +`make scan-grade4` завершается успешно только если `govulncheck`, `app` и `ingress` проходят строгий gate. Vendor images всегда сканируются в той же команде, а их известный остаточный риск явно виден в выводе и в этом triage. Нулевой результат в собственном scope не означает отсутствие всех уязвимостей системы. diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 31da287..0b46ce0 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -1,19 +1,38 @@ -# Модель угроз — заполнить +# Модель угроз — lab7, уровень 4 ## Активы и акторы -TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. +Активы: password hashes, session tokens, сообщения и membership, оригиналы/thumbnail вложений, DB/S3/broker/Redis credentials, AppRole credentials, CA/leaf keys, OpenBao root/unseal material и telemetry. Пользовательские password/token и содержимое сообщений не должны попадать в логи или traces. + +Акторы: участник чата; зарегистрированный посторонний; внешний клиент без локального CA; атакующий с сетевым доступом к host; скомпрометированный API/worker/dispatcher; оператор стенда. Оператор доверенный и владеет CA key, `.operator/openbao-init.json` и bootstrap credentials. Docker daemon/host, kernel и локальная учётная запись оператора находятся вне защищаемой модели: их компрометация означает компрометацию всего single-host стенда. ## Границы доверия -TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. +Публичная граница — loopback TLS ingress 8443. Следующие границы — mTLS ingress→API, dispatcher/worker→broker, API/worker/dispatcher→Collector и отдельные mTLS telemetry backend paths. PostgreSQL/OpenBao используют native TLS; Redis/S3/broker/telemetry имеют TLS gateway и отдельный закрытый backend network. Secrets переходят из operator-generated ignored files в Compose secret mounts, затем AppRole выдаёт только allowlisted значения процессу. Полные ports, CA и identities перечислены в `contracts/trust-matrix.md`. | Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | | --- | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | TODO | - -На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. +| MITM подменяет публичный ingress или клиент принимает чужой CA/hostname | Клиент говорит только с lab7 ingress | TLS 1.3, local CA, SAN localhost/127.0.0.1, без `--insecure` | `make test-security`: empty trust store вызывает `SSLCertVerificationError` | CA key у локального оператора; CRL/OCSP нет | +| Клиент обходит LB через API:8444 или выдаёт себя за LB | Business API доступен только после ingress | API port не published; RequireAndVerifyClientCert; exact URI SAN allowlist | `make test-security-grade3`: no cert, foreign CA, wrong same-CA URI deny; correct LB allow | Компрометация LB private key даёт сетевую identity LB до ручного отзыва | +| Утечка DB превращает hashes в быстрый offline password recovery или legacy hash остаётся слабым | Password не хранится открыто/быстрым hash; policy обновляется | Argon2id, random 16-byte salt, PHC parameters, floor 19 MiB/t2/p1; successful-login compare-and-set rehash | `go test ./internal/security ./student_tests`; legacy `m=8192,t=1` заменён, plaintext отсутствует | Параметры учебные и требуют повторной калибровки на production hardware | +| Credential stuffing распределяется между двумя API и заставляет выполнять дорогой Argon2 | Лимит входа общий и применяется до KDF | Atomic UPSERT в PostgreSQL по SHA-256 normalized username; 5/60s; 429 + Retry-After; verify 23.485943 ms | `make test-rate-limit-grade3`; `make login-dos-benchmark`: около 117 ms CPU/min/identifier | Нет IP/device dimension; атакующий может перебирать много username | +| Уникальные username/session/idempotency keys бесконечно увеличивают auth tables | Истёкшее состояние не должно создавать storage/query bottleneck | Индексированный cleanup batch 256; первый запуск и далее раз в 128 операций; отдельный limiter cutoff `now-window`; `SKIP LOCKED` | `make test-state-pruning-grade4`: expired row удалена, active window сохранено | Это opportunistic cleanup, не отдельный scheduler; большой исторический backlog убывает постепенно | +| Посторонний читает/прикрепляет чужое вложение или подделывает `X-User-Id` | Доступ определяет Bearer user и membership | DB membership checks для metadata/content/message; Basic только login; X-User-Id игнорируется | `make test` public smoke | Stolen bearer token действует до expiry/logout; revocation — удаление session | +| Скомпрометированный API читает worker/admin secret или меняет policy | Сервис получает только свои полномочия | AppRole per service; exact KV v2 read path; API не имеет policy/write capabilities/root | `make test-openbao-policy` foreign read, policy admin, write deny | Secret после чтения находится в памяти процесса; SecretID 7 d и unlimited uses до revoke | +| Скомпрометированный API использует S3 root или изменяет готовые objects | API пишет только staging и читает ready attachments | Разные API/worker MinIO users/policies; root только bootstrap container | `./tests/minio_policy.sh`: attachment write, staging read, bucket create, anonymous GET deny | Worker имеет более широкие object rights, нужные pipeline | +| Чужой контейнер читает DB/broker/Redis или plaintext backend hop | Сеть и role ограничивают lateral movement | Separate internal networks; ports не published; DB/Rabbit/Redis ACL и разные roles; TLS gateway | runtime port inspection; S3/OpenBao policy tests; bootstrap ACL commands | Docker daemon/root может подключить контейнер к network; proxy→backend hop plaintext | +| Чужая same-CA identity пишет в broker/Collector или читает telemetry backend | Signals/jobs доступны только назначенному service | API/worker/dispatcher/Collector/Prometheus/Grafana mTLS leaf; HAProxy `verify required` и exact CN ACL; isolated backends | `make test-security-grade4`: no cert/same-CA intruder deny, scoped identities allow; grade3 backend test | CN ACL зависит от защиты CA; компрометация разрешённого leaf действует до отзыва | +| Старый или просроченный leaf продолжает работать после rotation | Только активная identity может войти | API URI allowlist — runtime secret; rotation удаляет old URI, TLS проверяет validity | `make rotate-leaf-grade4`: old URI и expired cert deny, new allow, image ID unchanged | Нет CRL/OCSP; отзыв выполняется allowlist/recreate оператором | +| Malformed/oversized request исчерпывает RAM/CPU | Один запрос ограничен до обработки | JSON `LimitReader`, attachment size limit, Argon floor/upper bounds, worker timeout/concurrency, container limits | unit/integration tests для oversized attachment; public validation errors | Closed-loop load не доказывает устойчивость к DDoS | +| Container получает host/root возможности или upload worker исчерпывает host | App compromise не равен host control; job ограничен | app/worker/dispatcher non-root, read-only, no-new-privileges, cap_drop ALL, tmpfs; worker 1 CPU/512 MiB, `GOMEMLIMIT=448MiB`, concurrency 1, timeout 60s; no socket/host network | `make test-security-grade4`; exact 40 Мп decode проходит без OOM | Один worker сериализует тяжёлые decode; stateful volumes writable; kernel/daemon вне модели | +| Private key/token/password или request body попадает в Git/image/telemetry | Bootstrap material доступен только оператору | `.gitignore`, runtime secret mounts, multi-stage image; logger не пишет headers/body; structured allowlist fields | `make test-telemetry-leak-grade4` сравнивает Loki с probe и local secret values; staged-secret audit | Secret после startup находится в process memory; host operator остаётся доверенным | ## Lifecycle и инциденты -TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. +Bootstrap выполняет оператор. CA/leaf/password generation использует OpenSSL and umask 077. OpenBao file storage persistent; root token и unseal share лежат не в storage/container, а в `.operator` mode 0600. AppRole role ID/SecretID лежат в `secrets/openbao` 0600 и монтируются только соответствующему service. App token TTL 15m/max 30m используется для единственного startup read; дальше secret хранится в памяти процесса. + +После обычного API restart приложение повторно аутентифицируется. После OpenBao restart хранилище sealed: operator запускает `scripts/bootstrap-openbao.sh`, затем пересоздаёт app processes, что автоматизировано только в operator-owned `scripts/restart.sh`. При seal уже работающий процесс сохраняет ранее прочитанные credentials, новый fail-closed не стартует. + +При компрометации AppRole оператор отзывает SecretID/token, выдаёт новый SecretID и пересоздаёт только affected service. При компрометации DB/S3/Rabbit/Redis credential нужно заменить credential в backend и KV, затем пересоздать service. Проверенный сценарий меняет RabbitMQ credential в backend и KV, пересоздаёт только worker с `--no-build` и доказывает отказ старого пароля. Для LB leaf выпускается новая уникальная URI identity, runtime allowlist заменяется без rebuild, а старый и просроченный leaf отвергаются. Автоматическая CA rotation и CRL/OCSP не реализованы. + +`govulncheck v1.10.0` на 2026-11-22 не нашёл reachable Go vulnerabilities. Локально собранные app/ingress images проходят строгий Trivy 0.76.2 gate по HIGH/CRITICAL fixed findings. MinIO/mc также сканируются: архивированный upstream содержит известные исправляемые vendor findings, которые нельзя полностью признать недостижимыми; это принятый риск учебного стенда и production-блокер. Полный triage находится в `security/SCAN_TRIAGE.md`. Скан — снимок базы уязвимостей, а не гарантия будущей безопасности; полный SBOM/signing и непрерывный registry scan не заявлены. diff --git a/student_tests/application_helper_test.go b/student_tests/application_helper_test.go new file mode 100644 index 0000000..885f297 --- /dev/null +++ b/student_tests/application_helper_test.go @@ -0,0 +1,36 @@ +package student_tests + +import ( + "time" + + "mtusi2026lab7/internal/application" +) + +const testCursorSigningKey = "student-tests-cursor-signing-key-at-least-32-bytes" + +func newTestService( + repository application.Repository, + sessionTTL time.Duration, + options ...application.ServiceOption, +) *application.Service { + if sessionTTL <= 0 { + sessionTTL = time.Hour + } + codec, err := application.NewCursorCodec(testCursorSigningKey) + if err != nil { + panic(err) + } + service, err := application.NewService(repository, codec, sessionTTL, options...) + if err != nil { + panic(err) + } + return service +} + +func newTestCursorCodec() *application.CursorCodec { + codec, err := application.NewCursorCodec(testCursorSigningKey) + if err != nil { + panic(err) + } + return codec +} diff --git a/student_tests/attachment_upload_test.go b/student_tests/attachment_upload_test.go new file mode 100644 index 0000000..08e074e --- /dev/null +++ b/student_tests/attachment_upload_test.go @@ -0,0 +1,249 @@ +package student_tests + +import ( + "bytes" + "context" + "encoding/json" + "image" + "image/color" + "image/png" + "io" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + "time" + + store "mtusi2026lab7/internal/adapter/memory" + "mtusi2026lab7/internal/application" + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/handlers" + "mtusi2026lab7/internal/transport/http/middleware" +) + +type httpFakeObjectStore struct { + mu sync.Mutex + objects map[string][]byte +} + +func (store *httpFakeObjectStore) Put(_ context.Context, object application.ObjectPut) error { + payload, err := io.ReadAll(object.Body) + if err != nil { + return err + } + store.mu.Lock() + store.objects[object.Key] = payload + store.mu.Unlock() + return nil +} + +func (store *httpFakeObjectStore) Get(_ context.Context, key string) (application.ObjectContent, error) { + store.mu.Lock() + defer store.mu.Unlock() + payload, exists := store.objects[key] + if !exists { + return application.ObjectContent{}, domain.ErrNotFound + } + copyOfPayload := append([]byte(nil), payload...) + return application.ObjectContent{ + Body: io.NopCloser(bytes.NewReader(copyOfPayload)), + SizeBytes: int64(len(copyOfPayload)), + }, nil +} + +func (store *httpFakeObjectStore) Delete(_ context.Context, key string) error { + store.mu.Lock() + delete(store.objects, key) + store.mu.Unlock() + return nil +} + +func setupAttachmentUploadServer( + t *testing.T, +) (*httptest.Server, *store.MemoryStore, *httpFakeObjectStore) { + t.Helper() + memoryStore := store.NewMemoryStore() + repository := store.NewMemoryRepository(memoryStore) + objectStore := &httpFakeObjectStore{objects: make(map[string][]byte)} + service := newTestService( + repository, + time.Hour, + application.WithObjectStore(objectStore), + ) + handler := handlers.NewHandler(service) + + mux := http.NewServeMux() + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/attachments", + requireLegacyAuth(memoryStore, handler.UploadAttachment), + ) + mux.HandleFunc( + "GET /api/v1/attachments/{attachment_id}", + requireLegacyAuth(memoryStore, handler.GetAttachment), + ) + mux.HandleFunc( + "GET /api/v1/attachments/{attachment_id}/content", + requireLegacyAuth(memoryStore, handler.DownloadAttachment), + ) + var root http.Handler = mux + root = middleware.Recovery(root) + root = middleware.RequestID(root) + return httptest.NewServer(root), memoryStore, objectStore +} + +func pngPayload(t *testing.T) []byte { + t.Helper() + var payload bytes.Buffer + img := image.NewRGBA(image.Rect(0, 0, 2, 2)) + img.Set(0, 0, color.RGBA{R: 255, A: 255}) + if err := png.Encode(&payload, img); err != nil { + t.Fatal(err) + } + return payload.Bytes() +} + +func uploadRequest( + t *testing.T, + baseURL string, + chatID string, + userID string, + filename string, + contentType string, + payload []byte, +) *http.Response { + t.Helper() + requestURL := baseURL + "/api/v1/chats/" + chatID + + "/attachments?filename=" + url.QueryEscape(filename) + request, err := http.NewRequest(http.MethodPost, requestURL, bytes.NewReader(payload)) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Content-Type", contentType) + request.Header.Set("X-User-Id", userID) + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatal(err) + } + return response +} + +func attachmentGetRequest(t *testing.T, requestURL string, userID string) *http.Response { + t.Helper() + request, err := http.NewRequest(http.MethodGet, requestURL, nil) + if err != nil { + t.Fatal(err) + } + request.Header.Set("X-User-Id", userID) + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatal(err) + } + return response +} + +func TestUploadAttachmentHTTPContract(t *testing.T) { + server, memoryStore, objectStore := setupAttachmentUploadServer(t) + defer server.Close() + user, err := memoryStore.CreateUser("attachment_user", "Attachment User") + if err != nil { + t.Fatal(err) + } + outsider, err := memoryStore.CreateUser("attachment_outsider", "Attachment Outsider") + if err != nil { + t.Fatal(err) + } + chat, err := memoryStore.CreateChat("Images", []string{user.ID}) + if err != nil { + t.Fatal(err) + } + payload := pngPayload(t) + response := uploadRequest(t, server.URL, chat.ID, user.ID, "кот.png", "image/png", payload) + defer response.Body.Close() + if response.StatusCode != http.StatusAccepted { + body, _ := io.ReadAll(response.Body) + t.Fatalf("status = %d, want 202: %s", response.StatusCode, body) + } + var attachment dto.AttachmentResponse + if err = json.NewDecoder(response.Body).Decode(&attachment); err != nil { + t.Fatal(err) + } + if attachment.Status != domain.AttachmentStatusQueued || attachment.Filename != "кот.png" { + t.Fatalf("unexpected response: %+v", attachment) + } + if attachment.Variants == nil || len(attachment.Variants) != 0 || attachment.ErrorCode != nil { + t.Fatalf("contract arrays/nulls differ: %+v", attachment) + } + objectStore.mu.Lock() + storedObjects := len(objectStore.objects) + objectStore.mu.Unlock() + if storedObjects != 1 { + t.Fatalf("stored objects = %d, want 1", storedObjects) + } + + metadataResponse := attachmentGetRequest(t, server.URL+"/api/v1/attachments/"+attachment.ID, user.ID) + defer metadataResponse.Body.Close() + if metadataResponse.StatusCode != http.StatusOK { + t.Fatalf("metadata status = %d, want 200", metadataResponse.StatusCode) + } + + contentResponse := attachmentGetRequest(t, + server.URL+"/api/v1/attachments/"+attachment.ID+"/content", user.ID) + defer contentResponse.Body.Close() + if contentResponse.StatusCode != http.StatusConflict { + t.Fatalf("queued content status=%d, want 409", contentResponse.StatusCode) + } + + for _, suffix := range []string{"", "/content"} { + outsiderResponse := attachmentGetRequest(t, + server.URL+"/api/v1/attachments/"+attachment.ID+suffix, outsider.ID) + _ = outsiderResponse.Body.Close() + if outsiderResponse.StatusCode != http.StatusNotFound { + t.Fatalf("outsider %q status = %d, want 404", suffix, outsiderResponse.StatusCode) + } + } + + missingVariant := attachmentGetRequest(t, + server.URL+"/api/v1/attachments/"+attachment.ID+"/content?variant=thumbnail", user.ID) + _ = missingVariant.Body.Close() + if missingVariant.StatusCode != http.StatusConflict { + t.Fatalf("queued variant status = %d, want 409", missingVariant.StatusCode) + } +} + +func TestUploadAttachmentHTTPErrorMapping(t *testing.T) { + server, memoryStore, _ := setupAttachmentUploadServer(t) + defer server.Close() + user, _ := memoryStore.CreateUser("attachment_errors", "Attachment Errors") + chat, _ := memoryStore.CreateChat("Images", []string{user.ID}) + validPNG := pngPayload(t) + + testCases := []struct { + name string + chatID string + filename string + contentType string + payload []byte + wantStatus int + }{ + {name: "unsafe filename", chatID: chat.ID, filename: "../image.png", contentType: "image/png", payload: validPNG, wantStatus: http.StatusBadRequest}, + {name: "unsupported content type", chatID: chat.ID, filename: "image.gif", contentType: "image/gif", payload: []byte("GIF89a"), wantStatus: http.StatusUnsupportedMediaType}, + {name: "MIME substitution", chatID: chat.ID, filename: "image.jpg", contentType: "image/jpeg", payload: validPNG, wantStatus: http.StatusUnsupportedMediaType}, + {name: "corrupt image", chatID: chat.ID, filename: "image.png", contentType: "image/png", payload: []byte("bad"), wantStatus: http.StatusUnsupportedMediaType}, + {name: "too large", chatID: chat.ID, filename: "image.png", contentType: "image/png", payload: bytes.Repeat([]byte{0}, domain.MaxAttachmentSizeBytes+1), wantStatus: http.StatusRequestEntityTooLarge}, + {name: "unknown chat", chatID: "11111111-1111-4111-8111-111111111111", filename: "image.png", contentType: "image/png", payload: validPNG, wantStatus: http.StatusNotFound}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + response := uploadRequest(t, server.URL, testCase.chatID, user.ID, + testCase.filename, testCase.contentType, testCase.payload) + defer response.Body.Close() + if response.StatusCode != testCase.wantStatus { + body, _ := io.ReadAll(response.Body) + t.Fatalf("status = %d, want %d: %s", response.StatusCode, testCase.wantStatus, body) + } + }) + } +} diff --git a/student_tests/auth_test.go b/student_tests/auth_test.go new file mode 100644 index 0000000..234fb7a --- /dev/null +++ b/student_tests/auth_test.go @@ -0,0 +1,379 @@ +package student_tests + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + store "mtusi2026lab7/internal/adapter/memory" + "mtusi2026lab7/internal/security" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/handlers" + "mtusi2026lab7/internal/transport/http/middleware" +) + +const testPassword = "Test-password-123" + +func setupSessionTestServer( + t *testing.T, + sessionTTL time.Duration, +) (*httptest.Server, *store.MemoryRepository) { + t.Helper() + + repository := store.NewMemoryRepository(store.NewMemoryStore()) + service := newTestService(repository, sessionTTL) + handler := handlers.NewHandler(service) + + mux := http.NewServeMux() + mux.HandleFunc("POST /api/v1/users", handler.CreateUser) + mux.HandleFunc("POST /api/v1/auth/sessions", handler.CreateSession) + mux.HandleFunc( + "GET /api/v1/users/me", + middleware.RequireAuth(service, handler.GetMe), + ) + mux.HandleFunc( + "DELETE /api/v1/auth/sessions/current", + middleware.RequireAuth(service, handler.DeleteCurrentSession), + ) + + var root http.Handler = mux + root = middleware.Recovery(root) + root = middleware.RequestID(root) + + return httptest.NewServer(root), repository +} + +func registerSessionTestUser( + t *testing.T, + baseURL string, + username string, +) dto.UserResponse { + t.Helper() + + payload, err := json.Marshal(map[string]string{ + "username": username, + "display_name": "Session test user", + "password": testPassword, + }) + if err != nil { + t.Fatalf("marshal registration request: %v", err) + } + + response, err := http.Post( + baseURL+"/api/v1/users", + "application/json", + bytes.NewReader(payload), + ) + if err != nil { + t.Fatalf("register user: %v", err) + } + defer response.Body.Close() + + if response.StatusCode != http.StatusCreated { + body, _ := io.ReadAll(response.Body) + t.Fatalf("expected registration status 201, got %d: %s", response.StatusCode, body) + } + + var user dto.UserResponse + if err := json.NewDecoder(response.Body).Decode(&user); err != nil { + t.Fatalf("decode registered user: %v", err) + } + + return user +} + +func createSessionRequest( + t *testing.T, + baseURL string, + username string, + password string, +) *http.Response { + t.Helper() + + credentials := base64.StdEncoding.EncodeToString( + []byte(username + ":" + password), + ) + + request, err := http.NewRequest( + http.MethodPost, + baseURL+"/api/v1/auth/sessions", + nil, + ) + if err != nil { + t.Fatalf("create login request: %v", err) + } + request.Header.Set("Authorization", "Basic "+credentials) + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send login request: %v", err) + } + + return response +} + +func TestSessionAuthenticationLifecycle(t *testing.T) { + testServer, repository := setupSessionTestServer(t, time.Hour) + defer testServer.Close() + + alice := registerSessionTestUser(t, testServer.URL, "session_alice") + eve := registerSessionTestUser(t, testServer.URL, "session_eve") + + _, passwordHash, err := repository.GetUserByUsername( + t.Context(), + alice.Username, + ) + if err != nil { + t.Fatalf("read registered user credentials: %v", err) + } + if passwordHash == testPassword || bytes.Contains( + []byte(passwordHash), + []byte(testPassword), + ) { + t.Fatal("repository contains plaintext password") + } + passwordMatches, err := security.VerifyPassword(testPassword, passwordHash) + if err != nil || !passwordMatches { + t.Fatalf("stored password hash does not verify: matches=%v err=%v", passwordMatches, err) + } + + wrongPasswordResponse := createSessionRequest( + t, + testServer.URL, + alice.Username, + "Wrong-password-123", + ) + wrongPasswordBody, err := io.ReadAll(wrongPasswordResponse.Body) + wrongPasswordResponse.Body.Close() + if err != nil { + t.Fatalf("read wrong-password response: %v", err) + } + if wrongPasswordResponse.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401 for wrong password, got %d", wrongPasswordResponse.StatusCode) + } + if got := wrongPasswordResponse.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` { + t.Fatalf("unexpected Basic challenge: %q", got) + } + + unknownUserResponse := createSessionRequest( + t, + testServer.URL, + "unknown_session_user", + "Wrong-password-123", + ) + unknownUserBody, err := io.ReadAll(unknownUserResponse.Body) + unknownUserResponse.Body.Close() + if err != nil { + t.Fatalf("read unknown-user response: %v", err) + } + if unknownUserResponse.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401 for unknown username, got %d", unknownUserResponse.StatusCode) + } + if got := unknownUserResponse.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` { + t.Fatalf("unexpected Basic challenge for unknown username: %q", got) + } + type credentialFailure struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + var wrongFailure, unknownFailure credentialFailure + if err = json.Unmarshal(wrongPasswordBody, &wrongFailure); err != nil { + t.Fatalf("decode wrong-password response: %v", err) + } + if err = json.Unmarshal(unknownUserBody, &unknownFailure); err != nil { + t.Fatalf("decode unknown-user response: %v", err) + } + if wrongFailure != unknownFailure || len(wrongPasswordBody) != len(unknownUserBody) { + t.Fatalf("credential failure responses disclose whether a username exists: wrong=%q unknown=%q", wrongPasswordBody, unknownUserBody) + } + + loginResponse := createSessionRequest( + t, + testServer.URL, + alice.Username, + testPassword, + ) + defer loginResponse.Body.Close() + if loginResponse.StatusCode != http.StatusCreated { + body, _ := io.ReadAll(loginResponse.Body) + t.Fatalf("expected login status 201, got %d: %s", loginResponse.StatusCode, body) + } + + var session dto.SessionResponse + if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil { + t.Fatalf("decode session: %v", err) + } + if session.Token == "" || session.TokenType != "Bearer" { + t.Fatalf("unexpected session token response: type=%q empty=%v", session.TokenType, session.Token == "") + } + if session.User != alice { + t.Fatalf("session belongs to another user: got %s, want %s", session.User.ID, alice.ID) + } + + testCases := []struct { + name string + authorization string + userIDHeader string + wantStatus int + }{ + { + name: "X-User-Id alone is rejected", + userIDHeader: alice.ID, + wantStatus: http.StatusUnauthorized, + }, + { + name: "Basic is rejected on business endpoint", + authorization: "Basic " + base64.StdEncoding.EncodeToString([]byte(alice.Username+":"+testPassword)), + wantStatus: http.StatusUnauthorized, + }, + { + name: "non-ASCII Bearer is rejected without panic", + authorization: "Bearer é", + wantStatus: http.StatusUnauthorized, + }, + { + name: "Bearer identity wins over X-User-Id", + authorization: "Bearer " + session.Token, + userIDHeader: eve.ID, + wantStatus: http.StatusOK, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + request, err := http.NewRequest( + http.MethodGet, + testServer.URL+"/api/v1/users/me", + nil, + ) + if err != nil { + t.Fatalf("create authenticated request: %v", err) + } + if testCase.authorization != "" { + request.Header.Set("Authorization", testCase.authorization) + } + if testCase.userIDHeader != "" { + request.Header.Set("X-User-Id", testCase.userIDHeader) + } + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send authenticated request: %v", err) + } + defer response.Body.Close() + + if response.StatusCode != testCase.wantStatus { + t.Fatalf("expected status %d, got %d", testCase.wantStatus, response.StatusCode) + } + + if testCase.wantStatus == http.StatusUnauthorized { + if got := response.Header.Get("WWW-Authenticate"); got != `Bearer realm="messenger"` { + t.Fatalf("unexpected Bearer challenge: %q", got) + } + return + } + + var currentUser dto.UserResponse + if err := json.NewDecoder(response.Body).Decode(¤tUser); err != nil { + t.Fatalf("decode current user: %v", err) + } + if currentUser.ID != alice.ID { + t.Fatalf("X-User-Id overrode Bearer identity: got %s, want %s", currentUser.ID, alice.ID) + } + }) + } + + logoutRequest, err := http.NewRequest( + http.MethodDelete, + testServer.URL+"/api/v1/auth/sessions/current", + nil, + ) + if err != nil { + t.Fatalf("create logout request: %v", err) + } + logoutRequest.Header.Set("Authorization", "Bearer "+session.Token) + + logoutResponse, err := http.DefaultClient.Do(logoutRequest) + if err != nil { + t.Fatalf("send logout request: %v", err) + } + logoutBody, err := io.ReadAll(logoutResponse.Body) + logoutResponse.Body.Close() + if err != nil { + t.Fatalf("read logout response: %v", err) + } + if logoutResponse.StatusCode != http.StatusNoContent { + t.Fatalf("expected logout status 204, got %d", logoutResponse.StatusCode) + } + if len(logoutBody) != 0 { + t.Fatalf("logout response contains a body: %q", logoutBody) + } + + revokedRequest, err := http.NewRequest( + http.MethodGet, + testServer.URL+"/api/v1/users/me", + nil, + ) + if err != nil { + t.Fatalf("create revoked-token request: %v", err) + } + revokedRequest.Header.Set("Authorization", "Bearer "+session.Token) + + revokedResponse, err := http.DefaultClient.Do(revokedRequest) + if err != nil { + t.Fatalf("send revoked-token request: %v", err) + } + revokedResponse.Body.Close() + if revokedResponse.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401 for revoked token, got %d", revokedResponse.StatusCode) + } +} + +func TestSessionExpiry(t *testing.T) { + testServer, _ := setupSessionTestServer(t, 25*time.Millisecond) + defer testServer.Close() + + user := registerSessionTestUser(t, testServer.URL, "session_expiry") + loginResponse := createSessionRequest( + t, + testServer.URL, + user.Username, + testPassword, + ) + + var session dto.SessionResponse + if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil { + loginResponse.Body.Close() + t.Fatalf("decode session: %v", err) + } + loginResponse.Body.Close() + + time.Sleep(75 * time.Millisecond) + + request, err := http.NewRequest( + http.MethodGet, + testServer.URL+"/api/v1/users/me", + nil, + ) + if err != nil { + t.Fatalf("create expired-token request: %v", err) + } + request.Header.Set("Authorization", "Bearer "+session.Token) + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send expired-token request: %v", err) + } + response.Body.Close() + + if response.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401 for expired token, got %d", response.StatusCode) + } +} diff --git a/student_tests/cursor_concurrency_test.go b/student_tests/cursor_concurrency_test.go new file mode 100644 index 0000000..c7690f5 --- /dev/null +++ b/student_tests/cursor_concurrency_test.go @@ -0,0 +1,406 @@ +package student_tests + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "runtime" + "sync" + "testing" + "time" + + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" +) + +func fetchCursorPage( + t *testing.T, + baseURL, chatID, userID string, + limit int, + cursor string, +) dto.MessagePageResponse { + t.Helper() + + endpoint := fmt.Sprintf( + "%s/api/v1/chats/%s/messages?limit=%d", + baseURL, + chatID, + limit, + ) + if cursor != "" { + endpoint += "&cursor=" + url.QueryEscape(cursor) + } + + req, err := http.NewRequest(http.MethodGet, endpoint, nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("X-User-Id", userID) + + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + body, _ := io.ReadAll(res.Body) + t.Fatalf("expected 200, got %d: %s", res.StatusCode, body) + } + + var page dto.MessagePageResponse + if err := json.NewDecoder(res.Body).Decode(&page); err != nil { + t.Fatalf("decode message page: %v", err) + } + return page +} + +func TestCursorTraversalAfterConcurrentWrites(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + const ( + clients = 10 + messagesPerClient = 100 + expectedMessages = clients * messagesPerClient + ) + + memberIDs := make([]string, 0, clients) + for client := 0; client < clients; client++ { + user, err := st.CreateUser( + fmt.Sprintf("cursor_client_%d", client), + fmt.Sprintf("Cursor client %d", client), + ) + if err != nil { + t.Fatal(err) + } + memberIDs = append(memberIDs, user.ID) + } + + chat, err := st.CreateChat("Concurrent cursor test", memberIDs) + if err != nil { + t.Fatal(err) + } + + start := make(chan struct{}) + var writers sync.WaitGroup + for client := 0; client < clients; client++ { + writers.Add(1) + go func(client int) { + defer writers.Done() + <-start + for message := 0; message < messagesPerClient; message++ { + _, err := st.CreateMessage( + chat.ID, + memberIDs[client], + fmt.Sprintf("client=%d message=%d", client, message), + ) + if err != nil { + t.Errorf("create message: %v", err) + return + } + } + }(client) + } + + close(start) + writers.Wait() + + seen := make(map[string]struct{}, expectedMessages) + duplicateCount := 0 + var previous *dto.MessageResponse + firstOrderingViolation := "" + cursor := "" + pageCount := 0 + + for { + pageCount++ + if pageCount > expectedMessages { + t.Fatal("pagination did not terminate") + } + + page := fetchCursorPage(t, ts.URL, chat.ID, memberIDs[0], 17, cursor) + for index := range page.Items { + message := page.Items[index] + if _, duplicate := seen[message.ID]; duplicate { + duplicateCount++ + } + seen[message.ID] = struct{}{} + + if previous != nil { + outOfOrder := message.CreatedAt.Before(previous.CreatedAt) || + (message.CreatedAt.Equal(previous.CreatedAt) && message.ID <= previous.ID) + if outOfOrder && firstOrderingViolation == "" { + firstOrderingViolation = fmt.Sprintf( + "previous=(%s,%s), current=(%s,%s)", + previous.CreatedAt.Format("15:04:05.999999999"), previous.ID, + message.CreatedAt.Format("15:04:05.999999999"), message.ID, + ) + } + } + + messageCopy := message + previous = &messageCopy + } + + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + + if len(seen) != expectedMessages || duplicateCount != 0 { + t.Fatalf( + "cursor traversal returned %d unique messages of %d and %d duplicates; first ordering violation: %s", + len(seen), expectedMessages, duplicateCount, firstOrderingViolation, + ) + } + if firstOrderingViolation != "" { + t.Fatalf("history is not ordered: %s", firstOrderingViolation) + } +} + +func TestCursorTraversalDuringConcurrentWrites(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + const ( + clients = 16 + messagesPerClient = 100 + seedMessages = 100 + pageLimit = 7 + expectedTotal = seedMessages + clients*messagesPerClient + ) + + memberIDs := make([]string, 0, clients) + for client := 0; client < clients; client++ { + user, err := st.CreateUser( + fmt.Sprintf("live_cursor_client_%d", client), + fmt.Sprintf("Live cursor client %d", client), + ) + if err != nil { + t.Fatalf("create user %d: %v", client, err) + } + memberIDs = append(memberIDs, user.ID) + } + + chat, err := st.CreateChat("Live concurrent cursor test", memberIDs) + if err != nil { + t.Fatalf("create chat: %v", err) + } + + // Начальные сообщения нужны, чтобы читатель сразу начал + // двигать курсор, пока остальные сообщения ещё записываются. + expectedIDs := make(map[string]struct{}, expectedTotal) + for index := 0; index < seedMessages; index++ { + message, err := st.CreateMessage( + chat.ID, + memberIDs[0], + fmt.Sprintf("seed message=%d", index), + ) + if err != nil { + t.Fatalf("create seed message %d: %v", index, err) + } + expectedIDs[message.ID] = struct{}{} + } + + var expectedMu sync.Mutex + var writers sync.WaitGroup + var ready sync.WaitGroup + + start := make(chan struct{}) + writerErrors := make(chan error, clients) + + for client := 0; client < clients; client++ { + writers.Add(1) + ready.Add(1) + + go func(client int) { + defer writers.Done() + + ready.Done() + <-start + + for index := 0; index < messagesPerClient; index++ { + // Отдаём планировщику возможность чаще переключать + // конкурентные горутины. + runtime.Gosched() + + message, err := st.CreateMessage( + chat.ID, + memberIDs[client], + fmt.Sprintf("client=%d message=%d", client, index), + ) + if err != nil { + writerErrors <- fmt.Errorf( + "client %d, message %d: %w", + client, + index, + err, + ) + return + } + + expectedMu.Lock() + expectedIDs[message.ID] = struct{}{} + expectedMu.Unlock() + + // Не даём всем писателям завершиться до того, + // как читатель успеет продвинуть курсор. + time.Sleep(50 * time.Microsecond) + } + }(client) + } + + // Сначала убеждаемся, что все горутины готовы, + // и только потом одновременно разрешаем запись. + ready.Wait() + + writersDone := make(chan struct{}) + go func() { + writers.Wait() + close(writersDone) + }() + + close(start) + + seen := make(map[string]struct{}, expectedTotal) + cursor := "" + var previous *dto.MessageResponse + + const maxPageRequests = expectedTotal * 4 + finished := false + + for requestNumber := 0; requestNumber < maxPageRequests; requestNumber++ { + page := fetchCursorPage( + t, + ts.URL, + chat.ID, + memberIDs[0], + pageLimit, + cursor, + ) + + for index := range page.Items { + message := page.Items[index] + + if _, duplicate := seen[message.ID]; duplicate { + t.Fatalf( + "message %s was returned more than once", + message.ID, + ) + } + + if previous != nil { + outOfOrder := + message.CreatedAt.Before(previous.CreatedAt) || + (message.CreatedAt.Equal(previous.CreatedAt) && + message.ID <= previous.ID) + + if outOfOrder { + t.Fatalf( + "messages are out of order: previous=(%s,%s), current=(%s,%s)", + previous.CreatedAt.Format(time.RFC3339Nano), + previous.ID, + message.CreatedAt.Format(time.RFC3339Nano), + message.ID, + ) + } + } + + seen[message.ID] = struct{}{} + messageCopy := message + previous = &messageCopy + } + + // Для продолжающегося чтения строим курсор по последнему + // фактически полученному сообщению. Это позволяет опрашивать + // историю, даже если в промежуточный момент сервер вернул + // NextCursor=nil. + if len(page.Items) > 0 { + last := page.Items[len(page.Items)-1] + var encodeErr error + cursor, encodeErr = newTestCursorCodec().EncodeMessage(domain.MessageCursor{ + CreatedAt: last.CreatedAt, + MessageID: last.ID, + ChatID: chat.ID, + }) + if encodeErr != nil { + t.Fatalf("encode traversal cursor: %v", encodeErr) + } + } + + select { + case <-writersDone: + finished = true + default: + } + + // Все писатели завершились, а после текущего курсора + // больше ничего нет: обход закончен. + if finished && len(page.Items) == 0 { + break + } + + if len(page.Items) == 0 { + runtime.Gosched() + } + + if requestNumber == maxPageRequests-1 { + t.Fatalf( + "pagination did not terminate after %d requests", + maxPageRequests, + ) + } + } + + <-writersDone + close(writerErrors) + + for writerErr := range writerErrors { + t.Errorf("create message: %v", writerErr) + } + + expectedMu.Lock() + missingIDs := make([]string, 0) + for id := range expectedIDs { + if _, found := seen[id]; !found { + missingIDs = append(missingIDs, id) + } + } + expectedCount := len(expectedIDs) + expectedMu.Unlock() + + if expectedCount != expectedTotal { + t.Fatalf( + "writers confirmed %d messages, expected %d", + expectedCount, + expectedTotal, + ) + } + + if len(missingIDs) != 0 { + const displayedMissingIDs = 5 + if len(missingIDs) > displayedMissingIDs { + missingIDs = missingIDs[:displayedMissingIDs] + } + + t.Fatalf( + "cursor traversal returned %d of %d confirmed messages; "+ + "examples of missing IDs: %v", + len(seen), + expectedTotal, + missingIDs, + ) + } + + if len(seen) != expectedTotal { + t.Fatalf( + "cursor traversal returned %d messages, expected %d", + len(seen), + expectedTotal, + ) + } +} diff --git a/student_tests/idempotency_test.go b/student_tests/idempotency_test.go new file mode 100644 index 0000000..7f07dff --- /dev/null +++ b/student_tests/idempotency_test.go @@ -0,0 +1,313 @@ +package student_tests + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "reflect" + "sync" + "testing" + + store "mtusi2026lab7/internal/adapter/memory" + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" +) + +func sendMessageRequest( + t *testing.T, + serverURL string, + chatID string, + actorID string, + key string, + body string, +) (int, []byte) { + t.Helper() + + request, err := http.NewRequest( + http.MethodPost, + fmt.Sprintf("%s/api/v1/chats/%s/messages", serverURL, chatID), + bytes.NewBufferString(body), + ) + if err != nil { + t.Fatalf("create message request: %v", err) + } + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-User-Id", actorID) + if key != "" { + request.Header.Set("Idempotency-Key", key) + } + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send message request: %v", err) + } + defer response.Body.Close() + + payload, err := io.ReadAll(response.Body) + if err != nil { + t.Fatalf("read message response: %v", err) + } + return response.StatusCode, payload +} + +func decodeMessageResponse(t *testing.T, payload []byte) dto.MessageResponse { + t.Helper() + + var message dto.MessageResponse + if err := json.Unmarshal(payload, &message); err != nil { + t.Fatalf("decode message response: %v; body=%s", err, payload) + } + return message +} + +func createMessageFixture(t *testing.T) (*store.MemoryStore, string, domain.User, string) { + t.Helper() + + server, memoryStore := setupTestServer() + t.Cleanup(server.Close) + + user, err := memoryStore.CreateUser("idempotency_user", "Idempotency User") + if err != nil { + t.Fatalf("create fixture user: %v", err) + } + chat, err := memoryStore.CreateChat("Idempotency Chat", []string{user.ID}) + if err != nil { + t.Fatalf("create fixture chat: %v", err) + } + + return memoryStore, server.URL, user, chat.ID +} + +func TestMessageIdempotencyKeyValidation(t *testing.T) { + _, serverURL, user, chatID := createMessageFixture(t) + + testCases := []struct { + name string + key string + }{ + {name: "missing", key: ""}, + {name: "space", key: "invalid key"}, + {name: "non ascii", key: "ключ"}, + {name: "too long", key: string(bytes.Repeat([]byte{'a'}, 129))}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + status, _ := sendMessageRequest( + t, + serverURL, + chatID, + user.ID, + testCase.key, + `{"text":"hello"}`, + ) + if status != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", status) + } + }) + } +} + +func TestMessageIdempotencyReplayAndConflict(t *testing.T) { + memoryStore, serverURL, user, chatID := createMessageFixture(t) + + status, firstPayload := sendMessageRequest( + t, serverURL, chatID, user.ID, "replay-key", `{"text":"hello"}`, + ) + if status != http.StatusCreated { + t.Fatalf("first request: expected 201, got %d: %s", status, firstPayload) + } + + status, replayPayload := sendMessageRequest( + t, + serverURL, + chatID, + user.ID, + "replay-key", + "{\n \"text\": \"hello\"\n}", + ) + if status != http.StatusCreated { + t.Fatalf("replay: expected 201, got %d: %s", status, replayPayload) + } + + first := decodeMessageResponse(t, firstPayload) + replay := decodeMessageResponse(t, replayPayload) + if !reflect.DeepEqual(first, replay) { + t.Fatalf("replay changed message: first=%+v replay=%+v", first, replay) + } + + status, _ = sendMessageRequest( + t, serverURL, chatID, user.ID, "replay-key", `{"text":"different"}`, + ) + if status != http.StatusConflict { + t.Fatalf("different body: expected 409, got %d", status) + } + + messages, _, err := memoryStore.GetMessages(chatID, user.ID, 10, nil) + if err != nil { + t.Fatalf("list messages: %v", err) + } + if len(messages) != 1 { + t.Fatalf("expected one stored message, got %d", len(messages)) + } +} + +func TestMessageIdempotencyScopesAreIndependent(t *testing.T) { + server, memoryStore := setupTestServer() + t.Cleanup(server.Close) + + alice, _ := memoryStore.CreateUser("scope_alice", "Alice") + bob, _ := memoryStore.CreateUser("scope_bob", "Bob") + firstChat, _ := memoryStore.CreateChat("First", []string{alice.ID, bob.ID}) + secondChat, _ := memoryStore.CreateChat("Second", []string{alice.ID, bob.ID}) + + testCases := []struct { + actorID string + chatID string + text string + }{ + {actorID: alice.ID, chatID: firstChat.ID, text: "alice first"}, + {actorID: bob.ID, chatID: firstChat.ID, text: "bob first"}, + {actorID: alice.ID, chatID: secondChat.ID, text: "alice second"}, + } + + for _, testCase := range testCases { + status, payload := sendMessageRequest( + t, + server.URL, + testCase.chatID, + testCase.actorID, + "shared-key", + fmt.Sprintf(`{"text":%q}`, testCase.text), + ) + if status != http.StatusCreated { + t.Fatalf("independent scope: expected 201, got %d: %s", status, payload) + } + } +} + +func TestConcurrentMessageIdempotencyCreatesExactlyOneMessage(t *testing.T) { + memoryStore, serverURL, user, chatID := createMessageFixture(t) + + const clients = 32 + start := make(chan struct{}) + results := make(chan dto.MessageResponse, clients) + errors := make(chan error, clients) + + var waitGroup sync.WaitGroup + for index := 0; index < clients; index++ { + waitGroup.Add(1) + go func() { + defer waitGroup.Done() + <-start + + request, err := http.NewRequest( + http.MethodPost, + fmt.Sprintf("%s/api/v1/chats/%s/messages", serverURL, chatID), + bytes.NewBufferString(`{"text":"concurrent replay"}`), + ) + if err != nil { + errors <- err + return + } + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-User-Id", user.ID) + request.Header.Set("Idempotency-Key", "one-concurrent-key") + + response, err := http.DefaultClient.Do(request) + if err != nil { + errors <- err + return + } + defer response.Body.Close() + payload, err := io.ReadAll(response.Body) + if err != nil { + errors <- err + return + } + if response.StatusCode != http.StatusCreated { + errors <- fmt.Errorf("expected 201, got %d: %s", response.StatusCode, payload) + return + } + + var message dto.MessageResponse + if err = json.Unmarshal(payload, &message); err != nil { + errors <- err + return + } + results <- message + }() + } + + close(start) + waitGroup.Wait() + close(results) + close(errors) + + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + + var expected dto.MessageResponse + count := 0 + for message := range results { + if count == 0 { + expected = message + } else if !reflect.DeepEqual(message, expected) { + t.Fatalf("concurrent replay returned different message: %+v != %+v", message, expected) + } + count++ + } + if count != clients { + t.Fatalf("expected %d successful responses, got %d", clients, count) + } + + messages, _, err := memoryStore.GetMessages(chatID, user.ID, clients+1, nil) + if err != nil { + t.Fatalf("list messages: %v", err) + } + if len(messages) != 1 { + t.Fatalf("expected exactly one stored message, got %d", len(messages)) + } +} + +func TestMessageIdempotencyTreatsMissingAndEmptyAttachmentsEqually(t *testing.T) { + _, serverURL, user, chatID := createMessageFixture(t) + + status, firstPayload := sendMessageRequest( + t, + serverURL, + chatID, + user.ID, + "default-attachments", + `{"text":"same semantic request"}`, + ) + if status != http.StatusCreated { + t.Fatalf("first request: expected 201, got %d: %s", status, firstPayload) + } + + status, replayPayload := sendMessageRequest( + t, + serverURL, + chatID, + user.ID, + "default-attachments", + `{"attachment_ids":[],"text":"same semantic request"}`, + ) + if status != http.StatusCreated { + t.Fatalf("replay: expected 201, got %d: %s", status, replayPayload) + } + + first := decodeMessageResponse(t, firstPayload) + replay := decodeMessageResponse(t, replayPayload) + if !reflect.DeepEqual(first, replay) { + t.Fatalf("missing attachment_ids and [] must replay identically") + } + if first.AttachmentIDs == nil || len(first.AttachmentIDs) != 0 { + t.Fatalf("response must contain attachment_ids: [], got %#v", first.AttachmentIDs) + } +} diff --git a/student_tests/message_attachments_test.go b/student_tests/message_attachments_test.go new file mode 100644 index 0000000..cb2fd65 --- /dev/null +++ b/student_tests/message_attachments_test.go @@ -0,0 +1,133 @@ +package student_tests + +import ( + "fmt" + "net/http" + "reflect" + "testing" + + "mtusi2026lab7/internal/domain" +) + +func TestMessageAttachmentContract(t *testing.T) { + memoryStore, serverURL, user, chatID := createMessageFixture(t) + + readyID := "11111111-1111-4111-8111-111111111111" + if err := memoryStore.PutAttachment(domain.Attachment{ + ID: readyID, + ChatID: chatID, + OwnerID: user.ID, + Status: domain.AttachmentStatusReady, + }); err != nil { + t.Fatalf("seed ready attachment: %v", err) + } + + status, payload := sendMessageRequest( + t, + serverURL, + chatID, + user.ID, + "attachment-only", + fmt.Sprintf(`{"text":"","attachment_ids":[%q]}`, readyID), + ) + if status != http.StatusCreated { + t.Fatalf("attachment-only message: expected 201, got %d: %s", status, payload) + } + + message := decodeMessageResponse(t, payload) + if message.Text != "" { + t.Fatalf("attachment-only message changed text: %q", message.Text) + } + if !reflect.DeepEqual(message.AttachmentIDs, []string{readyID}) { + t.Fatalf("attachment_ids changed: %#v", message.AttachmentIDs) + } + + items, _, err := memoryStore.GetMessages(chatID, user.ID, 10, nil) + if err != nil { + t.Fatalf("read stored messages: %v", err) + } + if len(items) != 1 || !reflect.DeepEqual(items[0].AttachmentIDs, []string{readyID}) { + t.Fatalf("stored attachment relation differs: %#v", items) + } +} + +func TestMessageAttachmentValidationAndAccess(t *testing.T) { + memoryStore, serverURL, user, chatID := createMessageFixture(t) + otherChat, err := memoryStore.CreateChat("Other chat", []string{user.ID}) + if err != nil { + t.Fatalf("create other chat: %v", err) + } + + pendingID := "22222222-2222-4222-8222-222222222222" + if err = memoryStore.PutAttachment(domain.Attachment{ + ID: pendingID, + ChatID: chatID, + OwnerID: user.ID, + Status: domain.AttachmentStatusPending, + }); err != nil { + t.Fatalf("seed pending attachment: %v", err) + } + + foreignID := "33333333-3333-4333-8333-333333333333" + if err = memoryStore.PutAttachment(domain.Attachment{ + ID: foreignID, + ChatID: otherChat.ID, + OwnerID: user.ID, + Status: domain.AttachmentStatusReady, + }); err != nil { + t.Fatalf("seed foreign attachment: %v", err) + } + + testCases := []struct { + name string + body string + wantStatus int + }{ + { + name: "empty without attachments", + body: `{"text":"","attachment_ids":[]}`, + wantStatus: http.StatusBadRequest, + }, + { + name: "invalid attachment uuid", + body: `{"text":"hello","attachment_ids":["not-a-uuid"]}`, + wantStatus: http.StatusBadRequest, + }, + { + name: "duplicate attachment", + body: fmt.Sprintf(`{"text":"hello","attachment_ids":[%q,%q]}`, pendingID, pendingID), + wantStatus: http.StatusBadRequest, + }, + { + name: "unknown attachment", + body: `{"text":"hello","attachment_ids":["44444444-4444-4444-8444-444444444444"]}`, + wantStatus: http.StatusNotFound, + }, + { + name: "attachment from another chat", + body: fmt.Sprintf(`{"text":"hello","attachment_ids":[%q]}`, foreignID), + wantStatus: http.StatusNotFound, + }, + { + name: "attachment not ready", + body: fmt.Sprintf(`{"text":"hello","attachment_ids":[%q]}`, pendingID), + wantStatus: http.StatusConflict, + }, + } + + for index, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + status, payload := sendMessageRequest( + t, + serverURL, + chatID, + user.ID, + fmt.Sprintf("attachment-validation-%d", index), + testCase.body, + ) + if status != testCase.wantStatus { + t.Fatalf("expected %d, got %d: %s", testCase.wantStatus, status, payload) + } + }) + } +} diff --git a/student_tests/messenger_test.go b/student_tests/messenger_test.go new file mode 100644 index 0000000..2648b5c --- /dev/null +++ b/student_tests/messenger_test.go @@ -0,0 +1,667 @@ +package student_tests + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "sort" + "sync" + "testing" + "time" + + store "mtusi2026lab7/internal/adapter/memory" + "mtusi2026lab7/internal/domain" + "mtusi2026lab7/internal/transport/http/dto" + "mtusi2026lab7/internal/transport/http/handlers" + "mtusi2026lab7/internal/transport/http/middleware" +) + +func requireLegacyAuth( + memoryStore *store.MemoryStore, + next http.HandlerFunc, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + userID := r.Header.Get("X-User-Id") + + user, err := memoryStore.GetUserByID(userID) + if err != nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + + ctx := context.WithValue( + r.Context(), + middleware.UserContextKey, + user, + ) + + next(w, r.WithContext(ctx)) + } +} + +// изолированный серв для тестов +func setupTestServer() (*httptest.Server, *store.MemoryStore) { + memoryStore := store.NewMemoryStore() + repository := store.NewMemoryRepository(memoryStore) + handler := handlers.NewHandler(newTestService(repository, time.Hour)) + + mux := http.NewServeMux() + mux.HandleFunc("POST /api/v1/users", handler.CreateUser) + mux.HandleFunc( + "GET /api/v1/users/me", + requireLegacyAuth(memoryStore, handler.GetMe), + ) + mux.HandleFunc( + "POST /api/v1/chats", + requireLegacyAuth(memoryStore, handler.CreateChat), + ) + mux.HandleFunc( + "GET /api/v1/chats", + requireLegacyAuth(memoryStore, handler.ListChats), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}", + requireLegacyAuth(memoryStore, handler.GetChat), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/messages", + requireLegacyAuth(memoryStore, handler.CreateMessage), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}/messages", + requireLegacyAuth(memoryStore, handler.GetMessages), + ) + + var root http.Handler = mux + root = middleware.Recovery(root) + root = middleware.RequestID(root) + + return httptest.NewServer(root), memoryStore +} + +// 1 тест на дубликат username -> 409 Conflict +func TestDuplicateUsername(t *testing.T) { + ts, _ := setupTestServer() + defer ts.Close() + + body := `{ + "username":"bob_the_builder", + "display_name":"Боб", + "password":"Test-password-123"}` + + // Первый раз — 201 Created + res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body)) + if res1.StatusCode != http.StatusCreated { + t.Fatalf("expected 201, got %d", res1.StatusCode) + } + + // Второй раз тот же username — 409 Conflict + res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body)) + if res2.StatusCode != http.StatusConflict { + t.Fatalf("expected 409 Conflict for duplicate username, got %d", res2.StatusCode) + } +} + +// 2 тест на неверный JSON и лишние поля -> 400 Invalid Request +func TestInvalidAndExtraJSON(t *testing.T) { + ts, _ := setupTestServer() + defer ts.Close() + + // Кривой JSON (malformed) + res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username": "bad"`)) + if res1.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for malformed json, got %d", res1.StatusCode) + } + + // Лишнее поле "age" (проверка DisallowUnknownFields) + res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username":"valid_user","display_name":"User","age":25}`)) + if res2.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for extra fields, got %d", res2.StatusCode) + } +} + +// 3 тст на пустое сообщение и сообщение из одних пробелов -> 400 Invalid Request +func TestEmptyMessageValidation(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("user_msg_test", "Tester") + chat, _ := st.CreateChat("Test Chat", []string{u.ID}) + + // Пустой текст + req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":""}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-Id", u.ID) + req.Header.Set("Idempotency-Key", "empty-text") + + res, _ := http.DefaultClient.Do(req) + if res.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for empty text, got %d", res.StatusCode) + } + + // Текст только из пробелов + reqSpaces, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":" "}`)) + reqSpaces.Header.Set("Content-Type", "application/json") + reqSpaces.Header.Set("X-User-Id", u.ID) + reqSpaces.Header.Set("Idempotency-Key", "spaces-text") + + resSpaces, _ := http.DefaultClient.Do(reqSpaces) + if resSpaces.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for whitespace-only text, got %d", resSpaces.StatusCode) + } +} + +// 4 тест: чужой чат для постороннего -> 404 Not Found (не 403!) +func TestOutsiderChatAccess(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + alice, _ := st.CreateUser("alice_secret", "Алиса") + eve, _ := st.CreateUser("eve_eavesdropper", "Ева") + + chat, _ := st.CreateChat("Секретный чат", []string{alice.ID}) + + // Ева пытается прочитать чат Алисы + req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/chats/%s", ts.URL, chat.ID), nil) + req.Header.Set("X-User-Id", eve.ID) + + res, _ := http.DefaultClient.Do(req) + if res.StatusCode != http.StatusNotFound { + t.Fatalf("expected 404 Not Found (no leak via 403), got %d", res.StatusCode) + } +} + +// 5 Тест: пагинация по нескольким страницам с курсором +func TestCursorPaginationMultiplePages(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("paging_user", "Пейджер") + chat, _ := st.CreateChat("Чат пагинации", []string{u.ID}) + + // Отправляем 5 сообщений + for i := 1; i <= 5; i++ { + st.CreateMessage(chat.ID, u.ID, fmt.Sprintf("Message %d", i)) + } + + // Запрашиваем порциями по limit=2 + var allReceived []string + cursor := "" + + for { + url := fmt.Sprintf("%s/api/v1/chats/%s/messages?limit=2", ts.URL, chat.ID) + if cursor != "" { + url += "&cursor=" + cursor + } + + req, _ := http.NewRequest(http.MethodGet, url, nil) + req.Header.Set("X-User-Id", u.ID) + res, _ := http.DefaultClient.Do(req) + + var page dto.MessagePageResponse + body, _ := io.ReadAll(res.Body) + json.Unmarshal(body, &page) + res.Body.Close() + + for _, m := range page.Items { + allReceived = append(allReceived, m.Text) + } + + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + + if len(allReceived) != 5 { + t.Fatalf("expected 5 messages total across pages, got %d", len(allReceived)) + } +} + +func TestChatCursorPaginationMultiplePages(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + user, err := st.CreateUser("chat_paging_user", "Пейджер чатов") + if err != nil { + t.Fatalf("failed to create user: %v", err) + } + + outsider, err := st.CreateUser("chat_paging_outsider", "Посторонний") + if err != nil { + t.Fatalf("failed to create outsider: %v", err) + } + + createdChats := make([]domain.Chat, 0, 5) + + for i := 1; i <= 5; i++ { + chat, createErr := st.CreateChat( + fmt.Sprintf("Chat %d", i), + []string{user.ID}, + ) + if createErr != nil { + t.Fatalf("failed to create chat %d: %v", i, createErr) + } + + createdChats = append(createdChats, chat) + + // Чужой чат создаётся между доступными чатами и не должен + // влиять на размер страницы или next_cursor пользователя. + if i == 3 { + if _, createErr = st.CreateChat( + "Outsider chat", + []string{outsider.ID}, + ); createErr != nil { + t.Fatalf("failed to create outsider chat: %v", createErr) + } + } + } + + sort.Slice(createdChats, func(i, j int) bool { + if createdChats[i].CreatedAt.Equal(createdChats[j].CreatedAt) { + return createdChats[i].ID < createdChats[j].ID + } + + return createdChats[i].CreatedAt.Before(createdChats[j].CreatedAt) + }) + + var receivedIDs []string + seenIDs := make(map[string]bool) + seenCursors := make(map[string]bool) + cursor := "" + finished := false + + for pageNumber := 1; pageNumber <= 10; pageNumber++ { + requestURL := ts.URL + "/api/v1/chats?limit=2" + if cursor != "" { + requestURL += "&cursor=" + url.QueryEscape(cursor) + } + + req, err := http.NewRequest(http.MethodGet, requestURL, nil) + if err != nil { + t.Fatalf("failed to create request: %v", err) + } + req.Header.Set("X-User-Id", user.ID) + + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("failed to list chats: %v", err) + } + + var page dto.ChatPageResponse + decodeErr := json.NewDecoder(res.Body).Decode(&page) + res.Body.Close() + + if res.StatusCode != http.StatusOK { + t.Fatalf("expected 200, got %d", res.StatusCode) + } + if decodeErr != nil { + t.Fatalf("failed to decode chat page: %v", decodeErr) + } + if len(page.Items) > 2 { + t.Fatalf("page contains %d chats with limit=2", len(page.Items)) + } + + for _, chat := range page.Items { + if seenIDs[chat.ID] { + t.Fatalf("chat %s was returned more than once", chat.ID) + } + + seenIDs[chat.ID] = true + receivedIDs = append(receivedIDs, chat.ID) + } + + if page.NextCursor == nil { + finished = true + break + } + + if seenCursors[*page.NextCursor] { + t.Fatalf("cursor cycle detected") + } + + seenCursors[*page.NextCursor] = true + cursor = *page.NextCursor + } + + if !finished { + t.Fatal("chat pagination did not finish") + } + + if len(receivedIDs) != len(createdChats) { + t.Fatalf( + "expected %d chats across all pages, got %d", + len(createdChats), + len(receivedIDs), + ) + } + + for i, chat := range createdChats { + if receivedIDs[i] != chat.ID { + t.Fatalf( + "chat order differs at position %d: expected %s, got %s", + i, + chat.ID, + receivedIDs[i], + ) + } + } +} + +func TestChatCursorValidation(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + alice, err := st.CreateUser("chat_cursor_alice", "Алиса") + if err != nil { + t.Fatalf("failed to create Alice: %v", err) + } + + bob, err := st.CreateUser("chat_cursor_bob", "Боб") + if err != nil { + t.Fatalf("failed to create Bob: %v", err) + } + + for i := 1; i <= 2; i++ { + if _, err = st.CreateChat( + fmt.Sprintf("Alice chat %d", i), + []string{alice.ID}, + ); err != nil { + t.Fatalf("failed to create Alice chat: %v", err) + } + } + + if _, err = st.CreateChat("Bob chat", []string{bob.ID}); err != nil { + t.Fatalf("failed to create Bob chat: %v", err) + } + + firstRequest, err := http.NewRequest( + http.MethodGet, + ts.URL+"/api/v1/chats?limit=1", + nil, + ) + if err != nil { + t.Fatalf("failed to create first request: %v", err) + } + firstRequest.Header.Set("X-User-Id", alice.ID) + + firstResponse, err := http.DefaultClient.Do(firstRequest) + if err != nil { + t.Fatalf("failed to request first page: %v", err) + } + + var firstPage dto.ChatPageResponse + decodeErr := json.NewDecoder(firstResponse.Body).Decode(&firstPage) + firstResponse.Body.Close() + + if firstResponse.StatusCode != http.StatusOK { + t.Fatalf("expected first page status 200, got %d", firstResponse.StatusCode) + } + if decodeErr != nil { + t.Fatalf("failed to decode first page: %v", decodeErr) + } + if firstPage.NextCursor == nil { + t.Fatal("expected next_cursor for Alice") + } + + foreignRequest, err := http.NewRequest( + http.MethodGet, + ts.URL+"/api/v1/chats?limit=1&cursor="+ + url.QueryEscape(*firstPage.NextCursor), + nil, + ) + if err != nil { + t.Fatalf("failed to create foreign cursor request: %v", err) + } + foreignRequest.Header.Set("X-User-Id", bob.ID) + + foreignResponse, err := http.DefaultClient.Do(foreignRequest) + if err != nil { + t.Fatalf("failed to send foreign cursor request: %v", err) + } + foreignResponse.Body.Close() + + if foreignResponse.StatusCode != http.StatusBadRequest { + t.Fatalf( + "expected 400 for another user's cursor, got %d", + foreignResponse.StatusCode, + ) + } + + malformedRequest, err := http.NewRequest( + http.MethodGet, + ts.URL+"/api/v1/chats?cursor=not-valid-base64!", + nil, + ) + if err != nil { + t.Fatalf("failed to create malformed cursor request: %v", err) + } + malformedRequest.Header.Set("X-User-Id", alice.ID) + + malformedResponse, err := http.DefaultClient.Do(malformedRequest) + if err != nil { + t.Fatalf("failed to send malformed cursor request: %v", err) + } + malformedResponse.Body.Close() + + if malformedResponse.StatusCode != http.StatusBadRequest { + t.Fatalf( + "expected 400 for malformed cursor, got %d", + malformedResponse.StatusCode, + ) + } +} + +// 6 тест: 100 сообщений от 10 клиентов одновременно, защита от гонок +func TestConcurrent100MessagesFrom10Clients(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + // Создаем 10 пользователей + var memberIDs []string + for i := 0; i < 10; i++ { + u, _ := st.CreateUser(fmt.Sprintf("client_%d", i), fmt.Sprintf("Client %d", i)) + memberIDs = append(memberIDs, u.ID) + } + + chat, err := st.CreateChat("Highload Chat", memberIDs) + if err != nil { + t.Fatalf("failed to create chat: %v", err) + } + + var wg sync.WaitGroup + totalClients := 10 + messagesPerClient := 10 + + for i := 0; i < totalClients; i++ { + wg.Add(1) + clientID := memberIDs[i] + + go func(senderID string, clientIndex int) { + defer wg.Done() + + for m := 0; m < messagesPerClient; m++ { + text := fmt.Sprintf("Client %d - Message %d", clientIndex, m) + payload := fmt.Sprintf(`{"text":"%s"}`, text) + + req, _ := http.NewRequest( + http.MethodPost, + fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), + bytes.NewBufferString(payload), + ) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-Id", senderID) + req.Header.Set( + "Idempotency-Key", + fmt.Sprintf("concurrent-%d-%d", clientIndex, m), + ) + + res, err := http.DefaultClient.Do(req) + if err != nil || res.StatusCode != http.StatusCreated { + t.Errorf("failed to send concurrent message: %v", err) + } + if res != nil { + res.Body.Close() + } + } + }(clientID, i) + } + + wg.Wait() + + // должно быть 100 сообщений в чате + items, _, err := st.GetMessages(chat.ID, memberIDs[0], 200, nil) + if err != nil { + t.Fatalf("failed to get messages: %v", err) + } + + if len(items) != 100 { + t.Fatalf("RACE CONDITION DETECTED: expected exactly 100 messages, got %d", len(items)) + } + + // уникальность ID + seenIDs := make(map[string]bool) + for _, m := range items { + if seenIDs[m.ID] { + t.Fatalf("duplicate message ID found: %s", m.ID) + } + seenIDs[m.ID] = true + } +} + +// 7 тест: защита от подделки курсора (чужой чат или битый Base64) -> 400 +func TestForeignAndMalformedCursor(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("cursor_tester", "Tester") + chatA, _ := st.CreateChat("Chat A", []string{u.ID}) + chatB, _ := st.CreateChat("Chat B", []string{u.ID}) + + // В Чат А кладем несколько сообщений, чтобы при limit=1 появился NextCursor + st.CreateMessage(chatA.ID, u.ID, "Message 1 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 2 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 3 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 4 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 5 in A") + + st.CreateMessage(chatB.ID, u.ID, "Message 1 in B") + st.CreateMessage(chatB.ID, u.ID, "Message 2 in B") + + // Получаем валидный курсор из Чата А (запрашиваем 1 из 2) + itemsA, hasMore, err := st.GetMessages(chatA.ID, u.ID, 1, nil) + if err != nil || !hasMore || len(itemsA) != 1 { + t.Fatalf("expected next_cursor in Chat A, err: %v", err) + } + nextCursor, err := newTestCursorCodec().EncodeMessage(domain.MessageCursor{ + CreatedAt: itemsA[0].CreatedAt, + MessageID: itemsA[0].ID, + ChatID: chatA.ID, + }) + if err != nil { + t.Fatalf("encode test cursor: %v", err) + } + + // 1. Пытаемся применить курсор от Чата А к Чату Б -> строго 400! + urlForeign := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=%s", ts.URL, chatB.ID, nextCursor) + reqForeign, _ := http.NewRequest(http.MethodGet, urlForeign, nil) + reqForeign.Header.Set("X-User-Id", u.ID) + resForeign, _ := http.DefaultClient.Do(reqForeign) + + if resForeign.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for foreign chat cursor, got %d", resForeign.StatusCode) + } + + // 2. Битый (невалидный) Base64 -> 400 + urlBad := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=not-a-valid-base64!@#", ts.URL, chatB.ID) + reqBad, _ := http.NewRequest(http.MethodGet, urlBad, nil) + reqBad.Header.Set("X-User-Id", u.ID) + resBad, _ := http.DefaultClient.Do(reqBad) + + if resBad.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for malformed cursor, got %d", resBad.StatusCode) + } +} + +// 8 тест валидации создания чата (создателя нет в списке / несуществующий юзер / дубликат) -> 400 +func TestChatCreationValidation(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + alice, _ := st.CreateUser("alice_chat_val", "Alice") + bob, _ := st.CreateUser("bob_chat_val", "Bob") + + // 1. Создатель (Alice) забыла добавить себя в member_ids + bodyNoCaller := fmt.Sprintf(`{"title":"No Caller Chat","member_ids":["%s"]}`, bob.ID) + req1, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyNoCaller)) + req1.Header.Set("Content-Type", "application/json") + req1.Header.Set("X-User-Id", alice.ID) + res1, _ := http.DefaultClient.Do(req1) + if res1.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 when caller is not in member_ids, got %d", res1.StatusCode) + } + + // 2. В участниках передан несуществующий UUID + bodyFakeUser := fmt.Sprintf(`{"title":"Fake User Chat","member_ids":["%s","00000000-0000-0000-0000-000000000000"]}`, alice.ID) + req2, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyFakeUser)) + req2.Header.Set("Content-Type", "application/json") + req2.Header.Set("X-User-Id", alice.ID) + res2, _ := http.DefaultClient.Do(req2) + if res2.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for non-existent member_id, got %d", res2.StatusCode) + } + + // 3. Дубликат участника в списке + bodyDuplicate := fmt.Sprintf(`{"title":"Duplicate Member","member_ids":["%s","%s"]}`, alice.ID, alice.ID) + req3, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyDuplicate)) + req3.Header.Set("Content-Type", "application/json") + req3.Header.Set("X-User-Id", alice.ID) + res3, _ := http.DefaultClient.Do(req3) + if res3.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for duplicate member_ids, got %d", res3.StatusCode) + } +} + +// 9 тест лимитов символов Unicode (длина до 4000 рун и отказ при >4000) +func TestUnicodeLimits(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("unicode_master", "Иван 🚀") + chat, _ := st.CreateChat("Unicode Chat", []string{u.ID}) + + // Ровно 4000 смайликов (в байтах это 16000 байт, но в рунах — ровно 4000!) + validRunes := make([]rune, 4000) + for i := range validRunes { + validRunes[i] = '🔥' + } + bodyValid := fmt.Sprintf(`{"text":"%s"}`, string(validRunes)) + req1, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyValid)) + req1.Header.Set("Content-Type", "application/json") + req1.Header.Set("X-User-Id", u.ID) + req1.Header.Set("Idempotency-Key", "unicode-valid") + res1, _ := http.DefaultClient.Do(req1) + if res1.StatusCode != http.StatusCreated { + t.Fatalf("expected 201 for 4000 unicode runes, got %d", res1.StatusCode) + } + + // 4001 символ -> строго 400 Invalid Request! + tooLongRunes := make([]rune, 4001) + for i := range tooLongRunes { + tooLongRunes[i] = 'a' + } + bodyTooLong := fmt.Sprintf(`{"text":"%s"}`, string(tooLongRunes)) + req2, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyTooLong)) + req2.Header.Set("Content-Type", "application/json") + req2.Header.Set("X-User-Id", u.ID) + req2.Header.Set("Idempotency-Key", "unicode-too-long") + res2, _ := http.DefaultClient.Do(req2) + if res2.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for 4001 runes, got %d", res2.StatusCode) + } +} diff --git a/student_tests/password_rehash_test.go b/student_tests/password_rehash_test.go new file mode 100644 index 0000000..cb8ef72 --- /dev/null +++ b/student_tests/password_rehash_test.go @@ -0,0 +1,61 @@ +package student_tests + +import ( + "encoding/base64" + "fmt" + "net/http" + "testing" + "time" + + "mtusi2026lab7/internal/security" + + "golang.org/x/crypto/argon2" +) + +func legacyPasswordHash(password string) string { + salt := []byte("legacy-salt-1234") + hash := argon2.IDKey([]byte(password), salt, 1, 8*1024, 1, 32) + return fmt.Sprintf( + "$argon2id$v=%d$m=8192,t=1,p=1$%s$%s", + argon2.Version, + base64.RawStdEncoding.EncodeToString(salt), + base64.RawStdEncoding.EncodeToString(hash), + ) +} + +func TestSuccessfulLoginRehashesLegacyPassword(t *testing.T) { + testServer, repository := setupSessionTestServer(t, time.Hour) + defer testServer.Close() + + user := registerSessionTestUser(t, testServer.URL, "rehash_user") + _, currentHash, err := repository.GetUserByUsername(t.Context(), user.Username) + if err != nil { + t.Fatal(err) + } + legacyHash := legacyPasswordHash(testPassword) + if err = repository.UpdatePasswordHash(t.Context(), user.ID, currentHash, legacyHash); err != nil { + t.Fatal(err) + } + + response := createSessionRequest(t, testServer.URL, user.Username, testPassword) + response.Body.Close() + if response.StatusCode != http.StatusCreated { + t.Fatalf("expected successful login, got %d", response.StatusCode) + } + + _, upgradedHash, err := repository.GetUserByUsername(t.Context(), user.Username) + if err != nil { + t.Fatal(err) + } + if upgradedHash == legacyHash { + t.Fatal("successful login did not replace the legacy hash") + } + matches, err := security.VerifyPassword(testPassword, upgradedHash) + if err != nil || !matches { + t.Fatalf("upgraded hash does not verify: matches=%v err=%v", matches, err) + } + needsRehash, err := security.NeedsPasswordRehash(upgradedHash) + if err != nil || needsRehash { + t.Fatalf("upgraded hash still needs rehash: needs=%v err=%v", needsRehash, err) + } +} diff --git a/student_tests/request_validation_test.go b/student_tests/request_validation_test.go new file mode 100644 index 0000000..70251df --- /dev/null +++ b/student_tests/request_validation_test.go @@ -0,0 +1,246 @@ +package student_tests + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "testing" +) + +type contractErrorResponse struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` + } `json:"error"` +} + +func requireContractError( + t *testing.T, + response *http.Response, + wantStatus int, + wantCode string, +) { + t.Helper() + defer response.Body.Close() + + if response.StatusCode != wantStatus { + body, _ := io.ReadAll(response.Body) + t.Fatalf( + "expected status %d, got %d: %s", + wantStatus, + response.StatusCode, + body, + ) + } + + requestID := response.Header.Get("X-Request-Id") + if requestID == "" { + t.Fatal("error response has no X-Request-Id") + } + if contentType := response.Header.Get("Content-Type"); contentType != "application/json; charset=utf-8" { + t.Fatalf("unexpected error Content-Type: %q", contentType) + } + + var payload contractErrorResponse + if err := json.NewDecoder(response.Body).Decode(&payload); err != nil { + t.Fatalf("decode error response: %v", err) + } + if payload.Error.Code != wantCode { + t.Fatalf( + "expected error code %q, got %q", + wantCode, + payload.Error.Code, + ) + } + if payload.Error.Message == "" { + t.Fatal("error response has an empty message") + } + if payload.Error.RequestID != requestID { + t.Fatal("body request_id differs from X-Request-Id") + } +} + +func sendRegistration( + t *testing.T, + baseURL string, + contentType string, + body []byte, +) *http.Response { + t.Helper() + + request, err := http.NewRequest( + http.MethodPost, + baseURL+"/api/v1/users", + bytes.NewReader(body), + ) + if err != nil { + t.Fatalf("create registration request: %v", err) + } + if contentType != "" { + request.Header.Set("Content-Type", contentType) + } + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send registration request: %v", err) + } + + return response +} + +func TestJSONRequestRequiresApplicationJSON(t *testing.T) { + testServer, _ := setupTestServer() + defer testServer.Close() + + body := []byte( + `{"username":"mime_probe","display_name":"Test",` + + `"password":"123456789012"}`, + ) + + for _, contentType := range []string{ + "", + "text/plain", + "application/xml", + "application/json; charset=iso-8859-1", + } { + contentType := contentType + t.Run(contentType, func(t *testing.T) { + response := sendRegistration( + t, + testServer.URL, + contentType, + body, + ) + requireContractError( + t, + response, + http.StatusUnsupportedMediaType, + "unsupported_media_type", + ) + }) + } + + response := sendRegistration( + t, + testServer.URL, + "application/json; charset=UTF-8", + body, + ) + defer response.Body.Close() + if response.StatusCode != http.StatusCreated { + responseBody, _ := io.ReadAll(response.Body) + t.Fatalf( + "expected application/json with UTF-8 charset to be accepted, "+ + "got %d: %s", + response.StatusCode, + responseBody, + ) + } +} + +func TestJSONRequestRejectsInvalidUTF8WithoutMutation(t *testing.T) { + testServer, _ := setupTestServer() + defer testServer.Close() + + body := append( + []byte( + `{"username":"utf8_probe","display_name":"Test",`+ + `"password":"12345678901`, + ), + 0xff, + ) + body = append(body, []byte(`"}`)...) + + response := sendRegistration( + t, + testServer.URL, + "application/json", + body, + ) + requireContractError( + t, + response, + http.StatusBadRequest, + "invalid_request", + ) + + validBody := []byte( + `{"username":"utf8_probe","display_name":"Test",` + + `"password":"12345678901�"}`, + ) + validResponse := sendRegistration( + t, + testServer.URL, + "application/json", + validBody, + ) + defer validResponse.Body.Close() + if validResponse.StatusCode != http.StatusCreated { + responseBody, _ := io.ReadAll(validResponse.Body) + t.Fatalf( + "invalid UTF-8 request mutated storage; expected subsequent "+ + "valid registration 201, got %d: %s", + validResponse.StatusCode, + responseBody, + ) + } +} + +func TestJSONRequestRejectsOversizedBody(t *testing.T) { + testServer, _ := setupTestServer() + defer testServer.Close() + + response := sendRegistration( + t, + testServer.URL, + "application/json", + bytes.Repeat([]byte(" "), (1<<20)+1), + ) + requireContractError( + t, + response, + http.StatusRequestEntityTooLarge, + "payload_too_large", + ) +} + +func TestBasicAuthRejectsInvalidUTF8(t *testing.T) { + testServer, _ := setupSessionTestServer(t, 0) + defer testServer.Close() + + credentials := append([]byte("unknown:"), 0xff) + request, err := http.NewRequest( + http.MethodPost, + testServer.URL+"/api/v1/auth/sessions", + nil, + ) + if err != nil { + t.Fatalf("create session request: %v", err) + } + request.Header.Set( + "Authorization", + "Basic "+base64.StdEncoding.EncodeToString(credentials), + ) + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send session request: %v", err) + } + defer response.Body.Close() + + if response.StatusCode != http.StatusUnauthorized { + body, _ := io.ReadAll(response.Body) + t.Fatalf( + "expected invalid UTF-8 Basic credentials to return 401, "+ + "got %d: %s", + response.StatusCode, + body, + ) + } + if got := response.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` { + t.Fatalf("unexpected Basic challenge: %q", got) + } +} diff --git a/tests/acl_audit_grade4.sh b/tests/acl_audit_grade4.sh new file mode 100755 index 0000000..5ecfda0 --- /dev/null +++ b/tests/acl_audit_grade4.sh @@ -0,0 +1,52 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +postgres_query() { + role=$1 + password_file=$2 + sql=$3 + docker compose exec -T postgres sh -ec \ + "export PGPASSWORD=\$(cat /run/secrets/$password_file); psql -v ON_ERROR_STOP=1 'host=postgres port=5432 dbname=messenger user=$role sslmode=verify-full sslrootcert=/run/secrets/tls_ca' -Atc '$sql'" +} + +[ "$(postgres_query messenger_api postgres_api_password 'SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()')" = t ] || { + printf '%s\n' "PostgreSQL API connection is not TLS" >&2 + exit 1 +} +postgres_query messenger_api postgres_api_password 'SELECT 1 FROM users LIMIT 1' >/dev/null +if postgres_query messenger_worker postgres_worker_password 'SELECT 1 FROM users LIMIT 1' >/dev/null 2>&1; then + printf '%s\n' "Worker can read the users table" >&2 + exit 1 +fi +if postgres_query messenger_dispatcher postgres_dispatcher_password 'SELECT 1 FROM users LIMIT 1' >/dev/null 2>&1; then + printf '%s\n' "Dispatcher can read the users table" >&2 + exit 1 +fi +postgres_query messenger_dispatcher postgres_dispatcher_password \ + 'SELECT status FROM attachments WHERE false FOR UPDATE' >/dev/null +postgres_query messenger_dispatcher postgres_dispatcher_password \ + 'UPDATE attachments SET updated_at = updated_at WHERE false' >/dev/null +if postgres_query messenger_dispatcher postgres_dispatcher_password \ + 'DELETE FROM attachments WHERE false' >/dev/null 2>&1; then + printf '%s\n' "Dispatcher can delete attachment metadata" >&2 + exit 1 +fi +printf '%s\n' "PASS: PostgreSQL verify-full and role GRANTs permit dispatcher recovery but deny unrelated/destructive access" + +docker compose exec -T redis sh -ec ' + password=$(cat /run/secrets/redis_api_password) + REDISCLI_AUTH="$password" redis-cli --user api -h 127.0.0.1 ping | grep -qx PONG + REDISCLI_AUTH="$password" redis-cli --user api -h 127.0.0.1 set chat:v2:grade4 ok | grep -qx OK + REDISCLI_AUTH="$password" redis-cli --user api -h 127.0.0.1 del chat:v2:grade4 >/dev/null + REDISCLI_AUTH="$password" redis-cli --user api -h 127.0.0.1 acl list 2>&1 | grep -q NOPERM + REDISCLI_AUTH="$password" redis-cli --user api -h 127.0.0.1 set outside:key denied 2>&1 | grep -q NOPERM +' +printf '%s\n' "PASS: Redis API ACL permits cache prefix only and denies ACL administration" + +permissions=$(docker compose exec -T broker rabbitmqctl list_permissions -p / -q) +printf '%s\n' "$permissions" | awk -F '\t' '$1 == "dispatcher" && $2 == "^attachment[.]process[.]v1$" && $3 == "^amq[.]default$" && $4 == "^$" {found=1} END {exit !found}' +printf '%s\n' "$permissions" | awk -F '\t' '$1 == "worker" && $2 == "^attachment[.]process[.]v1$" && $3 == "^$" && $4 == "^attachment[.]process[.]v1$" {found=1} END {exit !found}' +printf '%s\n' "PASS: RabbitMQ dispatcher/worker permissions match the single attachment queue" diff --git a/tests/async_resilience.py b/tests/async_resilience.py new file mode 100644 index 0000000..2c414b6 --- /dev/null +++ b/tests/async_resilience.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Grade-3 asynchronous durability scenario against the local Compose stack.""" +import hashlib +import subprocess +import time +from pathlib import Path + +from client import Client, arguments, check, run +from image_probe import jpeg_size + +ROOT = Path(__file__).resolve().parents[1] + + +def compose(*args): + command = ["docker", "compose"] + if (ROOT / ".env").exists(): + command += ["--env-file", ".env"] + command += list(args) + subprocess.run(command, cwd=ROOT, check=True, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def sql(statement): + command = ["docker", "compose"] + if (ROOT / ".env").exists(): + command += ["--env-file", ".env"] + command += ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-Atc", statement] + return subprocess.run(command, cwd=ROOT, check=True, text=True, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.strip() + + +def main(): + args = arguments("Lab5 worker-stop and broker-restart durability scenario") + client = Client(args.base_url, args.ca_file) + compose("stop", "worker") + try: + alice, bob, _, chat = client.bootstrap() + attachment, original = client.attachment(alice, chat) + linked = client.message(alice, chat, "", attachments=[attachment["id"]])["json"] + check(linked["attachment_ids"] == [attachment["id"]], "queued attachment was not linkable") + client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=bob) + + # Accepted staging, DB intent and durable queue must survive both API and + # broker restart while no worker is available. + compose("restart", "api", "broker") + compose("up", "-d", "--wait", "api", "broker") + compose("restart", "dispatcher") + snapshot = client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=bob, schema="Attachment")["json"] + check(snapshot["status"] in ("queued", "processing"), "accepted job disappeared or failed during restart") + + compose("start", "worker") + ready = client.wait_ready(bob, snapshot) + downloaded = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob) + check(downloaded["bytes"] == original, "original changed after asynchronous recovery") + variants = [item for item in ready["variants"] if item["name"] == "thumbnail"] + check(len(variants) == 1, "recovery did not produce exactly one thumbnail") + variant = variants[0] + thumbnail = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", actor=bob) + check(hashlib.sha256(thumbnail["bytes"]).hexdigest() == variant["sha256"], "thumbnail checksum mismatch") + check(jpeg_size(thumbnail["bytes"]) == (256, 160), "thumbnail dimensions mismatch") + + # Force a redelivery of the same logical job. Deterministic keys and the + # variant primary key must turn it into the same effect, not a duplicate. + attachment_id = attachment["id"] + sql("UPDATE attachment_jobs SET status='queued', published_at=NULL, error_code=NULL WHERE attachment_id='" + attachment_id + "'") + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + if sql("SELECT status FROM attachment_jobs WHERE attachment_id='" + attachment_id + "'") == "succeeded": + break + time.sleep(0.2) + else: + raise AssertionError("redelivered job did not finish") + count = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='" + attachment_id + "' AND name='thumbnail'") + check(count == "1", "redelivery created duplicate variants") + after_duplicate = client.call("GET", "/api/v1/attachments/" + attachment_id, actor=bob, schema="Attachment")["json"] + repeated = [item for item in after_duplicate["variants"] if item["name"] == "thumbnail"] + check(len(repeated) == 1 and repeated[0]["sha256"] == variant["sha256"], "redelivery changed the logical result") + # A transient storage failure is retried a bounded number of times and + # ends with a stable, non-sensitive API error code. + compose("stop", "worker") + failed_attachment, _ = client.attachment(alice, chat) + failed_id = failed_attachment["id"] + client.message(alice, chat, "", attachments=[failed_id]) + sql("UPDATE attachments SET staging_key='staging/" + failed_id + "/missing' WHERE id='" + failed_id + "'") + compose("start", "worker") + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + failed_snapshot = client.call("GET", "/api/v1/attachments/" + failed_id, actor=bob, schema="Attachment")["json"] + if failed_snapshot["status"] == "failed": + break + time.sleep(0.2) + else: + raise AssertionError("job did not reach failed after bounded retries") + check(failed_snapshot["error_code"] == "retry_exhausted", "unsafe or unexpected final error code") + retry_state = sql("SELECT attempt || ':' || status FROM attachment_jobs WHERE attachment_id='" + failed_id + "'") + check(retry_state == "5:failed", "job did not stop at configured retry limit") + client.call("GET", "/api/v1/attachments/" + failed_id + "/content", 409, actor=bob) + + print("PASS: durable recovery, idempotent redelivery and bounded final failure verified.") + finally: + compose("up", "-d", "api", "broker", "dispatcher", "worker") + + +if __name__ == "__main__": + run(main) + diff --git a/tests/attachment_boundaries.py b/tests/attachment_boundaries.py new file mode 100644 index 0000000..d04e8a7 --- /dev/null +++ b/tests/attachment_boundaries.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Black-box attachment validation and exact contract-boundary checks.""" + +import os +import struct +import zlib + +from attachment_memory import cleanup, noisy_png, png_chunk +from client import Client, check, run + + +MAX_BYTES = 10 * 1024 * 1024 + + +def exact_size_png(sample, target_size=MAX_BYTES): + check(sample.endswith(png_chunk(b"IEND", b"")), "sample PNG has no final IEND") + prefix, iend = sample[:-12], sample[-12:] + filler_size = target_size - len(prefix) - len(iend) - 12 + check(filler_size >= 0, "sample PNG is larger than boundary") + result = prefix + png_chunk(b"ruSt", bytes(filler_size)) + iend + check(len(result) == target_size, "exact-size PNG construction failed") + return result + + +def exact_pixel_png(width=10_000, height=4_000): + compressor = zlib.compressobj(level=9) + row = bytes(1 + width * 3) + parts = [] + for _ in range(height): + chunk = compressor.compress(row) + if chunk: + parts.append(chunk) + parts.append(compressor.flush()) + return ( + b"\x89PNG\r\n\x1a\n" + + png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + png_chunk(b"IDAT", b"".join(parts)) + + png_chunk(b"IEND", b"") + ) + + +def config_only_png(width, height): + return ( + b"\x89PNG\r\n\x1a\n" + + png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + ) + + +def upload(client, actor, chat, filename, payload, expected, schema=None): + return client.call( + "POST", + "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], filename), + expected, + actor=actor, + raw=payload, + headers={"Content-Type": "image/png"}, + schema=schema, + ) + + +def main(): + client = Client(os.environ.get("BASE_URL"), None, timeout=30) + alice, bob, eve, chat = client.bootstrap() + users = [alice["id"], bob["id"], eve["id"]] + sample = open(os.path.join(os.path.dirname(__file__), "fixtures", "sample.png"), "rb").read() + + try: + boundary = exact_size_png(sample) + response = upload(client, alice, chat, "exact-10mib.png", boundary, 202, "Attachment") + attachment = client.wait_ready(alice, response["json"], wait_seconds=90) + check(attachment["size_bytes"] == MAX_BYTES, "10 MiB boundary size changed") + downloaded = client.call( + "GET", "/api/v1/attachments/%s/content" % attachment["id"], + 200, actor=alice, + )["bytes"] + check(downloaded == boundary, "10 MiB original changed after round trip") + + pixels = exact_pixel_png() + pixel_response = upload(client, alice, chat, "exact-40m-pixels.png", pixels, 202, "Attachment") + client.wait_ready(alice, pixel_response["json"], wait_seconds=90) + + upload(client, alice, chat, "over-pixels.png", config_only_png(20_000, 10_000), 413) + upload(client, alice, chat, "truncated.png", sample[:33], 415) + + corrupted = noisy_png() + check(len(corrupted) > 70_000, "corruption fixture is too small") + corrupted = bytearray(corrupted) + corrupted[70_000] ^= 0xff + upload(client, alice, chat, "corrupt-after-prefix.png", bytes(corrupted), 415) + + upload(client, alice, chat, "%20%20%20", sample, 400) + upload(client, alice, chat, "c1%C2%85.png", sample, 400) + upload(client, alice, chat, "invalid-%FF.png", sample, 400) + print("PASS: exact byte/pixel boundaries, complete decode, and filename validation are correct.") + finally: + cleanup(chat["id"], users) + + +if __name__ == "__main__": + run(main) + diff --git a/tests/attachment_memory.py b/tests/attachment_memory.py new file mode 100644 index 0000000..73e776e --- /dev/null +++ b/tests/attachment_memory.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Concurrent real PNG uploads with Docker API-container memory sampling.""" + +import concurrent.futures +import json +import os +import struct +import subprocess +import threading +import time +import uuid +import zlib + +from client import Client, check, run + + +def png_chunk(kind, payload): + return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload)) + + +def noisy_png(width=2048, height=1024): + rows = bytearray() + for _ in range(height): + rows.append(0) + rows.extend(os.urandom(width * 3)) + return ( + b"\x89PNG\r\n\x1a\n" + + png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + png_chunk(b"IDAT", zlib.compress(bytes(rows), level=0)) + + png_chunk(b"IEND", b"") + ) + + +def bytes_from_docker(value): + number, unit = value.split()[0], value.split()[0][-3:] + if unit in {"KiB", "MiB", "GiB"}: + number = value.split()[0][:-3] + else: + unit = "B" + factor = {"B": 1, "KiB": 1024, "MiB": 1024**2, "GiB": 1024**3}[unit] + return int(float(number) * factor) + + +def api_container_ids(): + result = subprocess.run( + ["docker", "compose", "ps", "-q", "api"], + check=True, text=True, capture_output=True, + ) + return [line for line in result.stdout.splitlines() if line] + + +def sample_memory(container_ids, stop_event, peaks): + while not stop_event.is_set(): + result = subprocess.run( + ["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}", *container_ids], + check=False, text=True, capture_output=True, + ) + if result.returncode == 0: + for line in result.stdout.splitlines(): + name, usage = line.split("\t", 1) + current = bytes_from_docker(usage.split(" / ", 1)[0]) + peaks[name] = max(peaks.get(name, 0), current) + stop_event.wait(0.05) + + +def cleanup(chat_id, user_ids): + object_script = ( + 'root_user="$(cat /run/secrets/minio_root_user)"\n' + 'root_password="$(cat /run/secrets/minio_root_password)"\n' + 'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n' + 'mc rm --recursive --force "local/${S3_BUCKET}/attachments/' + chat_id + '/" >/dev/null 2>&1 || true\n' + ) + subprocess.run( + ["docker", "compose", "run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap", "-ec", object_script], + check=True, + ) + quoted_users = ",".join("'%s'" % value for value in user_ids) + sql = f""" +BEGIN; +DELETE FROM messages WHERE chat_id = '{chat_id}'; +DELETE FROM attachments WHERE chat_id = '{chat_id}'; +DELETE FROM sessions WHERE user_id IN ({quoted_users}); +DELETE FROM chat_members WHERE chat_id = '{chat_id}'; +DELETE FROM chats WHERE id = '{chat_id}'; +DELETE FROM users WHERE id IN ({quoted_users}); +COMMIT; +""" + subprocess.run( + [ + "docker", "compose", "exec", "-T", "postgres", "sh", "-ec", + "export PGPASSWORD=$(cat /run/secrets/postgres_admin_password); " + "exec psql -v ON_ERROR_STOP=1 -U lab7_admin -d messenger", + ], + input=sql, text=True, check=True, + ) + + +def main(): + concurrency = 12 + base_url = os.environ.get("BASE_URL", "http://127.0.0.1:8080") + client = Client(base_url, None, timeout=30) + alice, bob, eve, chat = client.bootstrap() + users = [alice["id"], bob["id"], eve["id"]] + payload = noisy_png() + stop_event = threading.Event() + peaks = {} + sampler = threading.Thread( + target=sample_memory, + args=(api_container_ids(), stop_event, peaks), + daemon=True, + ) + sampler.start() + started = time.monotonic() + + def upload(index): + response = client.call( + "POST", + "/api/v1/chats/%s/attachments?filename=memory-%02d.png" % (chat["id"], index), + 202, + actor=alice, + raw=payload, + headers={"Content-Type": "image/png", "X-Load-Id": uuid.uuid4().hex}, + schema="Attachment", + ) + return response["headers"]["X-Instance-Id"] + + try: + with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool: + instances = list(pool.map(upload, range(concurrency))) + elapsed = time.monotonic() - started + stop_event.set() + sampler.join(timeout=10) + check(len(set(instances)) >= 2, "uploads did not exercise both API replicas") + check(len(peaks) >= 2, "memory was not sampled for both API replicas") + summary = { + "concurrency": concurrency, + "payload_bytes": len(payload), + "total_uploaded_bytes": len(payload) * concurrency, + "elapsed_seconds": round(elapsed, 3), + "successful_uploads": len(instances), + "api_instances_observed": len(set(instances)), + "peak_memory_bytes_by_container": peaks, + } + print(json.dumps(summary, ensure_ascii=False, sort_keys=True)) + print("PASS: concurrent attachment uploads remained within configured API memory limits.") + finally: + stop_event.set() + sampler.join(timeout=10) + cleanup(chat["id"], users) + + +if __name__ == "__main__": + run(main) + diff --git a/tests/histogram_calibration.py b/tests/histogram_calibration.py new file mode 100644 index 0000000..d52a92f --- /dev/null +++ b/tests/histogram_calibration.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +"""Compare client timings with Prometheus histogram quantiles and buckets.""" + +import concurrent.futures +import json +import math +import time +import urllib.parse +import urllib.request + +from attachment_memory import cleanup +from client import Client + + +def json_get(base_url, path, params=None, timeout=10): + query = "?" + urllib.parse.urlencode(params, doseq=True) if params else "" + with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response: + return json.load(response) + + +def percentile(values, quantile): + ordered = sorted(values) + return ordered[max(0, math.ceil(quantile * len(ordered)) - 1)] + + +def prometheus_scalar(base_url, expression): + payload = json_get(base_url, "/api/v1/query", {"query": expression}) + assert payload["status"] == "success", payload + results = payload["data"]["result"] + assert results, expression + return float(results[0]["value"][1]) + + +def histogram_boundaries(base_url, metric_name): + payload = json_get( + base_url, + "/api/v1/series", + {"match[]": metric_name + "_bucket"}, + ) + assert payload["status"] == "success", payload + return {series["le"] for series in payload["data"]} + + +def comparable(observed, telemetry, lower=0.2, upper=5.0): + ratio = telemetry / observed + assert lower <= ratio <= upper, (observed, telemetry, ratio) + return ratio + + +def main(): + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://localhost:8080") + parser.add_argument("--prometheus-url", default="http://localhost:9090") + parser.add_argument("--timeout", type=int, default=120) + args = parser.parse_args() + + client = Client(args.base_url, timeout=20) + alice, bob, eve, chat = client.bootstrap() + users = [alice["id"], bob["id"], eve["id"]] + content = open("tests/fixtures/sample.png", "rb").read() + try: + warmup_started = time.monotonic() + warmup = client.call( + "POST", + f'/api/v1/chats/{chat["id"]}/attachments?filename=calibration-warmup.png', + 202, + actor=alice, + raw=content, + headers={"Content-Type": "image/png"}, + schema="Attachment", + )["json"] + client.wait_ready(alice, warmup, args.timeout) + assert time.monotonic() > warmup_started + # Histograms are cumulative. Ensure Prometheus has scraped a baseline + # before the measured jobs, otherwise all jobs may land in the first + # sample and increase() correctly has no earlier value to subtract. + time.sleep(12) + + attachment_started = {} + + def upload(index): + local = Client(args.base_url, timeout=20) + started = time.monotonic() + attachment = local.call( + "POST", + f'/api/v1/chats/{chat["id"]}/attachments?filename=calibration-{index}.png', + 202, + actor=alice, + raw=content, + headers={"Content-Type": "image/png"}, + schema="Attachment", + )["json"] + attachment_started[attachment["id"]] = started + return attachment + + with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool: + attachments = list(pool.map(upload, range(12))) + ready_seconds = [] + for attachment in attachments: + client.wait_ready(alice, attachment, args.timeout) + ready_seconds.append( + time.monotonic() - attachment_started[attachment["id"]] + ) + + http_seconds = [] + for _ in range(400): + response = client.call("GET", "/api/v1/chats", actor=alice) + http_seconds.append(response["elapsed"]) + + time.sleep(12) + http_metric = prometheus_scalar( + args.prometheus_url, + "histogram_quantile(0.95, sum by (le) " + "(increase(messenger_http_server_duration_seconds_bucket[2m])))", + ) + worker_metric = prometheus_scalar( + args.prometheus_url, + "histogram_quantile(0.95, sum by (le) " + "(increase(messenger_worker_job_duration_seconds_bucket[2m])))", + ) + ready_metric = prometheus_scalar( + args.prometheus_url, + "histogram_quantile(0.95, sum by (le) " + "(increase(messenger_attachment_ready_duration_seconds_bucket[2m])))", + ) + client_http_p95 = percentile(http_seconds, 0.95) + client_ready_p95 = percentile(ready_seconds, 0.95) + + http_boundaries = histogram_boundaries( + args.prometheus_url, "messenger_http_server_duration_seconds" + ) + worker_boundaries = histogram_boundaries( + args.prometheus_url, "messenger_worker_job_duration_seconds" + ) + ready_boundaries = histogram_boundaries( + args.prometheus_url, "messenger_attachment_ready_duration_seconds" + ) + assert {"0.005", "0.01", "0.05", "0.1", "1.0"}.issubset( + http_boundaries + ), http_boundaries + assert {"0.05", "0.1", "0.25", "1.0", "10.0"}.issubset( + worker_boundaries + ), worker_boundaries + assert {"0.1", "0.25", "1.0", "10.0", "120.0"}.issubset( + ready_boundaries + ), ready_boundaries + assert 0 < http_metric < 1, http_metric + assert 0 < worker_metric < 10, worker_metric + assert 0 < ready_metric < 10, ready_metric + + print( + json.dumps( + { + "status": "PASS", + "samples": { + "http": len(http_seconds), + "attachments": len(ready_seconds), + }, + "http_p95_seconds": { + "client": client_http_p95, + "prometheus": http_metric, + "ratio": comparable(client_http_p95, http_metric), + }, + "ready_p95_seconds": { + "client_polling_upper_bound": client_ready_p95, + "prometheus": ready_metric, + "ratio": comparable( + client_ready_p95, ready_metric, lower=0.1, upper=5.0 + ), + }, + "worker_p95_seconds": worker_metric, + "boundaries": { + "http": sorted(http_boundaries), + "worker": sorted(worker_boundaries), + "ready": sorted(ready_boundaries), + }, + }, + ensure_ascii=False, + indent=2, + ) + ) + finally: + cleanup(chat["id"], users) + + +if __name__ == "__main__": + main() + diff --git a/tests/level4_resilience.py b/tests/level4_resilience.py new file mode 100644 index 0000000..93e0cec --- /dev/null +++ b/tests/level4_resilience.py @@ -0,0 +1,315 @@ +#!/usr/bin/env python3 +"""Grade-4 fault injection and media pipeline verification.""" + +import hashlib +import json +import struct +import subprocess +import time +from pathlib import Path + +from client import Client, arguments, check, run +from image_probe import jpeg_size + +ROOT = Path(__file__).resolve().parents[1] + + +def compose(*args, capture=False, check_result=True): + command = ["docker", "compose"] + if (ROOT / ".env").exists(): + command += ["--env-file", ".env"] + command += list(args) + return subprocess.run( + command, + cwd=ROOT, + check=check_result, + text=capture, + stdout=subprocess.PIPE if capture else subprocess.DEVNULL, + stderr=subprocess.PIPE if capture else subprocess.DEVNULL, + ) + + +def sql(statement): + result = compose( + "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", + "-v", "ON_ERROR_STOP=1", "-Atc", statement, + capture=True, + ) + return result.stdout.strip() + + +def restart_count(service): + container_id = compose("ps", "-q", service, capture=True).stdout.strip() + check(bool(container_id), service + " container is not running") + result = subprocess.run( + ["docker", "inspect", "--format", "{{.RestartCount}}", container_id], + check=True, + text=True, + stdout=subprocess.PIPE, + ) + return int(result.stdout.strip()) + + +def wait_until(predicate, timeout, description): + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + last = predicate() + if last: + return last + time.sleep(0.2) + raise AssertionError(description + "; last=" + repr(last)) + + +def wait_failed(client, actor, attachment, timeout=30): + current = attachment + + def poll(): + nonlocal current + current = client.call( + "GET", + "/api/v1/attachments/" + attachment["id"], + actor=actor, + schema="Attachment", + )["json"] + return current if current["status"] == "failed" else None + + return wait_until(poll, timeout, "attachment did not become failed") + + +def webp_size(data): + check( + len(data) >= 30 and data[:4] == b"RIFF" and data[8:12] == b"WEBP", + "optimized output is not a WebP RIFF container", + ) + chunk = data[12:16] + payload = data[20:] + if chunk == b"VP8 ": + marker = payload.find(b"\x9d\x01\x2a") + check(marker >= 0 and len(payload) >= marker + 7, "invalid VP8 frame") + width, height = struct.unpack_from("= 5 and payload[0] == 0x2F, "invalid VP8L frame") + bits = int.from_bytes(payload[1:5], "little") + return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1 + if chunk == b"VP8X": + check(len(payload) >= 10, "invalid VP8X frame") + width = int.from_bytes(payload[4:7], "little") + 1 + height = int.from_bytes(payload[7:10], "little") + 1 + return width, height + raise AssertionError("unsupported WebP primary chunk " + repr(chunk)) + + +def verify_variants(client, actor, ready, original): + check(ready["status"] == "ready", "attachment is not ready") + by_name = {item["name"]: item for item in ready["variants"]} + check( + set(by_name) == {"thumbnail", "crop", "optimized"}, + "ready attachment must contain exactly three level-4 variants", + ) + expected = { + "thumbnail": ("image/jpeg", (256, 160)), + "crop": ("image/jpeg", (128, 128)), + "optimized": ("image/webp", (320, 200)), + } + for name, (content_type, dimensions) in expected.items(): + metadata = by_name[name] + check( + (metadata["width"], metadata["height"]) == dimensions, + name + " metadata dimensions mismatch", + ) + downloaded = client.call( + "GET", + "/api/v1/attachments/" + ready["id"] + "/content?variant=" + name, + actor=actor, + ) + check( + downloaded["headers"].get_content_type() == content_type, + name + " content type mismatch", + ) + check( + len(downloaded["bytes"]) == metadata["size_bytes"] and + hashlib.sha256(downloaded["bytes"]).hexdigest() == metadata["sha256"], + name + " checksum/size mismatch", + ) + actual = ( + webp_size(downloaded["bytes"]) + if name == "optimized" + else jpeg_size(downloaded["bytes"]) + ) + check(actual == dimensions, name + " actual dimensions mismatch") + downloaded_original = client.call( + "GET", + "/api/v1/attachments/" + ready["id"] + "/content", + actor=actor, + )["bytes"] + check(downloaded_original == original, "original bytes changed") + check( + sql("SELECT staging_key IS NULL FROM attachments WHERE id='" + ready["id"] + "'") == "t", + "successful processing did not safely clear staging", + ) + + +def jobctl(*args, expect_success=True): + result = compose( + "run", "--rm", "--no-deps", "--entrypoint", "/app/jobctl", + "dispatcher", *args, + capture=True, + check_result=False, + ) + if expect_success: + check(result.returncode == 0, "jobctl failed: " + result.stderr) + else: + check(result.returncode != 0, "unsafe jobctl command unexpectedly succeeded") + return result + + +def main(): + args = arguments("Lab5 grade-4 fault injection scenario") + client = Client(args.base_url, args.ca_file) + alice, bob, _, chat = client.bootstrap() + + # Media pipeline: crop and optimized are real files with deterministic + # metadata; optimized is not enlarged beyond the 320x200 fixture. + baseline, original = client.attachment(alice, chat) + ready = client.wait_ready(bob, baseline) + verify_variants(client, bob, ready, original) + + # Crash after DB commit but before publish. The outbox row has no marker, + # dispatcher restarts, publishes it, and no operator creates a second job. + compose("stop", "worker") + wait_until( + lambda: sql("SELECT count(*) FROM attachment_jobs WHERE status='queued' AND published_at IS NULL") == "0", + 10, + "outbox was not initially drained", + ) + dispatcher_restarts = restart_count("dispatcher") + compose("exec", "-T", "dispatcher", "touch", "/tmp/mtusi-fault-before-publish") + outbox_attachment, outbox_original = client.attachment(alice, chat) + wait_until( + lambda: restart_count("dispatcher") > dispatcher_restarts, + 15, + "dispatcher fault marker did not crash the process", + ) + check( + sql("SELECT count(*) FROM attachment_jobs WHERE attachment_id='" + outbox_attachment["id"] + "'") == "1", + "outbox recovery created another logical job", + ) + wait_until( + lambda: sql("SELECT published_at IS NOT NULL FROM attachment_jobs WHERE attachment_id='" + outbox_attachment["id"] + "'") == "t", + 15, + "outbox row was not published after dispatcher restart", + ) + compose("start", "worker") + outbox_ready = client.wait_ready(bob, outbox_attachment) + verify_variants(client, bob, outbox_ready, outbox_original) + + # Crash after all object writes and before the result transaction/ack. + # Expire the lease explicitly to make the deterministic test fast. + worker_restarts = restart_count("worker") + compose("exec", "-T", "worker", "touch", "/tmp/mtusi-fault-after-objects") + crashed_attachment, crashed_original = client.attachment(alice, chat) + wait_until( + lambda: restart_count("worker") > worker_restarts, + 20, + "worker fault marker did not crash the process", + ) + sql( + "UPDATE attachment_jobs SET lease_until=CURRENT_TIMESTAMP-INTERVAL '1 second' " + "WHERE attachment_id='" + crashed_attachment["id"] + "' AND status='processing'" + ) + crashed_ready = client.wait_ready(bob, crashed_attachment) + verify_variants(client, bob, crashed_ready, crashed_original) + check( + int(sql( + "SELECT count(*) FROM attachment_job_events e JOIN attachment_jobs j USING(job_id) " + "WHERE j.attachment_id='" + crashed_attachment["id"] + "' AND e.event_type='lease_recovered'" + )) >= 1, + "expired processing lease was not audited as recovered", + ) + check( + sql( + "SELECT count(*) FROM attachment_variants WHERE attachment_id='" + + crashed_attachment["id"] + "'" + ) == "3", + "crash/redelivery multiplied variants", + ) + + # A trusted metadata integrity mismatch is permanent and fails on attempt 1. + compose("stop", "worker") + permanent, _ = client.attachment(alice, chat) + sql( + "UPDATE attachments SET sha256=decode(repeat('00',32),'hex') WHERE id='" + + permanent["id"] + "'" + ) + compose("start", "worker") + permanent_failed = wait_failed(client, bob, permanent) + check(permanent_failed["error_code"] == "invalid_image", "permanent error code mismatch") + check( + sql( + "SELECT attempt || ':' || status FROM attachment_jobs WHERE attachment_id='" + + permanent["id"] + "'" + ) == "1:failed", + "permanent failure was retried", + ) + + # A transient missing staging object consumes the bounded retry budget, + # appears in the failed registry, and can be replayed only after staging is + # restored. Replaying the resulting succeeded job must be rejected. + compose("stop", "worker") + transient, transient_original = client.attachment(alice, chat) + transient_id = transient["id"] + job_id = sql( + "SELECT job_id::text FROM attachment_jobs WHERE attachment_id='" + transient_id + "'" + ) + original_staging = sql( + "SELECT staging_key FROM attachments WHERE id='" + transient_id + "'" + ) + sql( + "UPDATE attachments SET staging_key='staging/" + transient_id + + "/missing' WHERE id='" + transient_id + "'" + ) + compose("start", "worker") + transient_failed = wait_failed(client, bob, transient, timeout=40) + check(transient_failed["error_code"] == "retry_exhausted", "transient final code mismatch") + check( + sql("SELECT attempt || ':' || status FROM attachment_jobs WHERE job_id='" + job_id + "'") == + "5:failed", + "transient failure did not stop at max attempts", + ) + check( + sql( + "SELECT count(*) FROM attachment_job_events WHERE job_id='" + job_id + + "' AND event_type='retry_scheduled'" + ) == "4", + "transient retry audit count mismatch", + ) + failed_registry = json.loads(jobctl("list-failed").stdout) + check(any(item["job_id"] == job_id for item in failed_registry), "failed registry omitted job") + + sql( + "UPDATE attachments SET staging_key='" + original_staging + + "' WHERE id='" + transient_id + "'" + ) + replay = json.loads(jobctl("replay", job_id).stdout) + check(replay["status"] == "queued" and replay["replay_count"] == 1, "replay was not audited") + replay_ready = client.wait_ready(bob, transient_failed) + verify_variants(client, bob, replay_ready, transient_original) + jobctl("replay", job_id, expect_success=False) + check( + sql( + "SELECT replay_count || ':' || status FROM attachment_jobs WHERE job_id='" + job_id + "'" + ) == "1:succeeded", + "rejected replay changed a successful job", + ) + + print( + "PASS: level-4 variants, outbox crash recovery, lease recovery, " + "backoff/failed registry and safe replay verified." + ) + + +if __name__ == "__main__": + run(main) + diff --git a/tests/level5_idempotency.py b/tests/level5_idempotency.py new file mode 100644 index 0000000..6fc1cc6 --- /dev/null +++ b/tests/level5_idempotency.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +"""Grade-5 track 2: repeatable versioned-pipeline idempotency experiment.""" + +import hashlib +import json +import time + +from client import Client, arguments, check, run +from level4_resilience import compose, restart_count, sql, verify_variants, wait_until + + +def jobctl(service, *args, expect_success=True): + result = compose( + "run", "--rm", "--no-deps", "--entrypoint", "/app/jobctl", + service, *args, + capture=True, + check_result=False, + ) + if expect_success: + check(result.returncode == 0, "jobctl failed: " + result.stderr) + else: + check(result.returncode != 0, "fault-injection command unexpectedly succeeded") + return result + + +def job_id(attachment_id, version): + return sql( + "SELECT job_id::text FROM attachment_jobs WHERE attachment_id='" + + attachment_id + "' AND pipeline_version=" + str(version) + ) + + +def variant_hashes(attachment_id, version): + rows = sql( + "SELECT name || ':' || encode(sha256,'hex') FROM attachment_variants " + "WHERE attachment_id='" + attachment_id + "' AND pipeline_version=" + + str(version) + " ORDER BY name" + ) + return tuple(rows.splitlines()) if rows else () + + +def wait_pipeline(client, actor, attachment, version, timeout=45): + current = attachment + + def poll(): + nonlocal current + current = client.call( + "GET", + "/api/v1/attachments/" + attachment["id"], + actor=actor, + schema="Attachment", + )["json"] + state = sql( + "SELECT status || ':' || pipeline_version FROM attachments WHERE id='" + + attachment["id"] + "'" + ) + return current if current["status"] == "ready" and len(current["variants"]) == 3 and state == "ready:" + str(version) else None + + return wait_until(poll, timeout, "pipeline v" + str(version) + " did not become ready") + + +def expire_processing_lease(attachment_id, version): + sql( + "UPDATE attachment_jobs SET lease_until=CURRENT_TIMESTAMP-INTERVAL '1 second' " + "WHERE attachment_id='" + attachment_id + "' AND pipeline_version=" + + str(version) + " AND status='processing'" + ) + + +def wait_queue_drained(): + return wait_until( + lambda: sql( + "SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')" + ) == "0", + 20, + "logical job queue did not drain", + ) + + +def main(): + args = arguments("Lab5 grade-5 versioned pipeline idempotency") + client = Client(args.base_url, args.ca_file) + alice, bob, _, chat = client.bootstrap() + + # H1: a crash before the first object-store side effect loses neither the + # confirmed upload nor its logical job. The final original must not exist + # yet, demonstrated by the rejected v2 upgrade source read. + before_restarts = restart_count("worker") + compose("exec", "-T", "worker", "touch", "/tmp/mtusi-fault-before-objects") + before, before_original = client.attachment(alice, chat) + wait_until( + lambda: restart_count("worker") > before_restarts, + 20, + "worker did not crash before object writes", + ) + check( + sql( + "SELECT status FROM attachment_jobs WHERE attachment_id='" + + before["id"] + "'" + ) == "processing", + "before-side-effect crash did not leave a leased job", + ) + rejected = jobctl("worker", "upgrade", before["id"], "2", expect_success=False) + check( + "upgrade source original is unavailable" in rejected.stderr, + "before-side-effect crash unexpectedly published the final original", + ) + expire_processing_lease(before["id"], 1) + before_ready = wait_pipeline(client, bob, before, 1) + verify_variants(client, bob, before_ready, before_original) + + # H2: after an object side effect but before result COMMIT/ack, a new + # pipeline can supersede the in-flight v1 job. The copied original is the + # durable handoff for v2; v1 cannot publish metadata after the upgrade. + after_restarts = restart_count("worker") + compose("exec", "-T", "worker", "touch", "/tmp/mtusi-fault-after-objects") + raced, raced_original = client.attachment(alice, chat) + wait_until( + lambda: restart_count("worker") > after_restarts, + 20, + "worker did not crash after object writes", + ) + v1_raced_job = job_id(raced["id"], 1) + check( + sql( + "SELECT status FROM attachment_jobs WHERE job_id='" + v1_raced_job + "'" + ) == "processing", + "after-side-effect crash did not preserve the leased v1 job", + ) + upgraded = json.loads(jobctl("worker", "upgrade", raced["id"], "2").stdout) + check( + upgraded["pipeline_version"] == 2 and upgraded["status"] == "queued", + "v2 upgrade did not create a queued versioned job", + ) + raced_ready = wait_pipeline(client, bob, raced, 2) + verify_variants(client, bob, raced_ready, raced_original) + check( + sql( + "SELECT status FROM attachment_jobs WHERE job_id='" + v1_raced_job + "'" + ) == "superseded", + "in-flight v1 job was not superseded", + ) + check( + sql( + "SELECT count(*) FROM attachment_variants WHERE attachment_id='" + + raced["id"] + "' AND pipeline_version=1" + ) == "0", + "stale v1 metadata committed after v2 became active", + ) + check( + sql( + "SELECT count(*) FROM attachment_job_events WHERE job_id='" + + v1_raced_job + "' AND event_type='superseded'" + ) == "1", + "superseded in-flight pipeline was not audited", + ) + + # H3: a completed v1 can be reprocessed by the distinct v2 profile. Both + # version histories remain, while API reads only active v2. + versioned, versioned_original = client.attachment(alice, chat) + v1_ready = wait_pipeline(client, bob, versioned, 1) + verify_variants(client, bob, v1_ready, versioned_original) + v1_job = job_id(versioned["id"], 1) + v1_hashes = variant_hashes(versioned["id"], 1) + check(len(v1_hashes) == 3, "v1 variant history is incomplete") + + upgraded = json.loads(jobctl("worker", "upgrade", versioned["id"], "2").stdout) + v2_job = upgraded["job_id"] + v2_ready = wait_pipeline(client, bob, versioned, 2) + verify_variants(client, bob, v2_ready, versioned_original) + v2_hashes = variant_hashes(versioned["id"], 2) + check(len(v2_hashes) == 3, "v2 variant history is incomplete") + check(v1_hashes != v2_hashes, "v1 and v2 profiles produced identical variant hashes") + check( + sql( + "SELECT count(*) FROM attachment_variants WHERE attachment_id='" + + versioned["id"] + "'" + ) == "6", + "version upgrade did not preserve both variant histories", + ) + + # Duplicate v2 deliveries followed by a reordered stale v1 delivery are + # all no-ops. Record the active result before injection and prove the old + # job cannot overwrite it. + active_before = variant_hashes(versioned["id"], 2) + original_sha_before = hashlib.sha256( + client.call( + "GET", + "/api/v1/attachments/" + versioned["id"] + "/content", + actor=bob, + )["bytes"] + ).hexdigest() + jobctl("dispatcher", "inject", v2_job) + jobctl("dispatcher", "inject", v2_job) + jobctl("dispatcher", "inject", v1_job) + time.sleep(2) + wait_queue_drained() + active_after = variant_hashes(versioned["id"], 2) + original_sha_after = hashlib.sha256( + client.call( + "GET", + "/api/v1/attachments/" + versioned["id"] + "/content", + actor=bob, + )["bytes"] + ).hexdigest() + check(active_after == active_before, "duplicate/reordered delivery changed active v2 hashes") + check(original_sha_after == original_sha_before, "duplicate/reordered delivery changed original") + check( + sql( + "SELECT status || ':' || pipeline_version FROM attachments WHERE id='" + + versioned["id"] + "'" + ) == "ready:2", + "stale v1 delivery rolled back the active pipeline", + ) + check( + sql( + "SELECT count(*) FROM attachment_variants WHERE attachment_id='" + + versioned["id"] + "'" + ) == "6", + "duplicate/reordered messages multiplied variant rows", + ) + check( + sql("SELECT status FROM attachment_jobs WHERE job_id='" + v2_job + "'") == "succeeded", + "duplicate v2 delivery changed successful job state", + ) + + print( + "PASS: pipeline v1/v2 history, crash before/after side effect, " + "superseded in-flight work, duplicate and reordered stale deliveries verified." + ) + + +if __name__ == "__main__": + run(main) + diff --git a/tests/minio_policy.sh b/tests/minio_policy.sh new file mode 100755 index 0000000..7c5e38c --- /dev/null +++ b/tests/minio_policy.sh @@ -0,0 +1,65 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +api_containers=$(docker compose ps -q api) +if [ -z "$api_containers" ]; then + printf "%s\n" "no running API containers found" >&2 + exit 1 +fi +for container_id in $api_containers; do + docker exec "$container_id" sh -ec ' + test ! -e /run/secrets/minio_root_user + test ! -e /run/secrets/minio_root_password + ! env | grep -Eq "^MINIO_ROOT_(USER|PASSWORD)=" + ' +done + +docker compose run --rm --entrypoint /bin/sh minio-bootstrap -ec ' +root_user="$(cat /run/secrets/minio_root_user)" +root_password="$(cat /run/secrets/minio_root_password)" +api_user="$(cat /run/secrets/s3_api_access_key)" +api_password="$(cat /run/secrets/s3_api_secret_key)" +bucket="messenger-attachments" +probe_key="policy-probe/object.txt" + +mc alias set admin http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null +mc alias set limited http://minio:9000 "$api_user" "$api_password" --api S3v4 >/dev/null + +cleanup() { + mc rm --force "admin/${bucket}/staging/${probe_key}" >/dev/null 2>&1 || true + mc rm --force "admin/${bucket}/attachments/${probe_key}" >/dev/null 2>&1 || true + mc rb --force "admin/forbidden-policy-probe" >/dev/null 2>&1 || true +} +trap cleanup EXIT INT TERM + +printf private-probe | mc pipe "limited/${bucket}/staging/${probe_key}" >/dev/null +if mc cat "limited/${bucket}/staging/${probe_key}" >/dev/null 2>&1; then + printf "%s\n" "API credentials unexpectedly read the staging prefix" >&2 + exit 1 +fi + +printf ready-object | mc pipe "admin/${bucket}/attachments/${probe_key}" >/dev/null +mc cat "limited/${bucket}/attachments/${probe_key}" >/dev/null +if printf overwrite | mc pipe "limited/${bucket}/attachments/${probe_key}" >/dev/null 2>&1; then + printf "%s\n" "API credentials unexpectedly wrote the attachments prefix" >&2 + exit 1 +fi + +if mc mb "limited/forbidden-policy-probe" >/dev/null 2>&1; then + printf "%s\n" "limited API credentials unexpectedly created another bucket" >&2 + exit 1 +fi +if wget -qO- "http://minio:9000/${bucket}/attachments/${probe_key}" >/dev/null 2>&1; then + printf "%s\n" "anonymous HTTP GET unexpectedly read a private object" >&2 + exit 1 +fi + +mc rm --force "admin/${bucket}/staging/${probe_key}" >/dev/null +mc rm --force "admin/${bucket}/attachments/${probe_key}" >/dev/null +trap - EXIT INT TERM +printf "%s\n" "PASS: API has no MinIO root credentials; staging is write-only, attachments are read-only, bucket creation and anonymous GET are denied." +' + diff --git a/tests/observability_alerts.py b/tests/observability_alerts.py new file mode 100644 index 0000000..c14a3e7 --- /dev/null +++ b/tests/observability_alerts.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Fire and resolve the two grade-4 Prometheus alerts.""" + +import argparse +import concurrent.futures +import json +import subprocess +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid + +from attachment_memory import cleanup +from client import Client + + +def compose(*args, check=True): + return subprocess.run( + ["docker", "compose", *args], + check=check, + text=True, + capture_output=True, + ) + + +def json_get(base_url, path, params=None, timeout=10): + query = "?" + urllib.parse.urlencode(params) if params else "" + with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response: + return json.load(response) + + +def wait_for(description, action, timeout, interval=2): + deadline = time.monotonic() + timeout + last_error = None + while time.monotonic() < deadline: + try: + value = action() + if value: + return value + except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error: + last_error = error + time.sleep(interval) + raise AssertionError(f"timeout waiting for {description}: {last_error}") + + +def alert(prometheus_url, alert_name, state=None): + payload = json_get(prometheus_url, "/api/v1/alerts") + assert payload["status"] == "success", payload + for item in payload["data"]["alerts"]: + if item.get("labels", {}).get("alertname") != alert_name: + continue + if state is None or item.get("state") == state: + return item + return None + + +def alert_resolved(prometheus_url, alert_name): + return alert(prometheus_url, alert_name) is None + + +def prometheus_scalar(base_url, expression): + payload = json_get(base_url, "/api/v1/query", {"query": expression}) + results = payload["data"]["result"] + return float(results[0]["value"][1]) if results else 0.0 + + +def trace_id_for_request(loki_url, request_id): + payload = json_get( + loki_url, + "/loki/api/v1/query_range", + { + "query": f'{{service_name="messenger-api"}} | request_id="{request_id}"', + "start": str(time.time_ns() - 10 * 60 * 1_000_000_000), + "end": str(time.time_ns()), + "direction": "backward", + "limit": "20", + }, + ) + for result in payload["data"]["result"]: + trace_id = result.get("stream", {}).get("trace_id") + if trace_id and len(trace_id) == 32: + return trace_id + return None + + +def db_error_span(tempo_url, trace_id): + payload = json_get(tempo_url, f"/api/traces/{trace_id}") + for batch in payload.get("batches", []): + for scope in batch.get("scopeSpans", []): + for span in scope.get("spans", []): + if ( + span.get("name", "").startswith("postgresql.") + and span.get("status", {}).get("code") == "STATUS_CODE_ERROR" + ): + return span.get("name") + return None + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://localhost:8080") + parser.add_argument("--prometheus-url", default="http://localhost:9090") + parser.add_argument("--loki-url", default="http://localhost:3100") + parser.add_argument("--tempo-url", default="http://localhost:3200") + parser.add_argument("--timeout", type=int, default=150) + args = parser.parse_args() + + client = Client(args.base_url, timeout=15) + alice, bob, eve, chat = client.bootstrap() + users = [alice["id"], bob["id"], eve["id"]] + postgres_paused = False + queue_result = {} + database_result = {} + try: + compose("stop", "worker") + queue_started = time.monotonic() + content = open("tests/fixtures/sample.png", "rb").read() + response = client.call( + "POST", + f'/api/v1/chats/{chat["id"]}/attachments?filename=queue-alert.png', + 202, + actor=alice, + raw=content, + headers={"Content-Type": "image/png"}, + schema="Attachment", + ) + queue_alert = wait_for( + "queue lag alert firing", + lambda: alert( + args.prometheus_url, "MessengerQueueLagGrowing", "firing" + ), + args.timeout, + ) + queue_result = { + "firing_after_seconds": round(time.monotonic() - queue_started, 3), + "depth": prometheus_scalar(args.prometheus_url, "max(messenger_queue_depth)"), + "oldest_age_seconds": prometheus_scalar( + args.prometheus_url, "max(messenger_queue_oldest_job_age_seconds)" + ), + "state": queue_alert["state"], + } + compose("up", "-d", "worker") + client.wait_ready(alice, response["json"], args.timeout) + queue_recovery_started = time.monotonic() + wait_for( + "queue lag alert resolved", + lambda: alert_resolved(args.prometheus_url, "MessengerQueueLagGrowing"), + args.timeout, + ) + queue_result["resolved_after_seconds"] = round( + time.monotonic() - queue_recovery_started, 3 + ) + + compose("pause", "postgres") + postgres_paused = True + database_started = time.monotonic() + request_ids = [str(uuid.uuid4()) for _ in range(8)] + + def failed_request(request_id): + isolated_client = Client(args.base_url, timeout=15) + isolated_client.call( + "GET", + "/api/v1/chats", + 503, + actor=alice, + headers={"X-Request-Id": request_id}, + ) + return request_id + + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: + list(pool.map(failed_request, request_ids)) + db_alert = wait_for( + "API high error rate alert firing", + lambda: alert( + args.prometheus_url, "MessengerAPIHighErrorRate", "firing" + ), + args.timeout, + ) + database_result = { + "firing_after_seconds": round(time.monotonic() - database_started, 3), + "failed_requests": len(request_ids), + "state": db_alert["state"], + } + compose("unpause", "postgres") + postgres_paused = False + wait_for( + "API readiness after PostgreSQL recovery", + lambda: client.call("GET", "/health/ready", schema="Health"), + 30, + ) + trace_id = wait_for( + "database failure correlated log", + lambda: trace_id_for_request(args.loki_url, request_ids[0]), + args.timeout, + ) + error_span = wait_for( + "database error span", + lambda: db_error_span(args.tempo_url, trace_id), + args.timeout, + ) + database_result.update({"trace_id": trace_id, "error_span": error_span}) + database_recovery_started = time.monotonic() + wait_for( + "API high error rate alert resolved", + lambda: alert_resolved(args.prometheus_url, "MessengerAPIHighErrorRate"), + args.timeout, + ) + database_result["resolved_after_seconds"] = round( + time.monotonic() - database_recovery_started, 3 + ) + + print( + json.dumps( + { + "status": "PASS", + "queue_lag": queue_result, + "database_outage": database_result, + }, + ensure_ascii=False, + indent=2, + ) + ) + finally: + if postgres_paused: + compose("unpause", "postgres", check=False) + compose("up", "-d", "worker", check=False) + wait_for( + "PostgreSQL before cleanup", + lambda: compose("exec", "-T", "postgres", "pg_isready", "-U", "messenger").returncode == 0, + 30, + ) + cleanup(chat["id"], users) + + +if __name__ == "__main__": + main() + diff --git a/tests/observability_grade3.py b/tests/observability_grade3.py new file mode 100644 index 0000000..801214f --- /dev/null +++ b/tests/observability_grade3.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Verify the grade-3 telemetry path after the public smoke test.""" + +import argparse +import json +import re +import time +import urllib.error +import urllib.parse +import urllib.request + + +TRACE_ID = re.compile(r"^[0-9a-f]{32}$") +FORBIDDEN_LABELS = { + "user_id", + "chat_id", + "message_id", + "attachment_id", + "request_id", + "url", + "filename", + "message_text", +} +REQUIRED_RESOURCE_LABELS = { + "service_name", + "service_version", + "service_instance_id", + "deployment_environment_name", +} + + +def json_get(base_url, path, params=None, timeout=5): + query = "" + if params: + query = "?" + urllib.parse.urlencode(params) + request = urllib.request.Request(base_url.rstrip("/") + path + query) + with urllib.request.urlopen(request, timeout=timeout) as response: + return json.load(response) + + +def wait_for(description, action, timeout): + deadline = time.monotonic() + timeout + last_error = None + while time.monotonic() < deadline: + try: + value = action() + if value: + return value + except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error: + last_error = error + time.sleep(2) + raise AssertionError(f"timeout waiting for {description}: {last_error}") + + +def prometheus_scalar(base_url, expression): + payload = json_get(base_url, "/api/v1/query", {"query": expression}) + assert payload["status"] == "success", payload + results = payload["data"]["result"] + if not results: + return 0.0 + return float(results[0]["value"][1]) + + +def trace_id_from_loki(base_url, service_name): + now = time.time_ns() + payload = json_get( + base_url, + "/loki/api/v1/query_range", + { + "query": f'{{service_name="{service_name}"}}', + "start": str(now - 30 * 60 * 1_000_000_000), + "end": str(now), + "direction": "backward", + "limit": "100", + }, + ) + assert payload["status"] == "success", payload + for stream in payload["data"]["result"]: + trace_id = stream.get("stream", {}).get("trace_id", "") + if TRACE_ID.fullmatch(trace_id): + return trace_id + for value in stream.get("values", []): + for candidate in value[1:]: + if isinstance(candidate, str) and TRACE_ID.fullmatch(candidate.strip()): + return candidate.strip() + if isinstance(candidate, dict): + trace_id = candidate.get("trace_id", "") + if TRACE_ID.fullmatch(trace_id): + return trace_id + return None + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--prometheus-url", default="http://localhost:9090") + parser.add_argument("--loki-url", default="http://localhost:3100") + parser.add_argument("--tempo-url", default="http://localhost:3200") + parser.add_argument("--grafana-url", default="http://localhost:3000") + parser.add_argument("--timeout", type=int, default=90) + args = parser.parse_args() + + wait_for( + "Grafana health", + lambda: json_get(args.grafana_url, "/api/health").get("database") == "ok", + args.timeout, + ) + dashboard = wait_for( + "provisioned dashboard", + lambda: json_get( + args.grafana_url, + "/api/dashboards/uid/mtusi-lab7-grade3", + ), + args.timeout, + ) + assert dashboard["dashboard"]["title"] == "MTUSI Lab 6 — Grade 3" + + api_series = wait_for( + "API metrics", + lambda: prometheus_scalar( + args.prometheus_url, + "count(messenger_http_server_requests_total)", + ), + args.timeout, + ) + job_series = wait_for( + "worker metrics", + lambda: prometheus_scalar( + args.prometheus_url, + "count(messenger_worker_jobs_total)", + ), + args.timeout, + ) + series_payload = json_get( + args.prometheus_url, + "/api/v1/series", + {"match[]": "messenger_http_server_requests_total"}, + ) + assert series_payload["status"] == "success" + assert series_payload["data"] + for labels in series_payload["data"]: + leaked = FORBIDDEN_LABELS.intersection(labels) + assert not leaked, f"forbidden metric labels: {sorted(leaked)}" + missing = REQUIRED_RESOURCE_LABELS.difference(labels) + assert not missing, f"missing resource labels: {sorted(missing)}" + assert labels["deployment_environment_name"] == "lab" + + api_trace_id = wait_for( + "correlated API log", + lambda: trace_id_from_loki(args.loki_url, "messenger-api"), + args.timeout, + ) + worker_trace_id = wait_for( + "correlated worker log", + lambda: trace_id_from_loki(args.loki_url, "messenger-worker"), + args.timeout, + ) + api_trace = json_get(args.tempo_url, f"/api/traces/{api_trace_id}") + worker_trace = json_get(args.tempo_url, f"/api/traces/{worker_trace_id}") + assert api_trace.get("batches"), "API trace not found in Tempo" + assert worker_trace.get("batches"), "worker trace not found in Tempo" + + print( + json.dumps( + { + "status": "PASS", + "api_metric_series": int(api_series), + "worker_metric_series": int(job_series), + "api_trace_id": api_trace_id, + "worker_trace_id": worker_trace_id, + "dashboard_uid": "mtusi-lab7-grade3", + }, + ensure_ascii=False, + indent=2, + ) + ) + + +if __name__ == "__main__": + main() + diff --git a/tests/observability_grade4.py b/tests/observability_grade4.py new file mode 100644 index 0000000..11338f9 --- /dev/null +++ b/tests/observability_grade4.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Verify grade-4 metrics and one end-to-end upload trace.""" + +import argparse +import json +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid + +from attachment_memory import cleanup +from client import Client + + +def json_get(base_url, path, params=None, timeout=10): + query = "?" + urllib.parse.urlencode(params) if params else "" + with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response: + return json.load(response) + + +def wait_for(description, action, timeout, interval=2): + deadline = time.monotonic() + timeout + last_error = None + while time.monotonic() < deadline: + try: + value = action() + if value: + return value + except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error: + last_error = error + time.sleep(interval) + raise AssertionError(f"timeout waiting for {description}: {last_error}") + + +def prometheus_scalar(base_url, expression): + payload = json_get(base_url, "/api/v1/query", {"query": expression}) + assert payload["status"] == "success", payload + results = payload["data"]["result"] + return float(results[0]["value"][1]) if results else 0.0 + + +def trace_id_for_request(loki_url, request_id): + payload = json_get( + loki_url, + "/loki/api/v1/query_range", + { + "query": f'{{service_name="messenger-api"}} | request_id="{request_id}"', + "start": str(time.time_ns() - 10 * 60 * 1_000_000_000), + "end": str(time.time_ns()), + "direction": "backward", + "limit": "20", + }, + ) + assert payload["status"] == "success", payload + for result in payload["data"]["result"]: + trace_id = result.get("stream", {}).get("trace_id") + if trace_id and len(trace_id) == 32: + return trace_id + return None + + +def flatten_trace(payload): + services = set() + spans = [] + for batch in payload.get("batches", []): + attributes = batch.get("resource", {}).get("attributes", []) + service = next( + ( + item.get("value", {}).get("stringValue") + for item in attributes + if item.get("key") == "service.name" + ), + None, + ) + if service: + services.add(service) + for scope in batch.get("scopeSpans", []): + for span in scope.get("spans", []): + spans.append((service, span)) + return services, spans + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://localhost:8080") + parser.add_argument("--prometheus-url", default="http://localhost:9090") + parser.add_argument("--loki-url", default="http://localhost:3100") + parser.add_argument("--tempo-url", default="http://localhost:3200") + parser.add_argument("--grafana-url", default="http://localhost:3000") + parser.add_argument("--timeout", type=int, default=120) + args = parser.parse_args() + + client = Client(args.base_url, timeout=20) + alice, bob, eve, chat = client.bootstrap() + users = [alice["id"], bob["id"], eve["id"]] + request_id = str(uuid.uuid4()) + content = open("tests/fixtures/sample.png", "rb").read() + try: + response = client.call( + "POST", + f'/api/v1/chats/{chat["id"]}/attachments?filename=grade4.png', + 202, + actor=alice, + raw=content, + headers={"Content-Type": "image/png", "X-Request-Id": request_id}, + schema="Attachment", + ) + attachment = client.wait_ready(alice, response["json"], args.timeout) + trace_id = wait_for( + "upload log correlation", + lambda: trace_id_for_request(args.loki_url, request_id), + args.timeout, + ) + trace = wait_for( + "complete upload trace", + lambda: json_get(args.tempo_url, f"/api/traces/{trace_id}"), + args.timeout, + ) + services, spans = flatten_trace(trace) + required_services = { + "messenger-api", + "messenger-dispatcher", + "messenger-worker", + } + assert required_services.issubset(services), (required_services, services) + kinds = {span.get("kind") for _, span in spans} + assert "SPAN_KIND_PRODUCER" in kinds, kinds + assert "SPAN_KIND_CONSUMER" in kinds, kinds + assert any(span.get("name", "").startswith("s3.") for _, span in spans) + assert any(span.get("name", "").startswith("postgresql.") for _, span in spans) + + metric_checks = { + "queue_depth": "count(messenger_queue_depth)", + "queue_oldest_age": "count(messenger_queue_oldest_job_age_seconds)", + "db_pool": "count(messenger_db_pool_connections)", + "worker_busy": "count(messenger_worker_busy)", + "worker_capacity": "count(messenger_worker_capacity)", + "process_cpu": "count(messenger_process_cpu_time_seconds_total)", + "process_memory": "count(messenger_process_memory_bytes)", + "ready_histogram": "sum(messenger_attachment_ready_duration_seconds_count)", + } + metrics = { + name: wait_for( + name, + lambda expression=expression: prometheus_scalar( + args.prometheus_url, expression + ), + args.timeout, + ) + for name, expression in metric_checks.items() + } + dashboard = json_get( + args.grafana_url, + "/api/dashboards/uid/mtusi-lab7-grade4", + ) + assert dashboard["dashboard"]["title"] == "MTUSI Lab 6 - Grade 4" + + print( + json.dumps( + { + "status": "PASS", + "attachment_id": attachment["id"], + "trace_id": trace_id, + "services": sorted(services), + "span_kinds": sorted(kinds), + "span_count": len(spans), + "metrics": metrics, + "dashboard_uid": "mtusi-lab7-grade4", + }, + ensure_ascii=False, + indent=2, + ) + ) + finally: + cleanup(chat["id"], users) + + +if __name__ == "__main__": + main() + diff --git a/tests/observability_incidents.py b/tests/observability_incidents.py new file mode 100644 index 0000000..81b681d --- /dev/null +++ b/tests/observability_incidents.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Verify two bounded failures from saved metrics, logs and traces.""" + +import argparse +import json +import re +import time +import urllib.error +import urllib.parse +import urllib.request + + +TRACE_ID = re.compile(r"^[0-9a-f]{32}$") + + +def json_get(base_url, path, params=None, timeout=5): + query = "?" + urllib.parse.urlencode(params) if params else "" + request = urllib.request.Request(base_url.rstrip("/") + path + query) + with urllib.request.urlopen(request, timeout=timeout) as response: + return json.load(response) + + +def wait_for(description, action, timeout): + deadline = time.monotonic() + timeout + last_error = None + while time.monotonic() < deadline: + try: + value = action() + if value: + return value + except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error: + last_error = error + time.sleep(2) + raise AssertionError(f"timeout waiting for {description}: {last_error}") + + +def prometheus_scalar(base_url, expression): + payload = json_get(base_url, "/api/v1/query", {"query": expression}) + assert payload["status"] == "success", payload + results = payload["data"]["result"] + return float(results[0]["value"][1]) if results else 0.0 + + +def incident_from_loki(base_url, service_name, filter_expression, predicate): + now = time.time_ns() + payload = json_get( + base_url, + "/loki/api/v1/query_range", + { + "query": f'{{service_name="{service_name}"}} | {filter_expression}', + "start": str(now - 2 * 60 * 60 * 1_000_000_000), + "end": str(now), + "direction": "backward", + "limit": "1000", + }, + ) + assert payload["status"] == "success", payload + for result in payload["data"]["result"]: + attributes = result.get("stream", {}) + trace_id = attributes.get("trace_id", "") + if predicate(attributes) and TRACE_ID.fullmatch(trace_id): + return { + "event": attributes.get("event"), + "route": attributes.get("route"), + "status_code": attributes.get("status_code"), + "outcome": attributes.get("outcome"), + "attempt": attributes.get("attempt"), + "trace_id": trace_id, + } + return None + + +def trace_exists(base_url, trace_id): + payload = json_get(base_url, f"/api/traces/{trace_id}") + return bool(payload.get("batches")) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--prometheus-url", default="http://localhost:9090") + parser.add_argument("--loki-url", default="http://localhost:3100") + parser.add_argument("--tempo-url", default="http://localhost:3200") + parser.add_argument("--timeout", type=int, default=90) + args = parser.parse_args() + + api_errors = wait_for( + "API 5xx metric", + lambda: prometheus_scalar( + args.prometheus_url, + 'sum(messenger_http_server_requests_total{status_class="5xx"})', + ), + args.timeout, + ) + worker_failures = wait_for( + "failed worker metric", + lambda: prometheus_scalar( + args.prometheus_url, + 'sum(messenger_worker_jobs_total{outcome="failed"})', + ), + args.timeout, + ) + storage_incident = wait_for( + "MinIO outage log", + lambda: incident_from_loki( + args.loki_url, + "messenger-api", + 'status_code="503"', + lambda attrs: ( + attrs.get("status_code") == "503" + and attrs.get("route") + == "POST /api/v1/chats/{chat_id}/attachments" + ), + ), + args.timeout, + ) + worker_incident = wait_for( + "failed worker log", + lambda: incident_from_loki( + args.loki_url, + "messenger-worker", + 'event="attachment_job_failed"', + lambda attrs: ( + attrs.get("event") == "attachment_job_failed" + and attrs.get("outcome") == "failed" + ), + ), + args.timeout, + ) + wait_for( + "MinIO outage trace", + lambda: trace_exists(args.tempo_url, storage_incident["trace_id"]), + args.timeout, + ) + wait_for( + "failed worker trace", + lambda: trace_exists(args.tempo_url, worker_incident["trace_id"]), + args.timeout, + ) + + print( + json.dumps( + { + "status": "PASS", + "api_5xx_total": int(api_errors), + "worker_failed_total": int(worker_failures), + "storage_incident": storage_incident, + "worker_incident": worker_incident, + }, + ensure_ascii=False, + indent=2, + ) + ) + + +if __name__ == "__main__": + main() + diff --git a/tests/observability_retry_trace.py b/tests/observability_retry_trace.py new file mode 100644 index 0000000..994500e --- /dev/null +++ b/tests/observability_retry_trace.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Verify that a retried attachment job remains in the original upload trace.""" + +import argparse +import json +import subprocess +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid + +from attachment_memory import cleanup +from client import Client +from observability_grade4 import flatten_trace, trace_id_for_request, wait_for + + +def compose(*args, check=True): + return subprocess.run( + ["docker", "compose", *args], + check=check, + text=True, + capture_output=True, + ) + + +def start_existing_container(service): + container_id = compose("ps", "-aq", service).stdout.strip() + if not container_id: + raise AssertionError(f"missing container for {service}") + subprocess.run( + ["docker", "start", container_id], + check=True, + text=True, + capture_output=True, + ) + + +def sql_scalar(statement): + result = compose( + "exec", + "-T", + "postgres", + "psql", + "-At", + "-U", + "messenger", + "-d", + "messenger", + "-c", + statement, + ) + return result.stdout.strip() + + +def json_get(base_url, path, timeout=10): + with urllib.request.urlopen(base_url.rstrip("/") + path, timeout=timeout) as response: + return json.load(response) + + +def attempt_from_span(span): + for item in span.get("attributes", []): + if item.get("key") == "job.attempt": + return int(item.get("value", {}).get("intValue", 0)) + return None + + +def complete_retry_trace(tempo_url, trace_id): + payload = json_get(tempo_url, f"/api/traces/{trace_id}") + services, spans = flatten_trace(payload) + consumers = [ + span for _, span in spans if span.get("kind") == "SPAN_KIND_CONSUMER" + ] + producers = [ + span for _, span in spans if span.get("kind") == "SPAN_KIND_PRODUCER" + ] + attempts = sorted( + attempt + for attempt in (attempt_from_span(span) for span in consumers) + if attempt is not None + ) + if len(consumers) < 2 or len(producers) < 2 or len(set(attempts)) < 2: + return None + return services, spans, attempts, consumers, producers + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://localhost:8080") + parser.add_argument("--loki-url", default="http://localhost:3100") + parser.add_argument("--tempo-url", default="http://localhost:3200") + parser.add_argument("--timeout", type=int, default=120) + args = parser.parse_args() + + client = Client(args.base_url, timeout=20) + alice, bob, eve, chat = client.bootstrap() + users = [alice["id"], bob["id"], eve["id"]] + minio_stopped = False + worker_stopped = False + request_id = str(uuid.uuid4()) + try: + compose("stop", "worker") + worker_stopped = True + content = open("tests/fixtures/sample.png", "rb").read() + upload = client.call( + "POST", + f'/api/v1/chats/{chat["id"]}/attachments?filename=retry-trace.png', + 202, + actor=alice, + raw=content, + headers={"Content-Type": "image/png", "X-Request-Id": request_id}, + schema="Attachment", + ) + compose("stop", "minio") + minio_stopped = True + start_existing_container("worker") + worker_stopped = False + attachment_id = upload["json"]["id"] + first_retry = wait_for( + "first failed attempt", + lambda: int( + sql_scalar( + "SELECT attempt FROM attachment_jobs " + f"WHERE attachment_id='{attachment_id}'" + ) + or "0" + ) + >= 2, + 30, + interval=0.05, + ) + assert first_retry + compose("up", "-d", "--wait", "minio") + minio_stopped = False + ready = client.wait_ready(alice, upload["json"], args.timeout) + trace_id = wait_for( + "upload trace id", + lambda: trace_id_for_request(args.loki_url, request_id), + args.timeout, + ) + services, spans, attempts, consumers, producers = wait_for( + "retry spans in the upload trace", + lambda: complete_retry_trace(args.tempo_url, trace_id), + args.timeout, + ) + assert any(span.get("name", "").startswith("s3.") for _, span in spans) + assert any( + span.get("name", "").startswith("postgresql.") for _, span in spans + ) + print( + json.dumps( + { + "status": "PASS", + "attachment_status": ready["status"], + "trace_id": trace_id, + "services": sorted(services), + "attempts": attempts, + "consumer_spans": len(consumers), + "producer_spans": len(producers), + "span_count": len(spans), + }, + ensure_ascii=False, + indent=2, + ) + ) + finally: + if minio_stopped: + compose("up", "-d", "--wait", "minio", check=False) + if worker_stopped: + try: + start_existing_container("worker") + except (AssertionError, subprocess.CalledProcessError): + compose("up", "-d", "worker", check=False) + cleanup(chat["id"], users) + + +if __name__ == "__main__": + main() + diff --git a/tests/openbao_lifecycle_grade4.sh b/tests/openbao_lifecycle_grade4.sh new file mode 100755 index 0000000..c3421a8 --- /dev/null +++ b/tests/openbao_lifecycle_grade4.sh @@ -0,0 +1,88 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +state_file="$project_root/.operator/openbao-init.json" +cd "$project_root" + +[ -s "$state_file" ] || { printf '%s\n' "OpenBao operator state is required" >&2; exit 1; } +root_token=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1], encoding="utf-8"))["root_token"])' "$state_file") +unseal_key=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1], encoding="utf-8"))["unseal_keys_b64"][0])' "$state_file") +sealed_by_test=false + +bao_root() { + docker compose exec -T -e BAO_TOKEN="$root_token" openbao bao "$@" +} + +recover() { + if [ "$sealed_by_test" = true ]; then + docker compose exec -T openbao bao operator unseal "$unseal_key" >/dev/null 2>&1 || true + docker compose up -d --no-deps --no-build --force-recreate api >/dev/null 2>&1 || true + fi +} +trap recover EXIT HUP INT TERM + +bao_root write auth/approle/role/grade4-lifecycle \ + token_policies=default,api token_ttl=10s token_max_ttl=24s \ + secret_id_ttl=5s secret_id_num_uses=1 >/dev/null +role_id=$(bao_root read -field=role_id auth/approle/role/grade4-lifecycle/role-id) +secret_id=$(bao_root write -f -field=secret_id auth/approle/role/grade4-lifecycle/secret-id) +token=$(docker compose exec -T openbao bao write -field=token auth/approle/login \ + role_id="$role_id" secret_id="$secret_id") + +if docker compose exec -T openbao bao write -field=token auth/approle/login \ + role_id="$role_id" secret_id="$secret_id" >/dev/null 2>&1; then + printf '%s\n' "One-use SecretID was accepted twice" >&2 + exit 1 +fi +printf '%s\n' "PASS: used SecretID is revoked" + +sleep 4 +docker compose exec -T -e BAO_TOKEN="$token" openbao bao token renew -increment=10s >/dev/null +sleep 7 +docker compose exec -T -e BAO_TOKEN="$token" openbao bao kv get secret/api >/dev/null +printf '%s\n' "PASS: renewable token works past its original TTL" + +sleep 14 +if docker compose exec -T -e BAO_TOKEN="$token" openbao bao kv get secret/api >/dev/null 2>&1; then + printf '%s\n' "Token exceeded its maximum TTL" >&2 + exit 1 +fi +printf '%s\n' "PASS: token expires at bounded maximum TTL" + +bao_root delete auth/approle/role/grade4-lifecycle >/dev/null + +curl --silent --show-error --fail --cacert secrets/pki/ca.crt \ + https://127.0.0.1:8443/health/live >/dev/null +bao_root operator seal >/dev/null +sealed_by_test=true +curl --silent --show-error --fail --cacert secrets/pki/ca.crt \ + https://127.0.0.1:8443/health/live >/dev/null +printf '%s\n' "PASS: running API keeps only already-loaded credentials while OpenBao is sealed" + +role_id_api=$(cat secrets/openbao/api_role_id.txt) +secret_id_api=$(cat secrets/openbao/api_secret_id.txt) +if docker compose exec -T openbao bao write -field=token auth/approle/login \ + role_id="$role_id_api" secret_id="$secret_id_api" >/dev/null 2>&1; then + printf '%s\n' "AppRole login succeeded while OpenBao was sealed" >&2 + exit 1 +fi +docker compose up -d --no-deps --no-build --force-recreate api >/dev/null +sleep 4 +if [ -n "$(docker compose ps --status running -q api)" ]; then + printf '%s\n' "Fresh API process remained running without OpenBao bootstrap" >&2 + exit 1 +fi +printf '%s\n' "PASS: fresh API fails closed while OpenBao is sealed" + +docker compose exec -T openbao bao operator unseal "$unseal_key" >/dev/null +sealed_by_test=false +docker compose up -d --no-deps --no-build --force-recreate api >/dev/null +attempts=0 +until curl --silent --show-error --fail --cacert secrets/pki/ca.crt \ + https://127.0.0.1:8443/health/live >/dev/null 2>&1; do + attempts=$((attempts + 1)) + [ "$attempts" -lt 40 ] || { printf '%s\n' "API did not recover after unseal" >&2; exit 1; } + sleep 1 +done +printf '%s\n' "PASS: operator unseal restores AppRole bootstrap without image rebuild" diff --git a/tests/openbao_policy.sh b/tests/openbao_policy.sh new file mode 100755 index 0000000..dd41cbe --- /dev/null +++ b/tests/openbao_policy.sh @@ -0,0 +1,35 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +role_id=$(cat secrets/openbao/api_role_id.txt) +secret_id=$(cat secrets/openbao/api_secret_id.txt) +token=$(docker compose exec -T openbao bao write -field=token auth/approle/login \ + role_id="$role_id" secret_id="$secret_id") + +bao_api() { + docker compose exec -T -e BAO_TOKEN="$token" openbao bao "$@" +} + +bao_api kv get secret/api >/dev/null +printf '%s\n' "PASS: API AppRole reads its own path" + +if bao_api kv get secret/worker >/dev/null 2>&1; then + printf '%s\n' "FAIL: API AppRole read worker path" >&2 + exit 1 +fi +printf '%s\n' "PASS: API AppRole cannot read worker path" + +if bao_api policy list >/dev/null 2>&1; then + printf '%s\n' "FAIL: API AppRole listed policies" >&2 + exit 1 +fi +printf '%s\n' "PASS: API AppRole cannot administer policies" + +if bao_api kv put secret/api probe=denied >/dev/null 2>&1; then + printf '%s\n' "FAIL: API AppRole wrote its read-only path" >&2 + exit 1 +fi +printf '%s\n' "PASS: API AppRole cannot write secrets" diff --git a/tests/rate_limit_grade3.py b/tests/rate_limit_grade3.py new file mode 100644 index 0000000..cb521b2 --- /dev/null +++ b/tests/rate_limit_grade3.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Verify that login throttling is shared by both API replicas.""" +import base64 + +from client import Client, arguments, check, run + + +def main(): + args = arguments("Grade 3 shared login rate-limit check") + client = Client(args.base_url, args.ca_file) + actor = client.user("ratelimit") + username = actor["registration"]["username"] + bad = base64.b64encode((username + ":definitely-wrong").encode()).decode() + headers = {"Authorization": "Basic " + bad} + + instances = set() + for _ in range(5): + result = client.call("POST", "/api/v1/auth/sessions", 401, headers=headers) + instances.add(result["headers"]["X-Instance-Id"]) + + blocked = client.call("POST", "/api/v1/auth/sessions", 429, headers=headers) + instances.add(blocked["headers"]["X-Instance-Id"]) + retry_after = blocked["headers"].get("Retry-After", "") + check(retry_after.isdigit() and int(retry_after) > 0, "invalid Retry-After") + check(blocked["json"]["error"]["code"] == "rate_limited", "wrong 429 error code") + check(len(instances) >= 2, "requests did not traverse both API replicas") + print("PASS: login limit is shared across replicas and returns 429 with Retry-After.") + + +if __name__ == "__main__": + run(main) diff --git a/tests/reconcile_integration.py b/tests/reconcile_integration.py new file mode 100644 index 0000000..184f459 --- /dev/null +++ b/tests/reconcile_integration.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Inject isolated DB/S3 inconsistencies and prove reconciler dry-run/apply/repeat.""" + +import json +import os +import subprocess +import time + + +USER_ID = "90000000-0000-4000-8000-000000000001" +CHAT_ID = "90000000-0000-4000-8000-000000000002" +MISSING_ID = "90000000-0000-4000-8000-000000000011" +PROTECTED_ID = "90000000-0000-4000-8000-000000000012" +FAILED_ID = "90000000-0000-4000-8000-000000000013" +MESSAGE_ID = "90000000-0000-4000-8000-000000000021" +PREFIX = "attachments/reconcile-integration" +ORPHAN_KEY = PREFIX + "/orphan" +FAILED_KEY = PREFIX + "/failed" + + +def run(command, *, input_text=None, capture=False): + result = subprocess.run( + command, + input=input_text, + text=True, + check=False, + capture_output=capture, + env=os.environ.copy(), + ) + if result.returncode != 0: + details = result.stderr.strip() if capture else "see command output" + raise RuntimeError("command failed: %s: %s" % (command[0], details)) + return result.stdout if capture else "" + + +def compose(*arguments, capture=False, input_text=None): + return run( + ["docker", "compose", *arguments], + input_text=input_text, + capture=capture, + ) + + +def database(sql): + compose( + "exec", "-T", "postgres", + "psql", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger", + input_text=sql, + ) + + +def object_command(script): + compose( + "run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap", + "-ec", script, + ) + + +def clean_objects(): + object_command( + 'root_user="$(cat /run/secrets/minio_root_user)"\n' + 'root_password="$(cat /run/secrets/minio_root_password)"\n' + 'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n' + 'mc rm --force "local/${S3_BUCKET}/' + ORPHAN_KEY + '" >/dev/null 2>&1 || true\n' + 'mc rm --force "local/${S3_BUCKET}/' + FAILED_KEY + '" >/dev/null 2>&1 || true\n' + ) + + +def clean_database(): + database(f""" +BEGIN; +DELETE FROM messages WHERE id = '{MESSAGE_ID}'; +DELETE FROM attachments WHERE id IN ('{MISSING_ID}', '{PROTECTED_ID}', '{FAILED_ID}'); +DELETE FROM chat_members WHERE chat_id = '{CHAT_ID}'; +DELETE FROM chats WHERE id = '{CHAT_ID}'; +DELETE FROM users WHERE id = '{USER_ID}'; +COMMIT; +""") + + +def inject_database(): + database(f""" +BEGIN; +INSERT INTO users (id, username, display_name, password_hash) +VALUES ('{USER_ID}', 'reconcile_fixture', 'Reconcile Fixture', 'not-used'); +INSERT INTO chats (id, title) VALUES ('{CHAT_ID}', 'Reconcile Integration'); +INSERT INTO chat_members (chat_id, user_id, position) VALUES ('{CHAT_ID}', '{USER_ID}', 0); +INSERT INTO attachments ( + id, chat_id, owner_id, object_key, filename, content_type, + size_bytes, sha256, width, height, status, error_code, created_at, updated_at +) VALUES + ('{MISSING_ID}', '{CHAT_ID}', '{USER_ID}', '{PREFIX}/missing', 'missing.png', 'image/png', + 7, decode(repeat('00', 32), 'hex'), 1, 1, 'ready', NULL, now() - interval '2 hours', now() - interval '2 hours'), + ('{PROTECTED_ID}', '{CHAT_ID}', '{USER_ID}', '{PREFIX}/protected-missing', 'protected.png', 'image/png', + 7, decode(repeat('00', 32), 'hex'), 1, 1, 'ready', NULL, now() - interval '2 hours', now() - interval '2 hours'), + ('{FAILED_ID}', '{CHAT_ID}', '{USER_ID}', '{FAILED_KEY}', 'failed.png', 'image/png', + 7, decode(repeat('00', 32), 'hex'), 1, 1, 'failed', 'fixture_failed', now() - interval '2 hours', now() - interval '2 hours'); +INSERT INTO messages (id, chat_id, sender_id, text) +VALUES ('{MESSAGE_ID}', '{CHAT_ID}', '{USER_ID}', 'protected attachment reference'); +INSERT INTO message_attachments (message_id, chat_id, attachment_id, position) +VALUES ('{MESSAGE_ID}', '{CHAT_ID}', '{PROTECTED_ID}', 0); +COMMIT; +""") + + +def inject_objects(): + object_command( + 'root_user="$(cat /run/secrets/minio_root_user)"\n' + 'root_password="$(cat /run/secrets/minio_root_password)"\n' + 'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n' + 'printf orphan | mc pipe "local/${S3_BUCKET}/' + ORPHAN_KEY + '" >/dev/null\n' + 'printf failed | mc pipe "local/${S3_BUCKET}/' + FAILED_KEY + '" >/dev/null\n' + ) + + +def reconcile(apply=False): + command = [ + "run", "--rm", "--entrypoint", "/app/reconciler", "api", + "--grace-period", "1s", + ] + if apply: + command.append("--apply") + output = compose(*command, capture=True) + return json.loads(output) + + +def kinds(result): + return {issue["kind"] for issue in result["issues"]} + + +def fixture_issues(result): + return [issue for issue in result["issues"] if issue["object_key"].startswith(PREFIX)] + + +def main(): + clean_objects() + clean_database() + try: + inject_database() + inject_objects() + time.sleep(2) + + dry_run = reconcile(False) + expected = { + "orphan_object", "missing_object", "referenced_missing_object", "failed_object", + } + if kinds({"issues": fixture_issues(dry_run)}) != expected: + raise RuntimeError("dry-run did not detect all injected inconsistencies") + if dry_run["deleted_objects"] or dry_run["failed_attachments"]: + raise RuntimeError("dry-run performed mutations") + + applied = reconcile(True) + applied_fixture = fixture_issues(applied) + applied_actions = {issue["kind"]: issue["action"] for issue in applied_fixture} + expected_actions = { + "orphan_object": "deleted", + "failed_object": "deleted", + "missing_object": "marked_failed", + "referenced_missing_object": "manual_repair_required", + } + if applied_actions != expected_actions: + raise RuntimeError("fixture apply actions differ: %s" % applied_actions) + + repeated = reconcile(True) + if repeated["deleted_objects"] or repeated["failed_attachments"]: + raise RuntimeError("repeated apply was not mutation-idempotent") + protected = [issue for issue in fixture_issues(repeated) if issue.get("protected")] + if len(protected) != 1 or protected[0]["action"] != "manual_repair_required": + raise RuntimeError("referenced missing attachment was not protected") + + print(json.dumps({ + "dry_run_issues": len(dry_run["issues"]), + "apply_fixture_deleted_objects": sum( + issue["action"] == "deleted" for issue in applied_fixture + ), + "apply_fixture_failed_attachments": sum( + issue["action"] == "marked_failed" for issue in applied_fixture + ), + "repeat_mutations": repeated["deleted_objects"] + repeated["failed_attachments"], + "protected_manual_issues": len(protected), + "scanned_attachments": applied["scanned_attachments"], + "scanned_objects": applied["scanned_objects"], + "duration_ms": applied["duration_ms"], + }, ensure_ascii=False)) + print("PASS: real PostgreSQL/MinIO reconciliation is dry-run safe, idempotent and reference-aware.") + finally: + clean_objects() + clean_database() + + +if __name__ == "__main__": + main() + diff --git a/tests/reconcile_scale.py b/tests/reconcile_scale.py new file mode 100644 index 0000000..cc2b46a --- /dev/null +++ b/tests/reconcile_scale.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Measure real PostgreSQL/MinIO reconciler traversal at two inventory sizes.""" + +import json +import subprocess +import time + + +PREFIX = "attachments/reconcile-scale" + + +def compose(*arguments, capture=False): + result = subprocess.run( + ["docker", "compose", *arguments], + check=False, + text=True, + capture_output=capture, + ) + if result.returncode != 0: + raise RuntimeError(result.stderr.strip() if capture else "docker compose command failed") + return result.stdout if capture else "" + + +def object_command(script): + compose("run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap", "-ec", script) + + +def clean(): + object_command( + 'root_user="$(cat /run/secrets/minio_root_user)"\n' + 'root_password="$(cat /run/secrets/minio_root_password)"\n' + 'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n' + 'mc rm --recursive --force "local/${S3_BUCKET}/' + PREFIX + '/" >/dev/null 2>&1 || true\n' + ) + + +def create(count): + object_command( + 'root_user="$(cat /run/secrets/minio_root_user)"\n' + 'root_password="$(cat /run/secrets/minio_root_password)"\n' + 'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n' + 'mkdir -p /tmp/reconcile-scale\n' + 'index=0\n' + 'while [ "$index" -lt ' + str(count) + ' ]; do\n' + ' printf x > "/tmp/reconcile-scale/object-${index}"\n' + ' index=$((index + 1))\n' + 'done\n' + 'mc cp --recursive /tmp/reconcile-scale/ "local/${S3_BUCKET}/' + PREFIX + '/" >/dev/null\n' + ) + + +def dry_run(): + started = time.monotonic() + output = compose( + "run", "--rm", "--entrypoint", "/app/reconciler", "api", + "--grace-period", "1s", + capture=True, + ) + elapsed = time.monotonic() - started + result = json.loads(output) + return { + "scanned_attachments": result["scanned_attachments"], + "scanned_objects": result["scanned_objects"], + "issues": len(result["issues"]), + "reconciler_duration_ms": result["duration_ms"], + "container_start_and_run_ms": round(elapsed * 1000), + } + + +def main(): + measurements = [] + clean() + try: + for count in (100, 1000): + clean() + create(count) + time.sleep(2) + measurement = dry_run() + measurement["injected_orphan_objects"] = count + if measurement["issues"] < count: + raise RuntimeError("reconciler did not observe all scale fixtures") + measurements.append(measurement) + print(json.dumps({"measurements": measurements}, ensure_ascii=False)) + print("PASS: reconciler traversal cost measured on real PostgreSQL/MinIO inventories.") + finally: + clean() + + +if __name__ == "__main__": + main() + diff --git a/tests/security_grade3.sh b/tests/security_grade3.sh new file mode 100755 index 0000000..ac84330 --- /dev/null +++ b/tests/security_grade3.sh @@ -0,0 +1,65 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +curl_from_test() { + docker compose --profile tests run --rm --no-deps --entrypoint curl security-test "$@" +} + +expect_tls_rejection() { + name=$1 + shift + if curl_from_test --silent --show-error --fail --cacert /run/secrets/ca.crt \ + "$@" https://api:8444/health/live >/dev/null 2>&1; then + printf '%s\n' "FAIL: $name was accepted" >&2 + exit 1 + fi + printf '%s\n' "PASS: $name rejected" +} + +expect_tls_rejection "missing client certificate" +expect_tls_rejection "client certificate from foreign CA" \ + --cert /run/secrets/foreign-client.crt --key /run/secrets/foreign-client.key +expect_tls_rejection "trusted certificate with forbidden identity" \ + --cert /run/secrets/wrong-client.crt --key /run/secrets/wrong-client.key + +curl_from_test --silent --show-error --fail --cacert /run/secrets/ca.crt \ + --cert /run/secrets/lb-client.crt --key /run/secrets/lb-client.key \ + https://api:8444/health/live >/dev/null +printf '%s\n' "PASS: allowed LB identity accepted" + +# `docker compose port` in Compose v5 reports `invalid IP:0` even for an +# unbound EXPOSE port, so verify the effective runtime bindings directly. +for container_id in $(docker compose ps -q api); do + bindings=$(docker inspect "$container_id" --format '{{json .NetworkSettings.Ports}}') + case "$bindings" in + *'"HostPort"'*) + printf '%s\n' "FAIL: API port is published and bypasses ingress" >&2 + exit 1 + ;; + esac +done +printf '%s\n' "PASS: API replicas have no published bypass port" + +prometheus_url="https://127.0.0.1:${PROMETHEUS_PORT:-19090}/-/ready" +if curl --silent --show-error --fail --cacert secrets/pki/ca.crt \ + "$prometheus_url" >/dev/null 2>&1; then + printf '%s\n' "FAIL: telemetry backend accepted a client without identity" >&2 + exit 1 +fi +printf '%s\n' "PASS: telemetry backend rejects a missing client identity" + +if curl --silent --show-error --fail --cacert secrets/pki/ca.crt \ + --cert secrets/pki/lb-client.crt --key secrets/pki/lb-client.key \ + "$prometheus_url" >/dev/null 2>&1; then + printf '%s\n' "FAIL: telemetry backend accepted the LB identity" >&2 + exit 1 +fi +printf '%s\n' "PASS: telemetry backend rejects a trusted but unauthorized identity" + +curl --silent --show-error --fail --cacert secrets/pki/ca.crt \ + --cert secrets/pki/grafana-client.crt --key secrets/pki/grafana-client.key \ + "$prometheus_url" >/dev/null +printf '%s\n' "PASS: telemetry backend accepts the scoped Grafana identity" diff --git a/tests/security_grade4.sh b/tests/security_grade4.sh new file mode 100755 index 0000000..3919f72 --- /dev/null +++ b/tests/security_grade4.sh @@ -0,0 +1,85 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +./tests/security_grade3.sh + +run_test_shell() { + docker compose --profile tests run --rm --no-deps --entrypoint sh security-test -ec "$1" +} + +expect_broker_denied() { + name=$1 + cert_args=$2 + if run_test_shell "printf 'AMQP\\000\\000\\011\\001' | timeout 5 openssl s_client -quiet -verify_return_error -CAfile /run/secrets/ca.crt -servername dependency-gateway $cert_args -connect dependency-gateway:5671 2>/dev/null | grep -a -q AMQPLAIN"; then + printf '%s\n' "FAIL: broker accepted $name" >&2 + exit 1 + fi + printf '%s\n' "PASS: broker rejected $name" +} + +expect_broker_allowed() { + name=$1 + cert=$2 + key=$3 + run_test_shell "printf 'AMQP\\000\\000\\011\\001' | timeout 5 openssl s_client -quiet -verify_return_error -CAfile /run/secrets/ca.crt -servername dependency-gateway -cert $cert -key $key -connect dependency-gateway:5671 2>/dev/null | grep -a -q AMQPLAIN" + printf '%s\n' "PASS: broker accepted scoped $name identity" +} + +expect_broker_denied "missing client certificate" "" +expect_broker_denied "same-CA intruder identity" "-cert /run/secrets/wrong-client.crt -key /run/secrets/wrong-client.key" +expect_broker_denied "API identity without a broker edge" "-cert /run/secrets/api-client.crt -key /run/secrets/api-client.key" +expect_broker_allowed worker /run/secrets/worker-client.crt /run/secrets/worker-client.key +expect_broker_allowed dispatcher /run/secrets/dispatcher-client.crt /run/secrets/dispatcher-client.key + +otel_status() { + cert_args=$1 + run_test_shell "curl --silent --show-error --output /dev/null --write-out '%{http_code}' --cacert /run/secrets/ca.crt $cert_args -H 'Content-Type: application/x-protobuf' --data-binary '' https://telemetry-gateway:4318/v1/traces" +} + +if status=$(otel_status "" 2>/dev/null) && [ "$status" = 200 ]; then + printf '%s\n' "FAIL: Collector accepted a missing client certificate" >&2 + exit 1 +fi +printf '%s\n' "PASS: Collector rejected a missing client certificate" + +status=$(otel_status "--cert /run/secrets/wrong-client.crt --key /run/secrets/wrong-client.key") +if [ "$status" != 403 ]; then + printf '%s\n' "FAIL: Collector wrong same-CA identity returned HTTP $status, expected 403" >&2 + exit 1 +fi +printf '%s\n' "PASS: Collector rejected a same-CA intruder identity" + +for identity in api worker dispatcher; do + status=$(otel_status "--cert /run/secrets/$identity-client.crt --key /run/secrets/$identity-client.key") + if [ "$status" != 200 ]; then + printf '%s\n' "FAIL: Collector rejected $identity with HTTP $status" >&2 + exit 1 + fi + printf '%s\n' "PASS: Collector accepted scoped $identity identity" +done + +for service in api worker dispatcher; do + for container_id in $(docker compose ps -q "$service"); do + readonly=$(docker inspect -f '{{.HostConfig.ReadonlyRootfs}}' "$container_id") + no_new_privileges=$(docker inspect -f '{{json .HostConfig.SecurityOpt}}' "$container_id") + cap_drop=$(docker inspect -f '{{json .HostConfig.CapDrop}}' "$container_id") + [ "$readonly" = true ] || { printf '%s\n' "FAIL: $service root filesystem is writable" >&2; exit 1; } + printf '%s' "$no_new_privileges" | grep -q 'no-new-privileges' || { printf '%s\n' "FAIL: $service lacks no-new-privileges" >&2; exit 1; } + printf '%s' "$cap_drop" | grep -q 'ALL' || { printf '%s\n' "FAIL: $service does not drop all capabilities" >&2; exit 1; } + done +done +printf '%s\n' "PASS: application containers are read-only, no-new-privileges, cap-drop=ALL" + +worker_id=$(docker compose ps -q worker) +worker_memory=$(docker inspect -f '{{.HostConfig.Memory}}' "$worker_id") +worker_nano_cpus=$(docker inspect -f '{{.HostConfig.NanoCpus}}' "$worker_id") +worker_environment=$(docker inspect -f '{{json .Config.Env}}' "$worker_id") +[ "$worker_memory" -eq 536870912 ] || { printf '%s\n' "FAIL: worker memory limit is $worker_memory" >&2; exit 1; } +[ "$worker_nano_cpus" -eq 1000000000 ] || { printf '%s\n' "FAIL: worker CPU limit is $worker_nano_cpus" >&2; exit 1; } +printf '%s' "$worker_environment" | grep -q 'WORKER_CONCURRENCY=1' || { printf '%s\n' "FAIL: worker concurrency is not 1" >&2; exit 1; } +printf '%s' "$worker_environment" | grep -q 'JOB_TIMEOUT_SECONDS=60' || { printf '%s\n' "FAIL: worker timeout is not 60s" >&2; exit 1; } +printf '%s' "$worker_environment" | grep -q 'GOMEMLIMIT=448MiB' || { printf '%s\n' "FAIL: worker Go memory limit is not 448MiB" >&2; exit 1; } +printf '%s\n' "PASS: worker has 512 MiB RAM, 1 CPU, concurrency=1, GOMEMLIMIT=448MiB and 60s job timeout" diff --git a/tests/slo_burn_rate.py b/tests/slo_burn_rate.py new file mode 100644 index 0000000..02d38c9 --- /dev/null +++ b/tests/slo_burn_rate.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +"""Grade-5 SLO experiment: short burst, sustained failure and ready latency.""" + +import concurrent.futures +import json +import subprocess +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid + +from attachment_memory import cleanup +from client import Client, Failure +from observability_alerts import db_error_span +from observability_grade4 import trace_id_for_request + + +API_ALERTS = {"MessengerAPIBurnRateFast", "MessengerAPIBurnRateSlow"} +READY_ALERTS = { + "MessengerAttachmentReadyBurnRateFast", + "MessengerAttachmentReadyBurnRateSlow", +} + + +def compose(*args, check=True): + return subprocess.run( + ["docker", "compose", *args], + check=check, + text=True, + capture_output=True, + ) + + +def start_existing_container(service): + container_id = compose("ps", "-aq", service).stdout.strip() + if not container_id: + raise AssertionError(f"missing container for {service}") + subprocess.run( + ["docker", "start", container_id], + check=True, + text=True, + capture_output=True, + ) + + +def json_get(base_url, path, params=None, timeout=10): + query = "?" + urllib.parse.urlencode(params) if params else "" + with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response: + return json.load(response) + + +def wait_for(description, action, timeout, interval=1): + deadline = time.monotonic() + timeout + last_error = None + while time.monotonic() < deadline: + try: + value = action() + if value: + return value + except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error: + last_error = error + time.sleep(interval) + raise AssertionError(f"timeout waiting for {description}: {last_error}") + + +def active_alerts(prometheus_url, names): + payload = json_get(prometheus_url, "/api/v1/alerts") + assert payload["status"] == "success", payload + return { + item["labels"]["alertname"]: item["state"] + for item in payload["data"]["alerts"] + if item.get("labels", {}).get("alertname") in names + } + + +def prometheus_scalar(base_url, expression): + payload = json_get(base_url, "/api/v1/query", {"query": expression}) + assert payload["status"] == "success", payload + results = payload["data"]["result"] + return float(results[0]["value"][1]) if results else 0.0 + + +def wait_firing(prometheus_url, names, started, timeout): + detected = {} + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + states = active_alerts(prometheus_url, names) + now = time.monotonic() + for name in names: + if states.get(name) == "firing" and name not in detected: + detected[name] = round(now - started, 3) + if set(detected) == set(names): + return detected + time.sleep(1) + raise AssertionError(f"alerts did not fire: {detected}, current={states}") + + +def observe_no_alert(prometheus_url, names, duration): + observed = [] + max_short = 0.0 + max_long = 0.0 + deadline = time.monotonic() + duration + while time.monotonic() < deadline: + states = active_alerts(prometheus_url, names) + if states: + observed.append(states) + max_short = max( + max_short, + prometheus_scalar(prometheus_url, "messenger:sli_api_error_ratio_30s"), + ) + max_long = max( + max_long, + prometheus_scalar(prometheus_url, "messenger:sli_api_error_ratio_5m"), + ) + time.sleep(1) + assert not observed, f"false positive burn-rate alerts: {observed}" + return {"pending_or_firing": 0, "max_30s_ratio": max_short, "max_5m_ratio": max_long} + + +def parallel_successes(base_url, actor, count, concurrency=16): + def request(_): + local = Client(base_url, timeout=10) + return local.call("GET", "/api/v1/chats", actor=actor)["status"] + + with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool: + statuses = list(pool.map(request, range(count))) + assert set(statuses) == {200}, set(statuses) + + +def parallel_failures(base_url, actor, count): + request_ids = [str(uuid.uuid4()) for _ in range(count)] + + def request(request_id): + local = Client(base_url, timeout=15) + local.call( + "GET", + "/api/v1/chats", + 503, + actor=actor, + headers={"X-Request-Id": request_id}, + ) + return request_id + + with concurrent.futures.ThreadPoolExecutor(max_workers=count) as pool: + return list(pool.map(request, request_ids)) + + +def main(): + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://localhost:8080") + parser.add_argument("--prometheus-url", default="http://localhost:9090") + parser.add_argument("--loki-url", default="http://localhost:3100") + parser.add_argument("--tempo-url", default="http://localhost:3200") + parser.add_argument("--grafana-url", default="http://localhost:3000") + parser.add_argument("--timeout", type=int, default=150) + args = parser.parse_args() + + dashboard = json_get( + args.grafana_url, "/api/dashboards/uid/mtusi-lab7-grade5" + ) + assert dashboard["dashboard"]["title"] == "MTUSI Lab 6 - Grade 5 SLO" + + client = Client(args.base_url, timeout=20) + alice, bob, eve, chat = client.bootstrap() + users = [alice["id"], bob["id"], eve["id"]] + postgres_paused = False + worker_stopped = False + api_result = {} + ready_result = {} + try: + parallel_successes(args.base_url, alice, 400) + time.sleep(6) + + compose("pause", "postgres") + postgres_paused = True + brief_request_ids = parallel_failures(args.base_url, alice, 4) + compose("unpause", "postgres") + postgres_paused = False + parallel_successes(args.base_url, alice, 100) + false_positive = observe_no_alert(args.prometheus_url, API_ALERTS, 25) + + compose("pause", "postgres") + postgres_paused = True + incident_started = time.monotonic() + stop_errors = threading.Event() + failure_ids = [] + failure_lock = threading.Lock() + + def error_stream(worker_id): + local = Client(args.base_url, timeout=15) + completed = 0 + while not stop_errors.is_set(): + request_id = str(uuid.uuid4()) + try: + result = local.call( + "GET", + "/api/v1/chats", + [200, 503], + actor=alice, + headers={"X-Request-Id": request_id}, + ) + if result["status"] == 503: + with failure_lock: + failure_ids.append(request_id) + completed += 1 + except Failure: + if not stop_errors.is_set(): + raise + return completed + + pool = concurrent.futures.ThreadPoolExecutor(max_workers=8) + futures = [pool.submit(error_stream, index) for index in range(8)] + try: + detection = wait_firing( + args.prometheus_url, API_ALERTS, incident_started, args.timeout + ) + finally: + if postgres_paused: + compose("unpause", "postgres", check=False) + postgres_paused = False + stop_errors.set() + failure_count = sum(future.result(timeout=30) for future in futures) + pool.shutdown(wait=True) + assert failure_ids, "sustained incident produced no 503" + + recovery_started = time.monotonic() + parallel_successes(args.base_url, alice, 900) + wait_for( + "API burn-rate alerts resolved", + lambda: not active_alerts(args.prometheus_url, API_ALERTS), + args.timeout, + ) + trace_id = wait_for( + "sustained DB incident log", + lambda: trace_id_for_request(args.loki_url, failure_ids[0]), + args.timeout, + ) + error_span = wait_for( + "sustained DB incident trace", + lambda: db_error_span(args.tempo_url, trace_id), + args.timeout, + ) + api_result = { + "brief_spike_failures": len(brief_request_ids), + "false_positive": false_positive, + "sustained_failures": failure_count, + "detection_seconds": detection, + "recovery_seconds": round(time.monotonic() - recovery_started, 3), + "trace_id": trace_id, + "root_cause_span": error_span, + } + print( + json.dumps({"phase": "api_slo", **api_result}, ensure_ascii=False), + flush=True, + ) + + wait_for( + "clean attachment alert state before ready experiment", + lambda: not active_alerts(args.prometheus_url, READY_ALERTS), + args.timeout, + ) + + content = open("tests/fixtures/sample.png", "rb").read() + + def upload(index, prefix): + local = Client(args.base_url, timeout=20) + return local.call( + "POST", + f'/api/v1/chats/{chat["id"]}/attachments?filename={prefix}-{index}.png', + 202, + actor=alice, + raw=content, + headers={"Content-Type": "image/png"}, + schema="Attachment", + )["json"] + + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as uploads: + baseline_attachments = list( + uploads.map(lambda index: upload(index, "slo-fast"), range(20)) + ) + for attachment in baseline_attachments: + client.wait_ready(alice, attachment, args.timeout) + + compose("stop", "worker") + worker_stopped = True + with concurrent.futures.ThreadPoolExecutor(max_workers=5) as uploads: + slow_attachments = list( + uploads.map(lambda index: upload(index, "slo-slow"), range(5)) + ) + time.sleep(12) + start_existing_container("worker") + worker_stopped = False + for attachment in slow_attachments: + client.wait_ready(alice, attachment, args.timeout) + ready_incident_started = time.monotonic() + ready_detection = wait_firing( + args.prometheus_url, READY_ALERTS, ready_incident_started, args.timeout + ) + + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as uploads: + recovery_attachments = list( + uploads.map(lambda index: upload(index, "slo-recovery"), range(100)) + ) + for attachment in recovery_attachments: + client.wait_ready(alice, attachment, args.timeout) + ready_recovery_started = time.monotonic() + wait_for( + "attachment burn-rate alerts resolved", + lambda: not active_alerts(args.prometheus_url, READY_ALERTS), + args.timeout, + ) + ready_result = { + "baseline_fast": len(baseline_attachments), + "slow_over_10s": len(slow_attachments), + "recovery_fast": len(recovery_attachments), + "detection_seconds": ready_detection, + "recovery_seconds": round( + time.monotonic() - ready_recovery_started, 3 + ), + "final_5m_slow_ratio": prometheus_scalar( + args.prometheus_url, + "messenger:sli_attachment_slow_ratio_5m", + ), + } + + print( + json.dumps( + { + "status": "PASS", + "api_slo": api_result, + "attachment_ready_slo": ready_result, + "dashboard_uid": "mtusi-lab7-grade5", + }, + ensure_ascii=False, + indent=2, + ) + ) + finally: + if postgres_paused: + compose("unpause", "postgres", check=False) + if worker_stopped: + try: + start_existing_container("worker") + except (AssertionError, subprocess.CalledProcessError): + compose("up", "-d", "worker", check=False) + wait_for( + "PostgreSQL before cleanup", + lambda: compose( + "exec", + "-T", + "postgres", + "pg_isready", + "-U", + "messenger", + check=False, + ).returncode + == 0, + 30, + ) + cleanup(chat["id"], users) + + +if __name__ == "__main__": + main() + diff --git a/tests/state_pruning_grade4.sh b/tests/state_pruning_grade4.sh new file mode 100755 index 0000000..860abdb --- /dev/null +++ b/tests/state_pruning_grade4.sh @@ -0,0 +1,71 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +admin_psql() { + docker compose exec -T postgres sh -ec ' + export PGPASSWORD=$(cat /run/secrets/postgres_admin_password) + exec psql -v ON_ERROR_STOP=1 -U lab7_admin -d messenger -At + ' +} + +admin_psql <<'SQL' +INSERT INTO login_rate_limits (identifier_hash, window_started_at, attempts) +VALUES (decode(repeat('42', 32), 'hex'), CURRENT_TIMESTAMP - INTERVAL '1 day', 1) +ON CONFLICT (identifier_hash) DO UPDATE +SET window_started_at = EXCLUDED.window_started_at, attempts = EXCLUDED.attempts; + +INSERT INTO login_rate_limits (identifier_hash, window_started_at, attempts) +VALUES (decode(repeat('43', 32), 'hex'), CURRENT_TIMESTAMP, 4) +ON CONFLICT (identifier_hash) DO UPDATE +SET window_started_at = EXCLUDED.window_started_at, attempts = EXCLUDED.attempts; +SQL + +docker compose up -d --no-deps --no-build --force-recreate api ingress >/dev/null +attempts=0 +until curl --silent --show-error --fail --cacert secrets/pki/ca.crt \ + https://127.0.0.1:${HTTPS_PORT:-8443}/health/live >/dev/null 2>&1; do + attempts=$((attempts + 1)) + [ "$attempts" -lt 40 ] || { + printf '%s\n' "API did not become ready for pruning test" >&2 + exit 1 + } + sleep 1 +done + +status=$(curl --silent --show-error --cacert secrets/pki/ca.crt \ + --user pruning-probe:wrong-password --output /dev/null --write-out '%{http_code}' \ + --request POST https://127.0.0.1:${HTTPS_PORT:-8443}/api/v1/auth/sessions) +[ "$status" = 401 ] || { + printf '%s\n' "Pruning probe returned HTTP $status, expected 401" >&2 + exit 1 +} + +remaining=$(admin_psql <<'SQL' +SELECT count(*) FROM login_rate_limits +WHERE identifier_hash = decode(repeat('42', 32), 'hex'); +SQL +) +[ "$remaining" = 0 ] || { + printf '%s\n' "Expired login limiter row was not pruned" >&2 + exit 1 +} + +active_attempts=$(admin_psql <<'SQL' +SELECT attempts FROM login_rate_limits +WHERE identifier_hash = decode(repeat('43', 32), 'hex'); +SQL +) +[ "$active_attempts" = 4 ] || { + printf '%s\n' "Active login limiter row was pruned or changed" >&2 + exit 1 +} + +admin_psql <<'SQL' +DELETE FROM login_rate_limits +WHERE identifier_hash = decode(repeat('43', 32), 'hex'); +SQL + +printf '%s\n' "PASS: bounded pruning removes expired state and preserves active limiter windows" diff --git a/tests/storage_outage.py b/tests/storage_outage.py new file mode 100644 index 0000000..dbe02c6 --- /dev/null +++ b/tests/storage_outage.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Verify contract responses and original durability during a real MinIO outage.""" + +import json +import os +import subprocess +import time + +from attachment_memory import cleanup +from client import Client, Failure, check, run + + +def compose(*arguments, **kwargs): + return subprocess.run(["docker", "compose", *arguments], check=True, **kwargs) + + +def wait_for_status(client, path, expected, timeout=20): + deadline = time.monotonic() + timeout + last_error = None + while time.monotonic() < deadline: + try: + return client.call("GET", path, expected=expected) + except Failure as error: + last_error = error + time.sleep(0.25) + raise Failure("%s did not reach %d: %s" % (path, expected, last_error)) + + +def restore_storage(client): + compose("up", "-d", "--wait", "minio") + compose("run", "--rm", "minio-bootstrap") + wait_for_status(client, "/health/ready", 200, timeout=30) + + +def main(): + client = Client(os.environ.get("BASE_URL"), None, timeout=15) + alice, bob, eve, chat = client.bootstrap() + users = [alice["id"], bob["id"], eve["id"]] + attachment, original = client.attachment(alice, chat) + storage_stopped = False + + try: + compose("stop", "minio") + storage_stopped = True + readiness = wait_for_status(client, "/health/ready", 503) + check(readiness["elapsed"] < 5, "readiness exceeded its bounded timeout") + + started = time.monotonic() + failure = client.call( + "POST", + "/api/v1/chats/%s/attachments?filename=outage.png" % chat["id"], + 503, + actor=alice, + raw=original, + headers={"Content-Type": "image/png"}, + ) + elapsed = time.monotonic() - started + check(failure["json"]["error"]["code"] == "unavailable", "wrong S3 outage error code") + check(elapsed < 15, "upload outage response exceeded API/client timeout") + + restore_storage(client) + storage_stopped = False + attachment = client.wait_ready(alice, attachment) + downloaded = client.call( + "GET", "/api/v1/attachments/%s/content" % attachment["id"], + 200, actor=alice, + )["bytes"] + check(downloaded == original, "existing original changed across MinIO outage") + print(json.dumps({ + "readiness_503_seconds": round(readiness["elapsed"], 3), + "upload_503_seconds": round(elapsed, 3), + "original_bytes_verified": len(original), + }, sort_keys=True)) + print("PASS: MinIO outage returns bounded JSON 503 and preserves existing originals.") + finally: + if storage_stopped: + restore_storage(client) + cleanup(chat["id"], users) + + +if __name__ == "__main__": + run(main) + diff --git a/tests/telemetry_backend_outage.py b/tests/telemetry_backend_outage.py new file mode 100644 index 0000000..f8382e3 --- /dev/null +++ b/tests/telemetry_backend_outage.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Prove bounded Collector degradation while Loki and Tempo are unavailable.""" + +import concurrent.futures +import json +import re +import subprocess +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid + +from attachment_memory import cleanup +from client import Client + + +def compose(*args, check=True): + return subprocess.run( + ["docker", "compose", *args], + check=check, + text=True, + capture_output=True, + ) + + +def json_get(base_url, path, params=None, timeout=10): + query = "?" + urllib.parse.urlencode(params) if params else "" + with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response: + return json.load(response) + + +def wait_for(description, action, timeout, interval=2): + deadline = time.monotonic() + timeout + last_error = None + while time.monotonic() < deadline: + try: + value = action() + if value: + return value + except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error: + last_error = error + time.sleep(interval) + raise AssertionError(f"timeout waiting for {description}: {last_error}") + + +def prometheus_scalar(base_url, expression): + payload = json_get(base_url, "/api/v1/query", {"query": expression}) + assert payload["status"] == "success", payload + results = payload["data"]["result"] + return float(results[0]["value"][1]) if results else 0.0 + + +def memory_bytes(value): + match = re.match(r"([0-9.]+)([KMG]iB)", value.strip()) + if not match: + raise ValueError(value) + factors = {"KiB": 1024, "MiB": 1024**2, "GiB": 1024**3} + return int(float(match.group(1)) * factors[match.group(2)]) + + +def sample_collector_memory(stop_event, samples): + container_id = compose("ps", "-q", "otel-collector").stdout.strip() + while not stop_event.is_set(): + result = subprocess.run( + [ + "docker", + "stats", + "--no-stream", + "--format", + "{{.MemUsage}}", + container_id, + ], + check=False, + text=True, + capture_output=True, + ) + if result.returncode == 0 and result.stdout.strip(): + samples.append(memory_bytes(result.stdout.split("/", 1)[0])) + stop_event.wait(0.5) + + +def trace_id_for_request(loki_url, request_id): + payload = json_get( + loki_url, + "/loki/api/v1/query_range", + { + "query": f'{{service_name="messenger-api"}} | request_id="{request_id}"', + "start": str(time.time_ns() - 10 * 60 * 1_000_000_000), + "end": str(time.time_ns()), + "direction": "backward", + "limit": "20", + }, + ) + for result in payload["data"]["result"]: + trace_id = result.get("stream", {}).get("trace_id") + if trace_id and len(trace_id) == 32: + return trace_id + return None + + +def main(): + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://localhost:8080") + parser.add_argument("--prometheus-url", default="http://localhost:9090") + parser.add_argument("--loki-url", default="http://localhost:3100") + parser.add_argument("--tempo-url", default="http://localhost:3200") + parser.add_argument("--timeout", type=int, default=120) + args = parser.parse_args() + + client = Client(args.base_url, timeout=20) + alice, bob, eve, chat = client.bootstrap() + users = [alice["id"], bob["id"], eve["id"]] + backends_stopped = False + stop_event = threading.Event() + memory_samples = [] + sampler = None + try: + failed_before = prometheus_scalar( + args.prometheus_url, + "sum(otelcol_exporter_send_failed_spans)", + ) + prometheus_scalar( + args.prometheus_url, + "sum(otelcol_exporter_send_failed_log_records)", + ) + accepted_before = prometheus_scalar( + args.prometheus_url, + "sum(otelcol_receiver_accepted_spans) + sum(otelcol_receiver_accepted_log_records)", + ) + compose("stop", "loki", "tempo") + backends_stopped = True + sampler = threading.Thread( + target=sample_collector_memory, + args=(stop_event, memory_samples), + daemon=True, + ) + sampler.start() + + def request(index): + local = Client(args.base_url, timeout=10) + return local.call("GET", "/api/v1/chats", actor=alice)["status"] + + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: + statuses = list(pool.map(request, range(400))) + assert set(statuses) == {200}, set(statuses) + + content = open("tests/fixtures/sample.png", "rb").read() + upload = client.call( + "POST", + f'/api/v1/chats/{chat["id"]}/attachments?filename=telemetry-outage.png', + 202, + actor=alice, + raw=content, + headers={"Content-Type": "image/png"}, + schema="Attachment", + ) + ready = client.wait_ready(alice, upload["json"], args.timeout) + + wait_for( + "expired Collector retry and counted telemetry loss", + lambda: ( + prometheus_scalar( + args.prometheus_url, + "sum(otelcol_exporter_send_failed_spans)", + ) + + prometheus_scalar( + args.prometheus_url, + "sum(otelcol_exporter_send_failed_log_records)", + ) + ) + > failed_before, + 75, + ) + failed_after = prometheus_scalar( + args.prometheus_url, + "sum(otelcol_exporter_send_failed_spans)", + ) + prometheus_scalar( + args.prometheus_url, + "sum(otelcol_exporter_send_failed_log_records)", + ) + accepted_after = prometheus_scalar( + args.prometheus_url, + "sum(otelcol_receiver_accepted_spans) + sum(otelcol_receiver_accepted_log_records)", + ) + queue_size = prometheus_scalar( + args.prometheus_url, "max(otelcol_exporter_queue_size)" + ) + queue_capacity = prometheus_scalar( + args.prometheus_url, "max(otelcol_exporter_queue_capacity)" + ) + assert queue_capacity == 256, queue_capacity + assert queue_size <= queue_capacity, (queue_size, queue_capacity) + assert accepted_after > accepted_before, (accepted_before, accepted_after) + assert ready["status"] == "ready" + + compose("up", "-d", "--wait", "loki", "tempo") + backends_stopped = False + recovery_request_id = str(uuid.uuid4()) + client.call( + "GET", + "/api/v1/chats", + actor=alice, + headers={"X-Request-Id": recovery_request_id}, + ) + recovery_trace_id = wait_for( + "logs after telemetry backend recovery", + lambda: trace_id_for_request(args.loki_url, recovery_request_id), + args.timeout, + ) + wait_for( + "trace after telemetry backend recovery", + lambda: json_get(args.tempo_url, f"/api/traces/{recovery_trace_id}").get( + "batches" + ), + args.timeout, + ) + stop_event.set() + sampler.join(timeout=10) + assert memory_samples, "Collector memory was not sampled" + peak_memory = max(memory_samples) + assert peak_memory < 256 * 1024**2, peak_memory + + print( + json.dumps( + { + "status": "PASS", + "business_requests": len(statuses), + "attachment_status": ready["status"], + "accepted_signal_delta": int(accepted_after - accepted_before), + "dropped_signal_delta": int(failed_after - failed_before), + "collector_queue_size": queue_size, + "collector_queue_capacity": queue_capacity, + "collector_peak_memory_bytes": peak_memory, + "collector_container_limit_bytes": 256 * 1024**2, + "recovery_trace_id": recovery_trace_id, + }, + ensure_ascii=False, + indent=2, + ) + ) + finally: + stop_event.set() + if sampler: + sampler.join(timeout=10) + if backends_stopped: + compose("up", "-d", "--wait", "loki", "tempo", check=False) + cleanup(chat["id"], users) + + +if __name__ == "__main__": + main() + diff --git a/tests/telemetry_leak_grade4.sh b/tests/telemetry_leak_grade4.sh new file mode 100755 index 0000000..8a6669d --- /dev/null +++ b/tests/telemetry_leak_grade4.sh @@ -0,0 +1,56 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +temp_file=$(mktemp "${TMPDIR:-/tmp}/mtusi-lab7-telemetry.XXXXXX") +case "$temp_file" in + "${TMPDIR:-/tmp}"/mtusi-lab7-telemetry.*) ;; + *) printf '%s\n' "Unexpected telemetry temporary file" >&2; exit 1 ;; +esac +trap 'rm -f "$temp_file"' EXIT HUP INT TERM + +sentinel_user="leak_probe_user" +sentinel_password="Telemetry-must-not-contain-this-7d91" +credentials=$(printf '%s' "$sentinel_user:$sentinel_password" | base64 | tr -d '\n') +status=$(curl --silent --show-error --output /dev/null --write-out '%{http_code}' \ + --cacert secrets/pki/ca.crt -H "Authorization: Basic $credentials" \ + -X POST https://127.0.0.1:8443/api/v1/auth/sessions) +[ "$status" = 401 ] || { printf '%s\n' "Login probe returned HTTP $status" >&2; exit 1; } + +sleep 6 +end_ns=$(date +%s%N) +start_ns=$((end_ns - 900000000000)) +curl --silent --show-error --fail --get \ + --cacert secrets/pki/ca.crt \ + --cert secrets/pki/grafana-client.crt --key secrets/pki/grafana-client.key \ + --data-urlencode 'query={service_name=~"messenger-.+"}' \ + --data-urlencode "start=$start_ns" --data-urlencode "end=$end_ns" \ + --data-urlencode 'limit=5000' \ + https://127.0.0.1:13100/loki/api/v1/query_range > "$temp_file" + +grep -q '"status":"success"' "$temp_file" || { + printf '%s\n' "Loki query did not succeed" >&2 + exit 1 +} +if grep -Fq "$sentinel_password" "$temp_file" || grep -Fq "$credentials" "$temp_file"; then + printf '%s\n' "Telemetry contains the login credential probe" >&2 + exit 1 +fi +if grep -Eiq 'authorization|bearer[[:space:]]|basic[[:space:]]|password_hash|client_token|secret_id' "$temp_file"; then + printf '%s\n' "Telemetry contains a forbidden credential field" >&2 + exit 1 +fi + +for secret_file in secrets/*.txt secrets/openbao/*.txt; do + [ -f "$secret_file" ] || continue + secret_value=$(cat "$secret_file") + [ -n "$secret_value" ] || continue + if grep -Fq "$secret_value" "$temp_file"; then + printf '%s\n' "Telemetry contains a value from an ignored secret file" >&2 + exit 1 + fi +done + +printf '%s\n' "PASS: Loki has structured events but no tested credentials, secret values or request bodies"