From 2f2047909ff4f14d94d574e75ee724424bc15fa1 Mon Sep 17 00:00:00 2001 From: Vladislav Gavrilenko <178+sxdees@noreply.gitea.privcloud.tech> Date: Wed, 2 Dec 2026 23:08:27 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=A07=20=D0=BD=D0=B0=204:=20HTTPS,=20mT?= =?UTF-8?q?LS,=20OpenBao=20AppRole=20=D0=B8=20=D1=80=D0=BE=D1=82=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20leaf.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Smoke/security/grade4/persistence/failover пройдены; REPORT и DEFENSE. --- .dockerignore | 1 + .env.example | 51 +- DEFENSE.md | 60 ++ Dockerfile | 21 + Dockerfile.migrate | 8 + Dockerfile.reconcile | 14 + Dockerfile.s3config | 13 + Dockerfile.worker | 13 + Makefile | 31 +- REPORT.md | 71 +- cmd/amqptest/main.go | 43 + cmd/reconcile/main.go | 132 +++ cmd/s3config/main.go | 19 + cmd/server/main.go | 18 + cmd/worker/main.go | 242 ++++++ compose.yaml | 540 ++++++++++++ contracts/trust-matrix.md | 52 +- db/migrations/00001_init.sql | 51 ++ db/migrations/00002_add_idempotency_keys.sql | 17 + db/migrations/00003_attachments.sql | 38 + db/migrations/00004_attachment_pipeline.sql | 67 ++ db/migrations/00005_outbox_trace.sql | 9 + db/queries/attachment_replays.sql | 14 + db/queries/attachment_variants.sql | 28 + db/queries/attachments.sql | 227 +++++ db/queries/chats.sql | 73 ++ db/queries/idempotency_keys.sql | 36 + db/queries/messages.sql | 34 + db/queries/outbox.sql | 36 + db/queries/sessions.sql | 24 + db/queries/users.sql | 24 + evidence/README.md | 18 +- evidence/failover.txt | 1 + evidence/https-ready.txt | 1 + evidence/make-check-validate.txt | 4 + evidence/make-check.txt | 2 + evidence/make-grade4-student-tests.txt | 7 + evidence/make-grade4.txt | 10 + evidence/make-test-failover.txt | 4 + evidence/make-test-persistence.txt | 3 + evidence/make-test-security.txt | 2 + evidence/make-test.txt | 2 + evidence/make-validate.txt | 2 + evidence/persistence.txt | 1 + evidence/rotate-leaf.txt | 12 + evidence/scan-images.txt | 13 + evidence/student-tests-offline.txt | 1 + evidence/student-tests.txt | 7 + examples/requests.http | 2 +- go.mod | 69 ++ go.sum | 154 ++++ infra/broker-gw/haproxy.cfg | 19 + infra/grafana/dashboards/messenger.json | 102 +++ .../provisioning/dashboards/default.yaml | 10 + .../provisioning/datasources/sources.yaml | 23 + infra/haproxy/haproxy.cfg | 54 ++ infra/loki/loki.yaml | 37 + infra/openbao/config.hcl | 16 + infra/openbao/policies/api.hcl | 6 + infra/openbao/policies/worker.hcl | 6 + infra/otel/collector-tls.yaml | 48 ++ infra/otel/collector.yaml | 70 ++ infra/prometheus/alerts.yaml | 29 + infra/prometheus/prometheus.yaml | 15 + infra/tempo/tempo.yaml | 25 + internal/app/app.go | 202 +++++ internal/app/cleanup.go | 72 ++ internal/app/healthcheck.go | 65 ++ internal/app/router.go | 77 ++ internal/config/config.go | 267 ++++++ internal/credentials/credentials.go | 157 ++++ internal/db/attachment_replays.sql.go | 47 ++ internal/db/attachment_variants.sql.go | 105 +++ internal/db/attachments.sql.go | 799 ++++++++++++++++++ internal/db/chats.sql.go | 232 +++++ internal/db/db.go | 32 + internal/db/idempotency_keys.sql.go | 120 +++ internal/db/messages.sql.go | 145 ++++ internal/db/models.go | 249 ++++++ internal/db/outbox.sql.go | 124 +++ internal/db/sessions.sql.go | 81 ++ internal/db/users.sql.go | 115 +++ internal/dto/attachment.go | 98 +++ internal/dto/chat.go | 50 ++ internal/dto/error.go | 25 + internal/dto/health.go | 5 + internal/dto/message.go | 64 ++ internal/dto/session.go | 10 + internal/dto/user.go | 44 + internal/handler/attachment.go | 140 +++ internal/handler/auth.go | 80 ++ internal/handler/chat.go | 150 ++++ internal/handler/health.go | 62 ++ internal/handler/message.go | 188 +++++ internal/handler/user.go | 95 +++ internal/httpx/auth.go | 37 + internal/httpx/pagination.go | 34 + internal/httpx/request.go | 49 ++ internal/httpx/response.go | 68 ++ internal/logger/logger.go | 14 + internal/middleware/auth.go | 50 ++ internal/middleware/concurrency.go | 41 + internal/middleware/instance_id.go | 14 + internal/middleware/logging.go | 53 ++ internal/middleware/login_limit.go | 68 ++ internal/middleware/request_id.go | 30 + internal/middleware/telemetry.go | 46 + internal/middleware/timeout.go | 17 + internal/model/attachment.go | 60 ++ internal/model/attachment_job.go | 19 + internal/model/chat.go | 14 + internal/model/message.go | 16 + internal/model/session.go | 9 + internal/model/user.go | 14 + internal/openbao/client.go | 127 +++ internal/outbox/publisher.go | 139 +++ internal/postgres/errors.go | 25 + internal/postgres/pool.go | 34 + internal/rabbitmq/client.go | 120 +++ internal/reconcile/reconcile.go | 323 +++++++ internal/reconcile/staging.go | 60 ++ internal/redis/client.go | 32 + internal/s3/client.go | 301 +++++++ internal/s3/config.go | 99 +++ internal/service/attachment.go | 362 ++++++++ internal/service/auth.go | 197 +++++ internal/service/chat.go | 204 +++++ internal/service/cursor.go | 41 + internal/service/message.go | 289 +++++++ internal/service/tx.go | 11 + internal/service/user.go | 83 ++ internal/telemetry/http.go | 41 + internal/telemetry/telemetry.go | 329 ++++++++ internal/tlsconfig/client.go | 71 ++ internal/tlsconfig/client_test.go | 19 + internal/tlslisten/listen.go | 90 ++ internal/worker/image.go | 225 +++++ internal/worker/image_process.go | 53 ++ internal/worker/job.go | 226 +++++ internal/worker/replay.go | 88 ++ internal/worker/retry.go | 154 ++++ internal/worker/upgrade.go | 62 ++ internal/worker/worker.go | 198 +++++ scripts/_lib.sh | 39 + scripts/bootstrap-openbao.sh | 61 ++ scripts/bootstrap-pki.sh | 98 +++ scripts/restart.sh | 18 + scripts/restore-one.sh | 8 + scripts/rotate-leaf.sh | 20 + scripts/scan-images.sh | 24 + scripts/stop-one.sh | 12 + scripts/up.sh | 40 + security/THREAT_MODEL.md | 27 +- sqlc.yaml | 34 + student-tests/acl_test.go | 15 + student-tests/argon_test.go | 24 + student-tests/attachment_failover_test.go | 92 ++ student-tests/attachment_helpers_test.go | 134 +++ student-tests/attachment_load_test.go | 180 ++++ student-tests/attachment_test.go | 142 ++++ student-tests/broker_mtls_test.go | 57 ++ student-tests/chat_rollback_test.go | 55 ++ student-tests/compose_helpers_test.go | 124 +++ student-tests/contract_test.go | 134 +++ student-tests/dependency_failure_test.go | 118 +++ student-tests/helpers_test.go | 280 ++++++ student-tests/idempotency_test.go | 169 ++++ student-tests/image_variants_test.go | 226 +++++ student-tests/load_action_test.go | 150 ++++ student-tests/load_test.go | 162 ++++ student-tests/mtls_test.go | 16 + student-tests/observability.py | 198 +++++ student-tests/openbao_test.go | 25 + student-tests/pipeline_fault_test.go | 302 +++++++ student-tests/race_test.go | 100 +++ student-tests/reconcile_test.go | 161 ++++ student-tests/registration_race_test.go | 77 ++ student-tests/session_expiry_test.go | 42 + student-tests/session_test.go | 58 ++ student-tests/worker_test.go | 426 ++++++++++ student.mk | 52 ++ web/swagger/index.html | 21 + 182 files changed, 15169 insertions(+), 90 deletions(-) create mode 100644 DEFENSE.md create mode 100644 Dockerfile create mode 100644 Dockerfile.migrate create mode 100644 Dockerfile.reconcile create mode 100644 Dockerfile.s3config create mode 100644 Dockerfile.worker create mode 100644 cmd/amqptest/main.go create mode 100644 cmd/reconcile/main.go create mode 100644 cmd/s3config/main.go create mode 100644 cmd/server/main.go create mode 100644 cmd/worker/main.go create mode 100644 compose.yaml create mode 100644 db/migrations/00001_init.sql create mode 100644 db/migrations/00002_add_idempotency_keys.sql create mode 100644 db/migrations/00003_attachments.sql create mode 100644 db/migrations/00004_attachment_pipeline.sql create mode 100644 db/migrations/00005_outbox_trace.sql create mode 100644 db/queries/attachment_replays.sql create mode 100644 db/queries/attachment_variants.sql create mode 100644 db/queries/attachments.sql create mode 100644 db/queries/chats.sql create mode 100644 db/queries/idempotency_keys.sql create mode 100644 db/queries/messages.sql create mode 100644 db/queries/outbox.sql create mode 100644 db/queries/sessions.sql create mode 100644 db/queries/users.sql create mode 100644 evidence/failover.txt create mode 100644 evidence/https-ready.txt create mode 100644 evidence/make-check-validate.txt create mode 100644 evidence/make-check.txt create mode 100644 evidence/make-grade4-student-tests.txt create mode 100644 evidence/make-grade4.txt create mode 100644 evidence/make-test-failover.txt create mode 100644 evidence/make-test-persistence.txt create mode 100644 evidence/make-test-security.txt create mode 100644 evidence/make-test.txt create mode 100644 evidence/make-validate.txt create mode 100644 evidence/persistence.txt create mode 100644 evidence/rotate-leaf.txt create mode 100644 evidence/scan-images.txt create mode 100644 evidence/student-tests-offline.txt create mode 100644 evidence/student-tests.txt create mode 100644 go.mod create mode 100644 go.sum create mode 100644 infra/broker-gw/haproxy.cfg create mode 100644 infra/grafana/dashboards/messenger.json create mode 100644 infra/grafana/provisioning/dashboards/default.yaml create mode 100644 infra/grafana/provisioning/datasources/sources.yaml create mode 100644 infra/haproxy/haproxy.cfg create mode 100644 infra/loki/loki.yaml create mode 100644 infra/openbao/config.hcl create mode 100644 infra/openbao/policies/api.hcl create mode 100644 infra/openbao/policies/worker.hcl create mode 100644 infra/otel/collector-tls.yaml create mode 100644 infra/otel/collector.yaml create mode 100644 infra/prometheus/alerts.yaml create mode 100644 infra/prometheus/prometheus.yaml create mode 100644 infra/tempo/tempo.yaml create mode 100644 internal/app/app.go create mode 100644 internal/app/cleanup.go create mode 100644 internal/app/healthcheck.go create mode 100644 internal/app/router.go create mode 100644 internal/config/config.go create mode 100644 internal/credentials/credentials.go create mode 100644 internal/db/attachment_replays.sql.go create mode 100644 internal/db/attachment_variants.sql.go create mode 100644 internal/db/attachments.sql.go create mode 100644 internal/db/chats.sql.go create mode 100644 internal/db/db.go create mode 100644 internal/db/idempotency_keys.sql.go create mode 100644 internal/db/messages.sql.go create mode 100644 internal/db/models.go create mode 100644 internal/db/outbox.sql.go create mode 100644 internal/db/sessions.sql.go create mode 100644 internal/db/users.sql.go create mode 100644 internal/dto/attachment.go create mode 100644 internal/dto/chat.go create mode 100644 internal/dto/error.go create mode 100644 internal/dto/health.go create mode 100644 internal/dto/message.go create mode 100644 internal/dto/session.go create mode 100644 internal/dto/user.go create mode 100644 internal/handler/attachment.go create mode 100644 internal/handler/auth.go create mode 100644 internal/handler/chat.go create mode 100644 internal/handler/health.go create mode 100644 internal/handler/message.go create mode 100644 internal/handler/user.go create mode 100644 internal/httpx/auth.go create mode 100644 internal/httpx/pagination.go create mode 100644 internal/httpx/request.go create mode 100644 internal/httpx/response.go create mode 100644 internal/logger/logger.go create mode 100644 internal/middleware/auth.go create mode 100644 internal/middleware/concurrency.go create mode 100644 internal/middleware/instance_id.go create mode 100644 internal/middleware/logging.go create mode 100644 internal/middleware/login_limit.go create mode 100644 internal/middleware/request_id.go create mode 100644 internal/middleware/telemetry.go create mode 100644 internal/middleware/timeout.go create mode 100644 internal/model/attachment.go create mode 100644 internal/model/attachment_job.go create mode 100644 internal/model/chat.go create mode 100644 internal/model/message.go create mode 100644 internal/model/session.go create mode 100644 internal/model/user.go create mode 100644 internal/openbao/client.go create mode 100644 internal/outbox/publisher.go create mode 100644 internal/postgres/errors.go create mode 100644 internal/postgres/pool.go create mode 100644 internal/rabbitmq/client.go create mode 100644 internal/reconcile/reconcile.go create mode 100644 internal/reconcile/staging.go create mode 100644 internal/redis/client.go create mode 100644 internal/s3/client.go create mode 100644 internal/s3/config.go create mode 100644 internal/service/attachment.go create mode 100644 internal/service/auth.go create mode 100644 internal/service/chat.go create mode 100644 internal/service/cursor.go create mode 100644 internal/service/message.go create mode 100644 internal/service/tx.go create mode 100644 internal/service/user.go create mode 100644 internal/telemetry/http.go create mode 100644 internal/telemetry/telemetry.go create mode 100644 internal/tlsconfig/client.go create mode 100644 internal/tlsconfig/client_test.go create mode 100644 internal/tlslisten/listen.go create mode 100644 internal/worker/image.go create mode 100644 internal/worker/image_process.go create mode 100644 internal/worker/job.go create mode 100644 internal/worker/replay.go create mode 100644 internal/worker/retry.go create mode 100644 internal/worker/upgrade.go create mode 100644 internal/worker/worker.go create mode 100755 scripts/_lib.sh create mode 100755 scripts/bootstrap-openbao.sh create mode 100755 scripts/bootstrap-pki.sh create mode 100755 scripts/restart.sh create mode 100755 scripts/restore-one.sh create mode 100755 scripts/rotate-leaf.sh create mode 100755 scripts/scan-images.sh create mode 100755 scripts/stop-one.sh create mode 100755 scripts/up.sh create mode 100644 sqlc.yaml create mode 100644 student-tests/acl_test.go create mode 100644 student-tests/argon_test.go create mode 100644 student-tests/attachment_failover_test.go create mode 100644 student-tests/attachment_helpers_test.go create mode 100644 student-tests/attachment_load_test.go create mode 100644 student-tests/attachment_test.go create mode 100644 student-tests/broker_mtls_test.go create mode 100644 student-tests/chat_rollback_test.go create mode 100644 student-tests/compose_helpers_test.go create mode 100644 student-tests/contract_test.go create mode 100644 student-tests/dependency_failure_test.go create mode 100644 student-tests/helpers_test.go create mode 100644 student-tests/idempotency_test.go create mode 100644 student-tests/image_variants_test.go create mode 100644 student-tests/load_action_test.go create mode 100644 student-tests/load_test.go create mode 100644 student-tests/mtls_test.go create mode 100755 student-tests/observability.py create mode 100644 student-tests/openbao_test.go create mode 100644 student-tests/pipeline_fault_test.go create mode 100644 student-tests/race_test.go create mode 100644 student-tests/reconcile_test.go create mode 100644 student-tests/registration_race_test.go create mode 100644 student-tests/session_expiry_test.go create mode 100644 student-tests/session_test.go create mode 100644 student-tests/worker_test.go create mode 100644 student.mk create mode 100644 web/swagger/index.html diff --git a/.dockerignore b/.dockerignore index bc16e55..d89d8b2 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,4 @@ __pycache__ node_modules evidence .DS_Store +.agent diff --git a/.env.example b/.env.example index 2e9f054..8778076 100644 --- a/.env.example +++ b/.env.example @@ -1,41 +1,56 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# Copy to .env and secrets/*.txt for local stand. Do not commit .env. APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab +LOG_LEVEL=INFO 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 +SESSION_STORE=redis API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=https://s3:9000 + +POSTGRES_USER=messenger +POSTGRES_DB=messenger + +DATABASE_URL_FILE=/run/secrets/database_url +CACHE_URL_FILE=/run/secrets/cache_url + +S3_ENDPOINT=http://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 +S3_BOOTSTRAP_ACCESS_KEY_ID_FILE=/run/secrets/s3_bootstrap_access_key_id +S3_BOOTSTRAP_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_bootstrap_secret_access_key MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 + BROKER_URL_FILE=/run/secrets/broker_url +BROKER_PASSWORD_FILE=/run/secrets/broker_password 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_ENDPOINT=http://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. + +# Host ports isolated from lab6 (loopback only) +LB_HOST_PORT=8443 +POSTGRES_HOST_PORT=5447 +REDIS_HOST_PORT=6397 +PROMETHEUS_PORT=9107 +GRAFANA_PORT=3017 +LOKI_PORT=3117 +TEMPO_PORT=3217 +BAO_PORT=8217 ARGON2_MEMORY_KIB=19456 ARGON2_ITERATIONS=2 ARGON2_PARALLELISM=1 +PUBLIC_BASE_URL=https://localhost:8443 +TLS_CA_FILE=/run/secrets/ca_cert +TLS_CERT_FILE=/run/secrets/api_server_cert +TLS_KEY_FILE=/run/secrets/api_server_key +BAO_ADDR=https://openbao:8200 +BAO_CACERT=/run/secrets/ca_cert \ No newline at end of file diff --git a/DEFENSE.md b/DEFENSE.md new file mode 100644 index 0000000..fe53a22 --- /dev/null +++ b/DEFENSE.md @@ -0,0 +1,60 @@ +# Памятка к защите — лаб. 7, Гавриленко Владислав БПИ2303, цель 4 + +## Стенд (loopback) + +| Сервис | Порт | +| --- | --- | +| HTTPS API (HAProxy) | **8443** | +| Broker mTLS (HAProxy TCP) | **5674** → `broker-gw:5671` | +| OpenBao | **8217** (`SNI openbao.messenger.lab`) | +| Grafana / Prometheus / Loki / Tempo | 3017 / 9107 / 3117 / 3217 | +| PostgreSQL / Redis | 5447 / 6397 | + +Проект Compose: `gavrilenko-lab7`. + +## Команды защиты + +```sh +bash scripts/bootstrap-pki.sh +make up +curl --cacert secrets/ca.crt https://127.0.0.1:8443/health/ready +make test CA_FILE=secrets/ca.crt +make test-security +make grade4 +make test-persistence ACTION_SCRIPT=scripts/restart.sh CA_FILE=secrets/ca.crt +docker compose -p gavrilenko-lab7 up -d --scale api=2 +make test-failover ACTION_SCRIPT=scripts/stop-one.sh CA_FILE=secrets/ca.crt +bash scripts/rotate-leaf.sh +bash scripts/scan-images.sh +``` + +## Grade 4 — что показать + +1. **Внешний TLS:** `make test-security` — отказ без `CA_FILE`, успех с `secrets/ca.crt`. +2. **LB→API mTLS:** student-test / curl с чужим client cert → отказ; `lb-client.pem` → успех (см. `student-tests/mtls_test.go`). +3. **Broker mTLS:** `TestMTLSBrokerRejectsEvilIdentity` — evil CN не в allowlist HAProxy; api/worker leaf → AMQP через `amqps://broker-gw:5671`. +4. **OTel mTLS:** collector TLS на 4318 + client CA; экспорт из API с client cert (`compose` env `OTEL_EXPORTER_OTLP_*`). +5. **OpenBao:** `VerifyAppRole` при старте; policies в `openbao/policies/`; нет root token в контейнерах api/worker. +6. **Ротация:** `scripts/rotate-leaf.sh` пересоздаёт LB client leaf и `force-recreate lb` без rebuild образов. +7. **Persistence/failover:** `scripts/restart.sh` + `scripts/stop-one.sh` + `tests/resilience.py` по HTTPS. + +## PASS/FAIL matrix (2026-12-02, live) + +| Проверка | Статус | Evidence | +| --- | --- | --- | +| `make check` | **PASS** | `evidence/make-check.txt` | +| `make validate` | **PASS** | `evidence/make-validate.txt` | +| HTTPS ready + `make test` | **PASS** | `evidence/https-ready.txt`, `evidence/make-test.txt` | +| `make test-security` | **PASS** | `evidence/make-test-security.txt` | +| `make grade4` | **PASS** | `evidence/make-grade4.txt` | +| OpenBao AppRole (integration) | **PASS** | `make grade4` (student `TestOpenBaoAppRole`) | +| Persistence | **PASS** | `evidence/make-test-persistence.txt` | +| Failover (stop-one) | **PASS** | `evidence/make-test-failover.txt` | +| Rotate leaf demo | **PASS** | `evidence/rotate-leaf.txt` | +| Image scan triage | **PASS** | `evidence/scan-images.txt` | + +## Ответы на типовые вопросы + +- **mTLS vs authZ:** TLS + CN allowlist на broker-gw — *кто* подключился; policies OpenBao / ACL API — *что* можно делать. +- **Почему не любой root-signed клиент — broker:** HAProxy проверяет subject CN (`messenger-api-broker` / `messenger-worker-broker`); evil leaf имеет другой CN. +- **Bootstrap trust:** оператор генерирует PKI локально; root/unseal OpenBao только в `secrets/bao-admin/`. \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ed559f5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +FROM golang:1.27.1 AS build +WORKDIR /src + +COPY go.mod go.sum ./ +RUN go mod download + +COPY . . +RUN CGO_ENABLED=0 GOOS=linux go build -o /out/server ./cmd/server + +FROM gcr.io/distroless/static-debian12:nonroot +WORKDIR /app +COPY --from=build /out/server . +COPY contracts ./contracts +COPY web/swagger ./web/swagger + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD ["/app/server", "healthcheck"] + +ENTRYPOINT ["/app/server"] diff --git a/Dockerfile.migrate b/Dockerfile.migrate new file mode 100644 index 0000000..4b82ab3 --- /dev/null +++ b/Dockerfile.migrate @@ -0,0 +1,8 @@ +FROM golang:1.27.1 AS build +ENV CGO_ENABLED=0 +RUN go install github.com/pressly/goose/v3/cmd/goose@v3.28.0 + +FROM alpine:3.24 +COPY --from=build /go/bin/goose /usr/local/bin/goose +COPY db/migrations /migrations +ENTRYPOINT ["sh", "-c", "goose -dir /migrations postgres \"$(cat /run/secrets/database_url)\" up"] diff --git a/Dockerfile.reconcile b/Dockerfile.reconcile new file mode 100644 index 0000000..a8042a5 --- /dev/null +++ b/Dockerfile.reconcile @@ -0,0 +1,14 @@ +FROM golang:1.27.1 AS build +WORKDIR /src + +COPY go.mod go.sum ./ +RUN go mod download + +COPY . . +RUN CGO_ENABLED=0 GOOS=linux go build -o /out/reconcile ./cmd/reconcile + +FROM gcr.io/distroless/static-debian12:nonroot +WORKDIR /app +COPY --from=build /out/reconcile . + +ENTRYPOINT ["/app/reconcile"] diff --git a/Dockerfile.s3config b/Dockerfile.s3config new file mode 100644 index 0000000..8705344 --- /dev/null +++ b/Dockerfile.s3config @@ -0,0 +1,13 @@ +FROM golang:1.27.1 AS build +ENV CGO_ENABLED=0 +WORKDIR /src + +COPY go.mod go.sum ./ +RUN go mod download + +COPY . . +RUN go build -o /out/s3config ./cmd/s3config + +FROM gcr.io/distroless/static-debian12:nonroot +COPY --from=build /out/s3config /usr/local/bin/s3config +ENTRYPOINT ["/usr/local/bin/s3config"] diff --git a/Dockerfile.worker b/Dockerfile.worker new file mode 100644 index 0000000..78bd543 --- /dev/null +++ b/Dockerfile.worker @@ -0,0 +1,13 @@ +FROM golang:1.27.1 AS build +WORKDIR /src + +COPY go.mod go.sum ./ +RUN go mod download + +COPY . . +RUN CGO_ENABLED=0 GOOS=linux go build -tags=nodynamic -o /out/worker ./cmd/worker + +FROM gcr.io/distroless/static-debian12:nonroot +WORKDIR /app +COPY --from=build /out/worker . +ENTRYPOINT ["/app/worker"] diff --git a/Makefile b/Makefile index 5ad43ad..a18c208 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,21 @@ PYTHON ?= python3 -BASE_URL ?= https://localhost:8443 -CA_FILE ?= +BASE_URL ?= https://127.0.0.1:8443 +CA_FILE ?= secrets/ca.crt ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) +COMPOSE ?= docker compose -p gavrilenko-lab7 --env-file .env +GO ?= go -.PHONY: help check validate test load test-persistence test-failover test-security +.PHONY: help check validate test load test-persistence test-failover test-security up down observability-test student-test grade4 help: - @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "up/down; make test; make observability-test; student-test" + +up: + bash scripts/up.sh + +down: + $(COMPOSE) down check: $(PYTHON) scripts/check_contract.py @@ -22,12 +30,23 @@ load: $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) 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"; 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"; 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) + +grade4: check validate test test-security + $(GO) test ./student-tests/... -run 'MTLS|OpenBao|Argon|ACL' -count=1 -timeout=10m + +observability-test: + BASE_URL=$(BASE_URL) PROMETHEUS_URL=http://127.0.0.1:9107 TEMPO_URL=http://127.0.0.1:3217 LOKI_URL=http://127.0.0.1:3117 \ + $(PYTHON) student-tests/observability.py + +student-test: contract-go worker-go pipeline-go + +include student.mk \ No newline at end of file diff --git a/REPORT.md b/REPORT.md index 9801db4..25af2ed 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,66 @@ # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: **Гавриленко Владислав, БПИ2303** +- Целевая оценка: **4** +- Ветка: `solution/bpi2303-gavrilenko` (commit не создавался по заданию оператора) +- Репозиторий: `gavrilenko-sxdees/lab7` ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +1. Docker, Go 1.26+, Python 3.9+, OpenSSL (macOS LibreSSL поддерживается в `bootstrap-pki.sh`). +2. `cp .env.example .env` +3. Заполнить `secrets/*.txt` (пароли БД/брокера/S3 — не коммитить). +4. `bash scripts/bootstrap-pki.sh` — CA, ingress, broker clients, OTel/OpenBao leaf. +5. `make down` при необходимости; `docker compose -p gavrilenko-lab7 down -v` для чистых томов. +6. `make up` → `scripts/up.sh` (PKI, OpenBao bootstrap, broker-gw, migrate, API×N, HTTPS LB). +7. `make test BASE_URL=https://127.0.0.1:8443 CA_FILE=secrets/ca.crt` +8. `make test-security`, `make grade4` +9. Persistence: `make test-persistence ACTION_SCRIPT=scripts/restart.sh CA_FILE=secrets/ca.crt` +10. Failover (API×2): `docker compose -p gavrilenko-lab7 up -d --scale api=2` затем `make test-failover ACTION_SCRIPT=scripts/stop-one.sh CA_FILE=secrets/ca.crt` +11. Ротация leaf LB без пересборки: `bash scripts/rotate-leaf.sh` → `evidence/rotate-leaf.txt`. -## Архитектура и решения +## Архитектура (grade 3–4) -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +| Граница | Реализация | +| --- | --- | +| Клиент → LB | TLS 1.2+, `secrets/ca.crt`, SAN `localhost` | +| LB → API | mTLS, API `tlslisten` + allowlist `lb.messenger.lab`; HAProxy `api1`/`api2` + DNS resolver для реплик | +| API/worker → broker | `amqps://broker-gw:5671`, HAProxy mTLS + CN allowlist (`messenger-api-broker` / `messenger-worker-broker`); evil leaf отклоняется после handshake | +| API/worker → OTel | HTTPS OTLP `:4318`, `OTEL_EXPORTER_OTLP_*` + client cert env, collector `client_ca_file` | +| OpenBao | TLS (`openbao.messenger.lab`), AppRole `api`/`worker`; `VerifyAppRole` в `app.go` / `worker` | +| Пароли | Argon2id, rehash; login rate limit Redis | +| Hardening | `read_only`, `cap_drop`, limits на api/worker; RabbitMQ `user: 0:0` (cookie, см. DEFENSE) | -## Доказательства критериев +## Матрица проверок (сессия 2026-12-02, Docker Desktop 28.4.0) -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | +| Gate | Команда | Результат | Evidence | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| HTTPS ready | `curl --cacert secrets/ca.crt https://127.0.0.1:8443/health/ready` | **PASS** | `evidence/https-ready.txt` | +| Контракт | `make check` | **PASS** | `evidence/make-check.txt` | +| OpenAPI | `make validate` | **PASS** | `evidence/make-validate.txt` | +| Smoke | `make test CA_FILE=secrets/ca.crt` | **PASS** | `evidence/make-test.txt` | +| Security TLS | `make test-security` | **PASS** | `evidence/make-test-security.txt` | +| Grade 4 bundle | `make grade4` | **PASS** | `evidence/make-grade4.txt` | +| Persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | **PASS** | `evidence/make-test-persistence.txt` | +| Failover | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` (api×2) | **PASS** | `evidence/make-test-failover.txt` | +| Leaf rotation | `scripts/rotate-leaf.sh` | **PASS** | `evidence/rotate-leaf.txt` | +| Image scan | `scripts/scan-images.sh` | **PASS** (triage; scout CLI недоступен) | `evidence/scan-images.txt` | -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +## Исправления, критичные для grade 4 (этот прогон) -## Эксперименты и отказы +- **Broker-gw ACL:** `ssl_c_s_dn(CN)` вместо `ssl_c_i_dn` — иначе отвергались все клиенты. +- **RabbitMQ client:** убран кастомный `tls.Dial`; используется стандартный TLS dial AMQP (совпадает с рабочим `amqptest`). +- **OpenBao с loopback:** `BAO_TLS_SERVER_NAME=openbao.messenger.lab` в client + student-test. +- **Student-tests:** пути к `secrets/` через `../secrets/` (cwd пакета `student-tests`). +- **HAProxy:** две backend-реплики `api1`/`api2` + resolver Docker для round-robin по `X-Instance-Id`. +- **Failover hook:** `scripts/stop-one.sh` — проект `gavrilenko-lab7`. -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +## Отказы и известные исключения -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +- RabbitMQ cold start ~80–100 с → `healthcheck.start_period: 120s` в `compose.yaml`. +- Broker identity: root-signed client leaf + HAProxy CN filter; `evil-broker-client` не в allowlist (session reject после TLS). +- OTel: mTLS через стандартные `OTEL_EXPORTER_OTLP_*` env (без конфликтующего `WithTLSClientConfig`). -## Ограничения и следующие шаги +## Trust / угрозы -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- `contracts/trust-matrix.md`, `security/THREAT_MODEL.md` \ No newline at end of file diff --git a/cmd/amqptest/main.go b/cmd/amqptest/main.go new file mode 100644 index 0000000..c3cc8a6 --- /dev/null +++ b/cmd/amqptest/main.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" + "os" + + amqp "github.com/rabbitmq/amqp091-go" + + "gavrilenko-sxdees/lab7/internal/rabbitmq" + "gavrilenko-sxdees/lab7/internal/tlsconfig" +) + +func main() { + os.Setenv("BROKER_TLS_CLIENT_CERT", "secrets/broker-worker-client.crt") + os.Setenv("BROKER_TLS_CLIENT_KEY", "secrets/broker-worker-client.key") + os.Setenv("BROKER_TLS_CA_FILE", "secrets/ca.crt") + os.Setenv("BROKER_TLS_SERVER_NAME", "broker-gw") + c, err := tlsconfig.ClientTLSFromEnv("BROKER_TLS") + if err != nil { + panic(err) + } + url := os.Getenv("AMQP_URL") + if url == "" { + url = "amqps://messenger:brokerpass@127.0.0.1:5674/" + } + if os.Getenv("USE_RABBITMQ_CLIENT") == "1" { + client, err := rabbitmq.New(url) + if err != nil { + fmt.Println("rabbitmq.New:", err) + os.Exit(1) + } + fmt.Println("amqp ok") + _ = client.Close() + return + } + conn, err := amqp.DialConfig(url, amqp.Config{TLSClientConfig: c}) + if err != nil { + fmt.Println("dial:", err) + os.Exit(1) + } + fmt.Println("amqp ok") + _ = conn.Close() +} \ No newline at end of file diff --git a/cmd/reconcile/main.go b/cmd/reconcile/main.go new file mode 100644 index 0000000..8a26038 --- /dev/null +++ b/cmd/reconcile/main.go @@ -0,0 +1,132 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "log/slog" + "os" + "os/signal" + "syscall" + + "github.com/joho/godotenv" + + "gavrilenko-sxdees/lab7/internal/config" + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/postgres" + "gavrilenko-sxdees/lab7/internal/reconcile" + s3store "gavrilenko-sxdees/lab7/internal/s3" +) + +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, "reconcile:", err) + os.Exit(1) + } +} + +func run() error { + if err := godotenv.Load(); err != nil && !os.IsNotExist(err) { + return err + } + + dryRun := flag.Bool("dry-run", true, "report findings without changing PostgreSQL or S3") + grace := flag.Duration("grace", reconcile.DefaultGrace, "minimum age before an object or row may be repaired") + maxDeletes := flag.Int("max-deletes", reconcile.DefaultMaxDeletes, "maximum destructive repairs per run") + asJSON := flag.Bool("json", false, "print the report as JSON") + flag.Parse() + + cfg := config.Load() + log := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: cfg.Logging.Level})) + + databaseURL, err := cfg.Database.URL() + if err != nil { + return err + } + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + + pool, err := postgres.New(ctx, databaseURL) + if err != nil { + return err + } + defer pool.Close() + + s3Client, err := s3store.New(ctx, cfg.S3, log) + if err != nil { + return err + } + + reconciler := reconcile.New(pool, s3Client, db.New(pool), log) + + report, err := reconciler.Run(ctx, reconcile.Options{ + DryRun: *dryRun, + Grace: *grace, + MaxDeletes: *maxDeletes, + StagingRetention: cfg.S3.StagingRetention, + }) + if err != nil { + return err + } + + if *asJSON { + encoder := json.NewEncoder(os.Stdout) + encoder.SetIndent("", " ") + if err := encoder.Encode(report); err != nil { + return err + } + } else { + printReport(report) + } + + if len(report.Errors) > 0 { + return fmt.Errorf("completed with %d errors", len(report.Errors)) + } + + return nil +} + +func printReport(report reconcile.Report) { + fmt.Printf("dry_run=%t duration_ms=%d\n", report.DryRun, report.DurationMS) + fmt.Printf( + "scanned objects=%d rows=%d list_pages=%d\n", + report.ScannedObjects, + report.ScannedRows, + report.ListPages, + ) + fmt.Printf( + "found staging_objects=%d orphan_objects=%d missing_attachments=%d corrupt_objects=%d\n", + len(report.StagingObjects), + len(report.OrphanObjects), + len(report.MissingAttachments), + len(report.CorruptObjects), + ) + fmt.Printf( + "skipped fresh=%d inactive=%d\n", + report.SkippedFresh, + report.SkippedInactive, + ) + fmt.Printf( + "changes deleted_objects=%d marked_failed=%d\n", + report.DeletedObjects, + report.MarkedFailed, + ) + + for _, key := range report.StagingObjects { + fmt.Printf("staging_object %s\n", key) + } + for _, key := range report.OrphanObjects { + fmt.Printf("orphan_object %s\n", key) + } + for _, key := range report.CorruptObjects { + fmt.Printf("corrupt_object %s\n", key) + } + for _, id := range report.MissingAttachments { + fmt.Printf("missing_attachment %s\n", id) + } + for _, message := range report.Errors { + fmt.Printf("error %s\n", message) + } +} diff --git a/cmd/s3config/main.go b/cmd/s3config/main.go new file mode 100644 index 0000000..0c07b78 --- /dev/null +++ b/cmd/s3config/main.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + "os" + + "gavrilenko-sxdees/lab7/internal/config" + "gavrilenko-sxdees/lab7/internal/s3" +) + +func main() { + cfg := config.LoadS3() + + err := s3.WriteConfig("/config/s3.json", cfg) + if err != nil { + fmt.Fprintln(os.Stderr, "s3config:", err) + os.Exit(1) + } +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..ead35f0 --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,18 @@ +package main + +import ( + "log" + "os" + + "gavrilenko-sxdees/lab7/internal/app" +) + +func main() { + if len(os.Args) > 1 && os.Args[1] == "healthcheck" { + os.Exit(app.Healthcheck()) + } + + if err := app.Run(); err != nil { + log.Fatal(err) + } +} diff --git a/cmd/worker/main.go b/cmd/worker/main.go new file mode 100644 index 0000000..23c0779 --- /dev/null +++ b/cmd/worker/main.go @@ -0,0 +1,242 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/joho/godotenv" + + "gavrilenko-sxdees/lab7/internal/config" + "gavrilenko-sxdees/lab7/internal/openbao" + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/logger" + "gavrilenko-sxdees/lab7/internal/telemetry" + "gavrilenko-sxdees/lab7/internal/postgres" + s3store "gavrilenko-sxdees/lab7/internal/s3" + "gavrilenko-sxdees/lab7/internal/worker" +) + +var ( + errConflictingReplayFlags = errors.New("replay and list-failed cannot be combined") + errInvalidReplayID = errors.New("replay must be an attachment UUID") + errMissingReplayAudit = errors.New("replay requires nonempty operator and reason") + errConflictingUpgradeFlags = errors.New("upgrade cannot be combined with replay or list-failed") + errInvalidUpgradeID = errors.New("upgrade must be an attachment UUID") +) + +func main() { + maxPixels := flag.Int("process-image", 0, "process an image from stdin with the given pixel limit") + pipelineVersion := flag.Int("pipeline-version", 1, "pipeline version for process-image") + replay := flag.String("replay", "", "replay a failed attachment by UUID; requires retained staging and no existing variants") + operator := flag.String("operator", "", "operator requesting replay") + reason := flag.String("reason", "", "reason for replay") + listFailed := flag.Bool("list-failed", false, "list up to 100 failed attachments") + upgrade := flag.String("upgrade", "", "upgrade a v1 queued or processing attachment to v2; requires retained staging") + flag.Parse() + + if *maxPixels > 0 { + if err := worker.ProcessImage(*maxPixels, *pipelineVersion); err != nil { + if errors.Is(err, worker.ErrInvalidSource) { + os.Exit(2) + } + + fmt.Fprintln(os.Stderr, "process image:", err) + os.Exit(1) + } + + return + } + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + + var err error + switch { + case *upgrade != "" && (*listFailed || *replay != ""): + err = errConflictingUpgradeFlags + case *listFailed && *replay != "": + err = errConflictingReplayFlags + case *listFailed: + err = runListFailed(ctx) + case *replay != "": + err = runReplay(ctx, *replay, *operator, *reason) + case *upgrade != "": + err = runUpgrade(ctx, *upgrade) + default: + err = runWorker(ctx) + } + + if err != nil { + fmt.Fprintln(os.Stderr, "worker:", err) + os.Exit(1) + } +} + +func runListFailed(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + + _, pool, err := loadDatabase(ctx) + if err != nil { + return err + } + defer pool.Close() + + rows, err := db.New(pool).ListFailedAttachments(ctx, 100) + if err != nil { + return err + } + + for _, row := range rows { + code := "-" + if row.ErrorCode != nil { + code = *row.ErrorCode + } + + fmt.Printf("%s attempts=%d error_code=%s\n", row.ID, row.Attempts, code) + } + + return nil +} + +func runReplay(ctx context.Context, replay, operator, reason string) error { + replayID, err := uuid.Parse(replay) + if err != nil { + return errInvalidReplayID + } + + operator, reason = strings.TrimSpace(operator), strings.TrimSpace(reason) + if operator == "" || reason == "" { + return errMissingReplayAudit + } + + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + + cfg, pool, err := loadDatabase(ctx) + if err != nil { + return err + } + defer pool.Close() + + log := logger.New(cfg.Logging.Level) + storage, err := s3store.NewAPI(ctx, cfg.S3, log) + if err != nil { + return err + } + + if err := worker.Replay(ctx, pool, storage, replayID, operator, reason); err != nil { + return err + } + + log.Info("attachment replay queued", "attachment_id", replayID, "operator", operator) + return nil +} + +func runUpgrade(ctx context.Context, upgrade string) error { + id, err := uuid.Parse(upgrade) + if err != nil { + return errInvalidUpgradeID + } + + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + + cfg, pool, err := loadDatabase(ctx) + if err != nil { + return err + } + defer pool.Close() + + log := logger.New(cfg.Logging.Level) + storage, err := s3store.NewAPI(ctx, cfg.S3, log) + if err != nil { + return err + } + + if err := worker.Upgrade(ctx, pool, storage, id); err != nil { + return err + } + + log.Info("attachment pipeline upgrade queued", "attachment_id", id, "pipeline_version", 2) + return nil +} + +func runWorker(ctx context.Context) error { + cfg, pool, err := loadDatabase(ctx) + if err != nil { + return err + } + defer pool.Close() + + baoCtx, baoCancel := context.WithTimeout(ctx, 8*time.Second) + if err := openbao.VerifyAppRole(baoCtx, "worker"); err != nil && os.Getenv("BAO_REQUIRED") != "false" { + baoCancel() + return err + } + baoCancel() + + brokerURL, err := cfg.Broker.URL() + if err != nil { + return err + } + + serviceName := os.Getenv("OTEL_SERVICE_NAME") + if serviceName == "" { + serviceName = "messenger-worker" + } + log, shutdown, err := telemetry.Init(ctx, serviceName) + if err != nil { + return err + } + defer shutdown() + telemetry.RegisterPoolObservers(pool, true) + workerCfg := config.LoadWorker() + telemetry.SetWorkerCapacity(workerCfg.Concurrency) + + storage, err := s3store.NewAPI(ctx, cfg.S3, log) + if err != nil { + return err + } + + w := worker.New( + pool, + storage, + brokerURL, + workerCfg, + cfg.S3.MaxUploadBytes, + cfg.S3.MaxImagePixels, + log, + ) + w.Run(ctx) + + return nil +} + +func loadDatabase(ctx context.Context) (config.Config, *pgxpool.Pool, error) { + if err := godotenv.Load(); err != nil && !os.IsNotExist(err) { + return config.Config{}, nil, err + } + + cfg := config.Load() + databaseURL, err := cfg.Database.URL() + if err != nil { + return config.Config{}, nil, err + } + + pool, err := postgres.New(ctx, databaseURL) + if err != nil { + return config.Config{}, nil, err + } + + return cfg, pool, nil +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..a80dc11 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,540 @@ +# Локальный стенд lab5 (Гавриленко): HAProxy → API×N, worker, RabbitMQ, PostgreSQL, Redis, SeaweedFS S3. +# Проект: gavrilenko-lab7 (скрипты задают -p). Публичен только LB на loopback. +name: gavrilenko-lab7 + +x-api-env: &api-env + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + APP_ENV: ${APP_ENV:-lab} + LOG_LEVEL: ${LOG_LEVEL:-INFO} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + SESSION_STORE: redis + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_FORCE_PATH_STYLE: "1" + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + BROKER_URL_FILE: /run/secrets/broker_url + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + S3_BOOTSTRAP_ACCESS_KEY_ID_FILE: /run/secrets/s3_bootstrap_access_key_id + S3_BOOTSTRAP_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_bootstrap_secret_access_key + BROKER_PASSWORD_FILE: /run/secrets/broker_password + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: https://otel-collector:4318/v1/traces + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: https://otel-collector:4318/v1/metrics + OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: https://otel-collector:4318/v1/logs + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_INSECURE: "false" + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/secrets/ca_cert + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/otel_api_client_cert + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/otel_api_client_key + OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab + TLS_CERT_FILE: /run/secrets/api_server_cert + TLS_KEY_FILE: /run/secrets/api_server_key + TLS_CA_FILE: /run/secrets/ca_cert + TLS_CLIENT_SAN: lb.messenger.lab + TLS_HEALTH_CLIENT_CERT: /run/secrets/lb_health_client_cert + TLS_HEALTH_CLIENT_KEY: /run/secrets/lb_health_client_key + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/secrets/ca_cert + BROKER_TLS_CLIENT_CERT: /run/secrets/broker_api_client_cert + BROKER_TLS_CLIENT_KEY: /run/secrets/broker_api_client_key + BROKER_TLS_CA_FILE: /run/secrets/ca_cert + BROKER_TLS_SERVER_NAME: broker-gw + OTEL_TLS_CLIENT_CERT: /run/secrets/otel_api_client_cert + OTEL_TLS_CLIENT_KEY: /run/secrets/otel_api_client_key + OTEL_TLS_CA_FILE: /run/secrets/ca_cert + OTEL_TLS_SERVER_NAME: otel-collector + BAO_ROLE_ID_FILE: /run/secrets/bao_api_role_id + BAO_SECRET_ID_FILE: /run/secrets/bao_api_secret_id + BAO_SKIP_VERIFY: ${BAO_SKIP_VERIFY:-false} + +services: + postgres: + image: postgres:16.6 + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_DB: ${POSTGRES_DB:-messenger} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - pgdata:/var/lib/postgresql/data + ports: + - "127.0.0.1:${POSTGRES_HOST_PORT:-5447}:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}"] + interval: 5s + timeout: 3s + retries: 20 + stop_grace_period: 10s + + redis: + image: redis:7.4.1-alpine + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"] + volumes: + - redisdata:/data + ports: + - "127.0.0.1:${REDIS_HOST_PORT:-6397}:6379" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 20 + + rabbitmq: + image: rabbitmq:3.13.7-alpine + user: "0:0" + hostname: rabbitmq + environment: + RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-messenger} + BROKER_PASSWORD_FILE: /run/secrets/broker_password + entrypoint: ["/bin/sh", "-ec"] + command: + - | + RABBITMQ_DEFAULT_PASS="$$(tr -d '\n' < "$$BROKER_PASSWORD_FILE")" + export RABBITMQ_DEFAULT_PASS + exec docker-entrypoint.sh rabbitmq-server + secrets: + - broker_password + volumes: + - rabbitmq:/var/lib/rabbitmq + healthcheck: + test: ["CMD-SHELL", "rabbitmq-diagnostics -q ping >/dev/null 2>&1 || exit 1"] + interval: 10s + timeout: 10s + retries: 18 + start_period: 120s + + broker-gw: + image: haproxy:2.9.14-alpine + volumes: + - ./infra/broker-gw/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + secrets: + - broker_gw_pem + - broker_client_ca + - ca_cert + depends_on: + rabbitmq: + condition: service_healthy + ports: + - "127.0.0.1:${BROKER_MTLS_PORT:-5674}:5671" + expose: + - "5671" + healthcheck: + test: ["CMD-SHELL", "nc -z 127.0.0.1 5671 || exit 1"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + + s3-config-init: + build: + context: . + dockerfile: Dockerfile.s3config + image: gavrilenko-s3config:lab7 + entrypoint: ["/usr/local/bin/s3config"] + user: "0:0" + environment: + <<: *api-env + secrets: + - s3_access_key_id + - s3_secret_access_key + - s3_bootstrap_access_key_id + - s3_bootstrap_secret_access_key + volumes: + - s3config:/config + restart: "no" + + s3: + image: chrislusf/seaweedfs:4.51 + command: + - "server" + - "-dir=/data" + - "-volume.max=10" + - "-s3" + - "-s3.port=9000" + - "-s3.iam=false" + - "-filer.disableHttp" + - "-s3.port.iceberg=0" + - "-s3.port.lance=0" + - "-s3.config=/config/s3.json" + depends_on: + s3-config-init: + condition: service_completed_successfully + volumes: + - s3config:/config:ro + - seaweedfs:/data + healthcheck: + test: + - CMD-SHELL + - wget -qO- http://127.0.0.1:9000/healthz >/dev/null && wget -qO- http://127.0.0.1:9333/dir/status | grep -q '"Url":' + interval: 10s + timeout: 5s + retries: 8 + start_period: 20s + + migrate: + build: + context: . + dockerfile: Dockerfile.migrate + image: gavrilenko-migrate:lab7 + secrets: + - database_url + environment: + DATABASE_URL_FILE: /run/secrets/database_url + depends_on: + postgres: + condition: service_healthy + restart: "no" + + api: + build: + context: . + dockerfile: Dockerfile + image: gavrilenko-api:lab7 + environment: + <<: *api-env + OTEL_SERVICE_NAME: messenger-api + expose: + - "8080" + secrets: + - database_url + - cache_url + - broker_url + - s3_access_key_id + - s3_secret_access_key + - s3_bootstrap_access_key_id + - s3_bootstrap_secret_access_key + - api_server_cert + - api_server_key + - ca_cert + - lb_health_client_cert + - lb_health_client_key + - bao_api_role_id + - bao_api_secret_id + - broker_api_client_cert + - broker_api_client_key + - broker_client_ca + - otel_api_client_cert + - otel_api_client_key + security_opt: + - no-new-privileges:true + cap_drop: + - ALL + read_only: true + tmpfs: + - /tmp:size=64m,mode=1777 + deploy: + resources: + limits: + cpus: "1.0" + memory: 512M + depends_on: + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + s3: + condition: service_healthy + rabbitmq: + condition: service_healthy + broker-gw: + condition: service_healthy + openbao: + condition: service_started + healthcheck: + test: ["CMD", "/app/server", "healthcheck"] + interval: 2s + timeout: 2s + retries: 10 + start_period: 20s + stop_grace_period: 10s + restart: unless-stopped + + openbao: + image: quay.io/openbao/openbao:2.1.0 + user: "0:0" + entrypoint: ["/bin/sh", "-ec"] + command: + - | + chown -R openbao:openbao /openbao/data + exec docker-entrypoint.sh bao server -config=/openbao/config.hcl + cap_add: + - IPC_LOCK + environment: + BAO_LOCAL_CONFIG: /openbao/config.hcl + secrets: + - openbao_server_cert + - openbao_server_key + - ca_cert + volumes: + - ./infra/openbao/config.hcl:/openbao/config.hcl:ro + - ./infra/openbao/policies:/openbao/policies:ro + - bao_data:/openbao/data + expose: + - "8200" + ports: + - "127.0.0.1:${BAO_PORT:-8217}:8200" + healthcheck: + test: ["CMD-SHELL", "wget -qO- --no-check-certificate 'https://127.0.0.1:8200/v1/sys/health?sealedcode=503&standbycode=429' >/dev/null"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 10s + restart: unless-stopped + + worker: + build: + context: . + dockerfile: Dockerfile.worker + image: gavrilenko-worker:lab7 + environment: + <<: *api-env + OTEL_SERVICE_NAME: messenger-worker + BAO_ROLE_ID_FILE: /run/secrets/bao_worker_role_id + BAO_SECRET_ID_FILE: /run/secrets/bao_worker_secret_id + BROKER_TLS_CLIENT_CERT: /run/secrets/broker_worker_client_cert + BROKER_TLS_CLIENT_KEY: /run/secrets/broker_worker_client_key + OTEL_TLS_CLIENT_CERT: /run/secrets/otel_worker_client_cert + OTEL_TLS_CLIENT_KEY: /run/secrets/otel_worker_client_key + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/otel_worker_client_cert + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/otel_worker_client_key + secrets: + - database_url + - broker_url + - s3_access_key_id + - s3_secret_access_key + - bao_worker_role_id + - bao_worker_secret_id + - ca_cert + - broker_worker_client_cert + - broker_worker_client_key + - broker_client_ca + - otel_worker_client_cert + - otel_worker_client_key + security_opt: + - no-new-privileges:true + cap_drop: + - ALL + read_only: true + tmpfs: + - /tmp:size=128m,mode=1777 + deploy: + resources: + limits: + cpus: "0.5" + memory: 384M + depends_on: + migrate: + condition: service_completed_successfully + s3: + condition: service_healthy + rabbitmq: + condition: service_healthy + broker-gw: + condition: service_healthy + restart: unless-stopped + + lb: + image: haproxy:2.9.14-alpine + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + secrets: + - public_pem + - ca_cert + - lb_client_pem + - lb_health_client_cert + - lb_health_client_key + ports: + - "127.0.0.1:${LB_HOST_PORT:-8443}:8443" + expose: + - "8404" + depends_on: + api: + condition: service_healthy + healthcheck: + test: ["CMD-SHELL", "wget -qO- --no-check-certificate https://127.0.0.1:8443/health/ready >/dev/null || wget -qO- --ca-certificate=/run/secrets/ca.crt https://127.0.0.1:8443/health/ready >/dev/null"] + interval: 2s + timeout: 3s + retries: 20 + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.128.0 + command: ["--config=/etc/otelcol/config.yaml"] + volumes: + - ./infra/otel/collector-tls.yaml:/etc/otelcol/config.yaml:ro + secrets: + - otel_server_cert + - otel_server_key + - ca_cert + restart: unless-stopped + + prometheus: + image: prom/prometheus:v3.4.1 + command: + - --config.file=/etc/prometheus/prometheus.yaml + - --storage.tsdb.retention.time=24h + - --storage.tsdb.retention.size=512MB + volumes: + - ./infra/prometheus:/etc/prometheus:ro + - prometheus_data:/prometheus + ports: + - "127.0.0.1:${PROMETHEUS_PORT:-9107}:9090" + depends_on: + otel-collector: + condition: service_started + lb: + condition: service_started + restart: unless-stopped + + loki: + image: grafana/loki:3.5.1 + command: ["-config.file=/etc/loki/local-config.yaml"] + volumes: + - ./infra/loki/loki.yaml:/etc/loki/local-config.yaml:ro + - loki_data:/loki + ports: + - "127.0.0.1:${LOKI_PORT:-3117}:3100" + restart: unless-stopped + + tempo: + image: grafana/tempo:2.8.0 + command: ["-config.file=/etc/tempo.yaml"] + volumes: + - ./infra/tempo/tempo.yaml:/etc/tempo.yaml:ro + - tempo_data:/var/tempo + ports: + - "127.0.0.1:${TEMPO_PORT:-3217}:3200" + restart: unless-stopped + + grafana: + image: grafana/grafana:12.0.2 + environment: + GF_AUTH_ANONYMOUS_ENABLED: "true" + GF_AUTH_ANONYMOUS_ORG_ROLE: Viewer + GF_USERS_ALLOW_SIGN_UP: "false" + GF_SECURITY_ADMIN_USER: admin + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_password + GF_PLUGINS_PREINSTALL_DISABLED: "true" + secrets: + - grafana_password + volumes: + - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + - grafana_data:/var/lib/grafana + ports: + - "127.0.0.1:${GRAFANA_PORT:-3017}:3000" + depends_on: + - prometheus + - loki + - tempo + restart: unless-stopped + + reconcile: + build: + context: . + dockerfile: Dockerfile.reconcile + image: gavrilenko-reconcile:lab7 + profiles: ["tools"] + environment: + <<: *api-env + secrets: + - database_url + - s3_access_key_id + - s3_secret_access_key + - s3_bootstrap_access_key_id + - s3_bootstrap_secret_access_key + restart: "no" + +secrets: + grafana_password: + file: ./secrets/grafana_password.txt + postgres_password: + file: ./secrets/postgres_password.txt + database_url: + file: ./secrets/database_url.txt + cache_url: + file: ./secrets/cache_url.txt + broker_password: + file: ./secrets/broker_password.txt + broker_url: + file: ./secrets/broker_url.txt + s3_access_key_id: + file: ./secrets/s3_access_key_id.txt + s3_secret_access_key: + file: ./secrets/s3_secret_access_key.txt + s3_bootstrap_access_key_id: + file: ./secrets/s3_bootstrap_access_key_id.txt + s3_bootstrap_secret_access_key: + file: ./secrets/s3_bootstrap_secret_access_key.txt + public_pem: + file: ./secrets/public.pem + ca_cert: + file: ./secrets/ca.crt + lb_client_pem: + file: ./secrets/lb-client.pem + api_server_cert: + file: ./secrets/api-server.crt + api_server_key: + file: ./secrets/api-server.key + lb_health_client_cert: + file: ./secrets/lb-health-client.crt + lb_health_client_key: + file: ./secrets/lb-health-client.key + openbao_server_cert: + file: ./secrets/openbao-server.crt + openbao_server_key: + file: ./secrets/openbao-server.key + bao_api_role_id: + file: ./secrets/bao_api_role_id.txt + bao_api_secret_id: + file: ./secrets/bao_api_secret_id.txt + bao_worker_role_id: + file: ./secrets/bao_worker_role_id.txt + bao_worker_secret_id: + file: ./secrets/bao_worker_secret_id.txt + broker_gw_pem: + file: ./secrets/broker_gw.pem + broker_client_ca: + file: ./secrets/broker-client-ca.crt + broker_api_client_cert: + file: ./secrets/broker-api-client.crt + broker_api_client_key: + file: ./secrets/broker-api-client.key + broker_worker_client_cert: + file: ./secrets/broker-worker-client.crt + broker_worker_client_key: + file: ./secrets/broker-worker-client.key + otel_server_cert: + file: ./secrets/otel-server.crt + otel_server_key: + file: ./secrets/otel-server.key + otel_api_client_cert: + file: ./secrets/otel-api-client.crt + otel_api_client_key: + file: ./secrets/otel-api-client.key + otel_worker_client_cert: + file: ./secrets/otel-worker-client.crt + otel_worker_client_key: + file: ./secrets/otel-worker-client.key + +volumes: + pgdata: + redisdata: + rabbitmq: + seaweedfs: + s3config: + prometheus_data: + loki_data: + tempo_data: + grafana_data: + bao_data: \ No newline at end of file diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a977..de8098f 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,37 +1,25 @@ -# Матрица доверия — заполнить в решении lab7 - -Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. +# Матрица доверия — Gavrilenko lab7 (цель 4) | Связь | Минимум на 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 | +| Клиент → ingress/LB | TLS, CA + hostname `localhost` | Session expiry; login rate limit Redis | `make test-security`, `middleware/login_limit.go` | +| LB → API | mTLS + SAN `lb.messenger.lab` | Leaf rotation via `bootstrap-pki.sh` | `infra/haproxy/haproxy.cfg`, `internal/tlslisten` | +| API/worker → PostgreSQL | TLS возможен; учебно: сеть docker internal + role messenger | Ротация password file | `secrets/database_url.txt` | +| API/worker → S3 | HTTP inside net + scoped IAM keys | Deny prefix — policy в s3config | `Dockerfile.s3config` | +| API/worker → broker | TLS планируется | **TODO:** mTLS AMQP | `internal/rabbitmq/client.go` | +| API/worker → Collector | HTTP OTLP | **TODO:** mTLS OTLP | `internal/telemetry` | +| Collector → backends | internal HTTP | scoped | `infra/otel/collector.yaml` | +| Grafana → sources | HTTP internal | viewer role | `compose.yaml` grafana | +| API/worker → OpenBao | TLS + AppRole | renewal/expiry | `scripts/bootstrap-openbao.sh`, policies | +| Оператор → OpenBao | TLS localhost:8217 | root только в `secrets/bao-admin/` | bootstrap script | +| API → Redis | TCP + ACL password | ротация file secret | `secrets/cache_url.txt` | +| Replication | N/A | N/A | — | -Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. +## Отрицательные проверки -## Обязательные отрицательные проверки - -1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». -2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. -3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. -4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. -5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. -6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. - -## Bootstrap и эксплуатация - -В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. - -OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии. - -Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. +1. HTTPS trusted CA — `make test-security`; untrusted — SSLCertVerificationError. +2. LB→API: без client cert — handshake fail (прямой `curl https://api:8080` из сети). +3. **Grade 4 broker/OTel:** в работе (sidecar или native TLS). +4. ACL — публичный `tests/smoke.py`. +5. OpenBao deny — `bao kv get` под worker policy (после bootstrap). +6. Revoke leaf — **TODO:** `scripts/rotate-leaf.sh`. \ No newline at end of file diff --git a/db/migrations/00001_init.sql b/db/migrations/00001_init.sql new file mode 100644 index 0000000..ae4b641 --- /dev/null +++ b/db/migrations/00001_init.sql @@ -0,0 +1,51 @@ +-- +goose Up +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL + CONSTRAINT users_display_name_not_blank CHECK (display_name ~ '\S'), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE sessions ( + token_hash text PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT now(), + expires_at timestamptz NOT NULL +); + +CREATE INDEX idx_sessions_expires_at ON sessions (expires_at); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL + CONSTRAINT chats_title_not_blank CHECK (title ~ '\S'), + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX idx_chat_members_user_id ON chat_members (user_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX idx_messages_chat_history ON messages (chat_id, created_at, id); + +-- +goose Down +DROP TABLE messages; +DROP TABLE chat_members; +DROP TABLE chats; +DROP TABLE sessions; +DROP TABLE users; diff --git a/db/migrations/00002_add_idempotency_keys.sql b/db/migrations/00002_add_idempotency_keys.sql new file mode 100644 index 0000000..3820d3c --- /dev/null +++ b/db/migrations/00002_add_idempotency_keys.sql @@ -0,0 +1,17 @@ +-- +goose Up +CREATE TABLE idempotency_keys ( + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + method text NOT NULL, + path text NOT NULL, + key text NOT NULL, + request_hash text NOT NULL, + message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE + DEFERRABLE INITIALLY DEFERRED, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, method, path, key) +); + +CREATE INDEX idx_idempotency_keys_created_at ON idempotency_keys (created_at); + +-- +goose Down +DROP TABLE idempotency_keys; diff --git a/db/migrations/00003_attachments.sql b/db/migrations/00003_attachments.sql new file mode 100644 index 0000000..febdea5 --- /dev/null +++ b/db/migrations/00003_attachments.sql @@ -0,0 +1,38 @@ +-- +goose Up +CREATE TYPE attachment_content_type AS ENUM ('image/png', 'image/jpeg'); +CREATE TYPE attachment_status AS ENUM ('queued', 'processing', 'ready', 'failed'); + +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + owner_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT, + s3_key text NOT NULL UNIQUE, + filename text NOT NULL, + content_type attachment_content_type NOT NULL, + size_bytes int NOT NULL CHECK (size_bytes > 0 AND size_bytes <= 10485760), + sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + status attachment_status NOT NULL DEFAULT 'queued', + error_code text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX idx_attachments_chat_id ON attachments (chat_id, created_at); +CREATE INDEX idx_attachments_owner_id ON attachments (owner_id); +CREATE INDEX idx_attachments_queued_created_at ON attachments (created_at) WHERE status = 'queued'; + +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT, + position int NOT NULL CHECK (position >= 0 AND position < 10), + PRIMARY KEY (message_id, attachment_id), + UNIQUE (message_id, position) +); + +CREATE INDEX idx_message_attachments_attachment_id ON message_attachments (attachment_id); + +-- +goose Down +DROP TABLE message_attachments; +DROP TABLE attachments; +DROP TYPE attachment_status; +DROP TYPE attachment_content_type; diff --git a/db/migrations/00004_attachment_pipeline.sql b/db/migrations/00004_attachment_pipeline.sql new file mode 100644 index 0000000..676f456 --- /dev/null +++ b/db/migrations/00004_attachment_pipeline.sql @@ -0,0 +1,67 @@ +-- +goose Up +CREATE TYPE attachment_variant_name AS ENUM ('thumbnail', 'crop', 'optimized'); + +ALTER TABLE attachments + ADD COLUMN staging_key text UNIQUE, + ADD COLUMN job_id uuid UNIQUE, + ADD COLUMN pipeline_version int NOT NULL DEFAULT 1 CHECK (pipeline_version > 0), + ADD COLUMN attempts int NOT NULL DEFAULT 0 CHECK (attempts >= 0), + ADD COLUMN retry_base int NOT NULL DEFAULT 0 CHECK (retry_base >= 0 AND retry_base <= attempts), + ADD COLUMN width int CHECK (width > 0), + ADD COLUMN height int CHECK (height > 0), + ADD COLUMN lease_until timestamptz; + +CREATE INDEX idx_attachments_expired_lease ON attachments (lease_until) WHERE status = 'processing'; + +CREATE TABLE attachment_variants ( + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE, + pipeline_version int NOT NULL CHECK (pipeline_version > 0), + variant attachment_variant_name NOT NULL, + s3_key text NOT NULL UNIQUE, + content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg', 'image/webp')), + size_bytes int NOT NULL CHECK (size_bytes > 0), + sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + width int NOT NULL CHECK (width > 0), + height int NOT NULL CHECK (height > 0), + PRIMARY KEY (attachment_id, pipeline_version, variant) +); + +CREATE TABLE outbox ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + job_id uuid NOT NULL REFERENCES attachments (job_id) ON DELETE CASCADE, + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE, + pipeline_version int NOT NULL CHECK (pipeline_version > 0), + attempt int NOT NULL CHECK (attempt > 0), + created_at timestamptz NOT NULL DEFAULT now(), + available_at timestamptz NOT NULL DEFAULT now(), + published_at timestamptz, + UNIQUE (job_id, pipeline_version, attempt) +); + +CREATE INDEX idx_outbox_pending ON outbox (available_at, id) WHERE published_at IS NULL; + +CREATE TABLE attachment_replays ( + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE, + attempt int NOT NULL CHECK (attempt > 0), + previous_error_code text, + operator text NOT NULL, + reason text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (attachment_id, attempt) +); + +-- +goose Down +DROP TABLE attachment_replays; +DROP TABLE outbox; +DROP TABLE attachment_variants; +DROP TYPE attachment_variant_name; +DROP INDEX idx_attachments_expired_lease; +ALTER TABLE attachments + DROP COLUMN height, + DROP COLUMN width, + DROP COLUMN lease_until, + DROP COLUMN retry_base, + DROP COLUMN attempts, + DROP COLUMN pipeline_version, + DROP COLUMN job_id, + DROP COLUMN staging_key; diff --git a/db/migrations/00005_outbox_trace.sql b/db/migrations/00005_outbox_trace.sql new file mode 100644 index 0000000..cf6eb55 --- /dev/null +++ b/db/migrations/00005_outbox_trace.sql @@ -0,0 +1,9 @@ +-- +goose Up +ALTER TABLE outbox + ADD COLUMN traceparent text NOT NULL DEFAULT '', + ADD COLUMN tracestate text NOT NULL DEFAULT ''; + +-- +goose Down +ALTER TABLE outbox + DROP COLUMN tracestate, + DROP COLUMN traceparent; \ No newline at end of file diff --git a/db/queries/attachment_replays.sql b/db/queries/attachment_replays.sql new file mode 100644 index 0000000..60044d1 --- /dev/null +++ b/db/queries/attachment_replays.sql @@ -0,0 +1,14 @@ +-- name: CreateAttachmentReplay :exec +INSERT INTO attachment_replays ( + attachment_id, + attempt, + previous_error_code, + operator, + reason +) VALUES ( + sqlc.arg(attachment_id), + sqlc.arg(attempt), + sqlc.narg(previous_error_code), + sqlc.arg(operator), + sqlc.arg(reason) +); diff --git a/db/queries/attachment_variants.sql b/db/queries/attachment_variants.sql new file mode 100644 index 0000000..6b38542 --- /dev/null +++ b/db/queries/attachment_variants.sql @@ -0,0 +1,28 @@ +-- name: CreateAttachmentVariant :exec +INSERT INTO attachment_variants ( + attachment_id, + pipeline_version, + variant, + s3_key, + content_type, + size_bytes, + width, + height, + sha256 +) VALUES ( + sqlc.arg(attachment_id), + sqlc.arg(pipeline_version), + sqlc.arg(variant), + sqlc.arg(s3_key), + sqlc.arg(content_type), + sqlc.arg(size_bytes), + sqlc.arg(width), + sqlc.arg(height), + sqlc.arg(sha256) +); + +-- name: ListAttachmentVariants :many +SELECT * FROM attachment_variants +WHERE attachment_id = sqlc.arg(attachment_id)::uuid + AND pipeline_version = sqlc.arg(pipeline_version)::int +ORDER BY variant; diff --git a/db/queries/attachments.sql b/db/queries/attachments.sql new file mode 100644 index 0000000..d0de5aa --- /dev/null +++ b/db/queries/attachments.sql @@ -0,0 +1,227 @@ +-- name: CreateAttachment :one +INSERT INTO attachments ( + id, + chat_id, + owner_id, + s3_key, + staging_key, + job_id, + filename, + content_type, + size_bytes, + sha256, + width, + height, + error_code +) +SELECT + sqlc.arg(id)::uuid, + sqlc.arg(chat_id)::uuid, + sqlc.arg(owner_id)::uuid, + sqlc.arg(s3_key)::text, + sqlc.arg(staging_key)::text, + sqlc.arg(job_id)::uuid, + sqlc.arg(filename)::text, + sqlc.arg(content_type)::attachment_content_type, + sqlc.arg(size_bytes)::int, + sqlc.arg(sha256)::text, + sqlc.arg(width)::int, + sqlc.arg(height)::int, + NULLIF(sqlc.arg(error_code)::text, '') +WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = sqlc.arg(chat_id) + AND user_id = sqlc.arg(owner_id) +) +RETURNING *; + +-- name: CreateMessageAttachment :exec +INSERT INTO message_attachments ( + message_id, + attachment_id, + position +) VALUES ( + sqlc.arg(message_id), + sqlc.arg(attachment_id), + sqlc.arg(position) +); + +-- name: GetAttachmentByID :one +SELECT * FROM attachments +WHERE id = $1::uuid; + +-- name: LockAttachmentByStagingKey :one +SELECT * FROM attachments +WHERE staging_key = sqlc.arg(staging_key)::text +FOR UPDATE; + +-- name: ListAttachmentsByIDs :many +SELECT status +FROM attachments +WHERE chat_id = sqlc.arg(chat_id)::uuid + AND id = ANY(sqlc.arg(ids)::uuid[]); + +-- name: ListMessageAttachmentIDs :many +SELECT attachment_id +FROM message_attachments +WHERE message_id = sqlc.arg(message_id)::uuid +ORDER BY position; + +-- name: ListMessageAttachmentsByMessageIDs :many +SELECT message_id, attachment_id +FROM message_attachments +WHERE message_id = ANY(sqlc.arg(message_ids)::uuid[]) +ORDER BY message_id, position; + +-- name: ListAttachmentsForReconcile :many +SELECT id, s3_key, staging_key, status, size_bytes, updated_at +FROM attachments; + +-- name: ListFailedAttachments :many +SELECT id, job_id, error_code, attempts, updated_at +FROM attachments +WHERE status = 'failed' +ORDER BY updated_at, id +LIMIT sqlc.arg(batch_size)::int; + +-- name: LockAttachmentJob :one +SELECT * FROM attachments +WHERE id = sqlc.arg(id)::uuid + AND status = 'processing' + AND job_id = sqlc.arg(job_id)::uuid + AND pipeline_version = sqlc.arg(pipeline_version)::int + AND attempts = sqlc.arg(attempt)::int + AND lease_until > now() +FOR UPDATE; + +-- name: LockExpiredAttachmentJobs :many +SELECT * FROM attachments +WHERE status = 'processing' + AND lease_until <= now() +ORDER BY lease_until, id +LIMIT sqlc.arg(batch_size)::int +FOR UPDATE SKIP LOCKED; + +-- name: LockFailedAttachmentForReplay :one +SELECT * FROM attachments +WHERE id = sqlc.arg(id)::uuid + AND status = 'failed' + AND staging_key IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM attachment_variants + WHERE attachment_id = attachments.id + ) +FOR UPDATE; + +-- name: LockAttachmentForUpgrade :one +SELECT * FROM attachments +WHERE id = sqlc.arg(id)::uuid + AND pipeline_version = 1 + AND status IN ('queued', 'processing') + AND staging_key IS NOT NULL +FOR UPDATE; + +-- name: ClearAttachmentStagingKey :exec +UPDATE attachments +SET staging_key = NULL +WHERE id = sqlc.arg(id)::uuid; + +-- name: MarkAttachmentFailedIfReady :execrows +UPDATE attachments +SET status = 'failed', + error_code = sqlc.arg(error_code)::text, + updated_at = now() +WHERE id = sqlc.arg(id)::uuid AND status = 'ready'; + +-- name: ClaimAttachmentJob :one +UPDATE attachments +SET status = 'processing', + attempts = attempts + 1, + lease_until = sqlc.arg(lease_until)::timestamptz, + updated_at = now() +WHERE id = sqlc.arg(id)::uuid + AND job_id = sqlc.arg(job_id)::uuid + AND pipeline_version = sqlc.arg(pipeline_version)::int + AND status = 'queued' + AND attempts + 1 = sqlc.arg(attempt)::int +RETURNING *; + +-- name: CompleteAttachmentJob :execrows +UPDATE attachments +SET status = 'ready', + error_code = NULL, + lease_until = NULL, + updated_at = now() +WHERE id = sqlc.arg(id)::uuid + AND status = 'processing' + AND attempts = sqlc.arg(attempt)::int + AND lease_until > now(); + +-- name: RetryAttachmentJob :execrows +UPDATE attachments +SET status = 'queued', + error_code = sqlc.arg(error_code)::text, + lease_until = NULL, + updated_at = now() +WHERE id = sqlc.arg(id)::uuid + AND status = 'processing' + AND attempts = sqlc.arg(attempt)::int + AND lease_until > now(); + +-- name: UpgradeAttachmentPipeline :execrows +UPDATE attachments +SET pipeline_version = 2, + status = 'queued', + retry_base = attempts, + error_code = NULL, + lease_until = NULL, + updated_at = now() +WHERE id = sqlc.arg(id)::uuid + AND pipeline_version = 1 + AND status IN ('queued', 'processing') + AND staging_key IS NOT NULL; + +-- name: ReplayAttachmentJob :execrows +UPDATE attachments +SET status = 'queued', + retry_base = attempts, + error_code = NULL, + lease_until = NULL, + updated_at = now() +WHERE id = sqlc.arg(id)::uuid + AND status = 'failed' + AND staging_key IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM attachment_variants + WHERE attachment_id = attachments.id + ); + +-- name: FailAttachmentJob :execrows +UPDATE attachments +SET status = 'failed', + error_code = sqlc.arg(error_code)::text, + lease_until = NULL, + updated_at = now() +WHERE id = sqlc.arg(id)::uuid + AND status = 'processing' + AND attempts = sqlc.arg(attempt)::int + AND lease_until > now(); + +-- name: RecoverExpiredAttachmentJob :execrows +UPDATE attachments +SET status = 'queued', + lease_until = NULL, + updated_at = now() +WHERE id = sqlc.arg(id)::uuid + AND status = 'processing' + AND lease_until <= now(); + +-- name: FailExpiredAttachmentJob :execrows +UPDATE attachments +SET status = 'failed', + error_code = 'retry_exhausted', + lease_until = NULL, + updated_at = now() +WHERE id = sqlc.arg(id)::uuid + AND status = 'processing' + AND lease_until <= now(); diff --git a/db/queries/chats.sql b/db/queries/chats.sql new file mode 100644 index 0000000..80d2ba3 --- /dev/null +++ b/db/queries/chats.sql @@ -0,0 +1,73 @@ +-- name: CreateChat :one +INSERT INTO chats ( + id, + title +) VALUES ( + sqlc.arg(id), + sqlc.arg(title) +) +RETURNING *; + +-- name: AddChatMembers :exec +INSERT INTO chat_members ( + chat_id, + user_id +) +SELECT + sqlc.arg(chat_id)::uuid, + unnest(sqlc.arg(user_ids)::uuid[]); + +-- name: IsChatMember :one +SELECT EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = sqlc.arg(chat_id) + AND user_id = sqlc.arg(user_id) +); + +-- name: GetChat :one +SELECT + c.*, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +WHERE c.id = sqlc.arg(id) + AND EXISTS ( + SELECT 1 FROM chat_members m + WHERE m.chat_id = c.id + AND m.user_id = sqlc.arg(user_id) + ); + +-- name: ListChatsFirstPage :many +SELECT + c.*, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +JOIN chat_members m ON m.chat_id = c.id +WHERE m.user_id = sqlc.arg(user_id) +ORDER BY c.created_at, c.id +LIMIT sqlc.arg(lim); + +-- name: ListChatsAfter :many +SELECT + c.*, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +JOIN chat_members m ON m.chat_id = c.id +WHERE m.user_id = sqlc.arg(user_id) + AND (c.created_at, c.id) > ( + sqlc.arg(after_created_at)::timestamptz, + sqlc.arg(after_id)::uuid + ) +ORDER BY c.created_at, c.id +LIMIT sqlc.arg(lim); diff --git a/db/queries/idempotency_keys.sql b/db/queries/idempotency_keys.sql new file mode 100644 index 0000000..9523927 --- /dev/null +++ b/db/queries/idempotency_keys.sql @@ -0,0 +1,36 @@ +-- name: CreateIdempotencyKey :execrows +INSERT INTO idempotency_keys ( + user_id, + method, + path, + key, + request_hash, + message_id +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(method), + sqlc.arg(path), + sqlc.arg(key), + sqlc.arg(request_hash), + sqlc.arg(message_id) +) +ON CONFLICT DO NOTHING; + +-- name: GetIdempotentMessage :one +SELECT + k.request_hash, + m.id, + m.chat_id, + m.sender_id, + m.text, + m.created_at +FROM idempotency_keys AS k +JOIN messages AS m ON m.id = k.message_id +WHERE k.user_id = sqlc.arg(user_id) + AND k.method = sqlc.arg(method) + AND k.path = sqlc.arg(path) + AND k.key = sqlc.arg(key); + +-- name: DeleteExpiredIdempotencyKeys :execrows +DELETE FROM idempotency_keys +WHERE created_at < sqlc.arg(cutoff); diff --git a/db/queries/messages.sql b/db/queries/messages.sql new file mode 100644 index 0000000..69635c4 --- /dev/null +++ b/db/queries/messages.sql @@ -0,0 +1,34 @@ +-- name: CreateMessage :one +INSERT INTO messages ( + id, + chat_id, + sender_id, + text +) +SELECT + sqlc.arg(id)::uuid, + sqlc.arg(chat_id)::uuid, + sqlc.arg(sender_id)::uuid, + sqlc.arg(text)::text +WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = sqlc.arg(chat_id) + AND user_id = sqlc.arg(sender_id) +) +RETURNING *; + +-- name: ListMessagesFirstPage :many +SELECT * FROM messages +WHERE chat_id = sqlc.arg(chat_id) +ORDER BY created_at, id +LIMIT sqlc.arg(lim); + +-- name: ListMessagesAfter :many +SELECT * FROM messages +WHERE chat_id = sqlc.arg(chat_id) + AND (created_at, id) > ( + sqlc.arg(after_created_at)::timestamptz, + sqlc.arg(after_id)::uuid + ) +ORDER BY created_at, id +LIMIT sqlc.arg(lim); diff --git a/db/queries/outbox.sql b/db/queries/outbox.sql new file mode 100644 index 0000000..70314ec --- /dev/null +++ b/db/queries/outbox.sql @@ -0,0 +1,36 @@ +-- name: CreateOutboxEntry :one +INSERT INTO outbox ( + job_id, + attachment_id, + pipeline_version, + attempt, + available_at, + traceparent, + tracestate +) +SELECT + job_id, + id, + pipeline_version, + sqlc.arg(attempt)::int, + sqlc.arg(available_at)::timestamptz, + sqlc.arg(traceparent)::text, + sqlc.arg(tracestate)::text +FROM attachments +WHERE id = sqlc.arg(attachment_id)::uuid + AND job_id IS NOT NULL +RETURNING *; + +-- name: LockPendingOutboxEntries :many +SELECT * FROM outbox +WHERE published_at IS NULL + AND available_at <= now() +ORDER BY available_at, id +LIMIT sqlc.arg(batch_size)::int +FOR UPDATE SKIP LOCKED; + +-- name: MarkOutboxPublished :execrows +UPDATE outbox +SET published_at = now() +WHERE id = sqlc.arg(id)::bigint + AND published_at IS NULL; diff --git a/db/queries/sessions.sql b/db/queries/sessions.sql new file mode 100644 index 0000000..065907f --- /dev/null +++ b/db/queries/sessions.sql @@ -0,0 +1,24 @@ +-- name: CreateSession :exec +INSERT INTO sessions ( + token_hash, + user_id, + expires_at +) VALUES ( + sqlc.arg(token_hash), + sqlc.arg(user_id), + sqlc.arg(expires_at) +); + +-- name: GetActiveSession :one +SELECT user_id, expires_at FROM sessions +WHERE token_hash = sqlc.arg(token_hash) + AND expires_at > now(); + +-- name: DeleteSession :execrows +DELETE FROM sessions +WHERE token_hash = sqlc.arg(token_hash) + AND expires_at > now(); + +-- name: DeleteExpiredSessions :execrows +DELETE FROM sessions +WHERE expires_at <= now(); diff --git a/db/queries/users.sql b/db/queries/users.sql new file mode 100644 index 0000000..fa0fbfb --- /dev/null +++ b/db/queries/users.sql @@ -0,0 +1,24 @@ +-- name: CreateUser :one +INSERT INTO users ( + id, + username, + display_name, + password_hash +) VALUES ( + sqlc.arg(id), + sqlc.arg(username), + sqlc.arg(display_name), + sqlc.arg(password_hash) +) +RETURNING id, username, display_name, created_at; + +-- name: GetUser :one +SELECT id, username, display_name, created_at FROM users +WHERE id = sqlc.arg(id); + +-- name: GetUserByUsername :one +SELECT * FROM users +WHERE username = sqlc.arg(username); + +-- name: UpdatePasswordHash :exec +UPDATE users SET password_hash = sqlc.arg(password_hash) WHERE id = sqlc.arg(id); diff --git a/evidence/README.md b/evidence/README.md index 8df7001..a36d3b3 100644 --- a/evidence/README.md +++ b/evidence/README.md @@ -1,5 +1,17 @@ -# Доказательства +# Evidence — lab7 grade 4 (Гавриленко БПИ2303) -Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки. +Артефакты проверок. Пути относительны к корню репозитория. -Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно. +| Файл | Описание | +| --- | --- | +| `make-check.txt` | `make check` (контракт skeleton) | +| `make-validate.txt` | `make validate` (OpenAPI) | +| `student-tests-offline.txt` | `go test -run 'Argon\|MTLSBroker\|MTLS'` (без API) | +| `make-test.txt` | `make test CA_FILE=secrets/ca.crt` | +| `make-test-security.txt` | `make test-security` | +| `make-grade4.txt` | `make grade4` | +| `persistence.txt` | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | +| `failover.txt` | `make test-failover ACTION_SCRIPT=scripts/restart.sh` | +| `rotate-leaf.txt` | `bash scripts/rotate-leaf.sh` | +| `scan-images.txt` | `bash scripts/scan-images.sh` | +| `https-ready.txt` | curl `/health/ready` через LB | \ No newline at end of file diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 0000000..feeece5 --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1 @@ +BLOCKED: requires running stack and ACTION_SCRIPT=scripts/restart.sh \ No newline at end of file diff --git a/evidence/https-ready.txt b/evidence/https-ready.txt new file mode 100644 index 0000000..13109c0 --- /dev/null +++ b/evidence/https-ready.txt @@ -0,0 +1 @@ +{"status":"ok"} diff --git a/evidence/make-check-validate.txt b/evidence/make-check-validate.txt new file mode 100644 index 0000000..9a3294c --- /dev/null +++ b/evidence/make-check-validate.txt @@ -0,0 +1,4 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +python3 scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. diff --git a/evidence/make-check.txt b/evidence/make-check.txt new file mode 100644 index 0000000..9a55330 --- /dev/null +++ b/evidence/make-check.txt @@ -0,0 +1,2 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/make-grade4-student-tests.txt b/evidence/make-grade4-student-tests.txt new file mode 100644 index 0000000..8df7877 --- /dev/null +++ b/evidence/make-grade4-student-tests.txt @@ -0,0 +1,7 @@ +--- FAIL: TestACLUnauthorizedChat (0.04s) + acl_test.go:9: POST /api/v1/users: request failed: Post "https://127.0.0.1:8443/api/v1/users": tls: failed to verify certificate: x509: certificate signed by unknown authority +--- FAIL: TestOpenBaoAppRole (0.00s) + openbao_test.go:22: openbao approle: openbao approle not bootstrapped +FAIL +FAIL gavrilenko-sxdees/lab7/student-tests 0.561s +FAIL diff --git a/evidence/make-grade4.txt b/evidence/make-grade4.txt new file mode 100644 index 0000000..edc6ad1 --- /dev/null +++ b/evidence/make-grade4.txt @@ -0,0 +1,10 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +python3 scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. +python3 tests/smoke.py --base-url "https://127.0.0.1:8443" --ca-file "secrets/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. +python3 tests/security.py --base-url "https://127.0.0.1:8443" --ca-file "secrets/ca.crt" +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. +go test ./student-tests/... -run 'MTLS|OpenBao|Argon|ACL' -count=1 -timeout=10m +ok gavrilenko-sxdees/lab7/student-tests 0.772s diff --git a/evidence/make-test-failover.txt b/evidence/make-test-failover.txt new file mode 100644 index 0000000..0e3e5d9 --- /dev/null +++ b/evidence/make-test-failover.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://127.0.0.1:8443" --ca-file "secrets/ca.crt" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 107, "failed_attempts": 1, "first_recovery_seconds": 2.833} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/make-test-persistence.txt b/evidence/make-test-persistence.txt new file mode 100644 index 0000000..fd28d3c --- /dev/null +++ b/evidence/make-test-persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "https://127.0.0.1:8443" --ca-file "secrets/ca.crt" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/make-test-security.txt b/evidence/make-test-security.txt new file mode 100644 index 0000000..5208c74 --- /dev/null +++ b/evidence/make-test-security.txt @@ -0,0 +1,2 @@ +python3 tests/security.py --base-url "https://127.0.0.1:8443" --ca-file "secrets/ca.crt" +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. diff --git a/evidence/make-test.txt b/evidence/make-test.txt new file mode 100644 index 0000000..04a2ec3 --- /dev/null +++ b/evidence/make-test.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://127.0.0.1:8443" --ca-file "secrets/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/make-validate.txt b/evidence/make-validate.txt new file mode 100644 index 0000000..683be25 --- /dev/null +++ b/evidence/make-validate.txt @@ -0,0 +1,2 @@ +python3 scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 0000000..feeece5 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1 @@ +BLOCKED: requires running stack and ACTION_SCRIPT=scripts/restart.sh \ No newline at end of file diff --git a/evidence/rotate-leaf.txt b/evidence/rotate-leaf.txt new file mode 100644 index 0000000..1a1e90f --- /dev/null +++ b/evidence/rotate-leaf.txt @@ -0,0 +1,12 @@ +Generating RSA private key, 2048 bit long modulus +.........................................................................................................................................................+++++ +...............................................................................+++++ +e is 65537 (0x10001) +Signature ok +subject=/C=RU/O=MTUSI/OU=lab7/CN=lb.messenger.lab +Getting CA Private Key + Container gavrilenko-lab7-lb-1 Recreate + Container gavrilenko-lab7-lb-1 Recreated + Container gavrilenko-lab7-lb-1 Starting + Container gavrilenko-lab7-lb-1 Started +LB leaf rotated diff --git a/evidence/scan-images.txt b/evidence/scan-images.txt new file mode 100644 index 0000000..ea820eb --- /dev/null +++ b/evidence/scan-images.txt @@ -0,0 +1,13 @@ +=== gavrilenko-lab7 image scan 2026-12-02T19:50:00Z === + +Compose images (pinned, project gavrilenko-lab7): +- gavrilenko-api:lab7 / gavrilenko-worker:lab7 / gavrilenko-migrate:lab7 (distroless runtime) +- haproxy:2.9.14-alpine, rabbitmq:3.13.7-alpine, postgres:16.6, redis:7.4.1-alpine +- quay.io/openbao/openbao:2.1.0, otel/opentelemetry-collector-contrib:0.128.0 +- grafana/grafana:12.0.2, grafana/loki:3.5.1, grafana/tempo:2.8.0, prom/prometheus:v3.4.1 +- chrislusf/seaweedfs:4.51 + +Triage: `docker scout quickview` not available in this environment (CLI printed help only). +Operator action: re-run `bash scripts/scan-images.sh` after `docker scout` is installed, or audit CVEs via Docker Desktop / registry advisories per security/THREAT_MODEL.md. + +PASS: image list captured; scan tooling deferred (non-blocking per script). \ No newline at end of file diff --git a/evidence/student-tests-offline.txt b/evidence/student-tests-offline.txt new file mode 100644 index 0000000..49b9ec7 --- /dev/null +++ b/evidence/student-tests-offline.txt @@ -0,0 +1 @@ +ok gavrilenko-sxdees/lab7/student-tests 0.358s diff --git a/evidence/student-tests.txt b/evidence/student-tests.txt new file mode 100644 index 0000000..7526c71 --- /dev/null +++ b/evidence/student-tests.txt @@ -0,0 +1,7 @@ +--- FAIL: TestACLUnauthorizedChat (0.00s) + acl_test.go:9: POST /api/v1/users: request failed: Post "https://127.0.0.1:8443/api/v1/users": dial tcp 127.0.0.1:8443: connect: connection refused +--- FAIL: TestOpenBaoAppRole (0.00s) + openbao_test.go:22: openbao approle: openbao approle not bootstrapped +FAIL +FAIL gavrilenko-sxdees/lab7/student-tests 0.504s +FAIL diff --git a/examples/requests.http b/examples/requests.http index c578132..052497b 100644 --- a/examples/requests.http +++ b/examples/requests.http @@ -1,7 +1,7 @@ # Optional HTTP-client worksheet; no extension is required by the course. # Replace IDs/token locally from real responses; do not commit filled-in credentials. # Canonical API: contracts/openapi.json and contracts/README.md. -@baseUrl = https://localhost:8443 +@baseUrl = http://localhost:8080 @aliceId = REPLACE_WITH_CREATED_ALICE_UUID @bobId = REPLACE_WITH_CREATED_BOB_UUID @chatId = REPLACE_WITH_CREATED_CHAT_UUID diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..3d0dd44 --- /dev/null +++ b/go.mod @@ -0,0 +1,69 @@ +module gavrilenko-sxdees/lab7 + +go 1.26.0 + +require ( + github.com/aws/aws-sdk-go-v2 v1.47.5 + github.com/aws/aws-sdk-go-v2/config v1.33.13 + github.com/aws/aws-sdk-go-v2/credentials v1.20.13 + github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6 + github.com/aws/smithy-go v1.28.7 + github.com/disintegration/imaging v1.6.2 + github.com/gen2brain/webp v0.6.4 + github.com/go-chi/chi/v5 v5.5.0 + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.11.0 + github.com/joho/godotenv v1.5.1 + github.com/rabbitmq/amqp091-go v1.10.0 + github.com/redis/go-redis/v9 v9.23.0 + go.opentelemetry.io/contrib/bridges/otelslog v0.21.0 + go.opentelemetry.io/otel v1.47.0 + go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 + go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 + go.opentelemetry.io/otel/metric v1.47.0 + go.opentelemetry.io/otel/sdk v1.47.0 + go.opentelemetry.io/otel/sdk/log v1.47.0 + go.opentelemetry.io/otel/sdk/metric v1.47.0 + go.opentelemetry.io/otel/trace v1.47.0 + golang.org/x/crypto v0.58.0 + golang.org/x/image v0.48.0 +) + +require ( + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.9 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.12.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.39.1 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/ebitengine/purego v0.10.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 + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/proto/otlp v1.11.0 // indirect + go.uber.org/atomic v1.12.0 // indirect + golang.org/x/net v0.60.0 // indirect + golang.org/x/sync v0.25.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/text v0.44.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect + google.golang.org/grpc v1.83.2 // indirect + google.golang.org/protobuf v1.36.12 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..75a06e5 --- /dev/null +++ b/go.sum @@ -0,0 +1,154 @@ +github.com/aws/aws-sdk-go-v2 v1.47.5 h1:5yA+A+BiXbDq1ZLbYwPViwhEGDMdR0MEhL8Jh2LnLS4= +github.com/aws/aws-sdk-go-v2 v1.47.5/go.mod h1:iNIkogrRvFwm+1OQIUOP2lPBtlXZboOIUWiCa+pHEMw= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 h1:MW0Iql1SOTgQPj8mCxrU/eH/K/AIDWi08ItOsXaWRLU= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25/go.mod h1:+ucVYmHYB3JqVueY0E1RHahdXAnKQbIHqybSbvOUbOM= +github.com/aws/aws-sdk-go-v2/config v1.33.13 h1:u52x6ISQOx172tpwM0VRxhJzEsTJYpMcEYUGM2A1wrw= +github.com/aws/aws-sdk-go-v2/config v1.33.13/go.mod h1:/ixtz6XPHb42zekjQ0LqD9XjTpTysNWhIGwufY1OzI4= +github.com/aws/aws-sdk-go-v2/credentials v1.20.13 h1:j4z41OtspmQ3ftQycaDunJ26b69a9SHfaSVUPqgRv8k= +github.com/aws/aws-sdk-go-v2/credentials v1.20.13/go.mod h1:SgPA1oS3b+dlMxZb618jDmGNscpXSCaxz15igS52OlE= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 h1:iXjy2SFhGYNB1jWZBhQqq8HbhsbPF23w+/zbMvPXsTg= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5/go.mod h1:k0RUiBnyXU0AXRJ9tJmY2jQke6XUIX2PNVnWtvgaPtc= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 h1:gzIWc3DTPfPbWKrQnmL6BV6WD7NPD1htxzgdk/bQ/Z4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8/go.mod h1:vvUA5cDAZWGo4R14FZPZfXfJCmgsafOWEq78Kg0D+ug= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 h1:PWv+vG8aCLS8qd+HPdYhK7Vees90aKHWFFQ1AGYD/8E= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8/go.mod h1:xxPZEpflYHJA12366ZGyq66z9dHPCoeCIu99Jck+MPw= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 h1:WOp5De9iWdEHDPh2Kb0tBP3vGBm/dVAuRGh4a4tqduo= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8/go.mod h1:z8W8YgfhbWl62XqcTtK+CxPrE+iHGRVUOtrrbIOp7ZY= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 h1:MCIR6iZaCKO4UE0hUvoWWLI6JVjppopV64JfAJaMjng= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23/go.mod h1:pphWFS+z0MmIPivj8c/6bATd1Z+Av7Ust75DPdEFsPA= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.9 h1:GACgECI422Xt5n4Pojr3O0aocPv8lfH4PJe2Aon5Wv8= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.9/go.mod h1:lPfnRkHpn1qWZJLbVEw10rIqSuCee1pNQTyGkUjAYh8= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 h1:+PMpWlJYOn2tm7sm6OZ/ZLd4jStl17T7wjNapd1Rczs= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8/go.mod h1:cnG3xZLGQL4c/bt8pjdzlFtZsW7epBBuNS04a5xMjdo= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8 h1:RS1Wt+K0r4X0ci9Vf4JYTUfHzsQihYA2LgGJeEneKpk= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8/go.mod h1:adMnTy5kyoUW86jhXnGSVc/mvMQI4GZd1qYWMeaS8M8= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6 h1:to7+Vr3rLkpYRwVKJ5QRriI0eE306vrVN/6TnVHgxvY= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6/go.mod h1:Jc89ASa2k7HMAskj3bSnt8bf+k+p2IApzkoXnEjkgUw= +github.com/aws/aws-sdk-go-v2/service/signin v1.12.1 h1:WZLC+k/CZx11kZGQDqu9mpA8yhiXGX2I//jhuJE1FDo= +github.com/aws/aws-sdk-go-v2/service/signin v1.12.1/go.mod h1:wxAk0D2oVBSjuXEIzvcKxTZfM90zticdAbh/VD42L0Y= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.1 h1:4VB/dnDo7pmXSLQMszSoBzWndENuc7mzwTpD6lQn77A= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.1/go.mod h1:UGsEYgWz4Gi+46vDQ5zkFLqUgJziyOE2SXjZjgmfmHc= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1 h1:w8yui2ZqdHmGwVBDGvazoIvKw/DnLENBLkYnN8q8iqo= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1/go.mod h1:gJSdIY6YUzDvqQLcMtPVZgBRHrFwzHryvpE8Igzbxps= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw= +github.com/aws/smithy-go v1.28.7 h1:h/n1SHrwVtaDYLz8mR1/Kq4Xh4RaFbFW7bOYckg9mfE= +github.com/aws/smithy-go v1.28.7/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +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/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c= +github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4= +github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= +github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= +github.com/gen2brain/webp v0.6.4 h1:SUDdmxADOAiPQ+5ylNmuHhuYf2dOi0KgKZHL5vpVCNU= +github.com/gen2brain/webp v0.6.4/go.mod h1:iGWMaCSw7t3I/Cv9llzEKmpnR36S8lS8VL/ZVjxU0JE= +github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg= +github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM= +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/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw= +github.com/rabbitmq/amqp091-go v1.10.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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +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.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +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/contrib/bridges/otelslog v0.21.0 h1:/CdgE52i1OEPHhsGUqrggYNRaZy4v4YgVenGd52dRBI= +go.opentelemetry.io/contrib/bridges/otelslog v0.21.0/go.mod h1:9pBdbVbuehIDzxN4accnzzxEUPT8Nq7grbZMo+J1VN4= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 h1:5WVp40k2fJHuc5BtNTgKk+EugKFT8Eg3lywFfCPI/nE= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0/go.mod h1:59nH0RYCGHRlwt15WyioeSYINBbuObeBpTowPhEKWHY= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 h1:7kszRN4Ze5GeAkUnBjBSUIunVBMA+mZIG04auueqguM= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0/go.mod h1:CLzakYy8jOdkBfcveCWYkeKJxujcF4xPhh2Z7IfE98U= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= +go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM= +go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= +go.opentelemetry.io/otel/sdk/log v1.47.0 h1:W4N/ZfgpkRRnmARnqYoQ6BrWA0mrj8IzVDNLlpmUJZY= +go.opentelemetry.io/otel/sdk/log v1.47.0/go.mod h1:Wu74Z2EmOKXi2FleSNAb0Hyau2G+r5kubSEMJw5aAMs= +go.opentelemetry.io/otel/sdk/log/logtest v0.23.0 h1:j3pm42QCrKYYLLkI6OrV1QHFkUfDA6/4EP+Y1PzggLg= +go.opentelemetry.io/otel/sdk/log/logtest v0.23.0/go.mod h1:zt0gEnuTZgDvqvczHwYswz93eqMaIr6upTTsdV/HUlU= +go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= +go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= +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.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/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.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik= +golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +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-20260928230214-8a89bd6388cc h1:rZHRz0ogq4Pid1IKtA/ivHi8XONVF5tqUQXA2TtgpkE= +google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:K/n0XLazCJHjD73YuMyNJsN38BPPy1kfFnKxUXaThFU= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +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/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/infra/broker-gw/haproxy.cfg b/infra/broker-gw/haproxy.cfg new file mode 100644 index 0000000..d015bd9 --- /dev/null +++ b/infra/broker-gw/haproxy.cfg @@ -0,0 +1,19 @@ +global + maxconn 256 + +defaults + mode tcp + timeout connect 5s + timeout client 120s + timeout server 120s + +frontend amqps_in + bind *:5671 ssl crt /run/secrets/broker_gw_pem ca-file /run/secrets/ca_cert verify required + acl broker_api ssl_c_s_dn(CN) -m str messenger-api-broker + acl broker_worker ssl_c_s_dn(CN) -m str messenger-worker-broker + tcp-request session reject if !broker_api !broker_worker + default_backend rabbit + +backend rabbit + server rmq rabbitmq:5672 check inter 2s fall 3 rise 1 + diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 0000000..e209386 --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,102 @@ +{ + "uid": "gavrilenko-messenger-lab6", + "title": "Messenger lab6 (Gavrilenko)", + "schemaVersion": 39, + "version": 1, + "refresh": "5s", + "time": { "from": "now-15m", "to": "now" }, + "panels": [ + { + "id": 1, + "title": "HTTP RPS by status class", + "type": "timeseries", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "x": 0, "y": 0, "w": 12, "h": 8 }, + "targets": [ + { + "expr": "sum by (status_class) (rate(http_server_requests_total{service_name=\"messenger-api\",route!~\"/health.*\"}[30s]))", + "legendFormat": "{{status_class}}" + } + ], + "fieldConfig": { "defaults": { "unit": "reqps" } } + }, + { + "id": 2, + "title": "API p50/p95/p99 (histogram)", + "type": "timeseries", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "x": 12, "y": 0, "w": 12, "h": 8 }, + "targets": [ + { "expr": "histogram_quantile(0.50, sum(rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health.*\"}[1m])) by (le))", "legendFormat": "p50" }, + { "expr": "histogram_quantile(0.95, sum(rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health.*\"}[1m])) by (le))", "legendFormat": "p95" }, + { "expr": "histogram_quantile(0.99, sum(rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health.*\"}[1m])) by (le))", "legendFormat": "p99" } + ], + "fieldConfig": { "defaults": { "unit": "s" } } + }, + { + "id": 3, + "title": "HAProxy 5xx ratio", + "type": "timeseries", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "x": 0, "y": 8, "w": 8, "h": 8 }, + "targets": [ + { + "expr": "sum(rate(haproxy_backend_http_responses_total{proxy=\"replicas\",code=\"5xx\"}[30s])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy=\"replicas\"}[30s])), 0.001)", + "legendFormat": "5xx ratio" + } + ] + }, + { + "id": 4, + "title": "Queue depth / oldest age (s)", + "type": "timeseries", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "x": 8, "y": 8, "w": 8, "h": 8 }, + "targets": [ + { "expr": "max(messenger_queue_depth)", "legendFormat": "depth" }, + { "expr": "max(messenger_queue_oldest_age_seconds)", "legendFormat": "oldest age" } + ] + }, + { + "id": 5, + "title": "DB pool & worker saturation", + "type": "timeseries", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "x": 16, "y": 8, "w": 8, "h": 8 }, + "targets": [ + { "expr": "max(messenger_db_pool_used)", "legendFormat": "pool used" }, + { "expr": "max(messenger_db_pool_limit)", "legendFormat": "pool limit" }, + { "expr": "max(messenger_worker_busy)", "legendFormat": "worker busy" }, + { "expr": "max(messenger_worker_capacity)", "legendFormat": "worker capacity" } + ] + }, + { + "id": 6, + "title": "Job outcomes", + "type": "timeseries", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "x": 0, "y": 16, "w": 12, "h": 8 }, + "targets": [ + { + "expr": "sum by (outcome) (rate(messenger_jobs_total{service_name=\"messenger-worker\"}[30s]))", + "legendFormat": "{{outcome}}" + } + ], + "fieldConfig": { "defaults": { "unit": "reqps" } } + }, + { + "id": 7, + "title": "Time to ready p95", + "type": "timeseries", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "x": 12, "y": 16, "w": 12, "h": 8 }, + "targets": [ + { + "expr": "histogram_quantile(0.95, sum(rate(messenger_attachment_ready_duration_seconds_bucket{service_name=\"messenger-worker\"}[1m])) by (le))", + "legendFormat": "p95 ready" + } + ], + "fieldConfig": { "defaults": { "unit": "s" } } + } + ] +} \ No newline at end of file diff --git a/infra/grafana/provisioning/dashboards/default.yaml b/infra/grafana/provisioning/dashboards/default.yaml new file mode 100644 index 0000000..6b39805 --- /dev/null +++ b/infra/grafana/provisioning/dashboards/default.yaml @@ -0,0 +1,10 @@ +apiVersion: 1 +providers: + - name: messenger + orgId: 1 + folder: "" + type: file + disableDeletion: false + updateIntervalSeconds: 30 + options: + path: /var/lib/grafana/dashboards \ No newline at end of file diff --git a/infra/grafana/provisioning/datasources/sources.yaml b/infra/grafana/provisioning/datasources/sources.yaml new file mode 100644 index 0000000..5190980 --- /dev/null +++ b/infra/grafana/provisioning/datasources/sources.yaml @@ -0,0 +1,23 @@ +apiVersion: 1 +datasources: + - name: Prometheus + type: prometheus + uid: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + - name: Loki + type: loki + uid: loki + access: proxy + url: http://loki:3100 + - name: Tempo + type: tempo + uid: tempo + access: proxy + url: http://tempo:3200 + jsonData: + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: -1m + spanEndTimeShift: 1m \ No newline at end of file diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 0000000..48f1fe1 --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,54 @@ +global + log stdout format raw local0 + maxconn 512 + +defaults + log global + mode http + option httplog + option dontlognull + timeout connect 5s + timeout client 60s + timeout server 60s + timeout check 3s + timeout http-keep-alive 10s + retries 2 + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 2s + +frontend fe_https + bind *:8443 ssl crt /run/secrets/public_pem alpn h2,http/1.1 + maxconn 256 + http-request set-header X-Forwarded-Proto https + use_backend readiness if { path_beg /health/ } + default_backend replicas + +backend replicas + balance roundrobin + option httpchk + option redispatch + option http-server-close + http-check send meth GET uri /health/ready ver TLS + http-check expect status 200 + server api1 api:8080 ssl verify required ca-file /run/secrets/ca_cert crt /run/secrets/lb_client_pem sni str(api.messenger.lab) alpn h2,http/1.1 resolvers docker init-addr libc,none + server api2 api:8080 ssl verify required ca-file /run/secrets/ca_cert crt /run/secrets/lb_client_pem sni str(api.messenger.lab) alpn h2,http/1.1 resolvers docker init-addr libc,none + +backend readiness + balance roundrobin + option httpchk + option http-server-close + http-check send meth GET uri /health/ready ver TLS + http-check expect status 200 + default-server ssl verify required ca-file /run/secrets/ca_cert crt /run/secrets/lb_client_pem sni str(api.messenger.lab) alpn http/1.1 + server api1 api:8080 resolvers docker init-addr libc,none + server api2 api:8080 resolvers docker init-addr libc,none + +frontend metrics + bind *:8404 + http-request use-service prometheus-exporter if { path /metrics } + diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml new file mode 100644 index 0000000..203a406 --- /dev/null +++ b/infra/loki/loki.yaml @@ -0,0 +1,37 @@ +auth_enabled: false +server: + http_listen_port: 3100 +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory +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: 24h + otlp_config: + resource_attributes: + attributes_config: + - action: structured_metadata + attributes: [service.instance.id] +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem +analytics: + reporting_enabled: false \ No newline at end of file diff --git a/infra/openbao/config.hcl b/infra/openbao/config.hcl new file mode 100644 index 0000000..2281757 --- /dev/null +++ b/infra/openbao/config.hcl @@ -0,0 +1,16 @@ +ui = false +disable_mlock = true + +storage "file" { + path = "/openbao/data" +} + +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/run/secrets/openbao_server_cert" + tls_key_file = "/run/secrets/openbao_server_key" + tls_client_ca_file = "/run/secrets/ca_cert" +} + +api_addr = "https://openbao:8200" +cluster_addr = "https://openbao:8201" \ No newline at end of file diff --git a/infra/openbao/policies/api.hcl b/infra/openbao/policies/api.hcl new file mode 100644 index 0000000..ab8068f --- /dev/null +++ b/infra/openbao/policies/api.hcl @@ -0,0 +1,6 @@ +path "secret/data/messenger/api/*" { + capabilities = ["read"] +} +path "secret/metadata/messenger/api/*" { + capabilities = ["read", "list"] +} \ No newline at end of file diff --git a/infra/openbao/policies/worker.hcl b/infra/openbao/policies/worker.hcl new file mode 100644 index 0000000..44a619f --- /dev/null +++ b/infra/openbao/policies/worker.hcl @@ -0,0 +1,6 @@ +path "secret/data/messenger/worker/*" { + capabilities = ["read"] +} +path "secret/metadata/messenger/worker/*" { + capabilities = ["read", "list"] +} \ No newline at end of file diff --git a/infra/otel/collector-tls.yaml b/infra/otel/collector-tls.yaml new file mode 100644 index 0000000..ce3fef2 --- /dev/null +++ b/infra/otel/collector-tls.yaml @@ -0,0 +1,48 @@ +receivers: + otlp: + protocols: + grpc: {endpoint: 0.0.0.0:4317} + http: + endpoint: 0.0.0.0:4318 + tls: + cert_file: /run/secrets/otel_server_cert + key_file: /run/secrets/otel_server_key + client_ca_file: /run/secrets/ca_cert +processors: + memory_limiter: + check_interval: 1s + limit_mib: 180 + spike_limit_mib: 40 + batch: + timeout: 1s + send_batch_size: 128 + send_batch_max_size: 256 +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + resource_to_telemetry_conversion: + enabled: true + otlphttp/tempo: + endpoint: http://tempo:4318 + timeout: 2s + otlphttp/loki: + endpoint: http://loki:3100/otlp + timeout: 2s +extensions: + health_check: + endpoint: 0.0.0.0:13133 +service: + extensions: [health_check] + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] \ No newline at end of file diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 0000000..f6c547a --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,70 @@ +receivers: + otlp: + protocols: + grpc: {endpoint: 0.0.0.0:4317} + http: {endpoint: 0.0.0.0:4318} +processors: + memory_limiter: + check_interval: 1s + limit_mib: 180 + spike_limit_mib: 40 + batch: + timeout: 1s + send_batch_size: 128 + send_batch_max_size: 256 +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + resource_to_telemetry_conversion: + enabled: true + otlphttp/tempo: + endpoint: http://tempo:4318 + timeout: 2s + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 15s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 64 + otlphttp/loki: + endpoint: http://loki:3100/otlp + timeout: 2s + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 15s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 64 +extensions: + health_check: + endpoint: 0.0.0.0:13133 +service: + telemetry: + metrics: + level: detailed + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 + extensions: [health_check] + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] \ No newline at end of file diff --git a/infra/prometheus/alerts.yaml b/infra/prometheus/alerts.yaml new file mode 100644 index 0000000..17b15ed --- /dev/null +++ b/infra/prometheus/alerts.yaml @@ -0,0 +1,29 @@ +groups: + - name: messenger_slo + interval: 2s + rules: + - alert: APIHighErrorRate + expr: (sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[30s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[30s])), 0.001) > 0.1 + for: 6s + labels: + severity: warning + annotations: + summary: API 5xx above 10% for 30s + runbook: DEFENSE.md#incident-db + - alert: QueueLag + expr: max(messenger_queue_oldest_age_seconds) > 5 and max(messenger_queue_depth) > 0 + for: 6s + labels: + severity: warning + annotations: + summary: Oldest pipeline job exceeds 5s + runbook: DEFENSE.md#incident-worker + - alert: ReadyBudgetFastBurn + expr: (sum(rate(messenger_attachment_sli_bad_total[10s])) / clamp_min(sum(rate(messenger_attachment_sli_total[10s])), 0.001) > 6 * 0.05) and (sum(rate(messenger_attachment_sli_bad_total[60s])) / clamp_min(sum(rate(messenger_attachment_sli_total[60s])), 0.001) > 6 * 0.05) + for: 10s + labels: + severity: critical + slo: ready_95 + annotations: + summary: Ready deadline budget burn >6x in 10s and 60s + runbook: DEFENSE.md#incident-worker \ No newline at end of file diff --git a/infra/prometheus/prometheus.yaml b/infra/prometheus/prometheus.yaml new file mode 100644 index 0000000..e4a05cb --- /dev/null +++ b/infra/prometheus/prometheus.yaml @@ -0,0 +1,15 @@ +global: + scrape_interval: 2s + evaluation_interval: 2s +rule_files: + - /etc/prometheus/alerts.yaml +scrape_configs: + - job_name: messenger + static_configs: + - targets: [collector:8889] + - job_name: collector_self + static_configs: + - targets: [collector:8888] + - job_name: ingress + static_configs: + - targets: [lb:8404] \ No newline at end of file diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml new file mode 100644 index 0000000..781efea --- /dev/null +++ b/infra/tempo/tempo.yaml @@ -0,0 +1,25 @@ +server: + http_listen_port: 3200 +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 +ingester: + trace_idle_period: 2s + max_block_duration: 5m +compactor: + compaction: + block_retention: 24h +storage: + trace: + backend: local + local: + path: /var/tempo/blocks + wal: + path: /var/tempo/wal +usage_report: + reporting_enabled: false \ No newline at end of file diff --git a/internal/app/app.go b/internal/app/app.go new file mode 100644 index 0000000..b162b2a --- /dev/null +++ b/internal/app/app.go @@ -0,0 +1,202 @@ +package app + +import ( + "context" + "fmt" + "net/http" + "os" + "os/signal" + "sync" + "syscall" + "time" + + "github.com/joho/godotenv" + + goredis "github.com/redis/go-redis/v9" + + "gavrilenko-sxdees/lab7/internal/config" + "gavrilenko-sxdees/lab7/internal/openbao" + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/outbox" + "gavrilenko-sxdees/lab7/internal/postgres" + "gavrilenko-sxdees/lab7/internal/redis" + s3store "gavrilenko-sxdees/lab7/internal/s3" + "gavrilenko-sxdees/lab7/internal/service" + "gavrilenko-sxdees/lab7/internal/telemetry" + "gavrilenko-sxdees/lab7/internal/tlslisten" +) + +func Run() error { + if err := godotenv.Load(); err != nil && !os.IsNotExist(err) { + return err + } + + cfg := config.Load() + + baoCtx, baoCancel := context.WithTimeout(context.Background(), 8*time.Second) + if err := openbao.VerifyAppRole(baoCtx, "api"); err != nil && os.Getenv("BAO_REQUIRED") != "false" { + baoCancel() + return fmt.Errorf("openbao service auth: %w", err) + } + baoCancel() + + serviceName := os.Getenv("OTEL_SERVICE_NAME") + if serviceName == "" { + serviceName = "messenger-api" + } + log, shutdownTelemetry, err := telemetry.Init(context.Background(), serviceName) + if err != nil { + return err + } + defer shutdownTelemetry() + log = log.With("instance_id", cfg.Server.InstanceID) + + dbURL, err := cfg.Database.URL() + if err != nil { + log.Error("read database url", "error", err) + return err + } + + pool, err := postgres.New(context.Background(), dbURL) + if err != nil { + log.Error("connect to database", "error", err) + return err + } + defer pool.Close() + telemetry.RegisterPoolObservers(pool, false) + + queries := db.New(pool) + + var rdb *goredis.Client + if cfg.UseCache() { + cacheURL, err := cfg.Redis.URL() + if err != nil { + log.Error("read redis url", "error", err) + return err + } + + rdb, err = redis.New(context.Background(), log, cacheURL) + if err != nil { + log.Error("create redis client", "error", err) + return err + } + defer rdb.Close() + } + + log.Info("session store configured", "store", cfg.SessionStore) + + s3Client, err := s3store.New(context.Background(), cfg.S3, log) + if err != nil { + log.Error("create s3 client", "error", err) + return err + } + + ensureCtx, cancelEnsure := context.WithTimeout(context.Background(), 10*time.Second) + err = s3Client.EnsureBucket(ensureCtx) + cancelEnsure() + if err != nil { + log.Error("ensure s3 bucket", "error", err) + return err + } + + log.Info("s3 storage ready", "endpoint", cfg.S3.Endpoint, "bucket", s3Client.Bucket()) + + brokerURL, err := cfg.Broker.URL() + if err != nil { + log.Error("read broker url", "error", err) + return err + } + publisher := outbox.NewPublisher(pool, brokerURL, log) + + backgroundCtx, stopBackground := context.WithCancel(context.Background()) + var backgroundWG sync.WaitGroup + backgroundWG.Go(func() { + publisher.Run(backgroundCtx) + }) + backgroundWG.Go(func() { + runSessionCleanup(backgroundCtx, log, queries, sessionCleanupInterval) + }) + backgroundWG.Go(func() { + runIdempotencyCleanup(backgroundCtx, log, queries, cfg.Server.IdempotencyTTL, idempotencyCleanupInterval) + }) + + defer func() { + stopBackground() + backgroundWG.Wait() + }() + + authService := service.NewAuthService(queries, rdb, cfg.Server.SessionTTL, log) + userService := service.NewUserService(queries) + chatService := service.NewChatService(pool, queries) + messageService := service.NewMessageService(pool, queries) + attachmentService := service.NewAttachmentService(pool, queries, s3Client, cfg.S3.MaxUploadBytes, cfg.S3.MaxImagePixels) + + router := NewRouter( + log, + cfg.Server.InstanceID, + cfg.Server.MaxInflightRequests, + cfg.S3.MaxUploadBytes, + rdb, + pool, + s3Client, + authService, + userService, + chatService, + messageService, + attachmentService, + ) + + server := &http.Server{ + Addr: cfg.Server.Host + ":" + cfg.Server.Port, + Handler: router, + } + + serverErrors := make(chan error, 1) + + go func() { + log.Info("server starting", "addr", server.Addr) + if tlslisten.TLSEnabled() { + tlsCfg, terr := tlslisten.LoadServerTLS( + cfg.Server.TLSCertFile, + cfg.Server.TLSKeyFile, + cfg.Server.TLSCAFile, + cfg.Server.TLSClientSAN, + ) + if terr != nil { + serverErrors <- terr + return + } + serverErrors <- tlslisten.ListenAndServeTLS(server, tlsCfg) + return + } + serverErrors <- server.ListenAndServe() + }() + + signalCh := make(chan os.Signal, 1) + signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM) + defer signal.Stop(signalCh) + + select { + case err := <-serverErrors: + if err == http.ErrServerClosed { + return nil + } + + log.Error("server failed", "error", err) + return err + + case sig := <-signalCh: + log.Info("shutdown signal received", "signal", sig.String()) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + if err := server.Shutdown(ctx); err != nil { + log.Error("server shutdown failed", "error", err) + return err + } + + log.Info("server stopped") + return nil + } +} diff --git a/internal/app/cleanup.go b/internal/app/cleanup.go new file mode 100644 index 0000000..ece69dd --- /dev/null +++ b/internal/app/cleanup.go @@ -0,0 +1,72 @@ +package app + +import ( + "context" + "log/slog" + "time" +) + +const ( + sessionCleanupInterval = time.Hour + idempotencyCleanupInterval = time.Hour +) + +type sessionCleaner interface { + DeleteExpiredSessions(ctx context.Context) (int64, error) +} + +type idempotencyCleaner interface { + DeleteExpiredIdempotencyKeys(ctx context.Context, cutoff time.Time) (int64, error) +} + +func runSessionCleanup(ctx context.Context, log *slog.Logger, q sessionCleaner, interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + n, err := q.DeleteExpiredSessions(ctx) + if err != nil { + if ctx.Err() == nil { + log.Error("delete expired sessions", "error", err) + } + continue + } + if n > 0 { + log.Info("expired sessions deleted", "count", n) + } + } + } +} + +func runIdempotencyCleanup( + ctx context.Context, + log *slog.Logger, + q idempotencyCleaner, + ttl time.Duration, + interval time.Duration, +) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + n, err := q.DeleteExpiredIdempotencyKeys(ctx, time.Now().Add(-ttl)) + if err != nil { + if ctx.Err() == nil { + log.Error("delete expired idempotency keys", "error", err) + } + continue + } + if n > 0 { + log.Info("expired idempotency keys deleted", "count", n) + } + } + } +} diff --git a/internal/app/healthcheck.go b/internal/app/healthcheck.go new file mode 100644 index 0000000..8b03fbb --- /dev/null +++ b/internal/app/healthcheck.go @@ -0,0 +1,65 @@ +package app + +import ( + "context" + "fmt" + "net/http" + "os" + "time" + + "gavrilenko-sxdees/lab7/internal/config" + "gavrilenko-sxdees/lab7/internal/tlslisten" + + "github.com/joho/godotenv" +) + +func Healthcheck() int { + if err := godotenv.Load(); err != nil && !os.IsNotExist(err) { + fmt.Fprintln(os.Stderr, "healthcheck: load env:", err) + return 1 + } + + cfg := config.Load() + scheme := "http" + if tlslisten.TLSEnabled() { + scheme = "https" + } + url := fmt.Sprintf("%s://localhost:%s/health/ready", scheme, cfg.Server.Port) + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + fmt.Fprintln(os.Stderr, "healthcheck: build request:", err) + return 1 + } + + client := http.DefaultClient + if tlslisten.TLSEnabled() { + hc, herr := tlslisten.ClientHTTP( + os.Getenv("TLS_HEALTH_CLIENT_CERT"), + os.Getenv("TLS_HEALTH_CLIENT_KEY"), + cfg.Server.TLSCAFile, + ) + if herr != nil { + fmt.Fprintln(os.Stderr, "healthcheck: tls client:", herr) + return 1 + } + client = hc + } + + resp, err := client.Do(req) + if err != nil { + fmt.Fprintln(os.Stderr, "healthcheck: request failed:", err) + return 1 + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + fmt.Fprintln(os.Stderr, "healthcheck: unexpected status", resp.StatusCode) + return 1 + } + + return 0 +} diff --git a/internal/app/router.go b/internal/app/router.go new file mode 100644 index 0000000..940bc54 --- /dev/null +++ b/internal/app/router.go @@ -0,0 +1,77 @@ +package app + +import ( + "log/slog" + "net/http" + "time" + + "github.com/go-chi/chi/v5" + goredis "github.com/redis/go-redis/v9" + + "gavrilenko-sxdees/lab7/internal/handler" + "gavrilenko-sxdees/lab7/internal/middleware" + "gavrilenko-sxdees/lab7/internal/service" +) + +func NewRouter( + log *slog.Logger, + instanceID string, + maxInflightRequests int, + maxUploadBytes int, + sessionCache *goredis.Client, + db handler.Pinger, + storage handler.Pinger, + authService *service.AuthService, + userService *service.UserService, + chatService *service.ChatService, + messageService *service.MessageService, + attachmentService *service.AttachmentService, +) http.Handler { + router := chi.NewRouter() + + loginLimiter := middleware.NewLoginLimiter(sessionCache) + + healthHandler := handler.NewHealthHandler(log, db, storage) + authHandler := handler.NewAuthHandler(authService) + userHandler := handler.NewUserHandler(userService) + chatHandler := handler.NewChatHandler(chatService) + messageHandler := handler.NewMessageHandler(messageService) + attachmentHandler := handler.NewAttachmentHandler(attachmentService, maxUploadBytes) + + router.Use(middleware.InstanceID(instanceID)) + router.Use(middleware.Telemetry()) + router.Use(middleware.RequestTimeout(5 * time.Second)) + router.Use(middleware.RequestID) + router.Use(middleware.Logging(log)) + router.Use(middleware.ConcurrencyLimit(maxInflightRequests)) + + router.Get("/health/live", healthHandler.Live) + router.Get("/health/ready", healthHandler.Ready) + + router.Post("/api/v1/users", userHandler.Create) + + router.With(loginLimiter.Limit).Post("/api/v1/auth/sessions", authHandler.CreateSession) + router.Delete("/api/v1/auth/sessions/current", authHandler.RevokeSession) + + router.Group(func(r chi.Router) { + r.Use(middleware.Auth(authService)) + + r.Get("/api/v1/users/me", userHandler.Me) + + r.Post("/api/v1/chats", chatHandler.Create) + r.Get("/api/v1/chats", chatHandler.List) + r.Get("/api/v1/chats/{chat_id}", chatHandler.Get) + + r.Post("/api/v1/chats/{chat_id}/messages", messageHandler.Create) + r.Get("/api/v1/chats/{chat_id}/messages", messageHandler.List) + + r.Post("/api/v1/chats/{chat_id}/attachments", attachmentHandler.Upload) + r.Get("/api/v1/attachments/{attachment_id}", attachmentHandler.Get) + r.Get("/api/v1/attachments/{attachment_id}/content", attachmentHandler.GetContent) + }) + + router.Handle("/swagger/*", http.StripPrefix("/swagger/", http.FileServer(http.Dir("web/swagger")))) + router.Handle("/contracts/*", http.StripPrefix("/contracts/", http.FileServer(http.Dir("contracts")))) + + return router +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..18acf03 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,267 @@ +package config + +import ( + "fmt" + "log" + "log/slog" + "os" + "strconv" + "strings" + "time" +) + +const ( + SessionStorePostgres = "postgres" + SessionStoreRedis = "redis" +) + +type Config struct { + Server ServerConfig + Logging LoggingConfig + Database DatabaseConfig + Redis RedisConfig + Broker BrokerConfig + S3 S3Config + SessionStore string +} + +func (c Config) UseCache() bool { + return c.SessionStore == SessionStoreRedis +} + +type ServerConfig struct { + Host string + Port string + MaxInflightRequests int + SessionTTL time.Duration + IdempotencyTTL time.Duration + InstanceID string + TLSCertFile string + TLSKeyFile string + TLSCAFile string + TLSClientSAN string +} + +type LoggingConfig struct { + Level slog.Level +} + +type DatabaseConfig struct { + URLFile string +} + +func (c DatabaseConfig) URL() (string, error) { + return readSecretFile(c.URLFile) +} + +type RedisConfig struct { + URLFile string +} + +func (c RedisConfig) URL() (string, error) { + return readSecretFile(c.URLFile) +} + +type BrokerConfig struct { + URLFile string +} + +func (c BrokerConfig) URL() (string, error) { + return readSecretFile(c.URLFile) +} + +type S3Config struct { + Endpoint string + Region string + Bucket string + APIAccessKeyFile string + APISecretKeyFile string + BootstrapAccessKeyFile string + BootstrapSecretKeyFile string + MaxUploadBytes int + MaxImagePixels int + StagingRetention time.Duration +} + +func (c S3Config) APIAccessKey() (string, error) { + return readSecretFile(c.APIAccessKeyFile) +} + +func (c S3Config) APISecretKey() (string, error) { + return readSecretFile(c.APISecretKeyFile) +} + +func (c S3Config) BootstrapAccessKey() (string, error) { + return readSecretFile(c.BootstrapAccessKeyFile) +} + +func (c S3Config) BootstrapSecretKey() (string, error) { + return readSecretFile(c.BootstrapSecretKeyFile) +} + +func Load() Config { + return Config{ + Server: ServerConfig{ + Host: getEnv("APP_HOST", "0.0.0.0"), + Port: getEnv("APP_PORT", "8080"), + MaxInflightRequests: getEnvNonNegativeInt("MAX_INFLIGHT_REQUESTS", 0), + SessionTTL: time.Duration(getEnvPositiveInt("SESSION_TTL_SECONDS", 3600)) * time.Second, + IdempotencyTTL: time.Duration(getEnvPositiveInt("IDEMPOTENCY_TTL_SECONDS", 86400)) * time.Second, + InstanceID: getInstanceID("INSTANCE_ID"), + TLSCertFile: getEnv("TLS_CERT_FILE", ""), + TLSKeyFile: getEnv("TLS_KEY_FILE", ""), + TLSCAFile: getEnv("TLS_CA_FILE", ""), + TLSClientSAN: getEnv("TLS_CLIENT_SAN", "lb.messenger.lab"), + }, + + Logging: LoggingConfig{ + Level: getEnvLogLevel("LOG_LEVEL", slog.LevelInfo), + }, + + Database: DatabaseConfig{ + URLFile: getEnv("DATABASE_URL_FILE", "/run/secrets/database_url"), + }, + + Redis: RedisConfig{ + URLFile: getEnv("CACHE_URL_FILE", "/run/secrets/cache_url"), + }, + + Broker: BrokerConfig{ + URLFile: getEnv("BROKER_URL_FILE", "/run/secrets/broker_url"), + }, + + S3: LoadS3(), + + SessionStore: getEnvSessionStore("SESSION_STORE", SessionStorePostgres), + } +} + +func LoadS3() S3Config { + return S3Config{ + Endpoint: getEnv("S3_ENDPOINT", "http://s3:9000"), + Region: getEnv("S3_REGION", "us-east-1"), + Bucket: getEnv("S3_BUCKET", "messenger-attachments"), + APIAccessKeyFile: getEnv("S3_ACCESS_KEY_ID_FILE", "/run/secrets/s3_access_key_id"), + APISecretKeyFile: getEnv("S3_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_secret_access_key"), + BootstrapAccessKeyFile: getEnv("S3_BOOTSTRAP_ACCESS_KEY_ID_FILE", "/run/secrets/s3_bootstrap_access_key_id"), + BootstrapSecretKeyFile: getEnv("S3_BOOTSTRAP_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_bootstrap_secret_access_key"), + MaxUploadBytes: getEnvPositiveInt("MAX_UPLOAD_BYTES", 10485760), + MaxImagePixels: getEnvPositiveInt("MAX_IMAGE_PIXELS", 40000000), + StagingRetention: time.Duration(getEnvPositiveInt("STAGING_RETENTION_SECONDS", 86400)) * time.Second, + } +} + +type WorkerConfig struct { + Concurrency int + MaxAttempts int + Timeout time.Duration +} + +func LoadWorker() WorkerConfig { + return WorkerConfig{ + Concurrency: getEnvPositiveInt("WORKER_CONCURRENCY", 2), + MaxAttempts: getEnvPositiveInt("JOB_MAX_ATTEMPTS", 5), + Timeout: time.Duration(getEnvPositiveInt("JOB_TIMEOUT_SECONDS", 60)) * time.Second, + } +} + +func getEnv(key, def string) string { + value := os.Getenv(key) + if value == "" { + return def + } + + return value +} + +func getEnvNonNegativeInt(key string, def int) int { + v := os.Getenv(key) + if v == "" { + return def + } + + value, err := strconv.Atoi(v) + if err != nil || value < 0 { + log.Printf("invalid non-negative int for %s=%q, using default %d", key, v, def) + return def + } + + return value +} + +func getEnvPositiveInt(key string, def int) int { + v := os.Getenv(key) + if v == "" { + return def + } + + value, err := strconv.Atoi(v) + if err != nil || value <= 0 { + log.Printf("invalid positive int for %s=%q, using default %d", key, v, def) + return def + } + + return value +} + +func getEnvLogLevel(key string, def slog.Level) slog.Level { + v := os.Getenv(key) + + switch v { + case "DEBUG": + return slog.LevelDebug + case "INFO": + return slog.LevelInfo + case "WARN": + return slog.LevelWarn + case "ERROR": + return slog.LevelError + case "": + return def + default: + log.Printf("invalid log level for %s=%q, using default %s", key, v, def) + return def + } +} + +func readSecretFile(path string) (string, error) { + b, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("read secret file %s: %w", path, err) + } + + value := strings.TrimSpace(string(b)) + if value == "" { + return "", fmt.Errorf("secret file %s is empty", path) + } + + return value, nil +} + +func getEnvSessionStore(key, def string) string { + v := strings.ToLower(os.Getenv(key)) + + switch v { + case "": + return def + case SessionStorePostgres, SessionStoreRedis: + return v + default: + log.Printf("invalid session store for %s=%q, using default %s", key, v, def) + return def + } +} + +func getInstanceID(key string) string { + if v := os.Getenv(key); v != "" { + return v + } + + host, err := os.Hostname() + if err != nil || host == "" { + log.Printf("cannot determine hostname, using \"unknown\" for %s: %v", key, err) + return "unknown" + } + + return host +} diff --git a/internal/credentials/credentials.go b/internal/credentials/credentials.go new file mode 100644 index 0000000..7b6665e --- /dev/null +++ b/internal/credentials/credentials.go @@ -0,0 +1,157 @@ +package credentials + +import ( + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "os" + "strconv" + "strings" + + "golang.org/x/crypto/argon2" + "golang.org/x/crypto/bcrypt" +) + +const tokenSize = 32 + +var ( + ErrPasswordMismatch = errors.New("password mismatch") + defaultMemoryKiB = 19456 + defaultIterations = 2 + defaultParallelism = 1 + defaultSaltLen = 16 + defaultKeyLen = 32 +) + +func init() { + if v := os.Getenv("ARGON2_MEMORY_KIB"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + defaultMemoryKiB = n + } + } + if v := os.Getenv("ARGON2_ITERATIONS"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + defaultIterations = n + } + } + if v := os.Getenv("ARGON2_PARALLELISM"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + defaultParallelism = n + } + } +} + +var dummyHash, _ = HashPassword("dummy-password-for-timing") + +func DummyVerify(plain string) { + _ = VerifyPassword(dummyHash, plain) +} + +func HashPassword(plain string) (string, error) { + salt := make([]byte, defaultSaltLen) + if _, err := rand.Read(salt); err != nil { + return "", err + } + hash := argon2.IDKey([]byte(plain), salt, uint32(defaultIterations), uint32(defaultMemoryKiB), uint8(defaultParallelism), uint32(defaultKeyLen)) + b64Salt := base64.RawStdEncoding.EncodeToString(salt) + b64Hash := base64.RawStdEncoding.EncodeToString(hash) + return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s", + defaultMemoryKiB, defaultIterations, defaultParallelism, b64Salt, b64Hash), nil +} + +func VerifyPassword(encoded, plain string) error { + if strings.HasPrefix(encoded, "$argon2id$") { + return verifyArgon2id(encoded, plain) + } + err := bcrypt.CompareHashAndPassword([]byte(encoded), prehashBcrypt(plain)) + if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) { + return ErrPasswordMismatch + } + return err +} + +func NeedsRehash(encoded string) bool { + if !strings.HasPrefix(encoded, "$argon2id$") { + return true + } + mem, iter, par, ok := parseArgon2Params(encoded) + if !ok { + return true + } + return mem != defaultMemoryKiB || iter != defaultIterations || par != defaultParallelism +} + +func verifyArgon2id(encoded, plain string) error { + mem, iter, par, ok := parseArgon2Params(encoded) + if !ok { + return fmt.Errorf("invalid argon2 hash") + } + parts := strings.Split(encoded, "$") + if len(parts) != 6 { + return fmt.Errorf("invalid argon2 hash") + } + salt, err := base64.RawStdEncoding.DecodeString(parts[4]) + if err != nil { + return err + } + want, err := base64.RawStdEncoding.DecodeString(parts[5]) + if err != nil { + return err + } + got := argon2.IDKey([]byte(plain), salt, uint32(iter), uint32(mem), uint8(par), uint32(len(want))) + if subtle.ConstantTimeCompare(got, want) != 1 { + return ErrPasswordMismatch + } + return nil +} + +func parseArgon2Params(encoded string) (memory, iterations, parallelism int, ok bool) { + idx := strings.Index(encoded, "$m=") + if idx < 0 { + return 0, 0, 0, false + } + rest := encoded[idx+1:] + fields := strings.Split(rest, "$") + if len(fields) < 1 { + return 0, 0, 0, false + } + for _, part := range strings.Split(fields[0], ",") { + kv := strings.SplitN(part, "=", 2) + if len(kv) != 2 { + continue + } + n, err := strconv.Atoi(kv[1]) + if err != nil { + return 0, 0, 0, false + } + switch kv[0] { + case "m": + memory = n + case "t": + iterations = n + case "p": + parallelism = n + } + } + return memory, iterations, parallelism, memory > 0 && iterations > 0 && parallelism > 0 +} + +func prehashBcrypt(plain string) []byte { + sum := sha256.Sum256([]byte(plain)) + return []byte(base64.StdEncoding.EncodeToString(sum[:])) +} + +func NewToken() string { + raw := make([]byte, tokenSize) + _, _ = rand.Read(raw) + return base64.RawURLEncoding.EncodeToString(raw) +} + +func HashToken(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} \ No newline at end of file diff --git a/internal/db/attachment_replays.sql.go b/internal/db/attachment_replays.sql.go new file mode 100644 index 0000000..088dfd5 --- /dev/null +++ b/internal/db/attachment_replays.sql.go @@ -0,0 +1,47 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: attachment_replays.sql + +package db + +import ( + "context" + + "github.com/google/uuid" +) + +const createAttachmentReplay = `-- name: CreateAttachmentReplay :exec +INSERT INTO attachment_replays ( + attachment_id, + attempt, + previous_error_code, + operator, + reason +) VALUES ( + $1, + $2, + $3, + $4, + $5 +) +` + +type CreateAttachmentReplayParams struct { + AttachmentID uuid.UUID + Attempt int + PreviousErrorCode *string + Operator string + Reason string +} + +func (q *Queries) CreateAttachmentReplay(ctx context.Context, arg CreateAttachmentReplayParams) error { + _, err := q.db.Exec(ctx, createAttachmentReplay, + arg.AttachmentID, + arg.Attempt, + arg.PreviousErrorCode, + arg.Operator, + arg.Reason, + ) + return err +} diff --git a/internal/db/attachment_variants.sql.go b/internal/db/attachment_variants.sql.go new file mode 100644 index 0000000..b6b2236 --- /dev/null +++ b/internal/db/attachment_variants.sql.go @@ -0,0 +1,105 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: attachment_variants.sql + +package db + +import ( + "context" + + "github.com/google/uuid" +) + +const createAttachmentVariant = `-- name: CreateAttachmentVariant :exec +INSERT INTO attachment_variants ( + attachment_id, + pipeline_version, + variant, + s3_key, + content_type, + size_bytes, + width, + height, + sha256 +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8, + $9 +) +` + +type CreateAttachmentVariantParams struct { + AttachmentID uuid.UUID + PipelineVersion int + Variant AttachmentVariantName + S3Key string + ContentType string + SizeBytes int + Width int + Height int + Sha256 string +} + +func (q *Queries) CreateAttachmentVariant(ctx context.Context, arg CreateAttachmentVariantParams) error { + _, err := q.db.Exec(ctx, createAttachmentVariant, + arg.AttachmentID, + arg.PipelineVersion, + arg.Variant, + arg.S3Key, + arg.ContentType, + arg.SizeBytes, + arg.Width, + arg.Height, + arg.Sha256, + ) + return err +} + +const listAttachmentVariants = `-- name: ListAttachmentVariants :many +SELECT attachment_id, pipeline_version, variant, s3_key, content_type, size_bytes, sha256, width, height FROM attachment_variants +WHERE attachment_id = $1::uuid + AND pipeline_version = $2::int +ORDER BY variant +` + +type ListAttachmentVariantsParams struct { + AttachmentID uuid.UUID + PipelineVersion int +} + +func (q *Queries) ListAttachmentVariants(ctx context.Context, arg ListAttachmentVariantsParams) ([]AttachmentVariant, error) { + rows, err := q.db.Query(ctx, listAttachmentVariants, arg.AttachmentID, arg.PipelineVersion) + if err != nil { + return nil, err + } + defer rows.Close() + items := []AttachmentVariant{} + for rows.Next() { + var i AttachmentVariant + if err := rows.Scan( + &i.AttachmentID, + &i.PipelineVersion, + &i.Variant, + &i.S3Key, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Width, + &i.Height, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/db/attachments.sql.go b/internal/db/attachments.sql.go new file mode 100644 index 0000000..31bed3f --- /dev/null +++ b/internal/db/attachments.sql.go @@ -0,0 +1,799 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: attachments.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const claimAttachmentJob = `-- name: ClaimAttachmentJob :one +UPDATE attachments +SET status = 'processing', + attempts = attempts + 1, + lease_until = $1::timestamptz, + updated_at = now() +WHERE id = $2::uuid + AND job_id = $3::uuid + AND pipeline_version = $4::int + AND status = 'queued' + AND attempts + 1 = $5::int +RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until +` + +type ClaimAttachmentJobParams struct { + LeaseUntil time.Time + ID uuid.UUID + JobID uuid.UUID + PipelineVersion int + Attempt int +} + +func (q *Queries) ClaimAttachmentJob(ctx context.Context, arg ClaimAttachmentJobParams) (Attachment, error) { + row := q.db.QueryRow(ctx, claimAttachmentJob, + arg.LeaseUntil, + arg.ID, + arg.JobID, + arg.PipelineVersion, + arg.Attempt, + ) + var i Attachment + err := row.Scan( + &i.ID, + &i.ChatID, + &i.OwnerID, + &i.S3Key, + &i.Filename, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Status, + &i.ErrorCode, + &i.CreatedAt, + &i.UpdatedAt, + &i.StagingKey, + &i.JobID, + &i.PipelineVersion, + &i.Attempts, + &i.RetryBase, + &i.Width, + &i.Height, + &i.LeaseUntil, + ) + return i, err +} + +const clearAttachmentStagingKey = `-- name: ClearAttachmentStagingKey :exec +UPDATE attachments +SET staging_key = NULL +WHERE id = $1::uuid +` + +func (q *Queries) ClearAttachmentStagingKey(ctx context.Context, id uuid.UUID) error { + _, err := q.db.Exec(ctx, clearAttachmentStagingKey, id) + return err +} + +const completeAttachmentJob = `-- name: CompleteAttachmentJob :execrows +UPDATE attachments +SET status = 'ready', + error_code = NULL, + lease_until = NULL, + updated_at = now() +WHERE id = $1::uuid + AND status = 'processing' + AND attempts = $2::int + AND lease_until > now() +` + +type CompleteAttachmentJobParams struct { + ID uuid.UUID + Attempt int +} + +func (q *Queries) CompleteAttachmentJob(ctx context.Context, arg CompleteAttachmentJobParams) (int64, error) { + result, err := q.db.Exec(ctx, completeAttachmentJob, arg.ID, arg.Attempt) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const createAttachment = `-- name: CreateAttachment :one +INSERT INTO attachments ( + id, + chat_id, + owner_id, + s3_key, + staging_key, + job_id, + filename, + content_type, + size_bytes, + sha256, + width, + height, + error_code +) +SELECT + $1::uuid, + $2::uuid, + $3::uuid, + $4::text, + $5::text, + $6::uuid, + $7::text, + $8::attachment_content_type, + $9::int, + $10::text, + $11::int, + $12::int, + NULLIF($13::text, '') +WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = $2 + AND user_id = $3 +) +RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until +` + +type CreateAttachmentParams struct { + ID uuid.UUID + ChatID uuid.UUID + OwnerID uuid.UUID + S3Key string + StagingKey string + JobID uuid.UUID + Filename string + ContentType AttachmentContentType + SizeBytes int + Sha256 string + Width int + Height int + ErrorCode string +} + +func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) { + row := q.db.QueryRow(ctx, createAttachment, + arg.ID, + arg.ChatID, + arg.OwnerID, + arg.S3Key, + arg.StagingKey, + arg.JobID, + arg.Filename, + arg.ContentType, + arg.SizeBytes, + arg.Sha256, + arg.Width, + arg.Height, + arg.ErrorCode, + ) + var i Attachment + err := row.Scan( + &i.ID, + &i.ChatID, + &i.OwnerID, + &i.S3Key, + &i.Filename, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Status, + &i.ErrorCode, + &i.CreatedAt, + &i.UpdatedAt, + &i.StagingKey, + &i.JobID, + &i.PipelineVersion, + &i.Attempts, + &i.RetryBase, + &i.Width, + &i.Height, + &i.LeaseUntil, + ) + return i, err +} + +const createMessageAttachment = `-- name: CreateMessageAttachment :exec +INSERT INTO message_attachments ( + message_id, + attachment_id, + position +) VALUES ( + $1, + $2, + $3 +) +` + +type CreateMessageAttachmentParams struct { + MessageID uuid.UUID + AttachmentID uuid.UUID + Position int +} + +func (q *Queries) CreateMessageAttachment(ctx context.Context, arg CreateMessageAttachmentParams) error { + _, err := q.db.Exec(ctx, createMessageAttachment, arg.MessageID, arg.AttachmentID, arg.Position) + return err +} + +const failAttachmentJob = `-- name: FailAttachmentJob :execrows +UPDATE attachments +SET status = 'failed', + error_code = $1::text, + lease_until = NULL, + updated_at = now() +WHERE id = $2::uuid + AND status = 'processing' + AND attempts = $3::int + AND lease_until > now() +` + +type FailAttachmentJobParams struct { + ErrorCode string + ID uuid.UUID + Attempt int +} + +func (q *Queries) FailAttachmentJob(ctx context.Context, arg FailAttachmentJobParams) (int64, error) { + result, err := q.db.Exec(ctx, failAttachmentJob, arg.ErrorCode, arg.ID, arg.Attempt) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const failExpiredAttachmentJob = `-- name: FailExpiredAttachmentJob :execrows +UPDATE attachments +SET status = 'failed', + error_code = 'retry_exhausted', + lease_until = NULL, + updated_at = now() +WHERE id = $1::uuid + AND status = 'processing' + AND lease_until <= now() +` + +func (q *Queries) FailExpiredAttachmentJob(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, failExpiredAttachmentJob, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getAttachmentByID = `-- name: GetAttachmentByID :one +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments +WHERE id = $1::uuid +` + +func (q *Queries) GetAttachmentByID(ctx context.Context, dollar_1 uuid.UUID) (Attachment, error) { + row := q.db.QueryRow(ctx, getAttachmentByID, dollar_1) + var i Attachment + err := row.Scan( + &i.ID, + &i.ChatID, + &i.OwnerID, + &i.S3Key, + &i.Filename, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Status, + &i.ErrorCode, + &i.CreatedAt, + &i.UpdatedAt, + &i.StagingKey, + &i.JobID, + &i.PipelineVersion, + &i.Attempts, + &i.RetryBase, + &i.Width, + &i.Height, + &i.LeaseUntil, + ) + return i, err +} + +const listAttachmentsByIDs = `-- name: ListAttachmentsByIDs :many +SELECT status +FROM attachments +WHERE chat_id = $1::uuid + AND id = ANY($2::uuid[]) +` + +type ListAttachmentsByIDsParams struct { + ChatID uuid.UUID + Ids []uuid.UUID +} + +func (q *Queries) ListAttachmentsByIDs(ctx context.Context, arg ListAttachmentsByIDsParams) ([]AttachmentStatus, error) { + rows, err := q.db.Query(ctx, listAttachmentsByIDs, arg.ChatID, arg.Ids) + if err != nil { + return nil, err + } + defer rows.Close() + items := []AttachmentStatus{} + for rows.Next() { + var status AttachmentStatus + if err := rows.Scan(&status); err != nil { + return nil, err + } + items = append(items, status) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listAttachmentsForReconcile = `-- name: ListAttachmentsForReconcile :many +SELECT id, s3_key, staging_key, status, size_bytes, updated_at +FROM attachments +` + +type ListAttachmentsForReconcileRow struct { + ID uuid.UUID + S3Key string + StagingKey *string + Status AttachmentStatus + SizeBytes int + UpdatedAt time.Time +} + +func (q *Queries) ListAttachmentsForReconcile(ctx context.Context) ([]ListAttachmentsForReconcileRow, error) { + rows, err := q.db.Query(ctx, listAttachmentsForReconcile) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListAttachmentsForReconcileRow{} + for rows.Next() { + var i ListAttachmentsForReconcileRow + if err := rows.Scan( + &i.ID, + &i.S3Key, + &i.StagingKey, + &i.Status, + &i.SizeBytes, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listFailedAttachments = `-- name: ListFailedAttachments :many +SELECT id, job_id, error_code, attempts, updated_at +FROM attachments +WHERE status = 'failed' +ORDER BY updated_at, id +LIMIT $1::int +` + +type ListFailedAttachmentsRow struct { + ID uuid.UUID + JobID *uuid.UUID + ErrorCode *string + Attempts int + UpdatedAt time.Time +} + +func (q *Queries) ListFailedAttachments(ctx context.Context, batchSize int) ([]ListFailedAttachmentsRow, error) { + rows, err := q.db.Query(ctx, listFailedAttachments, batchSize) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListFailedAttachmentsRow{} + for rows.Next() { + var i ListFailedAttachmentsRow + if err := rows.Scan( + &i.ID, + &i.JobID, + &i.ErrorCode, + &i.Attempts, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listMessageAttachmentIDs = `-- name: ListMessageAttachmentIDs :many +SELECT attachment_id +FROM message_attachments +WHERE message_id = $1::uuid +ORDER BY position +` + +func (q *Queries) ListMessageAttachmentIDs(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) { + rows, err := q.db.Query(ctx, listMessageAttachmentIDs, messageID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []uuid.UUID{} + for rows.Next() { + var attachment_id uuid.UUID + if err := rows.Scan(&attachment_id); err != nil { + return nil, err + } + items = append(items, attachment_id) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listMessageAttachmentsByMessageIDs = `-- name: ListMessageAttachmentsByMessageIDs :many +SELECT message_id, attachment_id +FROM message_attachments +WHERE message_id = ANY($1::uuid[]) +ORDER BY message_id, position +` + +type ListMessageAttachmentsByMessageIDsRow struct { + MessageID uuid.UUID + AttachmentID uuid.UUID +} + +func (q *Queries) ListMessageAttachmentsByMessageIDs(ctx context.Context, messageIds []uuid.UUID) ([]ListMessageAttachmentsByMessageIDsRow, error) { + rows, err := q.db.Query(ctx, listMessageAttachmentsByMessageIDs, messageIds) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListMessageAttachmentsByMessageIDsRow{} + for rows.Next() { + var i ListMessageAttachmentsByMessageIDsRow + if err := rows.Scan(&i.MessageID, &i.AttachmentID); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const lockAttachmentByStagingKey = `-- name: LockAttachmentByStagingKey :one +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments +WHERE staging_key = $1::text +FOR UPDATE +` + +func (q *Queries) LockAttachmentByStagingKey(ctx context.Context, stagingKey string) (Attachment, error) { + row := q.db.QueryRow(ctx, lockAttachmentByStagingKey, stagingKey) + var i Attachment + err := row.Scan( + &i.ID, + &i.ChatID, + &i.OwnerID, + &i.S3Key, + &i.Filename, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Status, + &i.ErrorCode, + &i.CreatedAt, + &i.UpdatedAt, + &i.StagingKey, + &i.JobID, + &i.PipelineVersion, + &i.Attempts, + &i.RetryBase, + &i.Width, + &i.Height, + &i.LeaseUntil, + ) + return i, err +} + +const lockAttachmentForUpgrade = `-- name: LockAttachmentForUpgrade :one +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments +WHERE id = $1::uuid + AND pipeline_version = 1 + AND status IN ('queued', 'processing') + AND staging_key IS NOT NULL +FOR UPDATE +` + +func (q *Queries) LockAttachmentForUpgrade(ctx context.Context, id uuid.UUID) (Attachment, error) { + row := q.db.QueryRow(ctx, lockAttachmentForUpgrade, id) + var i Attachment + err := row.Scan( + &i.ID, + &i.ChatID, + &i.OwnerID, + &i.S3Key, + &i.Filename, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Status, + &i.ErrorCode, + &i.CreatedAt, + &i.UpdatedAt, + &i.StagingKey, + &i.JobID, + &i.PipelineVersion, + &i.Attempts, + &i.RetryBase, + &i.Width, + &i.Height, + &i.LeaseUntil, + ) + return i, err +} + +const lockAttachmentJob = `-- name: LockAttachmentJob :one +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments +WHERE id = $1::uuid + AND status = 'processing' + AND job_id = $2::uuid + AND pipeline_version = $3::int + AND attempts = $4::int + AND lease_until > now() +FOR UPDATE +` + +type LockAttachmentJobParams struct { + ID uuid.UUID + JobID uuid.UUID + PipelineVersion int + Attempt int +} + +func (q *Queries) LockAttachmentJob(ctx context.Context, arg LockAttachmentJobParams) (Attachment, error) { + row := q.db.QueryRow(ctx, lockAttachmentJob, + arg.ID, + arg.JobID, + arg.PipelineVersion, + arg.Attempt, + ) + var i Attachment + err := row.Scan( + &i.ID, + &i.ChatID, + &i.OwnerID, + &i.S3Key, + &i.Filename, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Status, + &i.ErrorCode, + &i.CreatedAt, + &i.UpdatedAt, + &i.StagingKey, + &i.JobID, + &i.PipelineVersion, + &i.Attempts, + &i.RetryBase, + &i.Width, + &i.Height, + &i.LeaseUntil, + ) + return i, err +} + +const lockExpiredAttachmentJobs = `-- name: LockExpiredAttachmentJobs :many +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments +WHERE status = 'processing' + AND lease_until <= now() +ORDER BY lease_until, id +LIMIT $1::int +FOR UPDATE SKIP LOCKED +` + +func (q *Queries) LockExpiredAttachmentJobs(ctx context.Context, batchSize int) ([]Attachment, error) { + rows, err := q.db.Query(ctx, lockExpiredAttachmentJobs, batchSize) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Attachment{} + for rows.Next() { + var i Attachment + if err := rows.Scan( + &i.ID, + &i.ChatID, + &i.OwnerID, + &i.S3Key, + &i.Filename, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Status, + &i.ErrorCode, + &i.CreatedAt, + &i.UpdatedAt, + &i.StagingKey, + &i.JobID, + &i.PipelineVersion, + &i.Attempts, + &i.RetryBase, + &i.Width, + &i.Height, + &i.LeaseUntil, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const lockFailedAttachmentForReplay = `-- name: LockFailedAttachmentForReplay :one +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments +WHERE id = $1::uuid + AND status = 'failed' + AND staging_key IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM attachment_variants + WHERE attachment_id = attachments.id + ) +FOR UPDATE +` + +func (q *Queries) LockFailedAttachmentForReplay(ctx context.Context, id uuid.UUID) (Attachment, error) { + row := q.db.QueryRow(ctx, lockFailedAttachmentForReplay, id) + var i Attachment + err := row.Scan( + &i.ID, + &i.ChatID, + &i.OwnerID, + &i.S3Key, + &i.Filename, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Status, + &i.ErrorCode, + &i.CreatedAt, + &i.UpdatedAt, + &i.StagingKey, + &i.JobID, + &i.PipelineVersion, + &i.Attempts, + &i.RetryBase, + &i.Width, + &i.Height, + &i.LeaseUntil, + ) + return i, err +} + +const markAttachmentFailedIfReady = `-- name: MarkAttachmentFailedIfReady :execrows +UPDATE attachments +SET status = 'failed', + error_code = $1::text, + updated_at = now() +WHERE id = $2::uuid AND status = 'ready' +` + +type MarkAttachmentFailedIfReadyParams struct { + ErrorCode string + ID uuid.UUID +} + +func (q *Queries) MarkAttachmentFailedIfReady(ctx context.Context, arg MarkAttachmentFailedIfReadyParams) (int64, error) { + result, err := q.db.Exec(ctx, markAttachmentFailedIfReady, arg.ErrorCode, arg.ID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const recoverExpiredAttachmentJob = `-- name: RecoverExpiredAttachmentJob :execrows +UPDATE attachments +SET status = 'queued', + lease_until = NULL, + updated_at = now() +WHERE id = $1::uuid + AND status = 'processing' + AND lease_until <= now() +` + +func (q *Queries) RecoverExpiredAttachmentJob(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, recoverExpiredAttachmentJob, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const replayAttachmentJob = `-- name: ReplayAttachmentJob :execrows +UPDATE attachments +SET status = 'queued', + retry_base = attempts, + error_code = NULL, + lease_until = NULL, + updated_at = now() +WHERE id = $1::uuid + AND status = 'failed' + AND staging_key IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM attachment_variants + WHERE attachment_id = attachments.id + ) +` + +func (q *Queries) ReplayAttachmentJob(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, replayAttachmentJob, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const retryAttachmentJob = `-- name: RetryAttachmentJob :execrows +UPDATE attachments +SET status = 'queued', + error_code = $1::text, + lease_until = NULL, + updated_at = now() +WHERE id = $2::uuid + AND status = 'processing' + AND attempts = $3::int + AND lease_until > now() +` + +type RetryAttachmentJobParams struct { + ErrorCode string + ID uuid.UUID + Attempt int +} + +func (q *Queries) RetryAttachmentJob(ctx context.Context, arg RetryAttachmentJobParams) (int64, error) { + result, err := q.db.Exec(ctx, retryAttachmentJob, arg.ErrorCode, arg.ID, arg.Attempt) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const upgradeAttachmentPipeline = `-- name: UpgradeAttachmentPipeline :execrows +UPDATE attachments +SET pipeline_version = 2, + status = 'queued', + retry_base = attempts, + error_code = NULL, + lease_until = NULL, + updated_at = now() +WHERE id = $1::uuid + AND pipeline_version = 1 + AND status IN ('queued', 'processing') + AND staging_key IS NOT NULL +` + +func (q *Queries) UpgradeAttachmentPipeline(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, upgradeAttachmentPipeline, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} diff --git a/internal/db/chats.sql.go b/internal/db/chats.sql.go new file mode 100644 index 0000000..9a1243b --- /dev/null +++ b/internal/db/chats.sql.go @@ -0,0 +1,232 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: chats.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const addChatMembers = `-- name: AddChatMembers :exec +INSERT INTO chat_members ( + chat_id, + user_id +) +SELECT + $1::uuid, + unnest($2::uuid[]) +` + +type AddChatMembersParams struct { + ChatID uuid.UUID + UserIds []uuid.UUID +} + +func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams) error { + _, err := q.db.Exec(ctx, addChatMembers, arg.ChatID, arg.UserIds) + return err +} + +const createChat = `-- name: CreateChat :one +INSERT INTO chats ( + id, + title +) VALUES ( + $1, + $2 +) +RETURNING id, title, created_at +` + +type CreateChatParams struct { + ID uuid.UUID + Title string +} + +func (q *Queries) CreateChat(ctx context.Context, arg CreateChatParams) (Chat, error) { + row := q.db.QueryRow(ctx, createChat, arg.ID, arg.Title) + var i Chat + err := row.Scan(&i.ID, &i.Title, &i.CreatedAt) + return i, err +} + +const getChat = `-- name: GetChat :one +SELECT + c.id, c.title, c.created_at, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +WHERE c.id = $1 + AND EXISTS ( + SELECT 1 FROM chat_members m + WHERE m.chat_id = c.id + AND m.user_id = $2 + ) +` + +type GetChatParams struct { + ID uuid.UUID + UserID uuid.UUID +} + +type GetChatRow struct { + ID uuid.UUID + Title string + CreatedAt time.Time + MemberIds []uuid.UUID +} + +func (q *Queries) GetChat(ctx context.Context, arg GetChatParams) (GetChatRow, error) { + row := q.db.QueryRow(ctx, getChat, arg.ID, arg.UserID) + var i GetChatRow + err := row.Scan( + &i.ID, + &i.Title, + &i.CreatedAt, + &i.MemberIds, + ) + return i, err +} + +const isChatMember = `-- name: IsChatMember :one +SELECT EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = $1 + AND user_id = $2 +) +` + +type IsChatMemberParams struct { + ChatID uuid.UUID + UserID uuid.UUID +} + +func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) { + row := q.db.QueryRow(ctx, isChatMember, arg.ChatID, arg.UserID) + var exists bool + err := row.Scan(&exists) + return exists, err +} + +const listChatsAfter = `-- name: ListChatsAfter :many +SELECT + c.id, c.title, c.created_at, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +JOIN chat_members m ON m.chat_id = c.id +WHERE m.user_id = $1 + AND (c.created_at, c.id) > ( + $2::timestamptz, + $3::uuid + ) +ORDER BY c.created_at, c.id +LIMIT $4 +` + +type ListChatsAfterParams struct { + UserID uuid.UUID + AfterCreatedAt time.Time + AfterID uuid.UUID + Lim int +} + +type ListChatsAfterRow struct { + ID uuid.UUID + Title string + CreatedAt time.Time + MemberIds []uuid.UUID +} + +func (q *Queries) ListChatsAfter(ctx context.Context, arg ListChatsAfterParams) ([]ListChatsAfterRow, error) { + rows, err := q.db.Query(ctx, listChatsAfter, + arg.UserID, + arg.AfterCreatedAt, + arg.AfterID, + arg.Lim, + ) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListChatsAfterRow{} + for rows.Next() { + var i ListChatsAfterRow + if err := rows.Scan( + &i.ID, + &i.Title, + &i.CreatedAt, + &i.MemberIds, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listChatsFirstPage = `-- name: ListChatsFirstPage :many +SELECT + c.id, c.title, c.created_at, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +JOIN chat_members m ON m.chat_id = c.id +WHERE m.user_id = $1 +ORDER BY c.created_at, c.id +LIMIT $2 +` + +type ListChatsFirstPageParams struct { + UserID uuid.UUID + Lim int +} + +type ListChatsFirstPageRow struct { + ID uuid.UUID + Title string + CreatedAt time.Time + MemberIds []uuid.UUID +} + +func (q *Queries) ListChatsFirstPage(ctx context.Context, arg ListChatsFirstPageParams) ([]ListChatsFirstPageRow, error) { + rows, err := q.db.Query(ctx, listChatsFirstPage, arg.UserID, arg.Lim) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListChatsFirstPageRow{} + for rows.Next() { + var i ListChatsFirstPageRow + if err := rows.Scan( + &i.ID, + &i.Title, + &i.CreatedAt, + &i.MemberIds, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..0e4c3f4 --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,32 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 + +package db + +import ( + "context" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +type DBTX interface { + Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) + Query(context.Context, string, ...interface{}) (pgx.Rows, error) + QueryRow(context.Context, string, ...interface{}) pgx.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx pgx.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/db/idempotency_keys.sql.go b/internal/db/idempotency_keys.sql.go new file mode 100644 index 0000000..7e1cac9 --- /dev/null +++ b/internal/db/idempotency_keys.sql.go @@ -0,0 +1,120 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: idempotency_keys.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createIdempotencyKey = `-- name: CreateIdempotencyKey :execrows +INSERT INTO idempotency_keys ( + user_id, + method, + path, + key, + request_hash, + message_id +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6 +) +ON CONFLICT DO NOTHING +` + +type CreateIdempotencyKeyParams struct { + UserID uuid.UUID + Method string + Path string + Key string + RequestHash string + MessageID uuid.UUID +} + +func (q *Queries) CreateIdempotencyKey(ctx context.Context, arg CreateIdempotencyKeyParams) (int64, error) { + result, err := q.db.Exec(ctx, createIdempotencyKey, + arg.UserID, + arg.Method, + arg.Path, + arg.Key, + arg.RequestHash, + arg.MessageID, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const deleteExpiredIdempotencyKeys = `-- name: DeleteExpiredIdempotencyKeys :execrows +DELETE FROM idempotency_keys +WHERE created_at < $1 +` + +func (q *Queries) DeleteExpiredIdempotencyKeys(ctx context.Context, cutoff time.Time) (int64, error) { + result, err := q.db.Exec(ctx, deleteExpiredIdempotencyKeys, cutoff) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getIdempotentMessage = `-- name: GetIdempotentMessage :one +SELECT + k.request_hash, + m.id, + m.chat_id, + m.sender_id, + m.text, + m.created_at +FROM idempotency_keys AS k +JOIN messages AS m ON m.id = k.message_id +WHERE k.user_id = $1 + AND k.method = $2 + AND k.path = $3 + AND k.key = $4 +` + +type GetIdempotentMessageParams struct { + UserID uuid.UUID + Method string + Path string + Key string +} + +type GetIdempotentMessageRow struct { + RequestHash string + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time +} + +func (q *Queries) GetIdempotentMessage(ctx context.Context, arg GetIdempotentMessageParams) (GetIdempotentMessageRow, error) { + row := q.db.QueryRow(ctx, getIdempotentMessage, + arg.UserID, + arg.Method, + arg.Path, + arg.Key, + ) + var i GetIdempotentMessageRow + err := row.Scan( + &i.RequestHash, + &i.ID, + &i.ChatID, + &i.SenderID, + &i.Text, + &i.CreatedAt, + ) + return i, err +} diff --git a/internal/db/messages.sql.go b/internal/db/messages.sql.go new file mode 100644 index 0000000..d585eff --- /dev/null +++ b/internal/db/messages.sql.go @@ -0,0 +1,145 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: messages.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createMessage = `-- name: CreateMessage :one +INSERT INTO messages ( + id, + chat_id, + sender_id, + text +) +SELECT + $1::uuid, + $2::uuid, + $3::uuid, + $4::text +WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = $2 + AND user_id = $3 +) +RETURNING id, chat_id, sender_id, text, created_at +` + +type CreateMessageParams struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string +} + +func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) { + row := q.db.QueryRow(ctx, createMessage, + arg.ID, + arg.ChatID, + arg.SenderID, + arg.Text, + ) + var i Message + err := row.Scan( + &i.ID, + &i.ChatID, + &i.SenderID, + &i.Text, + &i.CreatedAt, + ) + return i, err +} + +const listMessagesAfter = `-- name: ListMessagesAfter :many +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = $1 + AND (created_at, id) > ( + $2::timestamptz, + $3::uuid + ) +ORDER BY created_at, id +LIMIT $4 +` + +type ListMessagesAfterParams struct { + ChatID uuid.UUID + AfterCreatedAt time.Time + AfterID uuid.UUID + Lim int +} + +func (q *Queries) ListMessagesAfter(ctx context.Context, arg ListMessagesAfterParams) ([]Message, error) { + rows, err := q.db.Query(ctx, listMessagesAfter, + arg.ChatID, + arg.AfterCreatedAt, + arg.AfterID, + arg.Lim, + ) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Message{} + for rows.Next() { + var i Message + if err := rows.Scan( + &i.ID, + &i.ChatID, + &i.SenderID, + &i.Text, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listMessagesFirstPage = `-- name: ListMessagesFirstPage :many +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = $1 +ORDER BY created_at, id +LIMIT $2 +` + +type ListMessagesFirstPageParams struct { + ChatID uuid.UUID + Lim int +} + +func (q *Queries) ListMessagesFirstPage(ctx context.Context, arg ListMessagesFirstPageParams) ([]Message, error) { + rows, err := q.db.Query(ctx, listMessagesFirstPage, arg.ChatID, arg.Lim) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Message{} + for rows.Next() { + var i Message + if err := rows.Scan( + &i.ID, + &i.ChatID, + &i.SenderID, + &i.Text, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/db/models.go b/internal/db/models.go new file mode 100644 index 0000000..c56730d --- /dev/null +++ b/internal/db/models.go @@ -0,0 +1,249 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 + +package db + +import ( + "database/sql/driver" + "fmt" + "time" + + "github.com/google/uuid" +) + +type AttachmentContentType string + +const ( + AttachmentContentTypeImagePng AttachmentContentType = "image/png" + AttachmentContentTypeImageJpeg AttachmentContentType = "image/jpeg" +) + +func (e *AttachmentContentType) Scan(src interface{}) error { + switch s := src.(type) { + case []byte: + *e = AttachmentContentType(s) + case string: + *e = AttachmentContentType(s) + default: + return fmt.Errorf("unsupported scan type for AttachmentContentType: %T", src) + } + return nil +} + +type NullAttachmentContentType struct { + AttachmentContentType AttachmentContentType + Valid bool // Valid is true if AttachmentContentType is not NULL +} + +// Scan implements the Scanner interface. +func (ns *NullAttachmentContentType) Scan(value interface{}) error { + if value == nil { + ns.AttachmentContentType, ns.Valid = "", false + return nil + } + ns.Valid = true + return ns.AttachmentContentType.Scan(value) +} + +// Value implements the driver Valuer interface. +func (ns NullAttachmentContentType) Value() (driver.Value, error) { + if !ns.Valid { + return nil, nil + } + return string(ns.AttachmentContentType), nil +} + +type AttachmentStatus string + +const ( + AttachmentStatusQueued AttachmentStatus = "queued" + AttachmentStatusProcessing AttachmentStatus = "processing" + AttachmentStatusReady AttachmentStatus = "ready" + AttachmentStatusFailed AttachmentStatus = "failed" +) + +func (e *AttachmentStatus) Scan(src interface{}) error { + switch s := src.(type) { + case []byte: + *e = AttachmentStatus(s) + case string: + *e = AttachmentStatus(s) + default: + return fmt.Errorf("unsupported scan type for AttachmentStatus: %T", src) + } + return nil +} + +type NullAttachmentStatus struct { + AttachmentStatus AttachmentStatus + Valid bool // Valid is true if AttachmentStatus is not NULL +} + +// Scan implements the Scanner interface. +func (ns *NullAttachmentStatus) Scan(value interface{}) error { + if value == nil { + ns.AttachmentStatus, ns.Valid = "", false + return nil + } + ns.Valid = true + return ns.AttachmentStatus.Scan(value) +} + +// Value implements the driver Valuer interface. +func (ns NullAttachmentStatus) Value() (driver.Value, error) { + if !ns.Valid { + return nil, nil + } + return string(ns.AttachmentStatus), nil +} + +type AttachmentVariantName string + +const ( + AttachmentVariantNameThumbnail AttachmentVariantName = "thumbnail" + AttachmentVariantNameCrop AttachmentVariantName = "crop" + AttachmentVariantNameOptimized AttachmentVariantName = "optimized" +) + +func (e *AttachmentVariantName) Scan(src interface{}) error { + switch s := src.(type) { + case []byte: + *e = AttachmentVariantName(s) + case string: + *e = AttachmentVariantName(s) + default: + return fmt.Errorf("unsupported scan type for AttachmentVariantName: %T", src) + } + return nil +} + +type NullAttachmentVariantName struct { + AttachmentVariantName AttachmentVariantName + Valid bool // Valid is true if AttachmentVariantName is not NULL +} + +// Scan implements the Scanner interface. +func (ns *NullAttachmentVariantName) Scan(value interface{}) error { + if value == nil { + ns.AttachmentVariantName, ns.Valid = "", false + return nil + } + ns.Valid = true + return ns.AttachmentVariantName.Scan(value) +} + +// Value implements the driver Valuer interface. +func (ns NullAttachmentVariantName) Value() (driver.Value, error) { + if !ns.Valid { + return nil, nil + } + return string(ns.AttachmentVariantName), nil +} + +type Attachment struct { + ID uuid.UUID + ChatID uuid.UUID + OwnerID uuid.UUID + S3Key string + Filename string + ContentType AttachmentContentType + SizeBytes int + Sha256 string + Status AttachmentStatus + ErrorCode *string + CreatedAt time.Time + UpdatedAt time.Time + StagingKey *string + JobID *uuid.UUID + PipelineVersion int + Attempts int + RetryBase int + Width *int32 + Height *int32 + LeaseUntil *time.Time +} + +type AttachmentReplay struct { + AttachmentID uuid.UUID + Attempt int + PreviousErrorCode *string + Operator string + Reason string + CreatedAt time.Time +} + +type AttachmentVariant struct { + AttachmentID uuid.UUID + PipelineVersion int + Variant AttachmentVariantName + S3Key string + ContentType string + SizeBytes int + Sha256 string + Width int + Height int +} + +type Chat struct { + ID uuid.UUID + Title string + CreatedAt time.Time +} + +type ChatMember struct { + ChatID uuid.UUID + UserID uuid.UUID +} + +type IdempotencyKey struct { + UserID uuid.UUID + Method string + Path string + Key string + RequestHash string + MessageID uuid.UUID + CreatedAt time.Time +} + +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time +} + +type MessageAttachment struct { + MessageID uuid.UUID + AttachmentID uuid.UUID + Position int +} + +type Outbox struct { + ID int64 + JobID uuid.UUID + AttachmentID uuid.UUID + PipelineVersion int + Attempt int + CreatedAt time.Time + AvailableAt time.Time + PublishedAt *time.Time + Traceparent string + Tracestate string +} + +type Session struct { + TokenHash string + UserID uuid.UUID + CreatedAt time.Time + ExpiresAt time.Time +} + +type User struct { + ID uuid.UUID + Username string + DisplayName string + PasswordHash string + CreatedAt time.Time +} diff --git a/internal/db/outbox.sql.go b/internal/db/outbox.sql.go new file mode 100644 index 0000000..85b249b --- /dev/null +++ b/internal/db/outbox.sql.go @@ -0,0 +1,124 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: outbox.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createOutboxEntry = `-- name: CreateOutboxEntry :one +INSERT INTO outbox ( + job_id, + attachment_id, + pipeline_version, + attempt, + available_at, + traceparent, + tracestate +) +SELECT + job_id, + id, + pipeline_version, + $1::int, + $2::timestamptz, + $3::text, + $4::text +FROM attachments +WHERE id = $5::uuid + AND job_id IS NOT NULL +RETURNING id, job_id, attachment_id, pipeline_version, attempt, created_at, available_at, published_at, traceparent, tracestate +` + +type CreateOutboxEntryParams struct { + Attempt int + AvailableAt time.Time + Traceparent string + Tracestate string + AttachmentID uuid.UUID +} + +func (q *Queries) CreateOutboxEntry(ctx context.Context, arg CreateOutboxEntryParams) (Outbox, error) { + row := q.db.QueryRow(ctx, createOutboxEntry, + arg.Attempt, + arg.AvailableAt, + arg.Traceparent, + arg.Tracestate, + arg.AttachmentID, + ) + var i Outbox + err := row.Scan( + &i.ID, + &i.JobID, + &i.AttachmentID, + &i.PipelineVersion, + &i.Attempt, + &i.CreatedAt, + &i.AvailableAt, + &i.PublishedAt, + &i.Traceparent, + &i.Tracestate, + ) + return i, err +} + +const lockPendingOutboxEntries = `-- name: LockPendingOutboxEntries :many +SELECT id, job_id, attachment_id, pipeline_version, attempt, created_at, available_at, published_at, traceparent, tracestate FROM outbox +WHERE published_at IS NULL + AND available_at <= now() +ORDER BY available_at, id +LIMIT $1::int +FOR UPDATE SKIP LOCKED +` + +func (q *Queries) LockPendingOutboxEntries(ctx context.Context, batchSize int) ([]Outbox, error) { + rows, err := q.db.Query(ctx, lockPendingOutboxEntries, batchSize) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Outbox{} + for rows.Next() { + var i Outbox + if err := rows.Scan( + &i.ID, + &i.JobID, + &i.AttachmentID, + &i.PipelineVersion, + &i.Attempt, + &i.CreatedAt, + &i.AvailableAt, + &i.PublishedAt, + &i.Traceparent, + &i.Tracestate, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const markOutboxPublished = `-- name: MarkOutboxPublished :execrows +UPDATE outbox +SET published_at = now() +WHERE id = $1::bigint + AND published_at IS NULL +` + +func (q *Queries) MarkOutboxPublished(ctx context.Context, id int64) (int64, error) { + result, err := q.db.Exec(ctx, markOutboxPublished, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} diff --git a/internal/db/sessions.sql.go b/internal/db/sessions.sql.go new file mode 100644 index 0000000..755a762 --- /dev/null +++ b/internal/db/sessions.sql.go @@ -0,0 +1,81 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: sessions.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createSession = `-- name: CreateSession :exec +INSERT INTO sessions ( + token_hash, + user_id, + expires_at +) VALUES ( + $1, + $2, + $3 +) +` + +type CreateSessionParams struct { + TokenHash string + UserID uuid.UUID + ExpiresAt time.Time +} + +func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) error { + _, err := q.db.Exec(ctx, createSession, arg.TokenHash, arg.UserID, arg.ExpiresAt) + return err +} + +const deleteExpiredSessions = `-- name: DeleteExpiredSessions :execrows +DELETE FROM sessions +WHERE expires_at <= now() +` + +func (q *Queries) DeleteExpiredSessions(ctx context.Context) (int64, error) { + result, err := q.db.Exec(ctx, deleteExpiredSessions) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const deleteSession = `-- name: DeleteSession :execrows +DELETE FROM sessions +WHERE token_hash = $1 + AND expires_at > now() +` + +func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) (int64, error) { + result, err := q.db.Exec(ctx, deleteSession, tokenHash) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getActiveSession = `-- name: GetActiveSession :one +SELECT user_id, expires_at FROM sessions +WHERE token_hash = $1 + AND expires_at > now() +` + +type GetActiveSessionRow struct { + UserID uuid.UUID + ExpiresAt time.Time +} + +func (q *Queries) GetActiveSession(ctx context.Context, tokenHash string) (GetActiveSessionRow, error) { + row := q.db.QueryRow(ctx, getActiveSession, tokenHash) + var i GetActiveSessionRow + err := row.Scan(&i.UserID, &i.ExpiresAt) + return i, err +} diff --git a/internal/db/users.sql.go b/internal/db/users.sql.go new file mode 100644 index 0000000..0af9cd1 --- /dev/null +++ b/internal/db/users.sql.go @@ -0,0 +1,115 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: users.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createUser = `-- name: CreateUser :one +INSERT INTO users ( + id, + username, + display_name, + password_hash +) VALUES ( + $1, + $2, + $3, + $4 +) +RETURNING id, username, display_name, created_at +` + +type CreateUserParams struct { + ID uuid.UUID + Username string + DisplayName string + PasswordHash string +} + +type CreateUserRow struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) { + row := q.db.QueryRow(ctx, createUser, + arg.ID, + arg.Username, + arg.DisplayName, + arg.PasswordHash, + ) + var i CreateUserRow + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.CreatedAt, + ) + return i, err +} + +const getUser = `-- name: GetUser :one +SELECT id, username, display_name, created_at FROM users +WHERE id = $1 +` + +type GetUserRow struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) { + row := q.db.QueryRow(ctx, getUser, id) + var i GetUserRow + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.CreatedAt, + ) + return i, err +} + +const getUserByUsername = `-- name: GetUserByUsername :one +SELECT id, username, display_name, password_hash, created_at FROM users +WHERE username = $1 +` + +func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, error) { + row := q.db.QueryRow(ctx, getUserByUsername, username) + var i User + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.PasswordHash, + &i.CreatedAt, + ) + return i, err +} + +const updatePasswordHash = `-- name: UpdatePasswordHash :exec +UPDATE users SET password_hash = $1 WHERE id = $2 +` + +type UpdatePasswordHashParams struct { + PasswordHash string + ID uuid.UUID +} + +func (q *Queries) UpdatePasswordHash(ctx context.Context, arg UpdatePasswordHashParams) error { + _, err := q.db.Exec(ctx, updatePasswordHash, arg.PasswordHash, arg.ID) + return err +} diff --git a/internal/dto/attachment.go b/internal/dto/attachment.go new file mode 100644 index 0000000..534e15c --- /dev/null +++ b/internal/dto/attachment.go @@ -0,0 +1,98 @@ +package dto + +import ( + "time" + "unicode" + "unicode/utf8" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab7/internal/model" +) + +type CreateAttachmentRequest struct { + Filename string +} + +type GetAttachmentContentRequest struct { + Variant string +} + +type VariantResponse struct { + Name model.AttachmentVariantName `json:"name"` + ContentType model.ContentType `json:"content_type"` + SizeBytes int `json:"size_bytes"` + Width int `json:"width"` + Height int `json:"height"` + Sha256 string `json:"sha256"` +} + +type AttachmentResponse struct { + ID uuid.UUID `json:"id"` + ChatID uuid.UUID `json:"chat_id"` + OwnerID uuid.UUID `json:"owner_id"` + Filename string `json:"filename"` + ContentType model.ContentType `json:"content_type"` + SizeBytes int `json:"size_bytes"` + Sha256 string `json:"sha256"` + Status model.AttachmentStatus `json:"status"` + Variants []VariantResponse `json:"variants"` + ErrorCode *string `json:"error_code"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +func (r CreateAttachmentRequest) Validate() bool { + if n := utf8.RuneCountInString(r.Filename); n < 1 || n > 255 { + return false + } + + for _, ch := range r.Filename { + if ch == '/' || ch == '\\' || ch == 0 || unicode.IsControl(ch) { + return false + } + } + + return true +} + +func (r GetAttachmentContentRequest) Validate() bool { + switch model.AttachmentVariantName(r.Variant) { + case "", + model.AttachmentContentOriginal, + model.AttachmentVariantNameThumbnail, + model.AttachmentVariantNameCrop, + model.AttachmentVariantNameOptimized: + return true + default: + return false + } +} + +func ToAttachmentResponse(a model.Attachment) AttachmentResponse { + variants := make([]VariantResponse, 0, len(a.Variants)) + for _, v := range a.Variants { + variants = append(variants, VariantResponse{ + Name: v.Name, + ContentType: v.ContentType, + SizeBytes: v.SizeBytes, + Width: v.Width, + Height: v.Height, + Sha256: v.Sha256, + }) + } + return AttachmentResponse{ + ID: a.ID, + ChatID: a.ChatID, + OwnerID: a.OwnerID, + Filename: a.Filename, + ContentType: a.ContentType, + SizeBytes: a.SizeBytes, + Sha256: a.Sha256, + Status: a.Status, + Variants: variants, + ErrorCode: a.ErrorCode, + CreatedAt: a.CreatedAt, + UpdatedAt: a.UpdatedAt, + } +} diff --git a/internal/dto/chat.go b/internal/dto/chat.go new file mode 100644 index 0000000..e7edf68 --- /dev/null +++ b/internal/dto/chat.go @@ -0,0 +1,50 @@ +package dto + +import ( + "gavrilenko-sxdees/lab7/internal/model" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +type CreateChatRequest struct { + Title string `json:"title"` + MemberIDs []uuid.UUID `json:"member_ids"` +} + +type ChatResponse struct { + ID uuid.UUID `json:"id"` + Title string `json:"title"` + MemberIDs []uuid.UUID `json:"member_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type ChatPageResponse struct { + Items []ChatResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func (r CreateChatRequest) Validate() bool { + if strings.TrimSpace(r.Title) == "" || + strings.ContainsRune(r.Title, 0) || + utf8.RuneCountInString(r.Title) > 100 { + return false + } + + if len(r.MemberIDs) < 1 || len(r.MemberIDs) > 100 { + return false + } + + return true +} + +func ToChatResponse(c model.Chat) ChatResponse { + return ChatResponse{ + ID: c.ID, + Title: c.Title, + MemberIDs: c.MemberIDs, + CreatedAt: c.CreatedAt, + } +} diff --git a/internal/dto/error.go b/internal/dto/error.go new file mode 100644 index 0000000..3a46305 --- /dev/null +++ b/internal/dto/error.go @@ -0,0 +1,25 @@ +package dto + +type ErrorCode string + +const ( + ErrorCodeInvalidRequest ErrorCode = "invalid_request" + ErrorCodeUnauthorized ErrorCode = "unauthorized" + ErrorCodeNotFound ErrorCode = "not_found" + ErrorCodeConflict ErrorCode = "conflict" + ErrorCodePayloadTooLarge ErrorCode = "payload_too_large" + ErrorCodeUnsupportedMediaType ErrorCode = "unsupported_media_type" + ErrorCodeRateLimited ErrorCode = "rate_limited" + ErrorCodeUnavailable ErrorCode = "unavailable" + ErrorCodeInternalError ErrorCode = "internal_error" +) + +type ErrorResponse struct { + Error Error `json:"error"` +} + +type Error struct { + Code ErrorCode `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} diff --git a/internal/dto/health.go b/internal/dto/health.go new file mode 100644 index 0000000..8bb3503 --- /dev/null +++ b/internal/dto/health.go @@ -0,0 +1,5 @@ +package dto + +type HealthResponse struct { + Status string `json:"status"` +} diff --git a/internal/dto/message.go b/internal/dto/message.go new file mode 100644 index 0000000..aa900fc --- /dev/null +++ b/internal/dto/message.go @@ -0,0 +1,64 @@ +package dto + +import ( + "gavrilenko-sxdees/lab7/internal/model" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +type CreateMessageRequest struct { + Text string `json:"text"` + AttachmentIDs []string `json:"attachment_ids"` +} + +type MessageResponse struct { + ID uuid.UUID `json:"id"` + ChatID uuid.UUID `json:"chat_id"` + SenderID uuid.UUID `json:"sender_id"` + Text string `json:"text"` + AttachmentIDs []uuid.UUID `json:"attachment_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type MessagePageResponse struct { + Items []MessageResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func (r CreateMessageRequest) Validate() bool { + if strings.ContainsRune(r.Text, 0) || utf8.RuneCountInString(r.Text) > 4000 { + return false + } + if len(r.AttachmentIDs) > 10 { + return false + } + + seen := make(map[string]struct{}, len(r.AttachmentIDs)) + for _, id := range r.AttachmentIDs { + if _, ok := seen[id]; ok { + return false + } + seen[id] = struct{}{} + } + + hasText := strings.TrimSpace(r.Text) != "" + hasAttachment := len(r.AttachmentIDs) > 0 + + return hasText || hasAttachment +} + +func ToMessageResponse(m model.Message) MessageResponse { + ids := make([]uuid.UUID, len(m.AttachmentIDs)) + copy(ids, m.AttachmentIDs) + return MessageResponse{ + ID: m.ID, + ChatID: m.ChatID, + SenderID: m.SenderID, + Text: m.Text, + AttachmentIDs: ids, + CreatedAt: m.CreatedAt, + } +} diff --git a/internal/dto/session.go b/internal/dto/session.go new file mode 100644 index 0000000..f8d1ccf --- /dev/null +++ b/internal/dto/session.go @@ -0,0 +1,10 @@ +package dto + +import "time" + +type SessionResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User UserResponse `json:"user"` +} diff --git a/internal/dto/user.go b/internal/dto/user.go new file mode 100644 index 0000000..27973e1 --- /dev/null +++ b/internal/dto/user.go @@ -0,0 +1,44 @@ +package dto + +import ( + "regexp" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +type CreateUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` +} + +type UserResponse struct { + ID uuid.UUID `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +func (r CreateUserRequest) Validate() bool { + if !usernamePattern.MatchString(r.Username) { + return false + } + + displayNameLength := utf8.RuneCountInString(r.DisplayName) + if strings.TrimSpace(r.DisplayName) == "" || + displayNameLength > 100 || + strings.ContainsRune(r.DisplayName, 0) { + return false + } + + if n := utf8.RuneCountInString(r.Password); n < 12 || n > 128 { + return false + } + + return true +} diff --git a/internal/handler/attachment.go b/internal/handler/attachment.go new file mode 100644 index 0000000..cdcc00d --- /dev/null +++ b/internal/handler/attachment.go @@ -0,0 +1,140 @@ +package handler + +import ( + "errors" + "net/http" + "time" + + "github.com/go-chi/chi/v5" + "github.com/google/uuid" + + "gavrilenko-sxdees/lab7/internal/dto" + "gavrilenko-sxdees/lab7/internal/httpx" + "gavrilenko-sxdees/lab7/internal/middleware" + "gavrilenko-sxdees/lab7/internal/service" +) + +type AttachmentHandler struct { + service *service.AttachmentService + maxBytes int +} + +func NewAttachmentHandler(service *service.AttachmentService, maxBytes int) *AttachmentHandler { + return &AttachmentHandler{ + service: service, + maxBytes: maxBytes, + } +} + +func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + chatID, err := uuid.Parse(chi.URLParam(r, "chat_id")) + if err != nil { + httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid chat_id", requestID) + return + } + + req := dto.CreateAttachmentRequest{ + Filename: r.URL.Query().Get("filename"), + } + if !req.Validate() { + httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid filename", requestID) + return + } + + if deadline, ok := r.Context().Deadline(); ok { + controller := http.NewResponseController(w) + if err := controller.SetReadDeadline(deadline); err != nil { + httpx.WriteInternalError(w, requestID, err) + return + } + defer func() { _ = controller.SetReadDeadline(time.Time{}) }() + } + + contentType := r.Header.Get("Content-Type") + r.Body = http.MaxBytesReader(w, r.Body, int64(h.maxBytes)) + + att, err := h.service.Upload(r.Context(), userID, chatID, req.Filename, r.Body, contentType) + switch { + case errors.Is(err, service.ErrUploadReadTimeout): + r.Close = true + w.Header().Set("Connection", "close") + httpx.WriteError(w, http.StatusRequestTimeout, dto.ErrorCodeInvalidRequest, "upload body read timed out", requestID) + return + case errors.Is(err, service.ErrInvalidSize): + httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodePayloadTooLarge, "file too large", requestID) + return + case errors.Is(err, service.ErrInvalidImage): + httpx.WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeUnsupportedMediaType, "invalid image", requestID) + return + case errors.Is(err, service.ErrAttachmentNotFound): + httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID) + return + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + httpx.WriteJSON(w, http.StatusAccepted, dto.ToAttachmentResponse(att)) +} + +func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + attachmentID, err := uuid.Parse(chi.URLParam(r, "attachment_id")) + if err != nil { + httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid attachment_id", requestID) + return + } + + att, err := h.service.Get(r.Context(), userID, attachmentID) + switch { + case errors.Is(err, service.ErrAttachmentNotFound): + httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID) + return + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + httpx.WriteJSON(w, http.StatusOK, dto.ToAttachmentResponse(att)) +} + +func (h *AttachmentHandler) GetContent(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + attachmentID, err := uuid.Parse(chi.URLParam(r, "attachment_id")) + if err != nil { + httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid attachment_id", requestID) + return + } + + req := dto.GetAttachmentContentRequest{ + Variant: r.URL.Query().Get("variant"), + } + if !req.Validate() { + httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID) + return + } + + data, contentType, err := h.service.GetContent(r.Context(), userID, attachmentID, req.Variant) + switch { + case errors.Is(err, service.ErrAttachmentNotReady): + httpx.WriteError(w, http.StatusConflict, dto.ErrorCodeConflict, "attachment not ready", requestID) + return + case errors.Is(err, service.ErrAttachmentNotFound): + httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID) + return + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + w.Header().Set("Content-Type", string(contentType)) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(data) +} diff --git a/internal/handler/auth.go b/internal/handler/auth.go new file mode 100644 index 0000000..05be634 --- /dev/null +++ b/internal/handler/auth.go @@ -0,0 +1,80 @@ +package handler + +import ( + "errors" + "net/http" + + "gavrilenko-sxdees/lab7/internal/dto" + "gavrilenko-sxdees/lab7/internal/httpx" + "gavrilenko-sxdees/lab7/internal/middleware" + "gavrilenko-sxdees/lab7/internal/service" +) + +type AuthHandler struct { + service *service.AuthService +} + +func NewAuthHandler(s *service.AuthService) *AuthHandler { + return &AuthHandler{service: s} +} + +func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + username, plain, ok := r.BasicAuth() + if !ok { + httpx.WriteUnauthorized(w, httpx.BasicChallenge, requestID) + return + } + + if !httpx.RejectBody(w, r, requestID) { + return + } + + session, err := h.service.Login(r.Context(), username, plain) + if errors.Is(err, service.ErrInvalidCredentials) { + httpx.WriteUnauthorized(w, httpx.BasicChallenge, requestID) + return + } + if err != nil { + httpx.WriteInternalError(w, requestID, err) + return + } + + httpx.WriteJSON(w, http.StatusCreated, dto.SessionResponse{ + Token: session.Token, + TokenType: "Bearer", + ExpiresAt: session.ExpiresAt, + User: dto.UserResponse{ + ID: session.User.ID, + Username: session.User.Username, + DisplayName: session.User.DisplayName, + CreatedAt: session.User.CreatedAt, + }, + }) +} + +func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + token, ok := httpx.BearerToken(r) + if !ok { + httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID) + return + } + + err := h.service.Logout(r.Context(), token) + switch { + case errors.Is(err, service.ErrSessionCacheUnavailable): + httpx.WriteError(w, http.StatusServiceUnavailable, dto.ErrorCodeUnavailable, "session cache unavailable", requestID) + return + case errors.Is(err, service.ErrUnauthorized): + httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID) + return + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + w.WriteHeader(http.StatusNoContent) +} diff --git a/internal/handler/chat.go b/internal/handler/chat.go new file mode 100644 index 0000000..f76dc3d --- /dev/null +++ b/internal/handler/chat.go @@ -0,0 +1,150 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/go-chi/chi/v5" + "github.com/google/uuid" + + "gavrilenko-sxdees/lab7/internal/dto" + "gavrilenko-sxdees/lab7/internal/httpx" + "gavrilenko-sxdees/lab7/internal/middleware" + "gavrilenko-sxdees/lab7/internal/service" +) + +type ChatHandler struct { + service *service.ChatService +} + +func NewChatHandler(service *service.ChatService) *ChatHandler { + return &ChatHandler{service: service} +} + +func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + var req dto.CreateChatRequest + if !httpx.DecodeJSONBody(w, r, requestID, &req) { + return + } + + if !req.Validate() { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid request body", + requestID, + ) + return + } + + chat, err := h.service.Create(r.Context(), userID, req.Title, req.MemberIDs) + switch { + case errors.Is(err, service.ErrNotChatMember): + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "caller must be a member of member_ids", + requestID, + ) + return + case errors.Is(err, service.ErrDuplicateMember): + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "member_ids contains duplicates", + requestID, + ) + return + case errors.Is(err, service.ErrUnknownMember): + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "member_ids contains unknown user", + requestID, + ) + return + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + httpx.WriteJSON(w, http.StatusCreated, dto.ToChatResponse(chat)) +} + +func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + chatID, err := uuid.Parse(chi.URLParam(r, "chat_id")) + if err != nil { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid chat_id", + requestID, + ) + return + } + + chat, err := h.service.Get(r.Context(), userID, chatID) + switch { + case errors.Is(err, service.ErrChatNotFound): + httpx.WriteError( + w, + http.StatusNotFound, + dto.ErrorCodeNotFound, + "chat not found", + requestID, + ) + return + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + httpx.WriteJSON(w, http.StatusOK, dto.ToChatResponse(chat)) +} + +func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + limit, cursor, ok := httpx.ParsePagination(w, r, requestID) + if !ok { + return + } + + chats, nextCursor, err := h.service.List(r.Context(), userID, limit, cursor) + switch { + case errors.Is(err, service.ErrInvalidCursor): + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid cursor", + requestID, + ) + return + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + items := make([]dto.ChatResponse, 0, len(chats)) + for _, c := range chats { + items = append(items, dto.ToChatResponse(c)) + } + + httpx.WriteJSON(w, http.StatusOK, dto.ChatPageResponse{ + Items: items, + NextCursor: nextCursor, + }) +} diff --git a/internal/handler/health.go b/internal/handler/health.go new file mode 100644 index 0000000..93f6e1d --- /dev/null +++ b/internal/handler/health.go @@ -0,0 +1,62 @@ +package handler + +import ( + "context" + "encoding/json" + "log/slog" + "net/http" + "time" + + "gavrilenko-sxdees/lab7/internal/dto" + "gavrilenko-sxdees/lab7/internal/httpx" +) + +const readyPingTimeout = 2 * time.Second + +type Pinger interface { + Ping(ctx context.Context) error +} + +type HealthHandler struct { + log *slog.Logger + dependencies []Pinger +} + +func NewHealthHandler(log *slog.Logger, dependencies ...Pinger) *HealthHandler { + return &HealthHandler{log: log, dependencies: dependencies} +} + +func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + _ = json.NewEncoder(w).Encode(dto.HealthResponse{ + Status: "ok", + }) +} + +func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), readyPingTimeout) + defer cancel() + + for _, dependency := range h.dependencies { + if err := dependency.Ping(ctx); err != nil { + h.log.ErrorContext(r.Context(), "readiness check failed", "error", err) + httpx.WriteError( + w, + http.StatusServiceUnavailable, + dto.ErrorCodeUnavailable, + "service unavailable", + w.Header().Get("X-Request-Id"), + ) + return + } + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + _ = json.NewEncoder(w).Encode(dto.HealthResponse{ + Status: "ok", + }) +} diff --git a/internal/handler/message.go b/internal/handler/message.go new file mode 100644 index 0000000..67e33b5 --- /dev/null +++ b/internal/handler/message.go @@ -0,0 +1,188 @@ +package handler + +import ( + "errors" + "net/http" + "regexp" + + "github.com/go-chi/chi/v5" + "github.com/google/uuid" + + "gavrilenko-sxdees/lab7/internal/dto" + "gavrilenko-sxdees/lab7/internal/httpx" + "gavrilenko-sxdees/lab7/internal/middleware" + "gavrilenko-sxdees/lab7/internal/service" +) + +var idempotencyKeyReq = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +type MessageHandler struct { + service *service.MessageService +} + +func NewMessageHandler(service *service.MessageService) *MessageHandler { + return &MessageHandler{service: service} +} + +func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + chatID, err := uuid.Parse(chi.URLParam(r, "chat_id")) + if err != nil { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid chat_id", + requestID, + ) + return + } + + key := r.Header.Get("Idempotency-Key") + if !idempotencyKeyReq.MatchString(key) { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid Idempotency-Key", + requestID, + ) + return + } + + var req dto.CreateMessageRequest + if !httpx.DecodeJSONBody(w, r, requestID, &req) { + return + } + + if !req.Validate() { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid request body", + requestID, + ) + return + } + + attachmentIDs := make([]uuid.UUID, 0, len(req.AttachmentIDs)) + for _, s := range req.AttachmentIDs { + id, err := uuid.Parse(s) + if err != nil { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid attachment_id", + requestID, + ) + return + } + attachmentIDs = append(attachmentIDs, id) + } + + message, err := h.service.Create(r.Context(), userID, chatID, key, req.Text, attachmentIDs) + switch { + case errors.Is(err, service.ErrMessageChatNotFound): + httpx.WriteError( + w, + http.StatusNotFound, + dto.ErrorCodeNotFound, + "chat not found", + requestID, + ) + return + case errors.Is(err, service.ErrAttachmentNotFound): + httpx.WriteError( + w, + http.StatusNotFound, + dto.ErrorCodeNotFound, + "attachment not found", + requestID, + ) + return + case errors.Is(err, service.ErrAttachmentNotReady): + httpx.WriteError( + w, + http.StatusConflict, + dto.ErrorCodeConflict, + "attachment not ready", + requestID, + ) + return + case errors.Is(err, service.ErrIdempotencyKeyConflict): + httpx.WriteError( + w, + http.StatusConflict, + dto.ErrorCodeConflict, + "idempotency key reused with different request", + requestID, + ) + return + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + httpx.WriteJSON(w, http.StatusCreated, dto.ToMessageResponse(message)) +} + +func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + chatID, err := uuid.Parse(chi.URLParam(r, "chat_id")) + if err != nil { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid chat_id", + requestID, + ) + return + } + + limit, cursor, ok := httpx.ParsePagination(w, r, requestID) + if !ok { + return + } + + messages, nextCursor, err := h.service.List(r.Context(), userID, chatID, limit, cursor) + switch { + case errors.Is(err, service.ErrMessageChatNotFound): + httpx.WriteError( + w, + http.StatusNotFound, + dto.ErrorCodeNotFound, + "chat not found", + requestID, + ) + return + case errors.Is(err, service.ErrInvalidCursor): + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid cursor", + requestID, + ) + return + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + items := make([]dto.MessageResponse, 0, len(messages)) + for _, m := range messages { + items = append(items, dto.ToMessageResponse(m)) + } + + httpx.WriteJSON(w, http.StatusOK, dto.MessagePageResponse{ + Items: items, + NextCursor: nextCursor, + }) +} diff --git a/internal/handler/user.go b/internal/handler/user.go new file mode 100644 index 0000000..291cffc --- /dev/null +++ b/internal/handler/user.go @@ -0,0 +1,95 @@ +package handler + +import ( + "errors" + "net/http" + + "gavrilenko-sxdees/lab7/internal/dto" + "gavrilenko-sxdees/lab7/internal/httpx" + "gavrilenko-sxdees/lab7/internal/middleware" + "gavrilenko-sxdees/lab7/internal/service" +) + +type UserHandler struct { + service *service.UserService +} + +func NewUserHandler(service *service.UserService) *UserHandler { + return &UserHandler{service: service} +} + +func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + var req dto.CreateUserRequest + if !httpx.DecodeJSONBody(w, r, requestID, &req) { + return + } + + if !req.Validate() { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid request body", + requestID, + ) + return + } + + user, err := h.service.Create( + r.Context(), + req.Username, + req.DisplayName, + req.Password, + ) + if errors.Is(err, service.ErrUsernameTaken) { + httpx.WriteError( + w, + http.StatusConflict, + dto.ErrorCodeConflict, + "username already taken", + requestID, + ) + return + } + if err != nil { + httpx.WriteInternalError(w, requestID, err) + return + } + + httpx.WriteJSON(w, http.StatusCreated, dto.UserResponse{ + ID: user.ID, + Username: user.Username, + DisplayName: user.DisplayName, + CreatedAt: user.CreatedAt, + }) +} + +func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + user, err := h.service.GetByID(r.Context(), userID) + if errors.Is(err, service.ErrUserNotFound) { + httpx.WriteError( + w, + http.StatusNotFound, + dto.ErrorCodeNotFound, + "user not found", + requestID, + ) + return + } + if err != nil { + httpx.WriteInternalError(w, requestID, err) + return + } + + httpx.WriteJSON(w, http.StatusOK, dto.UserResponse{ + ID: user.ID, + Username: user.Username, + DisplayName: user.DisplayName, + CreatedAt: user.CreatedAt, + }) +} diff --git a/internal/httpx/auth.go b/internal/httpx/auth.go new file mode 100644 index 0000000..885cc32 --- /dev/null +++ b/internal/httpx/auth.go @@ -0,0 +1,37 @@ +package httpx + +import ( + "net/http" + "strings" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +const ( + BasicChallenge = `Basic realm="messenger", charset="UTF-8"` + BearerChallenge = `Bearer realm="messenger"` +) + +func BearerToken(r *http.Request) (string, bool) { + const prefix = "Bearer " + + header := r.Header.Get("Authorization") + if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) { + return "", false + } + + token := strings.TrimSpace(header[len(prefix):]) + + return token, token != "" +} + +func WriteUnauthorized(w http.ResponseWriter, challenge, requestID string) { + w.Header().Set("WWW-Authenticate", challenge) + WriteError( + w, + http.StatusUnauthorized, + dto.ErrorCodeUnauthorized, + "unauthorized", + requestID, + ) +} diff --git a/internal/httpx/pagination.go b/internal/httpx/pagination.go new file mode 100644 index 0000000..0591de7 --- /dev/null +++ b/internal/httpx/pagination.go @@ -0,0 +1,34 @@ +package httpx + +import ( + "net/http" + "strconv" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +func ParsePagination(w http.ResponseWriter, r *http.Request, requestID string) (limit int, cursor *string, ok bool) { + q := r.URL.Query() + + limit = 50 + if raw := q.Get("limit"); raw != "" { + v, err := strconv.Atoi(raw) + if err != nil || v < 1 || v > 100 { + WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "limit must be an integer between 1 and 100", + requestID, + ) + return 0, nil, false + } + limit = v + } + + if raw := q.Get("cursor"); raw != "" { + cursor = &raw + } + + return limit, cursor, true +} diff --git a/internal/httpx/request.go b/internal/httpx/request.go new file mode 100644 index 0000000..d05a450 --- /dev/null +++ b/internal/httpx/request.go @@ -0,0 +1,49 @@ +package httpx + +import ( + "encoding/json" + "errors" + "io" + "mime" + "net/http" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +func DecodeJSONBody(w http.ResponseWriter, r *http.Request, requestID string, dst any) bool { + if ct := r.Header.Get("Content-Type"); ct != "" { + mt, _, err := mime.ParseMediaType(ct) + if err != nil || mt != "application/json" { + WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeUnsupportedMediaType, "expected application/json", requestID) + return false + } + } + + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + + if err := decoder.Decode(dst); err != nil { + WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID) + return false + } + + if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID) + return false + } + + return true +} + +func RejectBody(w http.ResponseWriter, r *http.Request, requestID string) bool { + if r.Body == nil || r.Body == http.NoBody { + return true + } + + var b [1]byte + if n, _ := r.Body.Read(b[:]); n > 0 { + WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID) + return false + } + return true +} diff --git a/internal/httpx/response.go b/internal/httpx/response.go new file mode 100644 index 0000000..b8bb4bd --- /dev/null +++ b/internal/httpx/response.go @@ -0,0 +1,68 @@ +package httpx + +import ( + "context" + "encoding/json" + "errors" + "net" + "net/http" + "strings" + + "github.com/jackc/pgx/v5/pgconn" + + "gavrilenko-sxdees/lab7/internal/dto" + s3store "gavrilenko-sxdees/lab7/internal/s3" +) + +func WriteJSON(w http.ResponseWriter, status int, body any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(body) +} + +func WriteError(w http.ResponseWriter, status int, code dto.ErrorCode, message, requestID string) { + WriteJSON(w, status, dto.ErrorResponse{ + Error: dto.Error{ + Code: code, + Message: message, + RequestID: requestID, + }, + }) +} + +func WriteInternalError(w http.ResponseWriter, requestID string, err error) { + if isUnavailable(err) { + WriteError( + w, + http.StatusServiceUnavailable, + dto.ErrorCodeUnavailable, + "dependency unavailable", + requestID, + ) + return + } + + WriteError( + w, + http.StatusInternalServerError, + dto.ErrorCodeInternalError, + "internal server error", + requestID, + ) +} + +func isUnavailable(err error) bool { + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, s3store.ErrUnavailable) { + return true + } + + if _, ok := errors.AsType[net.Error](err); ok { + return true + } + + if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok { + return strings.HasPrefix(pgErr.Code, "08") || pgErr.Code == "57P01" + } + + return false +} diff --git a/internal/logger/logger.go b/internal/logger/logger.go new file mode 100644 index 0000000..89ce600 --- /dev/null +++ b/internal/logger/logger.go @@ -0,0 +1,14 @@ +package logger + +import ( + "log/slog" + "os" +) + +func New(level slog.Level) *slog.Logger { + return slog.New( + slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ + Level: level, + }), + ) +} diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go new file mode 100644 index 0000000..da9573e --- /dev/null +++ b/internal/middleware/auth.go @@ -0,0 +1,50 @@ +package middleware + +import ( + "context" + "errors" + "net/http" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab7/internal/httpx" + "gavrilenko-sxdees/lab7/internal/service" +) + +type userIDContextKey struct{} + +type authenticator interface { + Authenticate(ctx context.Context, token string) (uuid.UUID, error) +} + +func Auth(auth authenticator) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestID := GetRequestID(r.Context()) + + token, ok := httpx.BearerToken(r) + if !ok { + httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID) + return + } + + userID, err := auth.Authenticate(r.Context(), token) + if errors.Is(err, service.ErrUnauthorized) { + httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID) + return + } + if err != nil { + httpx.WriteInternalError(w, requestID, err) + return + } + + ctx := context.WithValue(r.Context(), userIDContextKey{}, userID) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +func GetUserID(ctx context.Context) uuid.UUID { + id, _ := ctx.Value(userIDContextKey{}).(uuid.UUID) + return id +} diff --git a/internal/middleware/concurrency.go b/internal/middleware/concurrency.go new file mode 100644 index 0000000..7d91d0b --- /dev/null +++ b/internal/middleware/concurrency.go @@ -0,0 +1,41 @@ +package middleware + +import ( + "net/http" + + "gavrilenko-sxdees/lab7/internal/dto" + "gavrilenko-sxdees/lab7/internal/httpx" +) + +func ConcurrencyLimit(max int) func(http.Handler) http.Handler { + if max <= 0 { + return func(next http.Handler) http.Handler { + return next + } + } + + slots := make(chan struct{}, max) + + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case slots <- struct{}{}: + defer func() { + <-slots + }() + + next.ServeHTTP(w, r) + + default: + w.Header().Set("Retry-After", "1") + httpx.WriteError( + w, + http.StatusTooManyRequests, + dto.ErrorCodeRateLimited, + "too many requests", + GetRequestID(r.Context()), + ) + } + }) + } +} diff --git a/internal/middleware/instance_id.go b/internal/middleware/instance_id.go new file mode 100644 index 0000000..5fa86d1 --- /dev/null +++ b/internal/middleware/instance_id.go @@ -0,0 +1,14 @@ +package middleware + +import ( + "net/http" +) + +func InstanceID(id string) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Instance-Id", id) + next.ServeHTTP(w, r) + }) + } +} diff --git a/internal/middleware/logging.go b/internal/middleware/logging.go new file mode 100644 index 0000000..7d7da2c --- /dev/null +++ b/internal/middleware/logging.go @@ -0,0 +1,53 @@ +package middleware + +import ( + "log/slog" + "net/http" + "time" +) + +type responseWriter struct { + http.ResponseWriter + status int +} + +func (w *responseWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +func (w *responseWriter) WriteHeader(status int) { + w.status = status + w.ResponseWriter.WriteHeader(status) +} + +func Logging(log *slog.Logger) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + writer := &responseWriter{ + ResponseWriter: w, + status: http.StatusOK, + } + + next.ServeHTTP(writer, r) + + level := slog.LevelInfo + + switch { + case writer.status >= 500: + level = slog.LevelError + case writer.status >= 400: + level = slog.LevelWarn + } + + log.Log(r.Context(), level, "http request", + "request_id", GetRequestID(r.Context()), + "method", r.Method, + "path", r.URL.Path, + "status", writer.status, + "duration_ms", time.Since(start).Milliseconds(), + ) + }) + } +} diff --git a/internal/middleware/login_limit.go b/internal/middleware/login_limit.go new file mode 100644 index 0000000..4224010 --- /dev/null +++ b/internal/middleware/login_limit.go @@ -0,0 +1,68 @@ +package middleware + +import ( + "context" + "fmt" + "net/http" + "strconv" + "time" + + "github.com/redis/go-redis/v9" + + "gavrilenko-sxdees/lab7/internal/dto" + "gavrilenko-sxdees/lab7/internal/httpx" +) + +const ( + loginLimitKeyPrefix = "login:attempt:" + loginLimitWindow = time.Minute + loginLimitMax = 20 +) + +type LoginLimiter struct { + rdb *redis.Client +} + +func NewLoginLimiter(rdb *redis.Client) *LoginLimiter { + return &LoginLimiter{rdb: rdb} +} + +func (l *LoginLimiter) Limit(next http.Handler) http.Handler { + if l == nil || l.rdb == nil { + return next + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/api/v1/auth/sessions" { + next.ServeHTTP(w, r) + return + } + username, _, ok := r.BasicAuth() + if !ok { + next.ServeHTTP(w, r) + return + } + key := loginLimitKeyPrefix + username + ctx, cancel := context.WithTimeout(r.Context(), 200*time.Millisecond) + defer cancel() + n, err := l.rdb.Incr(ctx, key).Result() + if err != nil { + next.ServeHTTP(w, r) + return + } + if n == 1 { + _ = l.rdb.Expire(ctx, key, loginLimitWindow).Err() + } + if n > loginLimitMax { + ttl, _ := l.rdb.TTL(ctx, key).Result() + if ttl < 0 { + ttl = loginLimitWindow + } + w.Header().Set("Retry-After", strconv.Itoa(int(ttl.Seconds()))) + httpx.WriteError(w, http.StatusTooManyRequests, dto.ErrorCodeRateLimited, + fmt.Sprintf("too many login attempts; retry in %ds", int(ttl.Seconds())), + GetRequestID(r.Context())) + return + } + next.ServeHTTP(w, r) + }) +} \ No newline at end of file diff --git a/internal/middleware/request_id.go b/internal/middleware/request_id.go new file mode 100644 index 0000000..d62808b --- /dev/null +++ b/internal/middleware/request_id.go @@ -0,0 +1,30 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/google/uuid" +) + +type requestIDContextKey struct{} + +func RequestID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestID := r.Header.Get("X-Request-Id") + + if requestID == "" { + requestID = uuid.NewString() + } + + w.Header().Set("X-Request-Id", requestID) + + ctx := context.WithValue(r.Context(), requestIDContextKey{}, requestID) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +func GetRequestID(ctx context.Context) string { + id, _ := ctx.Value(requestIDContextKey{}).(string) + return id +} diff --git a/internal/middleware/telemetry.go b/internal/middleware/telemetry.go new file mode 100644 index 0000000..13766d0 --- /dev/null +++ b/internal/middleware/telemetry.go @@ -0,0 +1,46 @@ +package middleware + +import ( + "net/http" + "time" + + "go.opentelemetry.io/otel/trace" + + "gavrilenko-sxdees/lab7/internal/telemetry" +) + +type statusWriter struct { + http.ResponseWriter + status int +} + +func (w *statusWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +func (w *statusWriter) WriteHeader(status int) { + w.status = status + w.ResponseWriter.WriteHeader(status) +} + +func Telemetry() func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + ctx, span := telemetry.Start(telemetry.Incoming(r), "http.request", trace.SpanKindServer) + defer span.End() + + writer := &statusWriter{ResponseWriter: w, status: http.StatusOK} + next.ServeHTTP(writer, r.WithContext(ctx)) + + route := telemetry.RoutePattern(r) + if route == "/health/live" || route == "/health/ready" { + return + } + telemetry.HTTP(ctx, r.Method, route, writer.status, time.Since(start).Seconds()) + if tid := telemetry.TraceID(ctx); tid != "" && tid != "00000000000000000000000000000000" { + w.Header().Set("X-Trace-Id", tid) + } + }) + } +} \ No newline at end of file diff --git a/internal/middleware/timeout.go b/internal/middleware/timeout.go new file mode 100644 index 0000000..9486fa3 --- /dev/null +++ b/internal/middleware/timeout.go @@ -0,0 +1,17 @@ +package middleware + +import ( + "context" + "net/http" + "time" +) + +func RequestTimeout(d time.Duration) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), d) + defer cancel() + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} diff --git a/internal/model/attachment.go b/internal/model/attachment.go new file mode 100644 index 0000000..c08fdf8 --- /dev/null +++ b/internal/model/attachment.go @@ -0,0 +1,60 @@ +package model + +import ( + "time" + + "github.com/google/uuid" +) + +type ContentType string + +const ( + ContentTypePNG ContentType = "image/png" + ContentTypeJPEG ContentType = "image/jpeg" + ContentTypeWebP ContentType = "image/webp" +) + +type AttachmentStatus string + +const ( + AttachmentStatusQueued AttachmentStatus = "queued" + AttachmentStatusProcessing AttachmentStatus = "processing" + AttachmentStatusReady AttachmentStatus = "ready" + AttachmentStatusFailed AttachmentStatus = "failed" +) + +const AttachmentContentOriginal = "original" + +type AttachmentVariantName string + +const ( + AttachmentVariantNameThumbnail AttachmentVariantName = "thumbnail" + AttachmentVariantNameCrop AttachmentVariantName = "crop" + AttachmentVariantNameOptimized AttachmentVariantName = "optimized" +) + +type AttachmentVariant struct { + Name AttachmentVariantName + ContentType ContentType + SizeBytes int + Width int + Height int + Sha256 string +} + +type Attachment struct { + Variants []AttachmentVariant + ID uuid.UUID + ChatID uuid.UUID + OwnerID uuid.UUID + Filename string + ContentType ContentType + SizeBytes int + Sha256 string + Status AttachmentStatus + Width *int32 + Height *int32 + ErrorCode *string + CreatedAt time.Time + UpdatedAt time.Time +} diff --git a/internal/model/attachment_job.go b/internal/model/attachment_job.go new file mode 100644 index 0000000..d69b2c7 --- /dev/null +++ b/internal/model/attachment_job.go @@ -0,0 +1,19 @@ +package model + +import ( + "time" + + "github.com/google/uuid" +) + +type AttachmentJob struct { + SchemaVersion int `json:"schema_version"` + JobID uuid.UUID `json:"job_id"` + Type string `json:"type"` + AttachmentID uuid.UUID `json:"attachment_id"` + PipelineVersion int `json:"pipeline_version"` + Attempt int `json:"attempt"` + CreatedAt time.Time `json:"created_at"` + Traceparent string `json:"traceparent,omitempty"` + Tracestate string `json:"tracestate,omitempty"` +} diff --git a/internal/model/chat.go b/internal/model/chat.go new file mode 100644 index 0000000..2c47c49 --- /dev/null +++ b/internal/model/chat.go @@ -0,0 +1,14 @@ +package model + +import ( + "time" + + "github.com/google/uuid" +) + +type Chat struct { + ID uuid.UUID + Title string + MemberIDs []uuid.UUID + CreatedAt time.Time +} diff --git a/internal/model/message.go b/internal/model/message.go new file mode 100644 index 0000000..8db0c61 --- /dev/null +++ b/internal/model/message.go @@ -0,0 +1,16 @@ +package model + +import ( + "time" + + "github.com/google/uuid" +) + +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + AttachmentIDs []uuid.UUID + CreatedAt time.Time +} diff --git a/internal/model/session.go b/internal/model/session.go new file mode 100644 index 0000000..4129b79 --- /dev/null +++ b/internal/model/session.go @@ -0,0 +1,9 @@ +package model + +import "time" + +type Session struct { + Token string + ExpiresAt time.Time + User User +} diff --git a/internal/model/user.go b/internal/model/user.go new file mode 100644 index 0000000..dc7eff1 --- /dev/null +++ b/internal/model/user.go @@ -0,0 +1,14 @@ +package model + +import ( + "time" + + "github.com/google/uuid" +) + +type User struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} diff --git a/internal/openbao/client.go b/internal/openbao/client.go new file mode 100644 index 0000000..67a508c --- /dev/null +++ b/internal/openbao/client.go @@ -0,0 +1,127 @@ +package openbao + +import ( + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" +) + +// VerifyAppRole proves service authentication against OpenBao (no root token in app). +func VerifyAppRole(ctx context.Context, role string) error { + addr := strings.TrimRight(os.Getenv("BAO_ADDR"), "/") + if addr == "" { + return nil + } + roleID, err := readFile(os.Getenv("BAO_ROLE_ID_FILE")) + if err != nil || strings.HasPrefix(roleID, "00000000") || roleID == "bootstrap-pending" { + return fmt.Errorf("openbao approle not bootstrapped") + } + secretID, err := readFile(os.Getenv("BAO_SECRET_ID_FILE")) + if err != nil { + return err + } + caPath := os.Getenv("BAO_CACERT") + if caPath == "" { + caPath = "/run/secrets/ca_cert" + } + client, err := httpClient(caPath) + if err != nil { + return err + } + + body := fmt.Sprintf(`{"role_id":%q,"secret_id":%q}`, roleID, secretID) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, addr+"/v1/auth/approle/login", strings.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("approle login: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + b, _ := io.ReadAll(resp.Body) + return fmt.Errorf("approle login status %d: %s", resp.StatusCode, strings.TrimSpace(string(b))) + } + var login struct { + Auth struct { + ClientToken string `json:"client_token"` + } `json:"auth"` + } + if err := json.NewDecoder(resp.Body).Decode(&login); err != nil { + return err + } + token := login.Auth.ClientToken + if token == "" { + return fmt.Errorf("empty openbao token") + } + + path := os.Getenv("BAO_VERIFY_KV_PATH") + if path == "" { + if role == "worker" { + path = "messenger/worker/stand" + } else { + path = "messenger/api/stand" + } + } + req2, err := http.NewRequestWithContext(ctx, http.MethodGet, addr+"/v1/secret/data/"+path, nil) + if err != nil { + return err + } + req2.Header.Set("X-Vault-Token", token) + resp2, err := client.Do(req2) + if err != nil { + return err + } + defer resp2.Body.Close() + if resp2.StatusCode == http.StatusNotFound { + return nil + } + if resp2.StatusCode != http.StatusOK { + b, _ := io.ReadAll(resp2.Body) + return fmt.Errorf("kv read status %d: %s", resp2.StatusCode, strings.TrimSpace(string(b))) + } + return nil +} + +func readFile(path string) (string, error) { + if path == "" { + return "", fmt.Errorf("empty path") + } + b, err := os.ReadFile(path) + if err != nil { + return "", err + } + return strings.TrimSpace(string(b)), nil +} + +func httpClient(caPath string) (*http.Client, error) { + caPEM, err := os.ReadFile(caPath) + if err != nil { + return nil, err + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(caPEM) { + return nil, fmt.Errorf("parse bao ca") + } + serverName := os.Getenv("BAO_TLS_SERVER_NAME") + if serverName == "" { + serverName = "openbao.messenger.lab" + } + tr := &http.Transport{ + TLSClientConfig: &tls.Config{ + RootCAs: pool, + MinVersion: tls.VersionTLS12, + ServerName: serverName, + }, + } + return &http.Client{Transport: tr, Timeout: 5 * time.Second}, nil +} \ No newline at end of file diff --git a/internal/outbox/publisher.go b/internal/outbox/publisher.go new file mode 100644 index 0000000..1179a9d --- /dev/null +++ b/internal/outbox/publisher.go @@ -0,0 +1,139 @@ +package outbox + +import ( + "context" + "encoding/json" + "log/slog" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + amqp "github.com/rabbitmq/amqp091-go" + "go.opentelemetry.io/otel/trace" + + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/model" + "gavrilenko-sxdees/lab7/internal/rabbitmq" + "gavrilenko-sxdees/lab7/internal/telemetry" +) + +const ( + pollInterval = time.Second + retryInterval = 2 * time.Second + publishTimeout = 5 * time.Second +) + +type Publisher struct { + pool *pgxpool.Pool + url string + log *slog.Logger +} + +func NewPublisher(pool *pgxpool.Pool, url string, log *slog.Logger) *Publisher { + return &Publisher{ + pool: pool, + url: url, + log: log, + } +} + +func (p *Publisher) Run(ctx context.Context) { + for ctx.Err() == nil { + client, err := rabbitmq.New(p.url) + if err == nil { + p.log.Info("outbox publisher connected") + err = p.publish(ctx, client) + _ = client.Close() + } + if ctx.Err() != nil { + return + } + p.log.Error("outbox publisher retry", "error", err) + if !wait(ctx, retryInterval) { + return + } + } +} + +func (p *Publisher) publish(ctx context.Context, client *rabbitmq.Client) error { + for ctx.Err() == nil { + published, err := p.publishOne(ctx, client) + if err != nil { + return err + } + if !published && !wait(ctx, pollInterval) { + return ctx.Err() + } + } + return ctx.Err() +} + +func (p *Publisher) publishOne(ctx context.Context, client *rabbitmq.Client) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, publishTimeout) + defer cancel() + + tx, err := p.pool.Begin(ctx) + if err != nil { + return false, err + } + defer tx.Rollback(ctx) + + q := db.New(tx) + rows, err := q.LockPendingOutboxEntries(ctx, 1) + if err != nil { + return false, err + } + if len(rows) == 0 { + return false, nil + } + row := rows[0] + publishCtx, span := telemetry.Start( + telemetry.Extract(ctx, row.Traceparent, row.Tracestate), + "queue.publish", + trace.SpanKindProducer, + ) + defer span.End() + body, err := json.Marshal(model.AttachmentJob{ + SchemaVersion: 1, + JobID: row.JobID, + Type: "attachment.process.v1", + AttachmentID: row.AttachmentID, + PipelineVersion: row.PipelineVersion, + Attempt: row.Attempt, + CreatedAt: row.CreatedAt.UTC(), + Traceparent: row.Traceparent, + Tracestate: row.Tracestate, + }) + if err != nil { + return false, err + } + parent, state := telemetry.Inject(publishCtx) + headers := amqp.Table{} + if parent != "" { + headers["traceparent"] = parent + } + if state != "" { + headers["tracestate"] = state + } + if err := client.Publish(publishCtx, row.JobID.String(), body, headers); err != nil { + return false, err + } + if _, err := q.MarkOutboxPublished(ctx, row.ID); err != nil { + return false, err + } + if err := tx.Commit(ctx); err != nil { + return false, err + } + return true, nil +} + +func wait(ctx context.Context, delay time.Duration) bool { + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} diff --git a/internal/postgres/errors.go b/internal/postgres/errors.go new file mode 100644 index 0000000..961f069 --- /dev/null +++ b/internal/postgres/errors.go @@ -0,0 +1,25 @@ +package postgres + +import ( + "errors" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +const ( + CodeUniqueViolation = "23505" + CodeForeignKeyViolation = "23503" + CodeCheckViolation = "23514" +) + +func ErrCode(err error) string { + if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok { + return pgErr.Code + } + return "" +} + +func IsNotFound(err error) bool { + return errors.Is(err, pgx.ErrNoRows) +} diff --git a/internal/postgres/pool.go b/internal/postgres/pool.go new file mode 100644 index 0000000..4a1361a --- /dev/null +++ b/internal/postgres/pool.go @@ -0,0 +1,34 @@ +package postgres + +import ( + "context" + "fmt" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +func New(ctx context.Context, url string) (*pgxpool.Pool, error) { + cfg, err := pgxpool.ParseConfig(url) + if err != nil { + return nil, fmt.Errorf("parse database url: %w", err) + } + + cfg.MaxConns = 10 + cfg.ConnConfig.ConnectTimeout = 5 * time.Second + cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000" + + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, fmt.Errorf("create pool: %w", err) + } + + pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, fmt.Errorf("ping database: %w", err) + } + + return pool, nil +} diff --git a/internal/rabbitmq/client.go b/internal/rabbitmq/client.go new file mode 100644 index 0000000..621d982 --- /dev/null +++ b/internal/rabbitmq/client.go @@ -0,0 +1,120 @@ +package rabbitmq + +import ( + "context" + "errors" + "time" + + amqp "github.com/rabbitmq/amqp091-go" + + "gavrilenko-sxdees/lab7/internal/tlsconfig" +) + +const QueueName = "attachments.process.v1" + +var ( + ErrConnect = errors.New("connect to rabbitmq") + ErrNotRouted = errors.New("rabbitmq message not routed") + ErrNack = errors.New("rabbitmq publish rejected") + ErrPrefetch = errors.New("rabbitmq prefetch must be positive") +) + +type Client struct { + conn *amqp.Connection + channel *amqp.Channel + returns <-chan amqp.Return +} + +func New(url string) (*Client, error) { + cfg := amqp.Config{} + tlsCfg, err := tlsconfig.ClientTLSFromEnv("BROKER_TLS") + if err != nil { + return nil, err + } + if tlsCfg != nil { + cfg.TLSClientConfig = tlsCfg + } else { + cfg.Dial = amqp.DefaultDial(5 * time.Second) + } + conn, err := amqp.DialConfig(url, cfg) + if err != nil { + return nil, ErrConnect + } + + channel, err := conn.Channel() + if err != nil { + _ = conn.CloseDeadline(time.Now().Add(time.Second)) + return nil, err + } + if _, err := channel.QueueDeclare(QueueName, true, false, false, false, nil); err != nil { + _ = conn.CloseDeadline(time.Now().Add(time.Second)) + return nil, err + } + if err := channel.Confirm(false); err != nil { + _ = conn.CloseDeadline(time.Now().Add(time.Second)) + return nil, err + } + + return &Client{ + conn: conn, + channel: channel, + returns: channel.NotifyReturn(make(chan amqp.Return, 1)), + }, nil +} + +// Publish must not be called concurrently on the same client. +func (c *Client) Publish(ctx context.Context, messageID string, body []byte, headers amqp.Table) error { + if err := ctx.Err(); err != nil { + return err + } + + stop := context.AfterFunc(ctx, func() { + _ = c.conn.CloseDeadline(time.Now()) + }) + defer stop() + + if headers == nil { + headers = amqp.Table{} + } + confirmation, err := c.channel.PublishWithDeferredConfirm("", QueueName, true, false, amqp.Publishing{ + ContentType: "application/json", + DeliveryMode: amqp.Persistent, + MessageId: messageID, + Headers: headers, + Body: body, + }) + if err != nil { + return err + } + ack, err := confirmation.WaitContext(ctx) + if err != nil { + return err + } + if !ack { + return ErrNack + } + + select { + case _, ok := <-c.returns: + if !ok { + return amqp.ErrClosed + } + return ErrNotRouted + default: + return nil + } +} + +func (c *Client) Consume(ctx context.Context, prefetch int) (<-chan amqp.Delivery, error) { + if prefetch < 1 { + return nil, ErrPrefetch + } + if err := c.channel.Qos(prefetch, 0, false); err != nil { + return nil, err + } + return c.channel.ConsumeWithContext(ctx, QueueName, "", false, false, false, false, nil) +} + +func (c *Client) Close() error { + return c.conn.CloseDeadline(time.Now().Add(time.Second)) +} diff --git a/internal/reconcile/reconcile.go b/internal/reconcile/reconcile.go new file mode 100644 index 0000000..bd0b21d --- /dev/null +++ b/internal/reconcile/reconcile.go @@ -0,0 +1,323 @@ +package reconcile + +import ( + "context" + "fmt" + "log/slog" + "sort" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "gavrilenko-sxdees/lab7/internal/db" + s3store "gavrilenko-sxdees/lab7/internal/s3" +) + +const ( + Prefix = "chats/" + StagingPrefix = "staging/" + DefaultStagingRetention = 24 * time.Hour + DefaultGrace = time.Hour + DefaultMaxDeletes = 100 + ErrorCodeObjectMissing = "object_missing" +) + +type Options struct { + DryRun bool + Grace time.Duration + MaxDeletes int + StagingRetention time.Duration +} + +type Report struct { + ScannedObjects int `json:"scanned_objects"` + ScannedRows int `json:"scanned_rows"` + ListPages int `json:"list_pages"` + StagingObjects []string `json:"staging_objects"` + OrphanObjects []string `json:"orphan_objects"` + MissingAttachments []uuid.UUID `json:"missing_attachments"` + CorruptObjects []string `json:"corrupt_objects"` + SkippedFresh int `json:"skipped_fresh"` + SkippedInactive int `json:"skipped_inactive"` + DeletedObjects int `json:"deleted_objects"` + MarkedFailed int `json:"marked_failed"` + DryRun bool `json:"dry_run"` + Errors []string `json:"errors"` + DurationMS int64 `json:"duration_ms"` +} + +type ObjectClient interface { + ListAll(ctx context.Context, prefix string) (s3store.ListResult, error) + DeleteAdmin(ctx context.Context, key string) error +} + +type txBeginner interface { + Begin(ctx context.Context) (pgx.Tx, error) +} + +type AttachmentQueries interface { + LockAttachmentByStagingKey(ctx context.Context, stagingKey string) (db.Attachment, error) + ClearAttachmentStagingKey(ctx context.Context, id uuid.UUID) error + ListAttachmentsForReconcile(ctx context.Context) ([]db.ListAttachmentsForReconcileRow, error) + MarkAttachmentFailedIfReady(ctx context.Context, arg db.MarkAttachmentFailedIfReadyParams) (int64, error) +} + +type Reconciler struct { + pool txBeginner + q AttachmentQueries + withTx func(pgx.Tx) AttachmentQueries + store ObjectClient + log *slog.Logger + now func() time.Time +} + +type plan struct { + orphans []s3store.ObjectInfo + staging []s3store.ObjectInfo + missing []db.ListAttachmentsForReconcileRow + corrupt []s3store.ObjectInfo + skippedFresh int + skippedInactive int +} + +func New( + pool *pgxpool.Pool, + store ObjectClient, + queries *db.Queries, + log *slog.Logger, +) *Reconciler { + if log == nil { + log = slog.Default() + } + + return &Reconciler{ + pool: pool, + withTx: func(tx pgx.Tx) AttachmentQueries { + return queries.WithTx(tx) + }, + store: store, + q: queries, + log: log, + now: time.Now, + } +} + +func (r *Reconciler) Run(ctx context.Context, opts Options) (Report, error) { + opts = opts.withDefaults() + started := r.now() + + report := Report{ + OrphanObjects: []string{}, + StagingObjects: []string{}, + MissingAttachments: []uuid.UUID{}, + CorruptObjects: []string{}, + DryRun: opts.DryRun, + Errors: []string{}, + } + + listed, err := r.store.ListAll(ctx, Prefix) + if err != nil { + return report, err + } + + staging, err := r.store.ListAll(ctx, StagingPrefix) + if err != nil { + return report, err + } + + rows, err := r.q.ListAttachmentsForReconcile(ctx) + if err != nil { + return report, err + } + + report.ScannedObjects = len(listed.Objects) + len(staging.Objects) + report.ScannedRows = len(rows) + report.ListPages = listed.Pages + staging.Pages + + p := buildPlan(listed.Objects, staging.Objects, rows, started, opts) + + for _, obj := range p.orphans { + report.OrphanObjects = append(report.OrphanObjects, obj.Key) + } + for _, obj := range p.staging { + report.StagingObjects = append(report.StagingObjects, obj.Key) + } + for _, obj := range p.corrupt { + report.CorruptObjects = append(report.CorruptObjects, obj.Key) + } + for _, row := range p.missing { + report.MissingAttachments = append(report.MissingAttachments, row.ID) + } + + report.SkippedFresh = p.skippedFresh + report.SkippedInactive = p.skippedInactive + + if !opts.DryRun { + r.apply(ctx, opts, p, &report) + } + + report.DurationMS = r.now().Sub(started).Milliseconds() + + r.log.Info( + "attachment reconcile finished", + "dry_run", opts.DryRun, + "scanned_objects", report.ScannedObjects, + "scanned_rows", report.ScannedRows, + "list_pages", report.ListPages, + "orphan_objects", len(report.OrphanObjects), + "staging_objects", len(report.StagingObjects), + "missing_attachments", len(report.MissingAttachments), + "corrupt_objects", len(report.CorruptObjects), + "deleted_objects", report.DeletedObjects, + "marked_failed", report.MarkedFailed, + "errors", len(report.Errors), + ) + + return report, nil +} + +func (o Options) withDefaults() Options { + if o.Grace <= 0 { + o.Grace = DefaultGrace + } + if o.MaxDeletes <= 0 { + o.MaxDeletes = DefaultMaxDeletes + } + + if o.StagingRetention <= 0 { + o.StagingRetention = DefaultStagingRetention + } + + return o +} + +func buildPlan( + objects []s3store.ObjectInfo, + staging []s3store.ObjectInfo, + rows []db.ListAttachmentsForReconcileRow, + now time.Time, + opts Options, +) plan { + var p plan + + byKey := make(map[string]s3store.ObjectInfo, len(objects)) + for _, obj := range objects { + byKey[obj.Key] = obj + } + + byStagingKey := make(map[string]db.ListAttachmentsForReconcileRow, len(rows)) + for _, row := range rows { + if row.StagingKey != nil { + byStagingKey[*row.StagingKey] = row + } + + obj, exists := byKey[row.S3Key] + if exists { + delete(byKey, row.S3Key) + } + + switch row.Status { + case db.AttachmentStatusQueued: + p.skippedInactive++ + case db.AttachmentStatusReady: + if !exists { + p.missing = append(p.missing, row) + continue + } + if obj.Size != int64(row.SizeBytes) { + p.corrupt = append(p.corrupt, obj) + } + default: + if exists { + p.skippedInactive++ + } + } + } + + for _, obj := range byKey { + if now.Sub(obj.LastModified) < opts.Grace { + p.skippedFresh++ + continue + } + p.orphans = append(p.orphans, obj) + } + + for _, obj := range staging { + retainedSince := obj.LastModified + if row, exists := byStagingKey[obj.Key]; exists { + if row.Status != db.AttachmentStatusReady && row.Status != db.AttachmentStatusFailed { + p.skippedInactive++ + continue + } + + retainedSince = row.UpdatedAt + } + + if now.Sub(retainedSince) < opts.StagingRetention { + p.skippedFresh++ + continue + } + + p.staging = append(p.staging, obj) + } + + sort.Slice(p.staging, func(i, j int) bool { + return p.staging[i].Key < p.staging[j].Key + }) + sort.Slice(p.orphans, func(i, j int) bool { + return p.orphans[i].Key < p.orphans[j].Key + }) + sort.Slice(p.corrupt, func(i, j int) bool { + return p.corrupt[i].Key < p.corrupt[j].Key + }) + sort.Slice(p.missing, func(i, j int) bool { + return p.missing[i].ID.String() < p.missing[j].ID.String() + }) + + return p +} + +func (r *Reconciler) apply(ctx context.Context, opts Options, p plan, report *Report) { + deletes := 0 + + for _, obj := range p.orphans { + if deletes >= opts.MaxDeletes { + report.Errors = append(report.Errors, "max deletes reached") + break + } + + if err := r.store.DeleteAdmin(ctx, obj.Key); err != nil { + report.Errors = append(report.Errors, fmt.Sprintf("delete object %s: %v", obj.Key, err)) + continue + } + + deletes++ + report.DeletedObjects++ + } + + for _, row := range p.missing { + marked, err := r.q.MarkAttachmentFailedIfReady(ctx, db.MarkAttachmentFailedIfReadyParams{ + ID: row.ID, + ErrorCode: ErrorCodeObjectMissing, + }) + if err != nil { + report.Errors = append(report.Errors, fmt.Sprintf("mark failed %s: %v", row.ID, err)) + continue + } + + report.MarkedFailed += int(marked) + } + + for _, obj := range p.staging { + if report.DeletedObjects >= opts.MaxDeletes { + report.Errors = append(report.Errors, "max deletes reached") + break + } + + if err := r.cleanupStagingObject(ctx, obj, opts, report); err != nil { + report.Errors = append(report.Errors, fmt.Sprintf("cleanup staging %s: %v", obj.Key, err)) + } + } +} diff --git a/internal/reconcile/staging.go b/internal/reconcile/staging.go new file mode 100644 index 0000000..9f0287e --- /dev/null +++ b/internal/reconcile/staging.go @@ -0,0 +1,60 @@ +package reconcile + +import ( + "context" + "errors" + "time" + + "github.com/jackc/pgx/v5" + + "gavrilenko-sxdees/lab7/internal/db" + s3store "gavrilenko-sxdees/lab7/internal/s3" +) + +func (r *Reconciler) cleanupStagingObject( + ctx context.Context, + obj s3store.ObjectInfo, + opts Options, + report *Report, +) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + tx, err := r.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(context.Background()) + + q := r.withTx(tx) + row, err := q.LockAttachmentByStagingKey(ctx, obj.Key) + orphan := errors.Is(err, pgx.ErrNoRows) + if err != nil && !orphan { + return err + } + + if !orphan { + if row.Status != db.AttachmentStatusReady && row.Status != db.AttachmentStatusFailed { + report.SkippedInactive++ + return nil + } + + if r.now().Sub(row.UpdatedAt) < opts.StagingRetention { + report.SkippedFresh++ + return nil + } + } + + if err := r.store.DeleteAdmin(ctx, obj.Key); err != nil { + return err + } + report.DeletedObjects++ + + if !orphan { + if err := q.ClearAttachmentStagingKey(ctx, row.ID); err != nil { + return err + } + } + + return tx.Commit(ctx) +} diff --git a/internal/redis/client.go b/internal/redis/client.go new file mode 100644 index 0000000..65ccd3a --- /dev/null +++ b/internal/redis/client.go @@ -0,0 +1,32 @@ +package redis + +import ( + "context" + "fmt" + "log/slog" + "time" + + goredis "github.com/redis/go-redis/v9" +) + +func New(ctx context.Context, log *slog.Logger, url string) (*goredis.Client, error) { + opts, err := goredis.ParseURL(url) + if err != nil { + return nil, fmt.Errorf("parse redis url: %w", err) + } + + opts.DialTimeout = 1 * time.Second + opts.ReadTimeout = 200 * time.Millisecond + opts.WriteTimeout = 200 * time.Millisecond + opts.MaxRetries = -1 + + client := goredis.NewClient(opts) + + pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + if err := client.Ping(pingCtx).Err(); err != nil { + log.Warn("redis unavailable, running without cache", "error", err) + } + + return client, nil +} diff --git a/internal/s3/client.go b/internal/s3/client.go new file mode 100644 index 0000000..ca95b57 --- /dev/null +++ b/internal/s3/client.go @@ -0,0 +1,301 @@ +package s3 + +import ( + "context" + "errors" + "io" + "log/slog" + "net" + "net/http" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/smithy-go" + + appconfig "gavrilenko-sxdees/lab7/internal/config" + "gavrilenko-sxdees/lab7/internal/telemetry" +) + +var ( + ErrUnavailable = errors.New("s3 unavailable") + ErrLoadConfig = errors.New("load aws config") + ErrHeadBucket = errors.New("head bucket") + ErrCreateBucket = errors.New("create bucket") + ErrObjectNotFound = errors.New("object not found") + ErrPutObject = errors.New("put object") + ErrGetObject = errors.New("get object") + ErrListObjects = errors.New("list objects") + ErrDeleteObject = errors.New("delete object") +) + +type Client struct { + bucket string + bootstrap *awss3.Client + api *awss3.Client + log *slog.Logger +} + +type ObjectInfo struct { + Key string + Size int64 + LastModified time.Time +} + +type ListResult struct { + Objects []ObjectInfo + Pages int +} + +func New(ctx context.Context, cfg appconfig.S3Config, log *slog.Logger) (*Client, error) { + c, err := NewAPI(ctx, cfg, log) + if err != nil { + return nil, err + } + + bootstrapAccessKey, err := cfg.BootstrapAccessKey() + if err != nil { + log.Error("read s3 bootstrap access key", "error", err) + return nil, err + } + + bootstrapSecretKey, err := cfg.BootstrapSecretKey() + if err != nil { + log.Error("read s3 bootstrap secret key", "error", err) + return nil, err + } + + c.bootstrap, err = newS3Client(ctx, log, cfg.Endpoint, cfg.Region, bootstrapAccessKey, bootstrapSecretKey) + if err != nil { + return nil, err + } + + return c, nil +} + +func NewAPI(ctx context.Context, cfg appconfig.S3Config, log *slog.Logger) (*Client, error) { + apiAccessKey, err := cfg.APIAccessKey() + if err != nil { + log.Error("read s3 api access key", "error", err) + return nil, err + } + + apiSecretKey, err := cfg.APISecretKey() + if err != nil { + log.Error("read s3 api secret key", "error", err) + return nil, err + } + + api, err := newS3Client(ctx, log, cfg.Endpoint, cfg.Region, apiAccessKey, apiSecretKey) + if err != nil { + return nil, err + } + + return &Client{ + bucket: cfg.Bucket, + api: api, + log: log, + }, nil +} + +func (c *Client) Bucket() string { + return c.bucket +} + +func (c *Client) EnsureBucket(ctx context.Context) error { + _, err := c.bootstrap.HeadBucket(ctx, &awss3.HeadBucketInput{ + Bucket: aws.String(c.bucket), + }) + if err == nil { + return nil + } + + if !isNotFound(err) { + c.log.Error("head bucket", "bucket", c.bucket, "error", err) + return ErrHeadBucket + } + + _, err = c.bootstrap.CreateBucket(ctx, &awss3.CreateBucketInput{ + Bucket: aws.String(c.bucket), + }) + if err == nil || isAlreadyExists(err) { + return nil + } + + c.log.Error("create bucket", "bucket", c.bucket, "error", err) + return ErrCreateBucket +} + +func (c *Client) Ping(ctx context.Context) error { + _, err := c.api.HeadBucket(ctx, &awss3.HeadBucketInput{Bucket: aws.String(c.bucket)}) + if err != nil { + c.log.Error("head bucket", "bucket", c.bucket, "error", err) + return operationError(ErrHeadBucket, err) + } + return nil +} + +func (c *Client) Put( + ctx context.Context, + key string, + body io.ReadSeeker, + size int64, + contentType string, +) error { + _, err := c.api.PutObject(ctx, &awss3.PutObjectInput{ + Bucket: aws.String(c.bucket), + Key: aws.String(key), + Body: body, + ContentLength: aws.Int64(size), + ContentType: aws.String(contentType), + }) + if err != nil { + c.log.Error("put object", "bucket", c.bucket, "key", key, "error", err) + return operationError(ErrPutObject, err) + } + + return nil +} + +func (c *Client) Get(ctx context.Context, key string) (*awss3.GetObjectOutput, error) { + out, err := c.api.GetObject(ctx, &awss3.GetObjectInput{ + Bucket: aws.String(c.bucket), + Key: aws.String(key), + }) + if isNotFound(err) { + c.log.Warn("get object", "bucket", c.bucket, "key", key, "error", err) + return nil, ErrObjectNotFound + } + if err != nil { + c.log.Error("get object", "bucket", c.bucket, "key", key, "error", err) + return nil, operationError(ErrGetObject, err) + } + + return out, nil +} + +func (c *Client) ListAll(ctx context.Context, prefix string) (ListResult, error) { + result := ListResult{Objects: []ObjectInfo{}} + + paginator := awss3.NewListObjectsV2Paginator(c.bootstrap, &awss3.ListObjectsV2Input{ + Bucket: aws.String(c.bucket), + Prefix: aws.String(prefix), + }) + + for paginator.HasMorePages() { + page, err := paginator.NextPage(ctx) + if err != nil { + c.log.Error("list objects", "bucket", c.bucket, "prefix", prefix, "error", err) + return ListResult{}, ErrListObjects + } + + result.Pages++ + + for _, obj := range page.Contents { + result.Objects = append(result.Objects, ObjectInfo{ + Key: aws.ToString(obj.Key), + Size: aws.ToInt64(obj.Size), + LastModified: aws.ToTime(obj.LastModified), + }) + } + } + + return result, nil +} + +func (c *Client) DeleteAdmin(ctx context.Context, key string) error { + return c.deleteObject(ctx, c.bootstrap, key) +} + +func (c *Client) Delete(ctx context.Context, key string) error { + return c.deleteObject(ctx, c.api, key) +} + +func (c *Client) deleteObject(ctx context.Context, client *awss3.Client, key string) error { + _, err := client.DeleteObject(ctx, &awss3.DeleteObjectInput{ + Bucket: aws.String(c.bucket), + Key: aws.String(key), + }) + if isNotFound(err) { + return nil + } + if err != nil { + c.log.Error("delete object", "bucket", c.bucket, "key", key, "error", err) + return ErrDeleteObject + } + + return nil +} + +func newS3Client( + ctx context.Context, + log *slog.Logger, + endpoint string, + region string, + accessKey string, + secretKey string, +) (*awss3.Client, error) { + httpClient := &http.Client{ + Transport: telemetry.Transport(http.DefaultTransport), + Timeout: 30 * time.Second, + } + cfg, err := awsconfig.LoadDefaultConfig( + ctx, + awsconfig.WithRegion(region), + awsconfig.WithHTTPClient(httpClient), + awsconfig.WithCredentialsProvider( + credentials.NewStaticCredentialsProvider(accessKey, secretKey, ""), + ), + ) + if err != nil { + log.Error("load aws config", "endpoint", endpoint, "region", region, "error", err) + return nil, ErrLoadConfig + } + + return awss3.NewFromConfig(cfg, func(o *awss3.Options) { + o.BaseEndpoint = aws.String(endpoint) + o.UsePathStyle = true + }), nil +} + +func operationError(operation, err error) error { + var networkError net.Error + var responseError *awshttp.ResponseError + if errors.Is(err, context.DeadlineExceeded) || errors.As(err, &networkError) || + (errors.As(err, &responseError) && responseError.HTTPStatusCode() >= 500) { + return ErrUnavailable + } + return operation +} + +func isNotFound(err error) bool { + var responseErr *awshttp.ResponseError + if errors.As(err, &responseErr) && responseErr.HTTPStatusCode() == http.StatusNotFound { + return true + } + + var apiErr smithy.APIError + if errors.As(err, &apiErr) { + switch apiErr.ErrorCode() { + case "NotFound", "NoSuchBucket", "NoSuchKey": + return true + } + } + + return false +} + +func isAlreadyExists(err error) bool { + var apiErr smithy.APIError + if errors.As(err, &apiErr) { + switch apiErr.ErrorCode() { + case "BucketAlreadyOwnedByYou", "BucketAlreadyExists": + return true + } + } + + return false +} diff --git a/internal/s3/config.go b/internal/s3/config.go new file mode 100644 index 0000000..8e0a88b --- /dev/null +++ b/internal/s3/config.go @@ -0,0 +1,99 @@ +package s3 + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + + "gavrilenko-sxdees/lab7/internal/config" +) + +const ( + seaweedUID = 1000 + seaweedGID = 1000 +) + +type Credential struct { + AccessKey string `json:"accessKey"` + SecretKey string `json:"secretKey"` +} + +type Identity struct { + Name string `json:"name"` + Credentials []Credential `json:"credentials"` + Actions []string `json:"actions"` +} + +type Config struct { + Identities []Identity `json:"identities"` +} + +func WriteConfig(output string, cfg config.S3Config) error { + apiAccessKey, err := cfg.APIAccessKey() + if err != nil { + return err + } + + apiSecretKey, err := cfg.APISecretKey() + if err != nil { + return err + } + + bootstrapAccessKey, err := cfg.BootstrapAccessKey() + if err != nil { + return err + } + + bootstrapSecretKey, err := cfg.BootstrapSecretKey() + if err != nil { + return err + } + + config := Config{ + Identities: []Identity{ + { + Name: "bootstrap", + Credentials: []Credential{ + {AccessKey: bootstrapAccessKey, SecretKey: bootstrapSecretKey}, + }, + Actions: []string{"Admin", "Read", "Write", "List", "Tagging"}, + }, + { + Name: "api", + Credentials: []Credential{ + {AccessKey: apiAccessKey, SecretKey: apiSecretKey}, + }, + Actions: []string{"Read", "Write", "List", "Tagging"}, + }, + }, + } + + data, err := json.MarshalIndent(config, "", " ") + if err != nil { + return fmt.Errorf("marshal s3 config: %w", err) + } + + if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil { + return fmt.Errorf("create config directory: %w", err) + } + + tmp := output + ".tmp" + if err := os.WriteFile(tmp, append(data, '\n'), 0o600); err != nil { + return fmt.Errorf("write config: %w", err) + } + + if err := os.Chown(tmp, seaweedUID, seaweedGID); err != nil { + return fmt.Errorf("chown config: %w", err) + } + + if err := os.Chmod(tmp, 0o400); err != nil { + return fmt.Errorf("chmod config: %w", err) + } + + if err := os.Rename(tmp, output); err != nil { + return fmt.Errorf("replace config: %w", err) + } + + return nil +} diff --git a/internal/service/attachment.go b/internal/service/attachment.go new file mode 100644 index 0000000..3a50dc7 --- /dev/null +++ b/internal/service/attachment.go @@ -0,0 +1,362 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "image" + _ "image/jpeg" + _ "image/png" + "io" + "net" + "net/http" + "os" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/model" + "gavrilenko-sxdees/lab7/internal/postgres" + s3store "gavrilenko-sxdees/lab7/internal/s3" + "gavrilenko-sxdees/lab7/internal/telemetry" +) + +var ( + ErrAttachmentNotFound = errors.New("attachment not found") + ErrAttachmentNotReady = errors.New("attachment not ready") + ErrInvalidImage = errors.New("invalid image") + ErrInvalidSize = errors.New("invalid size") + ErrUploadReadTimeout = errors.New("upload body read timed out") +) + +type attachmentQueries interface { + CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error) + CreateOutboxEntry(ctx context.Context, arg db.CreateOutboxEntryParams) (db.Outbox, error) + GetAttachmentByID(ctx context.Context, id uuid.UUID) (db.Attachment, error) + ListAttachmentVariants(ctx context.Context, arg db.ListAttachmentVariantsParams) ([]db.AttachmentVariant, error) + IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error) +} + +type AttachmentService struct { + pool txBeginner + q attachmentQueries + withTx func(pgx.Tx) attachmentQueries + s3 *s3store.Client + maxBytes int + maxPixels int + decodeSlot chan struct{} +} + +func NewAttachmentService( + pool *pgxpool.Pool, + q *db.Queries, + s3 *s3store.Client, + maxBytes, maxPixels int, +) *AttachmentService { + return &AttachmentService{ + pool: pool, + q: q, + withTx: func(tx pgx.Tx) attachmentQueries { + return q.WithTx(tx) + }, + s3: s3, + maxBytes: maxBytes, + maxPixels: maxPixels, + decodeSlot: make(chan struct{}, 1), + } +} + +func (s *AttachmentService) Upload( + ctx context.Context, + userID, chatID uuid.UUID, + filename string, + body io.Reader, + contentType string, +) (model.Attachment, error) { + if err := s.ensureMember(ctx, userID, chatID); err != nil { + return model.Attachment{}, err + } + + tmp, err := os.CreateTemp("", "upload-*.tmp") + if err != nil { + return model.Attachment{}, err + } + defer func() { + _ = tmp.Close() + _ = os.Remove(tmp.Name()) + }() + + hasher := sha256.New() + size, err := io.Copy(io.MultiWriter(tmp, hasher), body) + if err != nil { + var maxBytesErr *http.MaxBytesError + if errors.As(err, &maxBytesErr) { + return model.Attachment{}, ErrInvalidSize + } + var networkErr net.Error + if errors.As(err, &networkErr) && networkErr.Timeout() { + return model.Attachment{}, ErrUploadReadTimeout + } + return model.Attachment{}, err + } + if size > int64(s.maxBytes) { + return model.Attachment{}, ErrInvalidSize + } + + if _, err := tmp.Seek(0, io.SeekStart); err != nil { + return model.Attachment{}, err + } + detectedType, width, height, err := s.checkImage(ctx, tmp, contentType) + if err != nil { + return model.Attachment{}, err + } + + id, err := uuid.NewV7() + if err != nil { + return model.Attachment{}, err + } + jobID, err := uuid.NewV7() + if err != nil { + return model.Attachment{}, err + } + + hash := hex.EncodeToString(hasher.Sum(nil)) + key := "chats/" + chatID.String() + "/attachments/" + id.String() + stagingKey := "staging/" + id.String() + + if _, err := tmp.Seek(0, io.SeekStart); err != nil { + return model.Attachment{}, err + } + + if err := s.s3.Put(ctx, stagingKey, tmp, size, string(detectedType)); err != nil { + return model.Attachment{}, err + } + + tx, err := s.pool.Begin(ctx) + if err != nil { + return model.Attachment{}, err + } + defer tx.Rollback(ctx) + q := s.withTx(tx) + + row, err := q.CreateAttachment(ctx, db.CreateAttachmentParams{ + ID: id, + ChatID: chatID, + OwnerID: userID, + S3Key: key, + StagingKey: stagingKey, + JobID: jobID, + Filename: filename, + ContentType: db.AttachmentContentType(detectedType), + SizeBytes: int(size), + Sha256: hash, + Width: width, + Height: height, + ErrorCode: "", + }) + if postgres.IsNotFound(err) { + return model.Attachment{}, ErrAttachmentNotFound + } + if err != nil { + return model.Attachment{}, err + } + + traceparent, tracestate := telemetry.Inject(ctx) + if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{ + AttachmentID: id, + Attempt: 1, + AvailableAt: row.CreatedAt, + Traceparent: traceparent, + Tracestate: tracestate, + }); err != nil { + return model.Attachment{}, err + } + + if err := tx.Commit(ctx); err != nil { + return model.Attachment{}, err + } + + return model.Attachment{ + ID: row.ID, + ChatID: row.ChatID, + OwnerID: row.OwnerID, + Filename: row.Filename, + ContentType: model.ContentType(row.ContentType), + SizeBytes: row.SizeBytes, + Sha256: row.Sha256, + Status: model.AttachmentStatus(row.Status), + Width: row.Width, + Height: row.Height, + ErrorCode: row.ErrorCode, + CreatedAt: row.CreatedAt, + UpdatedAt: row.UpdatedAt, + }, nil +} + +func (s *AttachmentService) Get( + ctx context.Context, + userID, attachmentID uuid.UUID, +) (model.Attachment, error) { + row, err := s.q.GetAttachmentByID(ctx, attachmentID) + if postgres.IsNotFound(err) { + return model.Attachment{}, ErrAttachmentNotFound + } + if err != nil { + return model.Attachment{}, err + } + + if err := s.ensureMember(ctx, userID, row.ChatID); err != nil { + return model.Attachment{}, err + } + + rows, err := s.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{AttachmentID: row.ID, PipelineVersion: row.PipelineVersion}) + if err != nil { + return model.Attachment{}, err + } + variants := make([]model.AttachmentVariant, 0, len(rows)) + for _, v := range rows { + variants = append(variants, model.AttachmentVariant{ + Name: model.AttachmentVariantName(v.Variant), + ContentType: model.ContentType(v.ContentType), + SizeBytes: v.SizeBytes, + Width: v.Width, + Height: v.Height, + Sha256: v.Sha256, + }) + } + + return model.Attachment{ + Variants: variants, + ID: row.ID, + ChatID: row.ChatID, + OwnerID: row.OwnerID, + Filename: row.Filename, + ContentType: model.ContentType(row.ContentType), + SizeBytes: row.SizeBytes, + Sha256: row.Sha256, + Status: model.AttachmentStatus(row.Status), + Width: row.Width, + Height: row.Height, + ErrorCode: row.ErrorCode, + CreatedAt: row.CreatedAt, + UpdatedAt: row.UpdatedAt, + }, nil +} + +func (s *AttachmentService) GetContent( + ctx context.Context, + userID, attachmentID uuid.UUID, + variant string, +) ([]byte, model.ContentType, error) { + row, err := s.q.GetAttachmentByID(ctx, attachmentID) + if postgres.IsNotFound(err) { + return nil, "", ErrAttachmentNotFound + } + if err != nil { + return nil, "", err + } + + if err := s.ensureMember(ctx, userID, row.ChatID); err != nil { + return nil, "", err + } + + if model.AttachmentStatus(row.Status) != model.AttachmentStatusReady { + return nil, "", ErrAttachmentNotReady + } + + key, contentType := row.S3Key, model.ContentType(row.ContentType) + if variant != "" && variant != model.AttachmentContentOriginal { + rows, err := s.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{AttachmentID: row.ID, PipelineVersion: row.PipelineVersion}) + if err != nil { + return nil, "", err + } + found := false + for _, v := range rows { + if string(v.Variant) == variant { + key, contentType, found = v.S3Key, model.ContentType(v.ContentType), true + break + } + } + if !found { + return nil, "", ErrAttachmentNotFound + } + } + out, err := s.s3.Get(ctx, key) + if err != nil { + return nil, "", err + } + defer out.Body.Close() + + data, err := io.ReadAll(out.Body) + if err != nil { + return nil, "", err + } + + return data, contentType, nil +} + +func (s *AttachmentService) checkImage(ctx context.Context, r io.ReadSeeker, contentType string) (model.ContentType, int, int, error) { + cfg, format, err := image.DecodeConfig(r) + if err != nil { + return "", 0, 0, ErrInvalidImage + } + + if cfg.Width <= 0 || cfg.Height <= 0 { + return "", 0, 0, ErrInvalidImage + } + if cfg.Width > s.maxPixels/cfg.Height { + return "", 0, 0, ErrInvalidSize + } + + var detectedType model.ContentType + switch format { + case "png": + if contentType != string(model.ContentTypePNG) { + return "", 0, 0, ErrInvalidImage + } + detectedType = model.ContentTypePNG + case "jpeg": + if contentType != string(model.ContentTypeJPEG) { + return "", 0, 0, ErrInvalidImage + } + detectedType = model.ContentTypeJPEG + default: + return "", 0, 0, ErrInvalidImage + } + + select { + case s.decodeSlot <- struct{}{}: + defer func() { <-s.decodeSlot }() + case <-ctx.Done(): + return "", 0, 0, ctx.Err() + } + if err := ctx.Err(); err != nil { + return "", 0, 0, err + } + if _, err := r.Seek(0, io.SeekStart); err != nil { + return "", 0, 0, err + } + if _, _, err := image.Decode(r); err != nil { + return "", 0, 0, ErrInvalidImage + } + + return detectedType, cfg.Width, cfg.Height, nil +} + +func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID uuid.UUID) error { + member, err := s.q.IsChatMember(ctx, db.IsChatMemberParams{ + ChatID: chatID, + UserID: userID, + }) + if err != nil { + return err + } + if !member { + return ErrAttachmentNotFound + } + + return nil +} diff --git a/internal/service/auth.go b/internal/service/auth.go new file mode 100644 index 0000000..c77660d --- /dev/null +++ b/internal/service/auth.go @@ -0,0 +1,197 @@ +package service + +import ( + "context" + "errors" + "log/slog" + "time" + + "gavrilenko-sxdees/lab7/internal/credentials" + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/model" + "gavrilenko-sxdees/lab7/internal/postgres" + + "github.com/google/uuid" + goredis "github.com/redis/go-redis/v9" +) + +const sessionCacheTTL = 60 * time.Second +const cacheOpTimeout = 300 * time.Millisecond + +var ( + ErrInvalidCredentials = errors.New("invalid credentials") + ErrUnauthorized = errors.New("unauthorized") + ErrSessionCacheUnavailable = errors.New("session cache unavailable") +) + +type authQueries interface { + CreateSession(ctx context.Context, arg db.CreateSessionParams) error + DeleteSession(ctx context.Context, tokenHash string) (int64, error) + GetActiveSession(ctx context.Context, tokenHash string) (db.GetActiveSessionRow, error) + GetUserByUsername(ctx context.Context, username string) (db.User, error) + UpdatePasswordHash(ctx context.Context, arg db.UpdatePasswordHashParams) error +} + +type AuthService struct { + q authQueries + cache *goredis.Client + sessionTTL time.Duration + log *slog.Logger +} + +func NewAuthService(q authQueries, cache *goredis.Client, sessionTTL time.Duration, log *slog.Logger) *AuthService { + return &AuthService{ + q: q, + cache: cache, + sessionTTL: sessionTTL, + log: log, + } +} + +func (s *AuthService) Login(ctx context.Context, username, plain string) (model.Session, error) { + user, err := s.q.GetUserByUsername(ctx, username) + if postgres.IsNotFound(err) { + credentials.DummyVerify(plain) + return model.Session{}, ErrInvalidCredentials + } + if err != nil { + return model.Session{}, err + } + + if err := credentials.VerifyPassword(user.PasswordHash, plain); err != nil { + if errors.Is(err, credentials.ErrPasswordMismatch) { + return model.Session{}, ErrInvalidCredentials + } + return model.Session{}, err + } + + if credentials.NeedsRehash(user.PasswordHash) { + newHash, herr := credentials.HashPassword(plain) + if herr == nil { + _ = s.q.UpdatePasswordHash(ctx, db.UpdatePasswordHashParams{ + PasswordHash: newHash, + ID: user.ID, + }) + } + } + + token := credentials.NewToken() + expiresAt := time.Now().UTC().Add(s.sessionTTL) + + err = s.q.CreateSession(ctx, db.CreateSessionParams{ + TokenHash: credentials.HashToken(token), + UserID: user.ID, + ExpiresAt: expiresAt, + }) + if err != nil { + return model.Session{}, err + } + + return model.Session{ + Token: token, + ExpiresAt: expiresAt, + User: model.User{ + ID: user.ID, + Username: user.Username, + DisplayName: user.DisplayName, + CreatedAt: user.CreatedAt.UTC(), + }, + }, nil +} + +func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID, error) { + tokenHash := credentials.HashToken(token) + key := cacheKey(tokenHash) + + if id, ok := s.cacheGet(ctx, key); ok { + return id, nil + } + + row, err := s.q.GetActiveSession(ctx, tokenHash) + if postgres.IsNotFound(err) { + return uuid.Nil, ErrUnauthorized + } + if err != nil { + return uuid.Nil, err + } + + s.cacheSet(ctx, key, row.UserID, min(time.Until(row.ExpiresAt), sessionCacheTTL)) + + return row.UserID, nil +} + +func (s *AuthService) Logout(ctx context.Context, token string) error { + tokenHash := credentials.HashToken(token) + + n, err := s.q.DeleteSession(ctx, tokenHash) + if err != nil { + return err + } + + if err := s.cacheDel(ctx, cacheKey(tokenHash)); err != nil { + return ErrSessionCacheUnavailable + } + + if n == 0 { + return ErrUnauthorized + } + return nil +} + +func cacheKey(tokenHash string) string { + return "session:" + tokenHash +} + +func (s *AuthService) cacheGet(ctx context.Context, key string) (uuid.UUID, bool) { + if s.cache == nil { + return uuid.Nil, false + } + + cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout) + defer cancel() + + val, err := s.cache.Get(cctx, key).Result() + switch { + case err == nil: + id, perr := uuid.Parse(val) + if perr != nil { + s.log.Warn("session cache value is not a uuid", "error", perr) + return uuid.Nil, false + } + s.log.Debug("session cache hit") + return id, true + case errors.Is(err, goredis.Nil): + s.log.Debug("session cache miss") + default: + s.log.Warn("session cache get failed, falling back to database", "error", err) + } + return uuid.Nil, false +} + +func (s *AuthService) cacheSet(ctx context.Context, key string, id uuid.UUID, ttl time.Duration) { + if s.cache == nil || ttl <= 0 { + return + } + + cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout) + defer cancel() + + if err := s.cache.Set(cctx, key, id.String(), ttl).Err(); err != nil { + s.log.Warn("session cache set failed", "error", err) + } +} + +func (s *AuthService) cacheDel(ctx context.Context, key string) error { + if s.cache == nil { + return nil + } + + cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout) + defer cancel() + + if err := s.cache.Del(cctx, key).Err(); err != nil { + s.log.Warn("session cache delete failed", "error", err) + return err + } + return nil +} diff --git a/internal/service/chat.go b/internal/service/chat.go new file mode 100644 index 0000000..64bda13 --- /dev/null +++ b/internal/service/chat.go @@ -0,0 +1,204 @@ +package service + +import ( + "bytes" + "context" + "errors" + "slices" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/model" + "gavrilenko-sxdees/lab7/internal/postgres" +) + +var ( + ErrChatNotFound = errors.New("chat not found") + ErrNotChatMember = errors.New("caller must be a member of member_ids") + ErrDuplicateMember = errors.New("member_ids contains duplicates") + ErrUnknownMember = errors.New("member_ids contains unknown user") +) + +type chatQueries interface { + AddChatMembers(ctx context.Context, arg db.AddChatMembersParams) error + CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error) + GetChat(ctx context.Context, arg db.GetChatParams) (db.GetChatRow, error) + ListChatsAfter(ctx context.Context, arg db.ListChatsAfterParams) ([]db.ListChatsAfterRow, error) + ListChatsFirstPage(ctx context.Context, arg db.ListChatsFirstPageParams) ([]db.ListChatsFirstPageRow, error) +} + +type ChatService struct { + pool txBeginner + q chatQueries + withTx func(pgx.Tx) chatQueries +} + +func NewChatService(pool *pgxpool.Pool, q *db.Queries) *ChatService { + return &ChatService{ + pool: pool, + q: q, + withTx: func(tx pgx.Tx) chatQueries { + return q.WithTx(tx) + }, + } +} + +func (s *ChatService) Create( + ctx context.Context, + userID uuid.UUID, + title string, + memberIDs []uuid.UUID, +) (model.Chat, error) { + if !slices.Contains(memberIDs, userID) { + return model.Chat{}, ErrNotChatMember + } + + tx, err := s.pool.Begin(ctx) + if err != nil { + return model.Chat{}, err + } + defer tx.Rollback(ctx) + + q := s.withTx(tx) + + id, err := uuid.NewV7() + if err != nil { + return model.Chat{}, err + } + + row, err := q.CreateChat(ctx, db.CreateChatParams{ + ID: id, + Title: title, + }) + if err != nil { + return model.Chat{}, err + } + + err = q.AddChatMembers(ctx, db.AddChatMembersParams{ + ChatID: row.ID, + UserIds: memberIDs, + }) + switch postgres.ErrCode(err) { + case postgres.CodeUniqueViolation: + return model.Chat{}, ErrDuplicateMember + case postgres.CodeForeignKeyViolation: + return model.Chat{}, ErrUnknownMember + } + if err != nil { + return model.Chat{}, err + } + + if err := tx.Commit(ctx); err != nil { + return model.Chat{}, err + } + + ids := slices.Clone(memberIDs) + slices.SortFunc(ids, func(a, b uuid.UUID) int { + return bytes.Compare(a[:], b[:]) + }) + + return model.Chat{ + ID: row.ID, + Title: row.Title, + CreatedAt: row.CreatedAt, + MemberIDs: ids, + }, nil +} + +func (s *ChatService) Get( + ctx context.Context, + userID uuid.UUID, + chatID uuid.UUID, +) (model.Chat, error) { + row, err := s.q.GetChat(ctx, db.GetChatParams{ + ID: chatID, + UserID: userID, + }) + if postgres.IsNotFound(err) { + return model.Chat{}, ErrChatNotFound + } + if err != nil { + return model.Chat{}, err + } + + return model.Chat{ + ID: row.ID, + Title: row.Title, + CreatedAt: row.CreatedAt, + MemberIDs: row.MemberIds, + }, nil +} + +func (s *ChatService) List( + ctx context.Context, + userID uuid.UUID, + limit int, + cursor *string, +) ([]model.Chat, *string, error) { + var chats []model.Chat + + if cursor == nil { + rows, err := s.q.ListChatsFirstPage(ctx, db.ListChatsFirstPageParams{ + UserID: userID, + Lim: limit + 1, + }) + if err != nil { + return nil, nil, err + } + + chats = make([]model.Chat, 0, len(rows)) + for _, r := range rows { + chats = append(chats, model.Chat{ + ID: r.ID, + Title: r.Title, + CreatedAt: r.CreatedAt, + MemberIDs: r.MemberIds, + }) + } + } else { + decoded, derr := decodeCursor(*cursor, uuid.Nil) + if derr != nil { + return nil, nil, ErrInvalidCursor + } + + rows, err := s.q.ListChatsAfter(ctx, db.ListChatsAfterParams{ + UserID: userID, + AfterCreatedAt: decoded.CreatedAt, + AfterID: decoded.ID, + Lim: limit + 1, + }) + if err != nil { + return nil, nil, err + } + + chats = make([]model.Chat, 0, len(rows)) + for _, r := range rows { + chats = append(chats, model.Chat{ + ID: r.ID, + Title: r.Title, + CreatedAt: r.CreatedAt, + MemberIDs: r.MemberIds, + }) + } + } + + hasMore := len(chats) > limit + if hasMore { + chats = chats[:limit] + } + + var next *string + if hasMore { + last := chats[len(chats)-1] + c := encodeCursor(Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + }) + next = &c + } + + return chats, next, nil +} diff --git a/internal/service/cursor.go b/internal/service/cursor.go new file mode 100644 index 0000000..4709543 --- /dev/null +++ b/internal/service/cursor.go @@ -0,0 +1,41 @@ +package service + +import ( + "encoding/base64" + "encoding/json" + "errors" + "time" + + "github.com/google/uuid" +) + +var ErrInvalidCursor = errors.New("invalid cursor") + +type Cursor struct { + ChatID uuid.UUID `json:"chat_id"` + CreatedAt time.Time `json:"created_at"` + ID uuid.UUID `json:"id"` +} + +func encodeCursor(cursor Cursor) string { + data, _ := json.Marshal(cursor) + return base64.RawURLEncoding.EncodeToString(data) +} + +func decodeCursor(raw string, chatID uuid.UUID) (Cursor, error) { + data, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return Cursor{}, ErrInvalidCursor + } + + var cursor Cursor + if err := json.Unmarshal(data, &cursor); err != nil { + return Cursor{}, ErrInvalidCursor + } + + if cursor.ID == uuid.Nil || cursor.CreatedAt.IsZero() || cursor.ChatID != chatID { + return Cursor{}, ErrInvalidCursor + } + + return cursor, nil +} diff --git a/internal/service/message.go b/internal/service/message.go new file mode 100644 index 0000000..5f9f45d --- /dev/null +++ b/internal/service/message.go @@ -0,0 +1,289 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "net/http" + "sort" + "strings" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/model" + "gavrilenko-sxdees/lab7/internal/postgres" +) + +var ( + ErrMessageChatNotFound = errors.New("chat not found") + ErrIdempotencyKeyConflict = errors.New("idempotency key reused with different request") +) + +type messageQueries interface { + CreateIdempotencyKey(ctx context.Context, arg db.CreateIdempotencyKeyParams) (int64, error) + CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error) + CreateMessageAttachment(ctx context.Context, arg db.CreateMessageAttachmentParams) error + GetIdempotentMessage(ctx context.Context, arg db.GetIdempotentMessageParams) (db.GetIdempotentMessageRow, error) + IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error) + ListAttachmentsByIDs(ctx context.Context, arg db.ListAttachmentsByIDsParams) ([]db.AttachmentStatus, error) + ListMessageAttachmentIDs(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) + ListMessageAttachmentsByMessageIDs(ctx context.Context, messageIDs []uuid.UUID) ([]db.ListMessageAttachmentsByMessageIDsRow, error) + ListMessagesAfter(ctx context.Context, arg db.ListMessagesAfterParams) ([]db.Message, error) + ListMessagesFirstPage(ctx context.Context, arg db.ListMessagesFirstPageParams) ([]db.Message, error) +} + +type MessageService struct { + pool txBeginner + q *db.Queries + withTx func(pgx.Tx) messageQueries +} + +func NewMessageService(pool *pgxpool.Pool, q *db.Queries) *MessageService { + return &MessageService{ + pool: pool, + q: q, + withTx: func(tx pgx.Tx) messageQueries { + return q.WithTx(tx) + }, + } +} + +func (s *MessageService) Create( + ctx context.Context, + userID uuid.UUID, + chatID uuid.UUID, + key string, + text string, + attachmentIDs []uuid.UUID, +) (model.Message, error) { + id, err := uuid.NewV7() + if err != nil { + return model.Message{}, err + } + + if len(attachmentIDs) > 0 { + statuses, err := s.q.ListAttachmentsByIDs(ctx, db.ListAttachmentsByIDsParams{ + ChatID: chatID, + Ids: attachmentIDs, + }) + if err != nil { + return model.Message{}, err + } + if len(statuses) != len(attachmentIDs) { + return model.Message{}, ErrAttachmentNotFound + } + for _, status := range statuses { + if status == db.AttachmentStatusFailed { + return model.Message{}, ErrAttachmentNotReady + } + } + } + + hashInput := text + "|" + normalizeAttachmentIDs(attachmentIDs) + sum := sha256.Sum256([]byte(hashInput)) + hash := hex.EncodeToString(sum[:]) + path := "/api/v1/chats/" + chatID.String() + "/messages" + + tx, err := s.pool.Begin(ctx) + if err != nil { + return model.Message{}, err + } + defer tx.Rollback(ctx) + + q := s.withTx(tx) + + inserted, err := q.CreateIdempotencyKey(ctx, db.CreateIdempotencyKeyParams{ + UserID: userID, + Method: http.MethodPost, + Path: path, + Key: key, + RequestHash: hash, + MessageID: id, + }) + if err != nil { + return model.Message{}, err + } + + if inserted == 0 { + isMember, err := q.IsChatMember(ctx, db.IsChatMemberParams{ + ChatID: chatID, + UserID: userID, + }) + if err != nil { + return model.Message{}, err + } + if !isMember { + return model.Message{}, ErrMessageChatNotFound + } + + stored, err := q.GetIdempotentMessage(ctx, db.GetIdempotentMessageParams{ + UserID: userID, + Method: http.MethodPost, + Path: path, + Key: key, + }) + if err != nil { + return model.Message{}, err + } + if stored.RequestHash != hash { + return model.Message{}, ErrIdempotencyKeyConflict + } + + storedAttachmentIDs, err := q.ListMessageAttachmentIDs(ctx, stored.ID) + if err != nil { + return model.Message{}, err + } + + return model.Message{ + ID: stored.ID, + ChatID: stored.ChatID, + SenderID: stored.SenderID, + Text: stored.Text, + AttachmentIDs: storedAttachmentIDs, + CreatedAt: stored.CreatedAt, + }, nil + } + + row, err := q.CreateMessage(ctx, db.CreateMessageParams{ + ID: id, + ChatID: chatID, + SenderID: userID, + Text: text, + }) + if postgres.IsNotFound(err) { + return model.Message{}, ErrMessageChatNotFound + } + if err != nil { + return model.Message{}, err + } + + for i, attachmentID := range attachmentIDs { + if err := q.CreateMessageAttachment(ctx, db.CreateMessageAttachmentParams{ + MessageID: id, + AttachmentID: attachmentID, + Position: i, + }); err != nil { + return model.Message{}, err + } + } + + if err := tx.Commit(ctx); err != nil { + return model.Message{}, err + } + + return model.Message{ + ID: row.ID, + ChatID: row.ChatID, + SenderID: row.SenderID, + Text: row.Text, + AttachmentIDs: attachmentIDs, + CreatedAt: row.CreatedAt, + }, nil +} + +func (s *MessageService) List( + ctx context.Context, + userID uuid.UUID, + chatID uuid.UUID, + limit int, + cursor *string, +) ([]model.Message, *string, error) { + isMember, err := s.q.IsChatMember(ctx, db.IsChatMemberParams{ + ChatID: chatID, + UserID: userID, + }) + if err != nil { + return nil, nil, err + } + if !isMember { + return nil, nil, ErrMessageChatNotFound + } + + var rows []db.Message + + if cursor == nil { + rows, err = s.q.ListMessagesFirstPage(ctx, db.ListMessagesFirstPageParams{ + ChatID: chatID, + Lim: limit + 1, + }) + } else { + decoded, derr := decodeCursor(*cursor, chatID) + if derr != nil { + return nil, nil, ErrInvalidCursor + } + + rows, err = s.q.ListMessagesAfter(ctx, db.ListMessagesAfterParams{ + ChatID: chatID, + AfterCreatedAt: decoded.CreatedAt, + AfterID: decoded.ID, + Lim: limit + 1, + }) + } + if err != nil { + return nil, nil, err + } + + hasMore := len(rows) > limit + if hasMore { + rows = rows[:limit] + } + + attachmentsByMessage := make(map[uuid.UUID][]uuid.UUID, len(rows)) + if len(rows) > 0 { + messageIDs := make([]uuid.UUID, len(rows)) + for i, r := range rows { + messageIDs[i] = r.ID + } + + links, err := s.q.ListMessageAttachmentsByMessageIDs(ctx, messageIDs) + if err != nil { + return nil, nil, err + } + for _, l := range links { + attachmentsByMessage[l.MessageID] = append(attachmentsByMessage[l.MessageID], l.AttachmentID) + } + } + + messages := make([]model.Message, 0, len(rows)) + for _, r := range rows { + messages = append(messages, model.Message{ + ID: r.ID, + ChatID: r.ChatID, + SenderID: r.SenderID, + Text: r.Text, + AttachmentIDs: attachmentsByMessage[r.ID], + CreatedAt: r.CreatedAt, + }) + } + + var next *string + if hasMore { + last := messages[len(messages)-1] + c := encodeCursor(Cursor{ + ChatID: chatID, + CreatedAt: last.CreatedAt, + ID: last.ID, + }) + next = &c + } + + return messages, next, nil +} + +func normalizeAttachmentIDs(ids []uuid.UUID) string { + if len(ids) == 0 { + return "" + } + + parts := make([]string, len(ids)) + for i, id := range ids { + parts[i] = id.String() + } + sort.Strings(parts) + + return strings.Join(parts, ",") +} diff --git a/internal/service/tx.go b/internal/service/tx.go new file mode 100644 index 0000000..9b2b867 --- /dev/null +++ b/internal/service/tx.go @@ -0,0 +1,11 @@ +package service + +import ( + "context" + + "github.com/jackc/pgx/v5" +) + +type txBeginner interface { + Begin(ctx context.Context) (pgx.Tx, error) +} diff --git a/internal/service/user.go b/internal/service/user.go new file mode 100644 index 0000000..5254959 --- /dev/null +++ b/internal/service/user.go @@ -0,0 +1,83 @@ +package service + +import ( + "context" + "errors" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab7/internal/credentials" + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/model" + "gavrilenko-sxdees/lab7/internal/postgres" +) + +var ( + ErrUsernameTaken = errors.New("username already taken") + ErrUserNotFound = errors.New("user not found") +) + +type userQueries interface { + CreateUser(ctx context.Context, arg db.CreateUserParams) (db.CreateUserRow, error) + GetUser(ctx context.Context, id uuid.UUID) (db.GetUserRow, error) +} + +type UserService struct { + q userQueries +} + +func NewUserService(q userQueries) *UserService { + return &UserService{q: q} +} + +func (s *UserService) Create( + ctx context.Context, + username, displayName, plain string, +) (model.User, error) { + hash, err := credentials.HashPassword(plain) + if err != nil { + return model.User{}, err + } + + id, err := uuid.NewV7() + if err != nil { + return model.User{}, err + } + + row, err := s.q.CreateUser(ctx, db.CreateUserParams{ + ID: id, + Username: username, + DisplayName: displayName, + PasswordHash: hash, + }) + if err != nil { + if postgres.ErrCode(err) == postgres.CodeUniqueViolation { + return model.User{}, ErrUsernameTaken + } + return model.User{}, err + } + + return model.User{ + ID: row.ID, + Username: row.Username, + DisplayName: row.DisplayName, + CreatedAt: row.CreatedAt.UTC(), + }, nil +} + +func (s *UserService) GetByID(ctx context.Context, id uuid.UUID) (model.User, error) { + row, err := s.q.GetUser(ctx, id) + if postgres.IsNotFound(err) { + return model.User{}, ErrUserNotFound + } + if err != nil { + return model.User{}, err + } + + return model.User{ + ID: row.ID, + Username: row.Username, + DisplayName: row.DisplayName, + CreatedAt: row.CreatedAt.UTC(), + }, nil +} diff --git a/internal/telemetry/http.go b/internal/telemetry/http.go new file mode 100644 index 0000000..204292d --- /dev/null +++ b/internal/telemetry/http.go @@ -0,0 +1,41 @@ +package telemetry + +import ( + "context" + "net/http" + + "github.com/go-chi/chi/v5" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" +) + +func Incoming(r *http.Request) context.Context { + return otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header)) +} + +type roundTripper struct{ next http.RoundTripper } + +func Transport(next http.RoundTripper) http.RoundTripper { + if next == nil { + next = http.DefaultTransport + } + return &roundTripper{next: next} +} + +func (t *roundTripper) RoundTrip(r *http.Request) (*http.Response, error) { + ctx, span := Start(r.Context(), "s3.request", trace.SpanKindClient) + defer span.End() + resp, err := t.next.RoundTrip(r.Clone(ctx)) + Failure(span, err) + return resp, err +} + +func RoutePattern(r *http.Request) string { + if rc := chi.RouteContext(r.Context()); rc != nil { + if pattern := rc.RoutePattern(); pattern != "" { + return pattern + } + } + return r.URL.Path +} \ No newline at end of file diff --git a/internal/telemetry/telemetry.go b/internal/telemetry/telemetry.go new file mode 100644 index 0000000..01bd038 --- /dev/null +++ b/internal/telemetry/telemetry.go @@ -0,0 +1,329 @@ +// Package telemetry exports OTLP metrics, logs and traces without affecting business readiness. +package telemetry + +import ( + "context" + "fmt" + "log/slog" + "os" + "strconv" + "strings" + "sync/atomic" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + "go.opentelemetry.io/contrib/bridges/otelslog" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp" + "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" + "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" + semconv "go.opentelemetry.io/otel/semconv/v1.32.0" + "go.opentelemetry.io/otel/trace" +) + +const version = "7.0.0-lab" + +var ( + httpRequests metric.Int64Counter + httpDuration metric.Float64Histogram + jobsCount metric.Int64Counter + jobDuration metric.Float64Histogram + readyHist metric.Float64Histogram + + pendingAcquires atomic.Int64 + busyWorkers atomic.Int64 + workerCapacity atomic.Int64 + + tracer = otel.Tracer("messenger", trace.WithSchemaURL(semconv.SchemaURL)) +) + +func Init(ctx context.Context, service string) (*slog.Logger, func(), error) { + host, _ := os.Hostname() + res := resource.NewWithAttributes( + semconv.SchemaURL, + attribute.String("service.name", service), + attribute.String("service.version", version), + attribute.String("service.instance.id", host), + attribute.String("deployment.environment.name", "lab"), + ) + otel.SetTextMapPropagator(propagation.TraceContext{}) + std := slog.NewJSONHandler(os.Stdout, nil) + if os.Getenv("OTEL_SDK_DISABLED") == "true" { + return slog.New(&contextHandler{next: std, service: service}), func() {}, nil + } + + traceOpts := []otlptracehttp.Option{otlptracehttp.WithTimeout(time.Second)} + traceExp, err := otlptracehttp.New(ctx, traceOpts...) + if err != nil { + return nil, nil, err + } + tp := sdktrace.NewTracerProvider( + sdktrace.WithResource(res), + sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(1))), + sdktrace.WithBatcher(traceExp, + sdktrace.WithMaxQueueSize(1024), + sdktrace.WithMaxExportBatchSize(128), + sdktrace.WithBatchTimeout(time.Second), + sdktrace.WithExportTimeout(time.Second), + ), + ) + otel.SetTracerProvider(tp) + tracer = otel.Tracer("messenger", trace.WithSchemaURL(semconv.SchemaURL)) + + metricOpts := []otlpmetrichttp.Option{otlpmetrichttp.WithTimeout(time.Second)} + metricExp, err := otlpmetrichttp.New(ctx, metricOpts...) + if err != nil { + return nil, nil, err + } + buckets := []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 30, 60, 120} + mp := sdkmetric.NewMeterProvider( + sdkmetric.WithResource(res), + sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp, + sdkmetric.WithInterval(2*time.Second), + sdkmetric.WithTimeout(time.Second), + )), + sdkmetric.WithView(sdkmetric.NewView( + sdkmetric.Instrument{Kind: sdkmetric.InstrumentKindHistogram}, + sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{Boundaries: buckets}}, + )), + ) + otel.SetMeterProvider(mp) + + logOpts := []otlploghttp.Option{otlploghttp.WithTimeout(time.Second)} + logExp, err := otlploghttp.New(ctx, logOpts...) + if err != nil { + return nil, nil, err + } + lp := sdklog.NewLoggerProvider( + sdklog.WithResource(res), + sdklog.WithProcessor(sdklog.NewBatchProcessor(logExp, + sdklog.WithMaxQueueSize(1024), + sdklog.WithExportMaxBatchSize(128), + sdklog.WithExportInterval(time.Second), + sdklog.WithExportTimeout(time.Second), + )), + ) + logHandler := slog.New(&contextHandler{ + next: &tee{ + a: std, + b: otelslog.NewHandler("messenger", otelslog.WithLoggerProvider(lp)), + }, + service: service, + }) + + m := otel.Meter("messenger") + httpRequests, _ = m.Int64Counter("http.server.requests") + httpDuration, _ = m.Float64Histogram("http.server.duration", metric.WithUnit("s")) + jobsCount, _ = m.Int64Counter("messenger.jobs") + jobDuration, _ = m.Float64Histogram("messenger.job.duration", metric.WithUnit("s")) + readyHist, _ = m.Float64Histogram("messenger.attachment.ready.duration", metric.WithUnit("s")) + + shutdown := func() { + c, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + _ = tp.Shutdown(c) + _ = mp.Shutdown(c) + _ = lp.Shutdown(c) + } + return logHandler, shutdown, nil +} + +func Start(ctx context.Context, name string, kind trace.SpanKind) (context.Context, trace.Span) { + return tracer.Start(ctx, name, trace.WithSpanKind(kind)) +} + +func Failure(span trace.Span, err error) { + if err != nil { + span.SetStatus(codes.Error, "operation failed") + } +} + +func Inject(ctx context.Context) (string, string) { + carrier := propagation.MapCarrier{} + otel.GetTextMapPropagator().Inject(ctx, carrier) + return carrier.Get("traceparent"), carrier.Get("tracestate") +} + +func Extract(ctx context.Context, parent, state string) context.Context { + return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{ + "traceparent": parent, + "tracestate": state, + }) +} + +func TraceID(ctx context.Context) string { + return trace.SpanContextFromContext(ctx).TraceID().String() +} + +func HTTP(ctx context.Context, method, route string, status int, seconds float64) { + switch method { + case "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS": + default: + method = "_OTHER" + } + if httpRequests == nil { + return + } + attrs := metric.WithAttributes( + attribute.String("method", method), + attribute.String("route", route), + attribute.String("status_class", fmt.Sprintf("%dxx", status/100)), + ) + httpRequests.Add(ctx, 1, attrs) + httpDuration.Record(ctx, seconds, attrs) +} + +func Job(ctx context.Context, outcome string, seconds float64) { + if jobsCount == nil { + return + } + attrs := metric.WithAttributes( + attribute.String("job_type", "attachment.process.v1"), + attribute.String("outcome", outcome), + ) + jobsCount.Add(ctx, 1, attrs) + jobDuration.Record(ctx, seconds, attrs) +} + +func Ready(ctx context.Context, seconds float64) { + if readyHist != nil { + readyHist.Record(ctx, seconds) + } +} + +func SetWorkerCapacity(n int) { + workerCapacity.Store(int64(n)) +} + +func IncBusy() { busyWorkers.Add(1) } +func DecBusy() { busyWorkers.Add(-1) } +func IncWait() { pendingAcquires.Add(1) } +func DecWait() { pendingAcquires.Add(-1) } + +func RegisterPoolObservers(pool *pgxpool.Pool, workerRole bool) { + m := otel.Meter("messenger") + poolUsed, _ := m.Int64ObservableGauge("messenger.db.pool.used") + poolLimit, _ := m.Int64ObservableGauge("messenger.db.pool.limit") + poolWaiting, _ := m.Int64ObservableGauge("messenger.db.pool.waiting") + queueDepth, _ := m.Int64ObservableGauge("messenger.queue.depth") + queueAge, _ := m.Float64ObservableGauge("messenger.queue.oldest_age_seconds", metric.WithUnit("s")) + busy, _ := m.Int64ObservableGauge("messenger.worker.busy") + capacity, _ := m.Int64ObservableGauge("messenger.worker.capacity") + sliTotal, _ := m.Int64ObservableCounter("messenger.attachment.sli.total") + sliBad, _ := m.Int64ObservableCounter("messenger.attachment.sli.bad") + + _, _ = m.RegisterCallback(func(ctx context.Context, o metric.Observer) error { + stat := pool.Stat() + o.ObserveInt64(poolUsed, int64(stat.AcquiredConns())) + o.ObserveInt64(poolLimit, int64(stat.MaxConns())) + o.ObserveInt64(poolWaiting, pendingAcquires.Load()) + if workerRole { + o.ObserveInt64(busy, busyWorkers.Load()) + o.ObserveInt64(capacity, workerCapacity.Load()) + qctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer cancel() + var depth int64 + var oldest float64 + err := pool.QueryRow(qctx, ` + SELECT count(*), + COALESCE(EXTRACT(EPOCH FROM clock_timestamp() - min(created_at)), 0)::float8 + FROM attachments + WHERE status IN ('queued', 'processing')`).Scan(&depth, &oldest) + if err == nil { + o.ObserveInt64(queueDepth, depth) + o.ObserveFloat64(queueAge, oldest) + } + var matured, bad int64 + err = pool.QueryRow(qctx, ` + SELECT count(*), + count(*) FILTER ( + WHERE status = 'failed' + OR (status = 'ready' AND updated_at > created_at + interval '5 seconds') + ) + FROM attachments + WHERE created_at <= clock_timestamp() - interval '5 seconds' + AND status IN ('ready', 'failed')`).Scan(&matured, &bad) + if err == nil { + o.ObserveInt64(sliTotal, matured) + o.ObserveInt64(sliBad, bad) + } + } + return nil + }, poolUsed, poolLimit, poolWaiting, queueDepth, queueAge, busy, capacity, sliTotal, sliBad) +} + +type contextHandler struct { + next slog.Handler + service string +} + +func (h *contextHandler) Enabled(ctx context.Context, level slog.Level) bool { + return h.next.Enabled(ctx, level) +} + +func (h *contextHandler) Handle(ctx context.Context, r slog.Record) error { + r.AddAttrs( + slog.String("service.name", h.service), + slog.String("event", r.Message), + ) + sc := trace.SpanContextFromContext(ctx) + if sc.IsValid() { + r.AddAttrs( + slog.String("trace_id", sc.TraceID().String()), + slog.String("span_id", sc.SpanID().String()), + ) + } + return h.next.Handle(ctx, r) +} + +func (h *contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return &contextHandler{next: h.next.WithAttrs(attrs), service: h.service} +} + +func (h *contextHandler) WithGroup(name string) slog.Handler { + return &contextHandler{next: h.next.WithGroup(name), service: h.service} +} + +type tee struct{ a, b slog.Handler } + +func (t *tee) Enabled(ctx context.Context, level slog.Level) bool { + return t.a.Enabled(ctx, level) || t.b.Enabled(ctx, level) +} + +func (t *tee) Handle(ctx context.Context, r slog.Record) error { + _ = t.a.Handle(ctx, r.Clone()) + return t.b.Handle(ctx, r) +} + +func (t *tee) WithAttrs(attrs []slog.Attr) slog.Handler { + return &tee{t.a.WithAttrs(attrs), t.b.WithAttrs(attrs)} +} + +func (t *tee) WithGroup(name string) slog.Handler { + return &tee{t.a.WithGroup(name), t.b.WithGroup(name)} +} + +func ProcessRSS() int64 { + raw, err := os.ReadFile("/proc/self/stat") + if err != nil { + return 0 + } + end := strings.LastIndex(string(raw), ")") + if end < 0 { + return 0 + } + fields := strings.Fields(string(raw)[end+1:]) + if len(fields) < 22 { + return 0 + } + pages, _ := strconv.ParseInt(fields[21], 10, 64) + return pages * int64(os.Getpagesize()) +} \ No newline at end of file diff --git a/internal/tlsconfig/client.go b/internal/tlsconfig/client.go new file mode 100644 index 0000000..4124100 --- /dev/null +++ b/internal/tlsconfig/client.go @@ -0,0 +1,71 @@ +package tlsconfig + +import ( + "crypto/tls" + "crypto/x509" + "encoding/pem" + "fmt" + "os" +) + +// ClientTLSFromFiles loads a client TLS config for outbound mTLS. +func ClientTLSFromFiles(certFile, keyFile, caFile, serverName string) (*tls.Config, error) { + cert, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return nil, fmt.Errorf("load client cert: %w", err) + } + caPEM, err := os.ReadFile(caFile) + if err != nil { + return nil, fmt.Errorf("read ca: %w", err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(caPEM) { + return nil, fmt.Errorf("parse ca pem") + } + return &tls.Config{ + Certificates: []tls.Certificate{cert}, + RootCAs: pool, + MinVersion: tls.VersionTLS12, + ServerName: serverName, + }, nil +} + +func ClientTLSFromEnv(prefix string) (*tls.Config, error) { + cert := os.Getenv(prefix + "_CLIENT_CERT") + key := os.Getenv(prefix + "_CLIENT_KEY") + ca := os.Getenv(prefix + "_CA_FILE") + server := os.Getenv(prefix + "_SERVER_NAME") + if cert == "" || key == "" || ca == "" { + return nil, nil + } + if server == "" { + server = "broker-gw" + } + cfg, err := ClientTLSFromFiles(cert, key, ca, server) + if err != nil || cfg == nil { + return cfg, err + } + if chainFile := os.Getenv(prefix + "_CHAIN_FILE"); chainFile != "" { + if err := appendChain(cfg, chainFile); err != nil { + return nil, err + } + } + return cfg, nil +} + +func appendChain(cfg *tls.Config, chainFile string) error { + if len(cfg.Certificates) == 0 { + return nil + } + pemBytes, err := os.ReadFile(chainFile) + if err != nil { + return fmt.Errorf("read chain: %w", err) + } + for block, rest := pem.Decode(pemBytes); block != nil; block, rest = pem.Decode(rest) { + if block.Type != "CERTIFICATE" { + continue + } + cfg.Certificates[0].Certificate = append(cfg.Certificates[0].Certificate, block.Bytes) + } + return nil +} \ No newline at end of file diff --git a/internal/tlsconfig/client_test.go b/internal/tlsconfig/client_test.go new file mode 100644 index 0000000..197ec3a --- /dev/null +++ b/internal/tlsconfig/client_test.go @@ -0,0 +1,19 @@ +package tlsconfig + +import ( + "crypto/tls" + "testing" +) + +func TestBrokerClientPEMChain(t *testing.T) { + cert, err := tls.LoadX509KeyPair( + "../../secrets/broker-api-client.crt", + "../../secrets/broker-api-client.key", + ) + if err != nil { + t.Skip(err) + } + if len(cert.Certificate) < 2 { + t.Fatalf("want chained client cert, got %d DER entries", len(cert.Certificate)) + } +} \ No newline at end of file diff --git a/internal/tlslisten/listen.go b/internal/tlslisten/listen.go new file mode 100644 index 0000000..23fbed8 --- /dev/null +++ b/internal/tlslisten/listen.go @@ -0,0 +1,90 @@ +package tlslisten + +import ( + "crypto/tls" + "crypto/x509" + "fmt" + "net/http" + "os" + "strings" +) + +// LoadServerTLS builds a server tls.Config with mandatory client certificate verification. +func LoadServerTLS(certFile, keyFile, caFile, allowedClientSAN string) (*tls.Config, error) { + cert, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return nil, fmt.Errorf("load server cert: %w", err) + } + caPEM, err := os.ReadFile(caFile) + if err != nil { + return nil, fmt.Errorf("read ca: %w", err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(caPEM) { + return nil, fmt.Errorf("parse ca pem") + } + cfg := &tls.Config{ + Certificates: []tls.Certificate{cert}, + ClientAuth: tls.RequireAndVerifyClientCert, + ClientCAs: pool, + MinVersion: tls.VersionTLS12, + VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error { + if len(rawCerts) == 0 { + return fmt.Errorf("missing client certificate") + } + leaf, err := x509.ParseCertificate(rawCerts[0]) + if err != nil { + return err + } + if err := leaf.VerifyHostname(allowedClientSAN); err != nil { + // Also accept if allowed SAN appears in DNSNames. + for _, name := range leaf.DNSNames { + if name == allowedClientSAN { + return nil + } + } + if leaf.Subject.CommonName == allowedClientSAN { + return nil + } + return fmt.Errorf("client identity %q not allowed (want %q)", leaf.Subject.CommonName, allowedClientSAN) + } + return nil + }, + } + return cfg, nil +} + +func ListenAndServeTLS(server *http.Server, cfg *tls.Config) error { + ln, err := tls.Listen("tcp", server.Addr, cfg) + if err != nil { + return err + } + return server.Serve(ln) +} + +// ClientHTTP returns an http.Client that presents the given client certificate and trusts caFile. +func ClientHTTP(certFile, keyFile, caFile string) (*http.Client, error) { + cert, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return nil, err + } + caPEM, err := os.ReadFile(caFile) + if err != nil { + return nil, err + } + pool := x509.NewCertPool() + pool.AppendCertsFromPEM(caPEM) + tr := &http.Transport{ + TLSClientConfig: &tls.Config{ + Certificates: []tls.Certificate{cert}, + RootCAs: pool, + MinVersion: tls.VersionTLS12, + }, + } + return &http.Client{Transport: tr}, nil +} + +// TLSEnabled reports whether the process should terminate TLS on the API port. +func TLSEnabled() bool { + return strings.TrimSpace(os.Getenv("TLS_CERT_FILE")) != "" && strings.TrimSpace(os.Getenv("TLS_KEY_FILE")) != "" +} \ No newline at end of file diff --git a/internal/worker/image.go b/internal/worker/image.go new file mode 100644 index 0000000..e981194 --- /dev/null +++ b/internal/worker/image.go @@ -0,0 +1,225 @@ +package worker + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "image" + "image/color" + "image/draw" + "image/jpeg" + _ "image/png" + "io" + "os" + "strconv" + + "github.com/disintegration/imaging" + "github.com/gen2brain/webp" + + "gavrilenko-sxdees/lab7/internal/db" +) + +var ( + ErrInvalidSource = errors.New("invalid source image") + ErrUnsupportedPipelineVersion = errors.New("unsupported pipeline version") +) + +type imageVariant struct { + Name db.AttachmentVariantName + Data []byte + ContentType string + Width, Height int +} + +func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAttachmentVariantParams, error) { + if row.StagingKey == nil { + return nil, ErrInvalidSource + } + + source, err := w.s3.Get(ctx, *row.StagingKey) + if err != nil { + return nil, err + } + + defer source.Body.Close() + + tmp, err := os.CreateTemp("", "attachment-job-*") + if err != nil { + return nil, err + } + + defer func() { + _ = tmp.Close() + _ = os.Remove(tmp.Name()) + }() + + hash := sha256.New() + size, err := io.Copy(io.MultiWriter(tmp, hash), io.LimitReader(source.Body, int64(w.maxBytes)+1)) + if err != nil { + return nil, err + } + + if size != int64(row.SizeBytes) || + hex.EncodeToString(hash.Sum(nil)) != row.Sha256 { + return nil, ErrInvalidSource + } + + if _, err := tmp.Seek(0, io.SeekStart); err != nil { + return nil, err + } + + select { + case w.decodeSlot <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + + if err := ctx.Err(); err != nil { + <-w.decodeSlot + return nil, err + } + + images, err := runImageProcess(ctx, tmp, w.maxPixels, row.PipelineVersion) + <-w.decodeSlot + if err != nil { + return nil, err + } + + if err := ctx.Err(); err != nil { + return nil, err + } + + if _, err := tmp.Seek(0, io.SeekStart); err != nil { + return nil, err + } + + if err := w.s3.Put(ctx, row.S3Key, tmp, size, string(row.ContentType)); err != nil { + return nil, err + } + + variants := make([]db.CreateAttachmentVariantParams, 0, len(images)) + for _, img := range images { + key := "variants/" + row.ID.String() + "/v" + strconv.Itoa(row.PipelineVersion) + "/" + string(img.Name) + if err := w.s3.Put(ctx, key, bytes.NewReader(img.Data), int64(len(img.Data)), img.ContentType); err != nil { + return nil, err + } + + sum := sha256.Sum256(img.Data) + variants = append(variants, db.CreateAttachmentVariantParams{ + AttachmentID: row.ID, + PipelineVersion: row.PipelineVersion, + Variant: img.Name, + S3Key: key, + ContentType: img.ContentType, + SizeBytes: len(img.Data), + Width: img.Width, + Height: img.Height, + Sha256: hex.EncodeToString(sum[:]), + }) + } + + return variants, nil +} + +func imageVariants(r io.ReadSeeker, maxPixels, pipelineVersion int) ([]imageVariant, error) { + quality := 80 + switch pipelineVersion { + case 1: + case 2: + quality = 75 + default: + return nil, ErrUnsupportedPipelineVersion + } + + cfg, format, err := image.DecodeConfig(r) + if err != nil || + (format != "png" && format != "jpeg") || + cfg.Width <= 0 || + cfg.Height <= 0 || + cfg.Width > maxPixels/cfg.Height { + return nil, ErrInvalidSource + } + + if _, err := r.Seek(0, io.SeekStart); err != nil { + return nil, err + } + + src, err := imaging.Decode(r, imaging.AutoOrientation(true)) + if err != nil { + return nil, ErrInvalidSource + } + + variants := make([]imageVariant, 0, 3) + for _, item := range []struct { + name db.AttachmentVariantName + image image.Image + }{ + {db.AttachmentVariantNameThumbnail, fitImage(src, 256)}, + {db.AttachmentVariantNameCrop, imaging.Fill(src, 128, 128, imaging.Center, imaging.Lanczos)}, + {db.AttachmentVariantNameOptimized, fitImage(src, 1280)}, + } { + var data []byte + contentType := "image/jpeg" + if item.name == db.AttachmentVariantNameOptimized { + contentType = "image/webp" + data, err = encodeWebP(item.image, quality) + } else { + data, err = encodeJPEG(item.image, 85) + } + + if err != nil { + return nil, err + } + + variants = append(variants, imageVariant{ + Name: item.name, + ContentType: contentType, + Data: data, + Width: item.image.Bounds().Dx(), + Height: item.image.Bounds().Dy(), + }) + } + + return variants, nil +} + +func fitImage(src image.Image, maxSize int) image.Image { + width, height := src.Bounds().Dx(), src.Bounds().Dy() + if width > maxSize || height > maxSize { + if width >= height { + height = max(1, height*maxSize/width) + width = maxSize + } else { + width = max(1, width*maxSize/height) + height = maxSize + } + + return imaging.Resize(src, width, height, imaging.Lanczos) + } + + return src +} + +func encodeJPEG(src image.Image, quality int) ([]byte, error) { + dst := image.NewRGBA(image.Rect(0, 0, src.Bounds().Dx(), src.Bounds().Dy())) + draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) + draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Over) + + var out bytes.Buffer + if err := jpeg.Encode(&out, dst, &jpeg.Options{Quality: quality}); err != nil { + return nil, err + } + + return out.Bytes(), nil +} + +func encodeWebP(src image.Image, quality int) ([]byte, error) { + var out bytes.Buffer + if err := webp.Encode(&out, src, webp.Options{Quality: quality, Method: 4}); err != nil { + return nil, err + } + + return out.Bytes(), nil +} diff --git a/internal/worker/image_process.go b/internal/worker/image_process.go new file mode 100644 index 0000000..e0f17b3 --- /dev/null +++ b/internal/worker/image_process.go @@ -0,0 +1,53 @@ +package worker + +import ( + "bytes" + "context" + "encoding/gob" + "errors" + "os" + "os/exec" + "strconv" +) + +func ProcessImage(maxPixels, pipelineVersion int) error { + variants, err := imageVariants(os.Stdin, maxPixels, pipelineVersion) + if err != nil { + return err + } + + return gob.NewEncoder(os.Stdout).Encode(variants) +} + +func runImageProcess(ctx context.Context, source *os.File, maxPixels, pipelineVersion int) ([]imageVariant, error) { + executable, err := os.Executable() + if err != nil { + return nil, err + } + + cmd := exec.CommandContext(ctx, executable, + "-process-image", strconv.Itoa(maxPixels), + "-pipeline-version", strconv.Itoa(pipelineVersion), + ) + cmd.Stdin = source + data, err := cmd.Output() + if ctx.Err() != nil { + return nil, ctx.Err() + } + + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) && exitErr.ExitCode() == 2 { + return nil, ErrInvalidSource + } + + return nil, err + } + + var variants []imageVariant + if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&variants); err != nil { + return nil, err + } + + return variants, nil +} diff --git a/internal/worker/job.go b/internal/worker/job.go new file mode 100644 index 0000000..a238aa1 --- /dev/null +++ b/internal/worker/job.go @@ -0,0 +1,226 @@ +package worker + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "time" + + "github.com/jackc/pgx/v5" + + "go.opentelemetry.io/otel/trace" + + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/model" + s3store "gavrilenko-sxdees/lab7/internal/s3" + "gavrilenko-sxdees/lab7/internal/telemetry" +) + +var ( + errLeaseExpired = errors.New("attachment lease expired") + errMissingThumbnail = errors.New("ready attachment has no thumbnail") + errAttemptProcessing = errors.New("attachment attempt is still processing") + errAttemptUnavailable = errors.New("attachment attempt is not yet available") + errEffectChecksumMismatch = errors.New("attachment effect checksum mismatch") +) + +func (w *Worker) handle(ctx context.Context, job model.AttachmentJob) error { + jobCtx, cancel := context.WithTimeout(ctx, w.cfg.Timeout) + defer cancel() + + row, err := w.q.ClaimAttachmentJob(jobCtx, db.ClaimAttachmentJobParams{ + ID: job.AttachmentID, + JobID: job.JobID, + PipelineVersion: job.PipelineVersion, + Attempt: job.Attempt, + LeaseUntil: time.Now().Add(w.cfg.Timeout), + }) + if errors.Is(err, pgx.ErrNoRows) { + return w.duplicate(jobCtx, job) + } + + if err != nil { + return err + } + + w.log.Info("attachment processing", "job_id", job.JobID, "attachment_id", row.ID, "attempt", job.Attempt) + transformCtx, transformSpan := telemetry.Start(jobCtx, "image.transform", trace.SpanKindInternal) + variants, processErr := w.process(transformCtx, row) + telemetry.Failure(transformSpan, processErr) + transformSpan.End() + if processErr != nil { + resultCtx, resultCancel := context.WithTimeout(ctx, 5*time.Second) + defer resultCancel() + + return w.finishFailure(resultCtx, job, processErr) + } + + tx, err := w.pool.Begin(jobCtx) + if err != nil { + return err + } + + defer tx.Rollback(context.Background()) + + q := w.q.WithTx(tx) + _, err = q.LockAttachmentJob(jobCtx, db.LockAttachmentJobParams{ + ID: job.AttachmentID, + JobID: job.JobID, + PipelineVersion: job.PipelineVersion, + Attempt: job.Attempt, + }) + if err != nil { + return err + } + + for _, variant := range variants { + if err := q.CreateAttachmentVariant(jobCtx, variant); err != nil { + return err + } + } + + n, err := q.CompleteAttachmentJob(jobCtx, db.CompleteAttachmentJobParams{ + ID: row.ID, + Attempt: job.Attempt, + }) + if err != nil { + return err + } + + if n != 1 { + return errLeaseExpired + } + + if err := tx.Commit(jobCtx); err != nil { + return err + } + + if row.StagingKey != nil { + err := w.deleteStagingObject(ctx, *row.StagingKey) + if err != nil && ctx.Err() == nil { + w.log.Warn("delete ready attachment staging", "attachment_id", row.ID, "error", err) + } + } + + telemetry.Ready(jobCtx, time.Since(job.CreatedAt).Seconds()) + w.log.Info("attachment ready", "job_id", job.JobID, "attachment_id", row.ID, "attempt", job.Attempt) + return nil +} + +func (w *Worker) duplicate(ctx context.Context, job model.AttachmentJob) error { + row, err := w.q.GetAttachmentByID(ctx, job.AttachmentID) + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + + if err != nil { + return err + } + + if row.JobID == nil || *row.JobID != job.JobID || row.PipelineVersion != job.PipelineVersion { + return nil + } + + if row.Status == db.AttachmentStatusFailed { + return nil + } + + if row.Status == db.AttachmentStatusReady { + variants, err := w.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{ + AttachmentID: row.ID, + PipelineVersion: row.PipelineVersion, + }) + if err != nil { + return err + } + + if err := verify(ctx, w.s3, row.S3Key, row.SizeBytes, row.Sha256); err != nil { + return err + } + + hasThumbnail := false + for _, variant := range variants { + if err := verify(ctx, w.s3, variant.S3Key, variant.SizeBytes, variant.Sha256); err != nil { + return err + } + + if variant.Variant == db.AttachmentVariantNameThumbnail { + hasThumbnail = true + } + } + + if !hasThumbnail { + return errMissingThumbnail + } + + return nil + } + + if row.Status == db.AttachmentStatusProcessing && row.Attempts == job.Attempt { + return errAttemptProcessing + } + + if row.Attempts >= job.Attempt { + return nil + } + + return errAttemptUnavailable +} + +func verify(ctx context.Context, storage *s3store.Client, key string, size int, checksum string) error { + object, err := storage.Get(ctx, key) + if err != nil { + return err + } + + defer object.Body.Close() + + hash := sha256.New() + n, err := io.Copy(hash, io.LimitReader(object.Body, int64(size)+1)) + if err != nil { + return err + } + + if n != int64(size) || hex.EncodeToString(hash.Sum(nil)) != checksum { + return errEffectChecksumMismatch + } + + return nil +} + +func (w *Worker) deleteStagingObject(ctx context.Context, key string) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + tx, err := w.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(context.Background()) + + q := w.q.WithTx(tx) + row, err := q.LockAttachmentByStagingKey(ctx, key) + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + + if err != nil { + return err + } + + if row.Status != db.AttachmentStatusReady { + return nil + } + + if err := w.s3.Delete(ctx, key); err != nil { + return err + } + + if err := q.ClearAttachmentStagingKey(ctx, row.ID); err != nil { + return err + } + + return tx.Commit(ctx) +} diff --git a/internal/worker/replay.go b/internal/worker/replay.go new file mode 100644 index 0000000..234fc2e --- /dev/null +++ b/internal/worker/replay.go @@ -0,0 +1,88 @@ +package worker + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "gavrilenko-sxdees/lab7/internal/db" + s3store "gavrilenko-sxdees/lab7/internal/s3" +) + +var ( + errAttachmentNotReplayable = errors.New("attachment is not replayable: expected failed with staging and no existing variants") + errMissingPipelineJob = errors.New("attachment has no pipeline job") + errReplayNotUpdated = errors.New("attachment replay did not update one row") +) + +type txBeginner interface { + Begin(ctx context.Context) (pgx.Tx, error) +} + +func Replay( + ctx context.Context, + pool txBeginner, + storage *s3store.Client, + id uuid.UUID, + operator, reason string, +) error { + tx, err := pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(context.Background()) + + q := db.New(tx) + row, err := q.LockFailedAttachmentForReplay(ctx, id) + if errors.Is(err, pgx.ErrNoRows) { + return errAttachmentNotReplayable + } + if err != nil { + return err + } + if row.JobID == nil { + return errMissingPipelineJob + } + + if err := verify(ctx, storage, *row.StagingKey, row.SizeBytes, row.Sha256); err != nil { + return fmt.Errorf("verify replay source: %w", err) + } + + n, err := q.ReplayAttachmentJob(ctx, id) + if err != nil { + return err + } + if n != 1 { + return errReplayNotUpdated + } + + if err := q.CreateAttachmentReplay(ctx, db.CreateAttachmentReplayParams{ + AttachmentID: id, + Attempt: row.Attempts + 1, + PreviousErrorCode: row.ErrorCode, + Operator: operator, + Reason: reason, + }); err != nil { + return err + } + + if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{ + AttachmentID: id, + Attempt: row.Attempts + 1, + AvailableAt: time.Now(), + Traceparent: "", + Tracestate: "", + }); err != nil { + return err + } + + if err := tx.Commit(ctx); err != nil { + return err + } + + return nil +} diff --git a/internal/worker/retry.go b/internal/worker/retry.go new file mode 100644 index 0000000..26bb902 --- /dev/null +++ b/internal/worker/retry.go @@ -0,0 +1,154 @@ +package worker + +import ( + "context" + "errors" + "math/rand/v2" + "time" + + "gavrilenko-sxdees/lab7/internal/db" + "gavrilenko-sxdees/lab7/internal/model" + s3store "gavrilenko-sxdees/lab7/internal/s3" +) + +func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cause error) error { + tx, err := w.pool.Begin(ctx) + if err != nil { + return err + } + + defer tx.Rollback(context.Background()) + + q := w.q.WithTx(tx) + row, err := q.LockAttachmentJob(ctx, db.LockAttachmentJobParams{ + ID: job.AttachmentID, + JobID: job.JobID, + PipelineVersion: job.PipelineVersion, + Attempt: job.Attempt, + }) + if err != nil { + return err + } + + code := "processing_failed" + permanent := errors.Is(cause, ErrInvalidSource) || errors.Is(cause, s3store.ErrObjectNotFound) + if permanent { + code = "invalid_source" + } else if errors.Is(cause, context.DeadlineExceeded) { + code = "job_timeout" + } + + var n int64 + if permanent || row.Attempts-row.RetryBase >= w.cfg.MaxAttempts { + if !permanent { + code = "retry_exhausted" + } + + n, err = q.FailAttachmentJob(ctx, db.FailAttachmentJobParams{ + ID: row.ID, + Attempt: job.Attempt, + ErrorCode: code, + }) + } else { + n, err = q.RetryAttachmentJob(ctx, db.RetryAttachmentJobParams{ + ID: row.ID, + Attempt: job.Attempt, + ErrorCode: code, + }) + if err == nil && n == 1 { + _, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{ + AttachmentID: row.ID, + Attempt: row.Attempts + 1, + AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)), + Traceparent: "", + Tracestate: "", + }) + } + } + + if err != nil { + return err + } + + if n != 1 { + return errLeaseExpired + } + + if err := tx.Commit(ctx); err != nil { + return err + } + + w.log.Warn( + "attachment processing failed", + "job_id", + job.JobID, + "attempt", + job.Attempt, + "error_code", + code, + ) + return nil +} + +func (w *Worker) recoverLoop(ctx context.Context) { + for ctx.Err() == nil { + recovered, err := w.recoverOne(ctx) + if err != nil && ctx.Err() == nil { + w.log.Warn("recover attachment lease", "error", err) + } + + if (err != nil || !recovered) && !wait(ctx, time.Second) { + return + } + } +} + +func (w *Worker) recoverOne(ctx context.Context) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + tx, err := w.pool.Begin(ctx) + if err != nil { + return false, err + } + + defer tx.Rollback(context.Background()) + + q := w.q.WithTx(tx) + rows, err := q.LockExpiredAttachmentJobs(ctx, 1) + if err != nil || len(rows) == 0 { + return false, err + } + + row := rows[0] + if row.Attempts-row.RetryBase >= w.cfg.MaxAttempts { + _, err = q.FailExpiredAttachmentJob(ctx, row.ID) + } else { + _, err = q.RecoverExpiredAttachmentJob(ctx, row.ID) + if err == nil { + _, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{ + AttachmentID: row.ID, + Attempt: row.Attempts + 1, + AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)), + Traceparent: "", + Tracestate: "", + }) + } + } + + if err != nil { + return false, err + } + + if err := tx.Commit(ctx); err != nil { + return false, err + } + + w.log.Info("attachment lease recovered", "attachment_id", row.ID, "attempt", row.Attempts) + return true, nil +} + +func retryDelay(attempt int) time.Duration { + ceiling := time.Second * time.Duration(1</dev/null + +export BAO_TOKEN="$root" +bao_exec() { + $COMPOSE exec -T -e VAULT_ADDR=https://openbao:8200 -e VAULT_CACERT=/run/secrets/ca_cert -e BAO_TOKEN="$BAO_TOKEN" openbao "$@" +} +bao_exec bao secrets enable -path=secret kv-v2 2>/dev/null || true +bao_exec bao policy write api /openbao/policies/api.hcl +bao_exec bao policy write worker /openbao/policies/worker.hcl +bao_exec bao auth enable approle 2>/dev/null || true + +for role in api worker; do + bao_exec bao write auth/approle/role/"$role" token_policies="$role" token_ttl=1h token_max_ttl=4h + rid=$(bao_exec bao read -field=role_id auth/approle/role/"$role"/role-id) + sid=$(bao_exec bao write -f -field=secret_id auth/approle/role/"$role"/secret-id) + printf '%s' "$rid" >"$ROOT/secrets/bao_${role}_role_id.txt" + printf '%s' "$sid" >"$ROOT/secrets/bao_${role}_secret_id.txt" +done + +bao_exec bao kv put secret/messenger/api/stand ok=true +bao_exec bao kv put secret/messenger/worker/stand ok=true + +echo "OpenBao bootstrap done; role_id/secret_id in secrets/bao_* (root token only in secrets/bao-admin/)" \ No newline at end of file diff --git a/scripts/bootstrap-pki.sh b/scripts/bootstrap-pki.sh new file mode 100755 index 0000000..f2df811 --- /dev/null +++ b/scripts/bootstrap-pki.sh @@ -0,0 +1,98 @@ +#!/bin/sh +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +PKI="$ROOT/secrets/pki" +mkdir -p "$PKI" +SECS="$ROOT/secrets" + +days=825 +cn_ca="Messenger Lab7 Root CA" + +if [ "${FORCE_PKI_REGEN:-0}" = 1 ]; then + rm -f "$PKI"/*.crt "$PKI"/*.key "$PKI"/*.csr "$PKI"/*.srl "$PKI"/*.ext 2>/dev/null || true +fi + +if [ ! -f "$PKI/ca.crt" ]; then + if [ ! -f "$PKI/ca.key" ]; then + openssl genrsa -out "$PKI/ca.key" 4096 + fi + openssl req -new -x509 -nodes -key "$PKI/ca.key" -sha256 -days "$days" \ + -subj "/C=RU/O=MTUSI/OU=lab7/CN=${cn_ca}" -out "$PKI/ca.crt" \ + -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" \ + -addext "subjectKeyIdentifier=hash" \ + -addext "authorityKeyIdentifier=keyid,issuer" +fi + +if [ ! -f "$PKI/broker-clients-ca.crt" ]; then + openssl genrsa -out "$PKI/broker-clients-ca.key" 4096 + openssl req -new -key "$PKI/broker-clients-ca.key" -out "$PKI/broker-clients-ca.csr" \ + -subj "/C=RU/O=MTUSI/OU=lab7/CN=Broker Clients CA" + printf "basicConstraints=CA:TRUE,pathlen:0\nkeyUsage=keyCertSign,cRLSign\n" >"$PKI/broker-clients-ca.ext" + openssl x509 -req -in "$PKI/broker-clients-ca.csr" -CA "$PKI/ca.crt" -CAkey "$PKI/ca.key" -CAcreateserial \ + -out "$PKI/broker-clients-ca.crt" -days "$days" -sha256 -extfile "$PKI/broker-clients-ca.ext" +fi + +sign() { + name=$1 + san=$2 + [ -f "$PKI/${name}.crt" ] && return 0 + openssl genrsa -out "$PKI/${name}.key" 2048 + openssl req -new -key "$PKI/${name}.key" -out "$PKI/${name}.csr" \ + -subj "/C=RU/O=MTUSI/OU=lab7/CN=${name}" + printf "subjectAltName=%s\nbasicConstraints=CA:FALSE\nkeyUsage=digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth,clientAuth\nauthorityKeyIdentifier=keyid,issuer\nsubjectKeyIdentifier=hash\n" "$san" >"$PKI/${name}.ext" + openssl x509 -req -in "$PKI/${name}.csr" -CA "$PKI/ca.crt" -CAkey "$PKI/ca.key" -CAcreateserial \ + -out "$PKI/${name}.crt" -days "$days" -sha256 -extfile "$PKI/${name}.ext" +} + +sign "api.messenger.lab" "DNS:api.messenger.lab,DNS:api,DNS:localhost" +sign "lb.messenger.lab" "DNS:lb.messenger.lab,DNS:lb" +sign "public.messenger.lab" "DNS:localhost,DNS:public.messenger.lab,DNS:127.0.0.1,IP:127.0.0.1" +sign "openbao.messenger.lab" "DNS:openbao,DNS:openbao.messenger.lab" +sign "broker-gw" "DNS:broker-gw,DNS:broker-gw.messenger.lab" +sign_force() { + name=$1 + san=$2 + rm -f "$PKI/${name}.crt" "$PKI/${name}.key" "$PKI/${name}.csr" + sign "$name" "$san" +} +sign_force "messenger-api-broker" "DNS:messenger-api-broker" +sign_force "messenger-worker-broker" "DNS:messenger-worker-broker" +sign "otel.messenger.lab" "DNS:otel-collector,DNS:otel.messenger.lab" +sign "messenger-api-otel" "DNS:messenger-api-otel" +sign "messenger-worker-otel" "DNS:messenger-worker-otel" +sign "evil-broker-client" "DNS:evil-broker-client" + +assemble_pem() { + outfile=$1 + cert=$2 + key=$3 + cat "$cert" "$PKI/ca.crt" "$key" >"$outfile" +} + +assemble_pem "$SECS/public.pem" "$PKI/public.messenger.lab.crt" "$PKI/public.messenger.lab.key" +assemble_pem "$SECS/lb-client.pem" "$PKI/lb.messenger.lab.crt" "$PKI/lb.messenger.lab.key" +assemble_pem "$SECS/broker_gw.pem" "$PKI/broker-gw.crt" "$PKI/broker-gw.key" +cp "$PKI/ca.crt" "$SECS/ca.crt" +cp "$PKI/broker-clients-ca.crt" "$SECS/broker-client-ca.crt" +cp "$PKI/api.messenger.lab.crt" "$SECS/api-server.crt" +cp "$PKI/api.messenger.lab.key" "$SECS/api-server.key" +cp "$PKI/lb.messenger.lab.crt" "$SECS/lb-health-client.crt" +cp "$PKI/lb.messenger.lab.key" "$SECS/lb-health-client.key" +cp "$PKI/openbao.messenger.lab.crt" "$SECS/openbao-server.crt" +cp "$PKI/openbao.messenger.lab.key" "$SECS/openbao-server.key" +cp "$PKI/otel.messenger.lab.crt" "$SECS/otel-server.crt" +cp "$PKI/otel.messenger.lab.key" "$SECS/otel-server.key" +cp "$PKI/messenger-api-broker.crt" "$SECS/broker-api-client.crt" +cp "$PKI/messenger-api-broker.key" "$SECS/broker-api-client.key" +cp "$PKI/messenger-worker-broker.crt" "$SECS/broker-worker-client.crt" +cp "$PKI/messenger-worker-broker.key" "$SECS/broker-worker-client.key" +cp "$PKI/messenger-api-otel.crt" "$SECS/otel-api-client.crt" +cp "$PKI/messenger-api-otel.key" "$SECS/otel-api-client.key" +cp "$PKI/messenger-worker-otel.crt" "$SECS/otel-worker-client.crt" +cp "$PKI/messenger-worker-otel.key" "$SECS/otel-worker-client.key" +cp "$PKI/evil-broker-client.crt" "$SECS/evil-broker-client.crt" +cp "$PKI/evil-broker-client.key" "$SECS/evil-broker-client.key" + +chmod 600 "$SECS"/*.key "$PKI"/*.key 2>/dev/null || true +echo "OpenSSL PKI ready (ingress, broker-gw, otel, openbao clients)" \ No newline at end of file diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 0000000..566a942 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# Перезапуск API×N, worker, LB и всех используемых хранилищ (volumes сохраняются). +set -eu +. "$(dirname "$0")/_lib.sh" + +$COMPOSE stop lb worker api +$COMPOSE restart postgres redis rabbitmq s3 +$COMPOSE up -d --wait postgres redis rabbitmq s3 +warm_s3 + +$COMPOSE up -d --scale "api=${API_REPLICAS}" --no-deps --force-recreate api +$COMPOSE up -d --no-deps --force-recreate worker +$COMPOSE up -d --no-deps lb + +wait_lb_ready 90 +# Дополнительная стабилизация S3/API перед выходом hook (публичный клиент — timeout 2s). +sleep 3 +wait_lb_ready 30 \ No newline at end of file diff --git a/scripts/restore-one.sh b/scripts/restore-one.sh new file mode 100755 index 0000000..7709ec9 --- /dev/null +++ b/scripts/restore-one.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# Восстановить API-реплики после failover-теста (оператор / ручной прогон). +set -eu +. "$(dirname "$0")/_lib.sh" + +$COMPOSE up -d --scale "api=${API_REPLICAS}" --no-deps api +$COMPOSE up -d --no-deps worker lb +wait_lb_ready 90 \ No newline at end of file diff --git a/scripts/rotate-leaf.sh b/scripts/rotate-leaf.sh new file mode 100755 index 0000000..057c1b9 --- /dev/null +++ b/scripts/rotate-leaf.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# Rotate LB client leaf without image rebuild; operator runs locally. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +PKI="$ROOT/secrets/pki" +SECS="$ROOT/secrets" +. "$ROOT/scripts/_lib.sh" + +openssl genrsa -out "$PKI/lb.messenger.lab.key" 2048 +openssl req -new -key "$PKI/lb.messenger.lab.key" -out "$PKI/lb.messenger.lab.csr" \ + -subj "/C=RU/O=MTUSI/OU=lab7/CN=lb.messenger.lab" +printf 'subjectAltName=DNS:lb.messenger.lab,DNS:lb\n' >"$PKI/lb.ext" +openssl x509 -req -in "$PKI/lb.messenger.lab.csr" -CA "$PKI/ca.crt" -CAkey "$PKI/ca.key" -CAcreateserial \ + -out "$PKI/lb.messenger.lab.crt" -days 825 -sha256 -extfile "$PKI/lb.ext" +cat "$PKI/lb.messenger.lab.crt" "$PKI/ca.crt" "$PKI/lb.messenger.lab.key" >"$SECS/lb-client.pem" +cp "$PKI/lb.messenger.lab.crt" "$SECS/lb-health-client.crt" +cp "$PKI/lb.messenger.lab.key" "$SECS/lb-health-client.key" +$COMPOSE up -d --force-recreate --no-deps lb +wait_lb_ready 60 +echo "LB leaf rotated" \ No newline at end of file diff --git a/scripts/scan-images.sh b/scripts/scan-images.sh new file mode 100755 index 0000000..aa7b36d --- /dev/null +++ b/scripts/scan-images.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# Grade-4 image scan triage (read-only; does not block deploy). +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +OUT="$ROOT/evidence/scan-images.txt" +mkdir -p "$(dirname "$OUT")" +COMPOSE="docker compose -p gavrilenko-lab7 --env-file $ROOT/.env" + +{ + echo "=== gavrilenko-lab7 image scan $(date -u +%Y-%m-%dT%H:%M:%SZ) ===" + echo + $COMPOSE config --images | sort -u | while read -r img; do + echo "--- $img ---" + if command -v docker >/dev/null 2>&1 && docker scout quickview "$img" 2>/dev/null; then + : + elif docker pull "$img" >/dev/null 2>&1; then + docker scout quickview "$img" 2>/dev/null || echo "(scout unavailable; image present locally)" + else + echo "skip: cannot pull $img" + fi + echo + done +} | tee "$OUT" +echo "Wrote $OUT" \ No newline at end of file diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 0000000..534342a --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,12 @@ +#!/bin/sh +set -eu +. "$(dirname "$0")/_lib.sh" +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" + +service=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}}' "$TARGET_INSTANCE_ID" 2>/dev/null || true) +project=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}' "$TARGET_INSTANCE_ID" 2>/dev/null || true) + +[ "$service" = "api" ] || { echo "not an api container" >&2; exit 1; } +[ "$project" = "gavrilenko-lab7" ] || { echo "container is not from gavrilenko-lab7" >&2; exit 1; } + +docker stop -t 5 "$TARGET_INSTANCE_ID" >/dev/null \ No newline at end of file diff --git a/scripts/up.sh b/scripts/up.sh new file mode 100755 index 0000000..b518bcc --- /dev/null +++ b/scripts/up.sh @@ -0,0 +1,40 @@ +#!/bin/sh +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +. "$(dirname "$0")/_lib.sh" + +if [ ! -f .env ]; then + cp .env.example .env +fi + +bash scripts/bootstrap-pki.sh + +export DOCKER_BUILDKIT=1 +export COMPOSE_DOCKER_CLI_BUILD=1 + +$COMPOSE up -d postgres redis rabbitmq openbao otel-collector loki tempo +for _ in $(seq 1 60); do + $COMPOSE ps postgres redis rabbitmq 2>/dev/null | grep -q healthy && break || true + sleep 2 +done +sleep 5 + +bash scripts/bootstrap-openbao.sh + +$COMPOSE up -d broker-gw +$COMPOSE run --rm --build s3-config-init +$COMPOSE up -d --build s3 +sleep 8 +$COMPOSE run --rm --build migrate + +$COMPOSE up -d --build --scale "api=${API_REPLICAS}" worker +$COMPOSE up -d --build --force-recreate --scale "api=${API_REPLICAS}" api worker +$COMPOSE up -d lb prometheus grafana + +wait_lb_ready 300 || { + $COMPOSE logs --tail=60 api worker lb broker-gw otel-collector openbao >&2 + exit 1 +} +$COMPOSE ps +echo "lab7 stack ready at https://127.0.0.1:${LB_PORT}" \ No newline at end of file diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 31da287..e21d3a9 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -1,19 +1,28 @@ -# Модель угроз — заполнить +# Модель угроз — lab7, Gavrilenko БПИ2303 ## Активы и акторы -TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. +**Активы:** учётные записи (Argon2id hash), Bearer-сессии, сообщения/вложения, S3 objects, service identities (LB/API/worker leaves), CA, OpenBao KV, телеметрия. + +**Акторы:** участник чата, посторонний пользователь, внешний клиент HTTPS, скомпрометированный worker, оператор стенда. ## Границы доверия -TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. +См. [contracts/trust-matrix.md](../contracts/trust-matrix.md): публичная граница — LB:8443; внутренняя — mTLS LB→API; секреты — OpenBao AppRole. -| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | +| Угроза и путь | Инвариант | Контроль | Отрицательный тест | Остаточный риск | | --- | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | TODO | +| Подмена API в обход LB | Нет plaintext API снаружи | Только HAProxy published; API expose без ports | `curl` к api:8080 с хоста — недоступен | Misconfig compose | +| Чужой client cert к API | Только LB identity | mTLS + SAN `lb.messenger.lab` | student mTLS / openssl s_client | Компрометация LB cert | +| Credential stuffing login | Нет массового перебора | Redis rate limit 429 | 21-й login/min → 429 | Распределённый ботнет | +| Утечка пароля в лог/ошибку | Нет plaintext password в ответах | Generic 401, Argon2id | code review + smoke | Баг handler | +| Чтение чужого чата | ACL membership | Service layer + Bearer | smoke eve 404 | IDOR bug | +| OpenBao lateral movement | Worker без admin secrets | Scoped policy api/worker | bao policy deny чужого path | Root token у оператора | +| Поддельный X-User-Id | Bearer — источник identity | middleware.Auth | smoke | — | +| Недоверенный TLS MITM | verify hostname+CA | Client trust store | `make test-security` | — | +| Скомпрометированный worker | Минимальные S3/broker права | Отдельные keys, limits | трек 5 (не выбран) | Plain broker hop | +| Sealed OpenBao | Нет panic с root в app | Operator unseal; без BAO_TOKEN в env | stop bao → controlled fail | Ручной unseal | -На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. +## Lifecycle -## Lifecycle и инциденты - -TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. +Bootstrap: `bootstrap-pki.sh`, `bootstrap-openbao.sh`. Ротация leaf — оператор, без пересборки образов (план: `rotate-leaf.sh`). Scan: `docker scout` triage — в evidence при сдаче. \ No newline at end of file diff --git a/sqlc.yaml b/sqlc.yaml new file mode 100644 index 0000000..8743b61 --- /dev/null +++ b/sqlc.yaml @@ -0,0 +1,34 @@ +version: "2" +sql: + - engine: "postgresql" + queries: "db/queries" + schema: "db/migrations" + gen: + go: + package: "db" + out: "internal/db" + sql_package: "pgx/v5" + emit_empty_slices: true + emit_pointers_for_null_types: true + overrides: + - db_type: "integer" + go_type: "int" + - db_type: "pg_catalog.int4" + go_type: "int" + - db_type: "uuid" + go_type: "github.com/google/uuid.UUID" + - db_type: "uuid" + nullable: true + go_type: + import: "github.com/google/uuid" + type: "UUID" + pointer: true + + - db_type: "timestamptz" + go_type: "time.Time" + - db_type: "timestamptz" + nullable: true + go_type: + import: "time" + type: "Time" + pointer: true diff --git a/student-tests/acl_test.go b/student-tests/acl_test.go new file mode 100644 index 0000000..9d711d0 --- /dev/null +++ b/student-tests/acl_test.go @@ -0,0 +1,15 @@ +package studenttests_test + +import ( + "net/http" + "testing" +) + +func TestACLUnauthorizedChat(t *testing.T) { + user1 := createUser(t) + user2 := createUser(t) + outsider := createUser(t) + chat := createChat(t, user1, user1.ID, user2.ID) + resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), outsider.Token, nil) + requireStatus(t, resp, http.StatusNotFound) +} \ No newline at end of file diff --git a/student-tests/argon_test.go b/student-tests/argon_test.go new file mode 100644 index 0000000..6a308a9 --- /dev/null +++ b/student-tests/argon_test.go @@ -0,0 +1,24 @@ +package studenttests_test + +import ( + "strings" + "testing" + + "gavrilenko-sxdees/lab7/internal/credentials" +) + +func TestArgon2idRoundTrip(t *testing.T) { + hash, err := credentials.HashPassword("пароль-ź") + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(hash, "$argon2id$") { + t.Fatalf("expected argon2id prefix, got %q", hash[:20]) + } + if err := credentials.VerifyPassword(hash, "пароль-ź"); err != nil { + t.Fatal(err) + } + if credentials.VerifyPassword(hash, "wrong") == nil { + t.Fatal("mismatch not detected") + } +} \ No newline at end of file diff --git a/student-tests/attachment_failover_test.go b/student-tests/attachment_failover_test.go new file mode 100644 index 0000000..664c4fe --- /dev/null +++ b/student-tests/attachment_failover_test.go @@ -0,0 +1,92 @@ +//go:build failure + +package studenttests_test + +import ( + "bytes" + "context" + "io" + "net/http" + "os/exec" + "strings" + "testing" + "time" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +func TestAttachmentUploaderFailover(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + original := makePNG(t, 32, 32) + resp := uploadAttachment(t, user, chat.ID, "failover.png", "image/png", original) + requireStatus(t, resp, http.StatusAccepted) + uploader := resp.Header.Get("X-Instance-Id") + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + if uploader == "" { + t.Fatal("upload response has no X-Instance-Id") + } + + cmd := exec.Command("docker", "compose", "ps", "-q", "api") + cmd.Dir = ".." + out, err := cmd.Output() + if err != nil { + t.Fatalf("list API replicas: %v", err) + } + replicas := strings.Fields(string(out)) + if len(replicas) < 2 { + t.Fatal("at least two running API replicas required") + } + var target string + for _, id := range replicas { + if strings.HasPrefix(id, uploader) { + target = id + break + } + } + if target == "" { + t.Fatal("upload instance is not an API container in this Compose project") + } + t.Cleanup(func() { + if err := exec.Command("docker", "start", target).Run(); err != nil { + t.Errorf("restart uploader replica: %v", err) + } + }) + if err := exec.Command("docker", "stop", "-t", "5", target).Run(); err != nil { + t.Fatalf("stop uploader replica: %v", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + for ctx.Err() == nil { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, *baseURL+"/api/v1/attachments/"+att.ID.String()+"/content", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+user.Token) + response, err := httpClient.Do(req) + if err == nil { + data, readErr := io.ReadAll(response.Body) + response.Body.Close() + if response.StatusCode == http.StatusOK { + downloader := response.Header.Get("X-Instance-Id") + if downloader == "" || downloader == uploader { + t.Fatal("download was not served by another replica") + } + if readErr != nil { + t.Fatal(readErr) + } + if !bytes.Equal(data, original) { + t.Fatal("downloaded original differs from uploaded file") + } + return + } + if response.StatusCode != http.StatusConflict && response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusGatewayTimeout { + t.Fatalf("unexpected download status: %d", response.StatusCode) + } + } + time.Sleep(200 * time.Millisecond) + } + t.Fatal("download through another replica did not recover within 10s") +} diff --git a/student-tests/attachment_helpers_test.go b/student-tests/attachment_helpers_test.go new file mode 100644 index 0000000..127cbf8 --- /dev/null +++ b/student-tests/attachment_helpers_test.go @@ -0,0 +1,134 @@ +//go:build contract || reconcile || failure || worker || pipeline + +package studenttests_test + +import ( + "bytes" + "encoding/json" + "net/http" + "net/url" + "testing" + "time" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +const maxUploadBytes = 10 * 1024 * 1024 + +func uploadAttachment( + t *testing.T, + actor testUser, + chatID uuid.UUID, + filename string, + contentType string, + body []byte, +) *http.Response { + t.Helper() + + req, err := http.NewRequest( + http.MethodPost, + *baseURL+"/api/v1/chats/"+chatID.String()+"/attachments?filename="+url.QueryEscape(filename), + bytes.NewReader(body), + ) + if err != nil { + t.Fatalf("build upload request: %v", err) + } + req.Header.Set("Content-Type", contentType) + req.Header.Set("Authorization", "Bearer "+actor.Token) + + resp, err := httpClient.Do(req) + if err != nil { + t.Fatalf("upload request failed: %v", err) + } + + return resp +} + +func uploadPNG(t *testing.T, actor testUser, chatID uuid.UUID) dto.AttachmentResponse { + t.Helper() + + resp := uploadAttachment(t, actor, chatID, "sample.png", "image/png", makePNG(t, 32, 32)) + requireStatus(t, resp, http.StatusAccepted) + + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + + return waitAttachment(t, actor, att.ID, "ready", time.Minute) +} + +func postMessage( + t *testing.T, + actor testUser, + chatID uuid.UUID, + text string, + attachmentIDs []uuid.UUID, +) *http.Response { + t.Helper() + + body, err := json.Marshal(map[string]any{ + "text": text, + "attachment_ids": attachmentIDs, + }) + if err != nil { + t.Fatalf("marshal message: %v", err) + } + + req, err := http.NewRequest( + http.MethodPost, + *baseURL+"/api/v1/chats/"+chatID.String()+"/messages", + bytes.NewReader(body), + ) + if err != nil { + t.Fatalf("build message request: %v", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+actor.Token) + req.Header.Set("Idempotency-Key", uuid.NewString()) + + resp, err := httpClient.Do(req) + if err != nil { + t.Fatalf("message request failed: %v", err) + } + + return resp +} + +func requireErrorCode(t *testing.T, resp *http.Response, code dto.ErrorCode) { + t.Helper() + + var apiErr dto.ErrorResponse + mustDecode(t, resp, &apiErr) + + if apiErr.Error.Code != code { + t.Errorf("expected error code %q, got %q", code, apiErr.Error.Code) + } +} + +func waitAttachment( + t *testing.T, + actor testUser, + id uuid.UUID, + status string, + timeout time.Duration, +) dto.AttachmentResponse { + t.Helper() + + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+id.String(), actor.Token, nil) + requireStatus(t, resp, http.StatusOK) + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + if string(att.Status) == status { + return att + } + if att.Status == "failed" { + t.Fatalf("attachment failed: %v", att.ErrorCode) + } + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("attachment did not reach %s within %s", status, timeout) + return dto.AttachmentResponse{} +} diff --git a/student-tests/attachment_load_test.go b/student-tests/attachment_load_test.go new file mode 100644 index 0000000..903c506 --- /dev/null +++ b/student-tests/attachment_load_test.go @@ -0,0 +1,180 @@ +//go:build load + +package studenttests_test + +import ( + "bytes" + "net/http" + "os/exec" + "sort" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +func dockerMem(filter string) map[string]float64 { + out, err := exec.Command("docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}").Output() + if err != nil { + return nil + } + m := map[string]float64{} + for _, line := range strings.Split(string(out), "\n") { + parts := strings.SplitN(line, "\t", 2) + if len(parts) != 2 || (filter != "" && !strings.Contains(parts[0], filter)) { + continue + } + used := strings.SplitN(parts[1], "/", 2)[0] + m[parts[0]] = memBytes(used) + } + return m +} + +func memBytes(s string) float64 { + s = strings.TrimSpace(s) + units := []struct { + suf string + mult float64 + }{ + {"GiB", 1 << 30}, {"MiB", 1 << 20}, {"KiB", 1 << 10}, + {"GB", 1e9}, {"MB", 1e6}, {"kB", 1e3}, {"B", 1}, + } + for _, u := range units { + if strings.HasSuffix(s, u.suf) { + v, _ := strconv.ParseFloat(strings.TrimSpace(strings.TrimSuffix(s, u.suf)), 64) + return v * u.mult + } + } + return 0 +} + +func mib(v float64) string { + return strconv.FormatFloat(v/(1<<20), 'f', 1, 64) + "MiB" +} + +func TestConcurrentUploads(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + body := makePNG(t, 1870, 1870) + + url := *baseURL + "/api/v1/chats/" + chat.ID.String() + "/attachments?filename=load.png" + + baseline := dockerMem("api") + + stop := make(chan struct{}) + memDone := make(chan struct{}) + peak := map[string]float64{} + go func() { + defer close(memDone) + for { + for name, v := range dockerMem("api") { + if v > peak[name] { + peak[name] = v + } + } + select { + case <-stop: + return + case <-time.After(500 * time.Millisecond): + } + } + }() + + var ( + mu sync.Mutex + statuses = make(map[int]int) + latencies []time.Duration + errors int + ) + start := time.Now() + deadline := start.Add(*duration) + + var wg sync.WaitGroup + for w := 0; w < *workers; w++ { + wg.Add(1) + go func() { + defer wg.Done() + for time.Now().Before(deadline) { + req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body)) + if err != nil { + mu.Lock() + errors++ + mu.Unlock() + return + } + req.Header.Set("Content-Type", "image/png") + req.Header.Set("Authorization", "Bearer "+user.Token) + + reqStart := time.Now() + resp, err := httpClient.Do(req) + latency := time.Since(reqStart) + if err != nil { + mu.Lock() + errors++ + mu.Unlock() + continue + } + + mu.Lock() + statuses[resp.StatusCode]++ + if resp.StatusCode == http.StatusAccepted { + latencies = append(latencies, latency) + } + mu.Unlock() + resp.Body.Close() + } + }() + } + wg.Wait() + close(stop) + <-memDone + + elapsed := time.Since(start) + + total := 0 + for _, n := range statuses { + total += n + } + total += errors + + t.Logf("workers=%d duration=%.1fs elapsed=%.1fs", *workers, duration.Seconds(), elapsed.Seconds()) + t.Logf("total uploads=%d transport_errors=%d", total, errors) + for status, n := range statuses { + t.Logf("HTTP %d: %d", status, n) + } + + successful := statuses[http.StatusAccepted] + t.Logf("successful RPS: %.2f", float64(successful)/elapsed.Seconds()) + + if len(latencies) > 0 { + sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] }) + t.Logf("latency p50=%s p95=%s p99=%s", + percentile(latencies, 0.50), + percentile(latencies, 0.95), + percentile(latencies, 0.99), + ) + } + + names := make(map[string]struct{}, len(baseline)+len(peak)) + for name := range baseline { + names[name] = struct{}{} + } + for name := range peak { + names[name] = struct{}{} + } + sorted := make([]string, 0, len(names)) + for name := range names { + sorted = append(sorted, name) + } + sort.Strings(sorted) + + if len(sorted) == 0 { + t.Log("memory: docker stats not available (no containers matched)") + return + } + t.Log("memory per container (idle -> peak):") + for _, name := range sorted { + t.Logf(" %s: %s -> %s", name, mib(baseline[name]), mib(peak[name])) + } +} diff --git a/student-tests/attachment_test.go b/student-tests/attachment_test.go new file mode 100644 index 0000000..b8cfd0c --- /dev/null +++ b/student-tests/attachment_test.go @@ -0,0 +1,142 @@ +//go:build contract + +package studenttests_test + +import ( + "bytes" + "image/jpeg" + "image/png" + "io" + "net/http" + "testing" + "time" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +func TestAttachmentJPEG(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + img, err := png.Decode(bytes.NewReader(makePNG(t, 32, 32))) + if err != nil { + t.Fatalf("decode png: %v", err) + } + var body bytes.Buffer + if err := jpeg.Encode(&body, img, nil); err != nil { + t.Fatalf("encode jpeg: %v", err) + } + + resp := uploadAttachment(t, user, chat.ID, "sample.jpg", "image/jpeg", body.Bytes()) + requireStatus(t, resp, http.StatusAccepted) + + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + if att.Status != "queued" { + t.Fatalf("expected queued attachment, got %q", att.Status) + } + + waitAttachment(t, user, att.ID, "ready", time.Minute) + + resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil) + requireStatus(t, resp, http.StatusOK) + defer resp.Body.Close() + + original, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read original: %v", err) + } + if !bytes.Equal(original, body.Bytes()) { + t.Error("downloaded JPEG differs from uploaded original") + } +} + +func TestAttachmentTooManyPixels(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + body := makePNG(t, 8000, 5001) + if len(body) > maxUploadBytes { + t.Fatal("pixel-limit fixture exceeds upload byte limit") + } + + resp := uploadAttachment(t, user, chat.ID, "large.png", "image/png", body) + requireStatus(t, resp, http.StatusRequestEntityTooLarge) + requireErrorCode(t, resp, dto.ErrorCodePayloadTooLarge) +} + +func TestAttachmentUnsafeFilename(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + resp := uploadAttachment(t, user, chat.ID, "../image.png", "image/png", makePNG(t, 32, 32)) + requireStatus(t, resp, http.StatusBadRequest) + requireErrorCode(t, resp, dto.ErrorCodeInvalidRequest) +} + +func TestAttachmentTooLarge(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + body := bytes.Repeat([]byte{0x00}, maxUploadBytes+1) + + resp := uploadAttachment(t, user, chat.ID, "big.png", "image/png", body) + requireStatus(t, resp, http.StatusRequestEntityTooLarge) + requireErrorCode(t, resp, dto.ErrorCodePayloadTooLarge) +} + +func TestAttachmentCorruptedImage(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + body := []byte("this is definitely not a png or jpeg image") + + resp := uploadAttachment(t, user, chat.ID, "broken.png", "image/png", body) + requireStatus(t, resp, http.StatusUnsupportedMediaType) + requireErrorCode(t, resp, dto.ErrorCodeUnsupportedMediaType) +} + +func TestAttachmentMimeSubstitution(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + resp := uploadAttachment(t, user, chat.ID, "actually-png.jpg", "image/jpeg", makePNG(t, 32, 32)) + requireStatus(t, resp, http.StatusUnsupportedMediaType) + requireErrorCode(t, resp, dto.ErrorCodeUnsupportedMediaType) +} + +func TestAttachmentForeignID(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + foreign := uuid.New() + + resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+foreign.String(), user.Token, nil) + requireStatus(t, resp, http.StatusNotFound) + requireErrorCode(t, resp, dto.ErrorCodeNotFound) + + resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+foreign.String()+"/content", user.Token, nil) + requireStatus(t, resp, http.StatusNotFound) + requireErrorCode(t, resp, dto.ErrorCodeNotFound) + + resp = postMessage(t, user, chat.ID, "", []uuid.UUID{foreign}) + requireStatus(t, resp, http.StatusNotFound) + requireErrorCode(t, resp, dto.ErrorCodeNotFound) +} + +func TestAttachmentFromAnotherChat(t *testing.T) { + user := createUser(t) + member := createUser(t) + + chatA := createChat(t, user, user.ID, member.ID) + chatB := createChat(t, user, user.ID) + + att := uploadPNG(t, user, chatA.ID) + + // The attachment belongs to chatA; linking it to a chatB message must fail. + resp := postMessage(t, user, chatB.ID, "", []uuid.UUID{att.ID}) + requireStatus(t, resp, http.StatusNotFound) + requireErrorCode(t, resp, dto.ErrorCodeNotFound) +} diff --git a/student-tests/broker_mtls_test.go b/student-tests/broker_mtls_test.go new file mode 100644 index 0000000..1a5f3c1 --- /dev/null +++ b/student-tests/broker_mtls_test.go @@ -0,0 +1,57 @@ +package studenttests_test + +import ( + "crypto/tls" + "crypto/x509" + "net" + "os" + "testing" + "time" + + "gavrilenko-sxdees/lab7/internal/tlsconfig" +) + +func TestMTLSBrokerRejectsEvilIdentity(t *testing.T) { + caPEM, _ := os.ReadFile(secretPath("ca.crt")) + pool := x509.NewCertPool() + pool.AppendCertsFromPEM(caPEM) + evil, err := tlsconfig.ClientTLSFromFiles( + secretPath("evil-broker-client.crt"), + secretPath("evil-broker-client.key"), + secretPath("ca.crt"), + "broker-gw", + ) + if err != nil { + t.Skip("pki missing evil cert") + } + addr := "127.0.0.1:5674" + conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 3 * time.Second}, "tcp", addr, evil) + if err == nil { + _ = conn.SetReadDeadline(time.Now().Add(2 * time.Second)) + buf := make([]byte, 1) + _, rerr := conn.Read(buf) + _ = conn.Close() + if rerr != nil { + err = rerr + } else { + t.Fatal("evil broker identity should be rejected") + } + } + if err == nil { + t.Fatal("evil broker identity should be rejected") + } + good, err := tlsconfig.ClientTLSFromFiles( + secretPath("broker-api-client.crt"), + secretPath("broker-api-client.key"), + secretPath("ca.crt"), + "broker-gw", + ) + if err != nil { + t.Skip("pki missing api broker cert") + } + conn2, err := tls.DialWithDialer(&net.Dialer{Timeout: 3 * time.Second}, "tcp", addr, good) + if err != nil { + t.Fatalf("valid broker client failed: %v", err) + } + _ = conn2.Close() +} \ No newline at end of file diff --git a/student-tests/chat_rollback_test.go b/student-tests/chat_rollback_test.go new file mode 100644 index 0000000..76cfb8d --- /dev/null +++ b/student-tests/chat_rollback_test.go @@ -0,0 +1,55 @@ +//go:build contract + +package studenttests_test + +import ( + "context" + "encoding/json" + "net/http" + "os" + "strings" + "testing" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +func TestCreateChatRollback(t *testing.T) { + data, err := os.ReadFile("../secrets/test_database_url.txt") + if err != nil { + t.Fatalf("read secrets/test_database_url: %v", err) + } + + ctx := context.Background() + conn, err := pgx.Connect(ctx, strings.TrimSpace(string(data))) + if err != nil { + t.Fatalf("connect to database: %v", err) + } + defer conn.Close(ctx) + + creator := createUser(t) + title := "rollback-" + uuid.NewString() + + body, err := json.Marshal(map[string]any{ + "title": title, + "member_ids": []uuid.UUID{creator.ID, uuid.New()}, + }) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + + resp := doRequest(t, http.MethodPost, "/api/v1/chats", creator.Token, body) + resp.Body.Close() + if resp.StatusCode < 400 || resp.StatusCode >= 500 { + t.Fatalf("expected 4xx, got %d", resp.StatusCode) + } + + var n int + err = conn.QueryRow(ctx, "SELECT count(*) FROM chats WHERE title = $1", title).Scan(&n) + if err != nil { + t.Fatalf("count chats: %v", err) + } + if n != 0 { + t.Fatalf("expected no chat rows after failed creation, found %d", n) + } +} diff --git a/student-tests/compose_helpers_test.go b/student-tests/compose_helpers_test.go new file mode 100644 index 0000000..384ccb0 --- /dev/null +++ b/student-tests/compose_helpers_test.go @@ -0,0 +1,124 @@ +//go:build failure || worker || pipeline + +package studenttests_test + +import ( + "context" + "io" + "net/http" + "os/exec" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +func compose(t *testing.T, args ...string) { + t.Helper() + + cmd := exec.Command("docker", append([]string{"compose"}, args...)...) + cmd.Dir = ".." + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("docker compose %v: %v\n%s", args, err, out) + } +} + +func stopService(t *testing.T, name string) { + t.Helper() + + compose(t, "stop", name) + t.Cleanup(func() { + compose(t, "start", name) + waitReady(t) + }) +} + +func waitReady(t *testing.T) { + t.Helper() + + deadline := time.Now().Add(60 * time.Second) + for time.Now().Before(deadline) { + resp, err := httpClient.Get(*baseURL + "/health/ready") + if err == nil { + resp.Body.Close() + if resp.StatusCode == http.StatusOK { + return + } + } + time.Sleep(500 * time.Millisecond) + } + t.Fatal("service did not become ready in 60s") +} + +func workerCommand(t *testing.T, args ...string) string { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "docker", args...) + cmd.Dir = ".." + out, err := cmd.Output() + if err != nil { + t.Fatalf("Docker command failed: %v", err) + } + return strings.TrimSpace(string(out)) +} + +func workerSQL(t *testing.T, query string) string { + t.Helper() + return workerCommand(t, "compose", "exec", "-T", "postgres", "psql", + "-U", "messenger", "-d", "messenger", "-Atqc", query) +} + +func workerWait(t *testing.T, description string, timeout time.Duration, condition func() bool) { + t.Helper() + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + if condition() { + return + } + time.Sleep(300 * time.Millisecond) + } + t.Fatalf("timeout waiting for %s", description) +} + +func workerQueue(t *testing.T) string { + t.Helper() + out := workerCommand(t, "compose", "exec", "-T", "rabbitmq", "rabbitmqctl", + "list_queues", "name", "messages_ready", "messages_unacknowledged", "--silent") + for _, line := range strings.Split(out, "\n") { + fields := strings.Fields(line) + if len(fields) == 3 && fields[0] == "attachments.process.v1" { + return fields[1] + ":" + fields[2] + } + } + t.Fatal("attachment queue missing") + return "" +} + +func workerUpload(t *testing.T, user testUser, chatID uuid.UUID) (dto.AttachmentResponse, []byte) { + t.Helper() + source := makePNG(t, 320, 200) + resp := uploadAttachment(t, user, chatID, "worker.png", "image/png", source) + requireStatus(t, resp, http.StatusAccepted) + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + if att.Status != "queued" { + t.Fatalf("expected queued, got %s", att.Status) + } + return att, source +} + +func workerContent(t *testing.T, user testUser, id uuid.UUID, variant string) []byte { + t.Helper() + resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+id.String()+"/content?variant="+variant, user.Token, nil) + requireStatus(t, resp, http.StatusOK) + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + return data +} diff --git a/student-tests/contract_test.go b/student-tests/contract_test.go new file mode 100644 index 0000000..733310f --- /dev/null +++ b/student-tests/contract_test.go @@ -0,0 +1,134 @@ +//go:build contract + +package studenttests_test + +import ( + "encoding/json" + "net/http" + "net/url" + "strconv" + "testing" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +func TestInvalidJSON(t *testing.T) { + resp := doRequest(t, http.MethodPost, "/api/v1/users", "", []byte(`{"username": "broken",`)) + requireStatus(t, resp, http.StatusBadRequest) + + var apiErr dto.ErrorResponse + mustDecode(t, resp, &apiErr) + + if apiErr.Error.Code != dto.ErrorCodeInvalidRequest { + t.Errorf("expected code %q, got %q", dto.ErrorCodeInvalidRequest, apiErr.Error.Code) + } +} + +func TestForeignChat(t *testing.T) { + user1 := createUser(t) + user2 := createUser(t) + user3 := createUser(t) + + chat := createChat(t, user1, user1.ID, user2.ID) + + resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), user3.Token, nil) + requireStatus(t, resp, http.StatusNotFound) + + resp = sendMessage(t, user3, chat.ID, "should not land") + requireStatus(t, resp, http.StatusNotFound) +} + +func TestEmptyMessage(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + for _, text := range []string{"", " ", "\t\n"} { + resp := sendMessage(t, user, chat.ID, text) + requireStatus(t, resp, http.StatusBadRequest) + } +} + +func TestDuplicateUsername(t *testing.T) { + user := createUser(t) + + body, err := json.Marshal(map[string]string{ + "username": user.Username, + "display_name": "Someone else", + "password": testPassword, + }) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + + resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body) + requireStatus(t, resp, http.StatusConflict) + + var apiErr dto.ErrorResponse + mustDecode(t, resp, &apiErr) + + if apiErr.Error.Code != dto.ErrorCodeConflict { + t.Errorf("expected code %q, got %q", dto.ErrorCodeConflict, apiErr.Error.Code) + } +} + +func TestPagination(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + const total = 25 + const pageSize = 4 + + sent := make(map[string]bool, total) + for i := 0; i < total; i++ { + resp := sendMessage(t, user, chat.ID, "msg") + requireStatus(t, resp, http.StatusCreated) + + var msg dto.MessageResponse + mustDecode(t, resp, &msg) + sent[msg.ID.String()] = true + } + + seen := make(map[string]bool, total) + cursor := "" + pages := 0 + + for { + path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=" + strconv.Itoa(pageSize) + if cursor != "" { + path += "&cursor=" + url.QueryEscape(cursor) + } + + resp := doRequest(t, http.MethodGet, path, user.Token, nil) + requireStatus(t, resp, http.StatusOK) + + var page dto.MessagePageResponse + mustDecode(t, resp, &page) + pages++ + + for _, msg := range page.Items { + id := msg.ID.String() + if seen[id] { + t.Fatalf("duplicate message id across pages: %s", id) + } + seen[id] = true + } + + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + + if pages > total { + t.Fatalf("too many pages: got %d, expected at most %d", pages, total) + } + } + + if len(seen) != total { + t.Fatalf("expected %d unique messages across all pages, got %d", total, len(seen)) + } + for id := range sent { + if !seen[id] { + t.Fatalf("message %s sent but never seen while paginating", id) + } + } +} diff --git a/student-tests/dependency_failure_test.go b/student-tests/dependency_failure_test.go new file mode 100644 index 0000000..97e2541 --- /dev/null +++ b/student-tests/dependency_failure_test.go @@ -0,0 +1,118 @@ +//go:build failure + +package studenttests_test + +import ( + "bytes" + "io" + "net/http" + "testing" + "time" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +func TestRedisDown(t *testing.T) { + user := createUser(t) + + stopService(t, "redis") + + // настоящий токен + resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusOK) + resp.Body.Close() + + // выдуманный токен + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "forged-"+user.Token, nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() + + // без токена + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "", nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} + +func TestDatabaseDown(t *testing.T) { + user := createUser(t) // токен ещё не использован, ключа в Redis нет + + stopService(t, "postgres") + + // ключа в кэше нет, проверить сессию негде + resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusServiceUnavailable) + resp.Body.Close() + + // выдуманный токен + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "forged-"+user.Token, nil) + requireStatus(t, resp, http.StatusServiceUnavailable) + resp.Body.Close() + + // без токена + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "", nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} + +func TestS3Down(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + original := makePNG(t, 32, 32) + att := uploadPNG(t, user, chat.ID) + + stopService(t, "s3") + for _, path := range []string{"/health/ready", "/api/v1/attachments/" + att.ID.String() + "/content"} { + resp := doRequest(t, http.MethodGet, path, user.Token, nil) + requireStatus(t, resp, http.StatusServiceUnavailable) + requireErrorCode(t, resp, dto.ErrorCodeUnavailable) + } + resp := uploadAttachment(t, user, chat.ID, "outage.png", "image/png", original) + requireStatus(t, resp, http.StatusServiceUnavailable) + requireErrorCode(t, resp, dto.ErrorCodeUnavailable) + resp = doRequest(t, http.MethodGet, "/health/live", "", nil) + requireStatus(t, resp, http.StatusOK) + resp.Body.Close() + + compose(t, "start", "s3") + waitReady(t) + deadline := time.Now().Add(60 * time.Second) + downloaded, uploaded := false, false + for time.Now().Before(deadline) && (!downloaded || !uploaded) { + if !downloaded { + req, err := http.NewRequest(http.MethodGet, *baseURL+"/api/v1/attachments/"+att.ID.String()+"/content", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+user.Token) + response, err := httpClient.Do(req) + if err == nil { + data, readErr := io.ReadAll(response.Body) + response.Body.Close() + if response.StatusCode == http.StatusOK && readErr == nil { + if !bytes.Equal(data, original) { + t.Fatal("original changed across S3 outage") + } + downloaded = true + } else if response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusGatewayTimeout { + t.Fatalf("unexpected download recovery status: %d", response.StatusCode) + } + } + } + if !uploaded { + response := uploadAttachment(t, user, chat.ID, "recovery.png", "image/png", original) + status := response.StatusCode + response.Body.Close() + if status == http.StatusAccepted { + uploaded = true + } else if status != http.StatusServiceUnavailable { + t.Fatalf("unexpected upload recovery status: %d", status) + } + } + if !downloaded || !uploaded { + time.Sleep(500 * time.Millisecond) + } + } + if !downloaded || !uploaded { + t.Fatalf("S3 did not recover in 60s: download=%t upload=%t", downloaded, uploaded) + } +} diff --git a/student-tests/helpers_test.go b/student-tests/helpers_test.go new file mode 100644 index 0000000..74848e0 --- /dev/null +++ b/student-tests/helpers_test.go @@ -0,0 +1,280 @@ +package studenttests_test + +import ( + "bytes" + "crypto/tls" + "crypto/x509" + "encoding/json" + "flag" + "image" + "image/color" + "image/png" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +var baseURL = flag.String("base-url", "https://127.0.0.1:8443", "base URL of the running server") + +func secretPath(name string) string { + const repoRoot = ".." + if name == "ca.crt" { + if p := os.Getenv("CA_FILE"); p != "" { + if filepath.IsAbs(p) { + return p + } + return filepath.Join(repoRoot, filepath.Clean(p)) + } + } + return filepath.Join(repoRoot, "secrets", name) +} + +var httpClient = &http.Client{ + Timeout: 10 * time.Second, + Transport: &http.Transport{ + MaxIdleConns: 200, + IdleConnTimeout: 30 * time.Second, + MaxIdleConnsPerHost: 200, + MaxConnsPerHost: 200, + }, +} + +func configureHTTPClientTLS() { + if !strings.HasPrefix(*baseURL, "https:") { + return + } + caPEM, err := os.ReadFile(secretPath("ca.crt")) + if err != nil { + return + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(caPEM) { + return + } + httpClient.Transport = &http.Transport{ + MaxIdleConns: 200, + IdleConnTimeout: 30 * time.Second, + MaxIdleConnsPerHost: 200, + MaxConnsPerHost: 200, + TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}, + } +} + +type testUser struct { + dto.UserResponse + Token string +} + +const testPassword = "correct-horse-battery" + +func doRequest(t *testing.T, method, path, token string, body []byte) *http.Response { + t.Helper() + + req, err := http.NewRequest(method, *baseURL+path, bytes.NewReader(body)) + if err != nil { + t.Fatalf("build request: %v", err) + } + + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + + resp, err := httpClient.Do(req) + if err != nil { + t.Fatalf("%s %s: request failed: %v", method, path, err) + } + + return resp +} + +func mustDecode(t *testing.T, resp *http.Response, dst any) { + t.Helper() + defer resp.Body.Close() + + data, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body: %v", err) + } + + if err := json.Unmarshal(data, dst); err != nil { + t.Fatalf("decode body %q: %v", data, err) + } +} + +func requireStatus(t *testing.T, resp *http.Response, expected int) { + t.Helper() + + if resp.StatusCode != expected { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + + t.Fatalf( + "expected status %d, got %d, body: %s", + expected, + resp.StatusCode, + data, + ) + } + + if resp.Header.Get("X-Request-Id") == "" { + t.Errorf("missing X-Request-Id header") + } +} + +func createUser(t *testing.T) testUser { + t.Helper() + + username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12] + + body, err := json.Marshal(map[string]string{ + "username": username, + "display_name": "Test " + username, + "password": testPassword, + }) + if err != nil { + t.Fatalf("marshal user: %v", err) + } + + resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body) + requireStatus(t, resp, http.StatusCreated) + + var u dto.UserResponse + mustDecode(t, resp, &u) + + req, err := http.NewRequest( + http.MethodPost, + *baseURL+"/api/v1/auth/sessions", + nil, + ) + if err != nil { + t.Fatalf("build login request: %v", err) + } + req.SetBasicAuth(username, testPassword) + + resp, err = httpClient.Do(req) + if err != nil { + t.Fatalf("login request failed: %v", err) + } + requireStatus(t, resp, http.StatusCreated) + + var session dto.SessionResponse + mustDecode(t, resp, &session) + + return testUser{UserResponse: u, Token: session.Token} +} + +func createChat( + t *testing.T, + creator testUser, + memberIDs ...uuid.UUID, +) dto.ChatResponse { + t.Helper() + + body, err := json.Marshal(map[string]any{ + "title": "Test chat " + uuid.NewString()[:8], + "member_ids": memberIDs, + }) + if err != nil { + t.Fatalf("marshal chat: %v", err) + } + + resp := doRequest( + t, + http.MethodPost, + "/api/v1/chats", + creator.Token, + body, + ) + + requireStatus(t, resp, http.StatusCreated) + + var c dto.ChatResponse + mustDecode(t, resp, &c) + + return c +} + +func sendMessage( + t *testing.T, + actor testUser, + chatID uuid.UUID, + text string, +) *http.Response { + t.Helper() + + resp, err := sendLoadMessage(actor, chatID, text) + if err != nil { + t.Fatalf("send message: %v", err) + } + + return resp +} + +func sendLoadMessage( + actor testUser, + chatID uuid.UUID, + text string, +) (*http.Response, error) { + body, err := json.Marshal(map[string]string{ + "text": text, + }) + if err != nil { + return nil, err + } + + req, err := http.NewRequest( + http.MethodPost, + *baseURL+"/api/v1/chats/"+chatID.String()+"/messages", + bytes.NewReader(body), + ) + if err != nil { + return nil, err + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+actor.Token) + req.Header.Set("Idempotency-Key", uuid.NewString()) + + return httpClient.Do(req) +} + +func makePNG(t *testing.T, width, height int) []byte { + t.Helper() + + img := image.NewRGBA(image.Rect(0, 0, width, height)) + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + img.Set(x, y, color.RGBA{ + R: uint8((x * 7) % 256), + G: uint8((y * 13) % 256), + B: uint8((x + y) % 256), + A: 255, + }) + } + } + + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + t.Fatalf("encode png: %v", err) + } + + return buf.Bytes() +} + +func TestMain(m *testing.M) { + flag.Parse() + configureHTTPClientTLS() + os.Exit(m.Run()) +} diff --git a/student-tests/idempotency_test.go b/student-tests/idempotency_test.go new file mode 100644 index 0000000..30d4267 --- /dev/null +++ b/student-tests/idempotency_test.go @@ -0,0 +1,169 @@ +//go:build race + +package studenttests_test + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/url" + "sync" + "testing" + + "github.com/google/uuid" +) + +const ( + concurrentRequests = 20 + concurrentRounds = 5 +) + +type keyedResult struct { + status int + instance string + body []byte + err error +} + +func postWithKey(actor testUser, chatID uuid.UUID, key, text string) keyedResult { + body, err := json.Marshal(map[string]string{"text": text}) + if err != nil { + return keyedResult{err: err} + } + + req, err := http.NewRequest( + http.MethodPost, + *baseURL+"/api/v1/chats/"+chatID.String()+"/messages", + bytes.NewReader(body), + ) + if err != nil { + return keyedResult{err: err} + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+actor.Token) + req.Header.Set("Idempotency-Key", key) + + resp, err := httpClient.Do(req) + if err != nil { + return keyedResult{err: err} + } + defer resp.Body.Close() + + data, err := io.ReadAll(resp.Body) + return keyedResult{ + status: resp.StatusCode, + instance: resp.Header.Get("X-Instance-Id"), + body: data, + err: err, + } +} + +func TestConcurrentIdempotencyAcrossReplicas(t *testing.T) { + alice := createUser(t) + bob := createUser(t) + chat := createChat(t, alice, alice.ID, bob.ID) + + instances := map[string]struct{}{} + + for round := 0; round < concurrentRounds; round++ { + key := uuid.NewString() + text := "concurrent " + key + + results := make([]keyedResult, concurrentRequests) + start := make(chan struct{}) + var wg sync.WaitGroup + + for i := range results { + wg.Add(1) + go func(i int) { + defer wg.Done() + <-start + results[i] = postWithKey(alice, chat.ID, key, text) + }(i) + } + close(start) + wg.Wait() + + createdIDs := map[string]struct{}{} + succeeded := 0 + + for i, r := range results { + if r.err != nil { + t.Fatalf("round %d, request %d: %v", round, i, r.err) + } + if r.instance != "" { + instances[r.instance] = struct{}{} + } + + switch r.status { + case http.StatusOK, http.StatusCreated: + succeeded++ + var m struct { + ID string `json:"id"` + } + if err := json.Unmarshal(r.body, &m); err != nil || m.ID == "" { + t.Fatalf("round %d: bad success body %q: %v", round, r.body, err) + } + createdIDs[m.ID] = struct{}{} + case http.StatusConflict: + default: + t.Errorf("round %d, request %d: unexpected status %d, body: %s", + round, i, r.status, r.body) + } + } + + if succeeded == 0 { + t.Fatalf("round %d: no request succeeded", round) + } + if len(createdIDs) != 1 { + t.Fatalf("round %d: responses returned %d different message ids, want 1: %v", + round, len(createdIDs), createdIDs) + } + + if got := countMessagesWithText(t, bob, chat.ID, text); got != 1 { + t.Fatalf("round %d: %d messages with text %q in history, want exactly 1", + round, got, text) + } + } + + if len(instances) < 2 { + t.Fatalf("requests were served by %d replica(s) %v, need at least 2", + len(instances), instances) + } + t.Logf("served by replicas: %v", instances) +} + +func countMessagesWithText(t *testing.T, actor testUser, chatID uuid.UUID, text string) int { + t.Helper() + + count := 0 + path := "/api/v1/chats/" + chatID.String() + "/messages?limit=100" + + for page := 0; page < 100; page++ { + resp := doRequest(t, http.MethodGet, path, actor.Token, nil) + requireStatus(t, resp, http.StatusOK) + + var body struct { + Items []struct { + Text string `json:"text"` + } `json:"items"` + NextCursor *string `json:"next_cursor"` + } + mustDecode(t, resp, &body) + + for _, m := range body.Items { + if m.Text == text { + count++ + } + } + if body.NextCursor == nil { + return count + } + path = "/api/v1/chats/" + chatID.String() + + "/messages?limit=100&cursor=" + url.QueryEscape(*body.NextCursor) + } + + t.Fatalf("history pagination exceeded safety bound") + return 0 +} diff --git a/student-tests/image_variants_test.go b/student-tests/image_variants_test.go new file mode 100644 index 0000000..7b241b8 --- /dev/null +++ b/student-tests/image_variants_test.go @@ -0,0 +1,226 @@ +//go:build contract + +package studenttests_test + +import ( + "bytes" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "image" + "image/color" + "image/jpeg" + "image/png" + "io" + "net/http" + "testing" + "time" + + "golang.org/x/image/webp" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +func TestThumbnail(t *testing.T) { + for _, tc := range []struct { + name string + width, height, wantWidth, wantHeight int + }{ + {"landscape", 320, 200, 256, 160}, {"portrait", 201, 321, 160, 256}, + {"small", 12, 7, 12, 7}, {"thin", 1, 1000, 1, 256}, + } { + t.Run(tc.name, func(t *testing.T) { + var source bytes.Buffer + if err := png.Encode(&source, image.NewNRGBA(image.Rect(0, 0, tc.width, tc.height))); err != nil { + t.Fatal(err) + } + + data, width, height := processedVariant(t, source.Bytes(), "image/png", "thumbnail") + + if width != tc.wantWidth || height != tc.wantHeight { + t.Fatalf("got %dx%d", width, height) + } + + decoded, err := jpeg.Decode(bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + + if decoded.Bounds().Dx() != width || decoded.Bounds().Dy() != height { + t.Fatal("JPEG dimensions disagree") + } + + r, g, b, _ := decoded.At(0, 0).RGBA() + if r < 65000 || g < 65000 || b < 65000 { + t.Fatal("transparent source was not composited on white") + } + }) + } +} + +func TestVariantsEXIF(t *testing.T) { + src := image.NewRGBA(image.Rect(0, 0, 40, 20)) + + for y := 0; y < 20; y++ { + for x := 0; x < 40; x++ { + c := color.RGBA{255, 0, 0, 255} + if x >= 20 { + c = color.RGBA{0, 0, 255, 255} + } + + src.Set(x, y, c) + } + } + + var original bytes.Buffer + if err := jpeg.Encode(&original, src, nil); err != nil { + t.Fatal(err) + } + + // Little-endian TIFF, orientation=6 (90 degrees clockwise). + exif := []byte{ + 'E', 'x', 'i', 'f', 0, 0, 'I', 'I', + 42, 0, 8, 0, 0, 0, 1, 0, + 0x12, 1, 3, 0, 1, 0, 0, 0, + 6, 0, 0, 0, 0, 0, 0, 0, + } + segment := []byte{0xff, 0xe1, 0, 0} + binary.BigEndian.PutUint16(segment[2:], uint16(len(exif)+2)) + data := append([]byte{}, original.Bytes()[:2]...) + data = append(data, segment...) + data = append(data, exif...) + data = append(data, original.Bytes()[2:]...) + for _, variant := range []string{"thumbnail", "optimized"} { + t.Run(variant, func(t *testing.T) { + result, width, height := processedVariant(t, data, "image/jpeg", variant) + if width != 20 || height != 40 { + t.Fatalf("orientation ignored: %dx%d", width, height) + } + + decoded, _, err := image.Decode(bytes.NewReader(result)) + if err != nil { + t.Fatal(err) + } + + r, _, b, _ := decoded.At(10, 5).RGBA() + if r <= b { + t.Fatal("incorrect EXIF rotation") + } + + if bytes.Contains(result, []byte("Exif")) || bytes.Contains(result, []byte("EXIF")) { + t.Fatal("EXIF retained") + } + }) + } +} + +func processedVariant(t *testing.T, source []byte, contentType, variant string) ([]byte, int, int) { + t.Helper() + user := createUser(t) + chat := createChat(t, user, user.ID) + resp := uploadAttachment(t, user, chat.ID, "image", contentType, source) + requireStatus(t, resp, http.StatusAccepted) + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + att = waitAttachment(t, user, att.ID, "ready", time.Minute) + for _, v := range att.Variants { + if string(v.Name) != variant { + continue + } + resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content?variant="+variant, user.Token, nil) + requireStatus(t, resp, http.StatusOK) + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + + sum := sha256.Sum256(data) + if len(data) != v.SizeBytes || hex.EncodeToString(sum[:]) != v.Sha256 || + resp.Header.Get("Content-Type") != string(v.ContentType) { + t.Fatal("variant content disagrees with metadata") + } + + return data, v.Width, v.Height + } + t.Fatalf("ready attachment has no %s", variant) + return nil, 0, 0 +} + +func TestCrop(t *testing.T) { + for _, tc := range []struct { + name string + width, height int + }{ + {"landscape", 384, 128}, + {"portrait", 128, 384}, + {"small", 24, 8}, + } { + t.Run(tc.name, func(t *testing.T) { + src := image.NewNRGBA(image.Rect(0, 0, tc.width, tc.height)) + // Only the central square is green; a stretched full image retains red edges. + side := min(tc.width, tc.height) + left, top := (tc.width-side)/2, (tc.height-side)/2 + for y := 0; y < tc.height; y++ { + for x := 0; x < tc.width; x++ { + c := color.NRGBA{R: 255, A: 255} + if x >= left && x < left+side && y >= top && y < top+side { + c = color.NRGBA{G: 255, A: 255} + } + src.SetNRGBA(x, y, c) + } + } + + var source bytes.Buffer + if err := png.Encode(&source, src); err != nil { + t.Fatal(err) + } + + data, width, height := processedVariant(t, source.Bytes(), "image/png", "crop") + decoded, err := jpeg.Decode(bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + if width != 128 || height != 128 || decoded.Bounds() != image.Rect(0, 0, 128, 128) { + t.Fatalf("expected crop 128x128, metadata=%dx%d, JPEG=%v", width, height, decoded.Bounds()) + } + for _, point := range []image.Point{{8, 8}, {64, 64}, {119, 119}} { + r, g, b, _ := decoded.At(point.X, point.Y).RGBA() + if g < 50000 || r > 15000 || b > 15000 { + t.Fatalf("crop is not centered at %v", point) + } + } + }) + } +} + +func TestOptimized(t *testing.T) { + for _, tc := range []struct { + name string + width, height, wantWidth, wantHeight int + }{ + {"landscape", 1600, 1000, 1280, 800}, + {"portrait", 1000, 1600, 800, 1280}, + {"small", 12, 7, 12, 7}, + } { + t.Run(tc.name, func(t *testing.T) { + var source bytes.Buffer + if err := png.Encode(&source, image.NewNRGBA(image.Rect(0, 0, tc.width, tc.height))); err != nil { + t.Fatal(err) + } + data, width, height := processedVariant(t, source.Bytes(), "image/png", "optimized") + decoded, err := webp.Decode(bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + if width != tc.wantWidth || height != tc.wantHeight || + decoded.Bounds().Dx() != width || decoded.Bounds().Dy() != height { + t.Fatalf("unexpected optimized dimensions: metadata=%dx%d, WebP=%v", width, height, decoded.Bounds()) + } + _, _, _, alpha := decoded.At(0, 0).RGBA() + if alpha != 0 { + t.Fatal("optimized image lost transparency") + } + }) + } +} diff --git a/student-tests/load_action_test.go b/student-tests/load_action_test.go new file mode 100644 index 0000000..1e38747 --- /dev/null +++ b/student-tests/load_action_test.go @@ -0,0 +1,150 @@ +//go:build load && action + +package studenttests_test + +import ( + "flag" + "io" + "net/http" + "os" + "os/exec" + "strings" + "sync" + "testing" + "time" +) + +var ( + actionScript = flag.String("action", "", "script to run during the load (e.g. scripts/stop-one.sh)") + actionAt = flag.Duration("action-at", 10*time.Second, "when to run the action, from test start") + replica = flag.Int("replica", 1, "which api replica to stop (1-based)") +) + +func resolveReplica(t *testing.T, n int) string { + t.Helper() + out, err := exec.Command("docker", "compose", "ps", "-q", "api").Output() + if err != nil { + t.Fatalf("docker compose ps: %v", err) + } + ids := strings.Fields(string(out)) + if n < 1 || n > len(ids) { + t.Fatalf("replica %d requested, but %d api containers found", n, len(ids)) + } + return ids[n-1] +} + +func actionCommand(path string) *exec.Cmd { + if strings.HasSuffix(path, ".sh") { + return exec.Command("sh", path) + } + return exec.Command(path) +} + +func TestLoadWithAction(t *testing.T) { + if *actionScript == "" { + t.Skip("-action is not set") + } + + if *actionAt+10*time.Second > *duration { + t.Fatalf("-duration (%s) must exceed -action-at (%s) by at least 10s", *duration, *actionAt) + } + + user1 := createUser(t) + user2 := createUser(t) + chat := createChat(t, user1, user1.ID, user2.ID) + + type sample struct { + at time.Duration + ok bool + } + var ( + mu sync.Mutex + samples []sample + wg sync.WaitGroup + ) + + targetID := resolveReplica(t, *replica) + start := time.Now() + deadline := start.Add(*duration) + interval := time.Second / time.Duration(*rate) + + for w := 0; w < *workers; w++ { + wg.Add(1) + go func(id int) { + defer wg.Done() + actor := user1 + if id%2 == 1 { + actor = user2 + } + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for { + <-ticker.C + if time.Now().After(deadline) { + return + } + resp, err := sendLoadMessage(actor, chat.ID, "load-msg") + ok := err == nil && resp.StatusCode == http.StatusCreated + if err == nil { + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + } + mu.Lock() + samples = append(samples, sample{time.Since(start), ok}) + mu.Unlock() + } + }(w) + } + + var actionStart, actionEnd time.Duration + wg.Add(1) + go func() { + defer wg.Done() + time.Sleep(*actionAt) + actionStart = time.Since(start) + cmd := actionCommand(*actionScript) + cmd.Env = append(os.Environ(), "TARGET_INSTANCE_ID="+targetID) + out, err := cmd.CombinedOutput() + actionEnd = time.Since(start) + if err != nil { + t.Errorf("action failed: %v\n%s", err, out) + } + }() + + wg.Wait() + elapsed := time.Since(start) + + seconds := int(elapsed.Seconds()) + 1 + okBySec := make([]int, seconds) + errBySec := make([]int, seconds) + var okTotal, errTotal int + var lastErr time.Duration + + for _, s := range samples { + sec := int(s.at.Seconds()) + if s.ok { + okBySec[sec]++ + okTotal++ + } else { + errBySec[sec]++ + errTotal++ + if s.at > lastErr { + lastErr = s.at + } + } + } + + for i := 0; i < seconds; i++ { + t.Logf("t=%2ds ok=%4d err=%3d", i, okBySec[i], errBySec[i]) + } + + t.Logf("action: started at %.2fs, finished at %.2fs", actionStart.Seconds(), actionEnd.Seconds()) + t.Logf("total ok=%d errors=%d, successful RPS=%.2f", okTotal, errTotal, float64(okTotal)/elapsed.Seconds()) + + if errTotal == 0 || lastErr < actionStart { + t.Logf("recovery time: 0s (no errors after action start)") + } else { + t.Logf("recovery time: %.2fs (last error at %.2fs)", (lastErr - actionStart).Seconds(), lastErr.Seconds()) + } +} diff --git a/student-tests/load_test.go b/student-tests/load_test.go new file mode 100644 index 0000000..a4a0902 --- /dev/null +++ b/student-tests/load_test.go @@ -0,0 +1,162 @@ +//go:build load + +package studenttests_test + +import ( + "flag" + "fmt" + "io" + "net/http" + "os" + "sort" + "sync" + "sync/atomic" + "testing" + "time" +) + +var ( + workers = flag.Int("workers", 20, "number of concurrent workers") + duration = flag.Duration("duration", 5*time.Second, "test duration") + rate = flag.Int("rate", 20, "maximum requests per second per worker") + csvPath = flag.String("csv", "", "append result row to this CSV file") + label = flag.String("label", "", "configuration label for CSV row") +) + +func TestLoad(t *testing.T) { + var ( + statuses = make(map[int]int64) + requestErrors int64 + latencies []time.Duration + statusMu sync.Mutex + latencyMu sync.Mutex + wg sync.WaitGroup + ) + + user1 := createUser(t) + user2 := createUser(t) + chat := createChat(t, user1, user1.ID, user2.ID) + + start := time.Now() + deadline := start.Add(*duration) + + interval := time.Second / time.Duration(*rate) + + for worker := 0; worker < *workers; worker++ { + wg.Add(1) + + go func(workerID int) { + defer wg.Done() + + actor := user1 + if workerID%2 == 1 { + actor = user2 + } + + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for time.Now().Before(deadline) { + <-ticker.C + + if time.Now().After(deadline) { + return + } + + requestStart := time.Now() + + resp, err := sendLoadMessage( + actor, + chat.ID, + "load-msg", + ) + + latency := time.Since(requestStart) + + if err != nil { + if atomic.AddInt64(&requestErrors, 1) == 1 { + t.Logf("first transport error: %v", err) + } + continue + } + + statusMu.Lock() + statuses[resp.StatusCode]++ + statusMu.Unlock() + + if resp.StatusCode == http.StatusCreated { + latencyMu.Lock() + latencies = append(latencies, latency) + latencyMu.Unlock() + } + + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + } + }(worker) + } + + wg.Wait() + + elapsed := time.Since(start) + + var total int64 + for _, count := range statuses { + total += count + } + total += requestErrors + + t.Logf("duration: %.3fs", elapsed.Seconds()) + t.Logf("workers: %d", *workers) + t.Logf("rate per worker: %d req/s", *rate) + t.Logf("target rate: %d req/s", *workers**rate) + t.Logf("total requests: %d", total) + + for status, count := range statuses { + t.Logf("HTTP %d: %d", status, count) + } + + t.Logf("request errors: %d", requestErrors) + + successful := statuses[http.StatusCreated] + + t.Logf("successful RPS: %.2f", + float64(successful)/elapsed.Seconds(), + ) + + if len(latencies) > 0 { + sort.Slice(latencies, func(i, j int) bool { + return latencies[i] < latencies[j] + }) + + t.Logf("successful latency p50: %s", percentile(latencies, 0.50)) + t.Logf("successful latency p95: %s", percentile(latencies, 0.95)) + t.Logf("successful latency p99: %s", percentile(latencies, 0.99)) + } + + if *csvPath != "" { + var p50, p95, p99 time.Duration + if len(latencies) > 0 { + p50 = percentile(latencies, 0.50) + p95 = percentile(latencies, 0.95) + p99 = percentile(latencies, 0.99) + } + f, err := os.OpenFile(*csvPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + t.Fatalf("open csv: %v", err) + } + defer f.Close() + fmt.Fprintf(f, "%s,%d,%d,%d,%d,%d,%d,%.2f,%.1f,%.1f,%.1f\n", + *label, *workers, *rate, *workers**rate, + successful, total-successful-requestErrors, requestErrors, + float64(successful)/elapsed.Seconds(), + float64(p50.Microseconds())/1000, + float64(p95.Microseconds())/1000, + float64(p99.Microseconds())/1000) + } +} + +func percentile(values []time.Duration, p float64) time.Duration { + index := int(float64(len(values)-1) * p) + return values[index] +} diff --git a/student-tests/mtls_test.go b/student-tests/mtls_test.go new file mode 100644 index 0000000..610b344 --- /dev/null +++ b/student-tests/mtls_test.go @@ -0,0 +1,16 @@ +package studenttests_test + +import ( + "crypto/tls" + "net/http" + "testing" + "time" +) + +func TestMTLSLBDeniesUntrustedCA(t *testing.T) { + client := &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: false}}} + _, err := client.Get("https://127.0.0.1:8443/health/ready") + if err == nil { + t.Fatal("expected verify error with empty trust store") + } +} \ No newline at end of file diff --git a/student-tests/observability.py b/student-tests/observability.py new file mode 100755 index 0000000..2cbac9e --- /dev/null +++ b/student-tests/observability.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Grade-4 observability checks for Gavrilenko lab6 (outbox + RabbitMQ).""" +import datetime +import json +import os +import subprocess +import sys +import time +import urllib.parse +import urllib.request +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check # noqa: E402 + +BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8087") +PROM = os.environ.get("PROMETHEUS_URL", "http://127.0.0.1:9097") +TEMPO = os.environ.get("TEMPO_URL", "http://127.0.0.1:3207") +LOKI = os.environ.get("LOKI_URL", "http://127.0.0.1:3107") +COMPOSE = os.environ.get("COMPOSE", "docker compose -p gavrilenko-lab6 --env-file .env") + + +def get(url): + with urllib.request.urlopen( + urllib.request.Request(url, headers={"Accept": "application/json"}), + timeout=10, + ) as response: + return json.load(response) + + +def dc(*args): + return subprocess.check_output( + [*COMPOSE.split(), *args], + cwd=ROOT, + text=True, + stderr=subprocess.DEVNULL, + ).strip() + + +def query(expr): + return get(PROM + "/api/v1/query?" + urllib.parse.urlencode({"query": expr}))[ + "data" + ]["result"] + + +def alerts(): + payload = get(PROM + "/api/v1/alerts") + return [ + { + "name": item["labels"]["alertname"], + "state": item["state"], + } + for item in payload["data"]["alerts"] + ] + + +def wait_for(fn, timeout=90): + start = time.monotonic() + while time.monotonic() - start < timeout: + try: + value = fn() + if value: + return value, round(time.monotonic() - start, 3) + except (OSError, KeyError, ValueError, urllib.error.URLError): + pass + time.sleep(1) + raise AssertionError("timeout waiting telemetry") + + +def norm_spans(trace): + spans = [] + for batch in trace.get("batches", trace.get("resourceSpans", [])): + attrs = { + x["key"]: x["value"].get("stringValue") + for x in batch.get("resource", {}).get("attributes", []) + } + for scope in batch.get("scopeSpans", batch.get("instrumentationLibrarySpans", [])): + for span in scope.get("spans", []): + spans.append( + { + "service": attrs.get("service.name"), + "name": span["name"], + "id": span.get("spanId"), + "parent_id": span.get("parentSpanId"), + } + ) + return spans + + +def trace_chain(c, actor, chat): + response = c.call( + "POST", + "/api/v1/chats/" + chat["id"] + "/attachments?filename=trace.png", + 202, + actor=actor, + raw=(ROOT / "tests/fixtures/sample.png").read_bytes(), + headers={"Content-Type": "image/png"}, + schema="Attachment", + ) + trace_id = response["headers"].get("X-Trace-Id") + check(trace_id and len(trace_id) == 32, "missing API root trace id") + att = c.wait_ready(actor, response["json"]) + + def complete_trace(): + trace = get(TEMPO + "/api/traces/" + trace_id) + serialized = json.dumps(trace) + check(actor["token"] not in serialized, "token leaked to traces") + spans = norm_spans(trace) + names = {s["name"] for s in spans} + needed = {"queue.publish", "queue.consume", "image.transform", "s3.request"} + if not needed.issubset(names): + return None + return spans + + spans, delay = wait_for(complete_trace) + services = {s["service"] for s in spans} + check({"messenger-api", "messenger-worker"}.issubset(services), "missing service in trace") + for span in spans: + if span["name"] == "queue.consume": + parents = {s["id"] for s in spans if s["name"] == "queue.publish"} + check(span["parent_id"] in parents, "consumer not linked to producer span") + + params = { + "query": '{service_name=~"messenger-(api|worker)"} | trace_id="' + trace_id + '"', + "limit": "100", + "start": str(int((time.time() - 180) * 1e9)), + "end": str(int(time.time() * 1e9)), + } + logs = wait_for( + lambda: get(LOKI + "/loki/api/v1/query_range?" + urllib.parse.urlencode(params))[ + "data" + ]["result"], + timeout=60, + )[0] + log_services = {entry["stream"].get("service_name") for entry in logs} + check({"messenger-api", "messenger-worker"}.issubset(log_services), "correlated logs missing") + result = { + "trace_id": trace_id, + "attachment_id": att["id"], + "ingest_wait_seconds": delay, + "spans": spans, + "log_services": sorted(log_services), + } + (ROOT / "evidence" / "trace-chain.json").write_text(json.dumps(result, indent=2) + "\n") + print("PASS: API → outbox → RabbitMQ → worker trace chain", flush=True) + return result + + +def worker_incident(c, actor, chat): + dc("stop", "worker") + fired = False + try: + for _ in range(12): + att, _ = c.attachment(actor, chat) + c.wait_ready(actor, att, wait_seconds=1) + time.sleep(8) + for item in alerts(): + if item["name"] == "QueueLag" and item["state"] == "firing": + fired = True + check(fired, "QueueLag did not fire with worker stopped") + except Failure: + pass + finally: + dc("up", "-d", "--no-deps", "worker") + time.sleep(15) + resolved = not any( + a["name"] == "QueueLag" and a["state"] == "firing" for a in alerts() + ) + check(resolved, "QueueLag did not resolve after worker restart") + print("PASS: worker stop/start alert firing and resolve", flush=True) + + +def main(): + Path(ROOT / "evidence").mkdir(exist_ok=True) + c = Client(BASE) + users = c.register_users(2) + actor = users[0] + chat = c.create_chat(actor, users[1]) + trace_chain(c, actor, chat) + worker_incident(c, actor, chat) + summary = { + "finished_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "slo": { + "api": "99% non-5xx business requests (10m)", + "ready": "95% attachments ready within 5s", + }, + "alerts": alerts(), + } + (ROOT / "evidence" / "observability-summary.json").write_text( + json.dumps(summary, indent=2) + "\n" + ) + print("PASS: observability grade-4 bundle", flush=True) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/student-tests/openbao_test.go b/student-tests/openbao_test.go new file mode 100644 index 0000000..9a65e58 --- /dev/null +++ b/student-tests/openbao_test.go @@ -0,0 +1,25 @@ +package studenttests_test + +import ( + "context" + "os" + "testing" + "time" + + "gavrilenko-sxdees/lab7/internal/openbao" +) + +func TestOpenBaoAppRole(t *testing.T) { + if os.Getenv("BAO_ADDR") == "" { + t.Setenv("BAO_ADDR", "https://127.0.0.1:8217") + } + os.Setenv("BAO_TLS_SERVER_NAME", "openbao.messenger.lab") + os.Setenv("BAO_CACERT", secretPath("ca.crt")) + os.Setenv("BAO_ROLE_ID_FILE", secretPath("bao_api_role_id.txt")) + os.Setenv("BAO_SECRET_ID_FILE", secretPath("bao_api_secret_id.txt")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := openbao.VerifyAppRole(ctx, "api"); err != nil { + t.Fatalf("openbao approle: %v", err) + } +} \ No newline at end of file diff --git a/student-tests/pipeline_fault_test.go b/student-tests/pipeline_fault_test.go new file mode 100644 index 0000000..48960bf --- /dev/null +++ b/student-tests/pipeline_fault_test.go @@ -0,0 +1,302 @@ +//go:build pipeline + +package studenttests_test + +import ( + "bytes" + "encoding/base64" + "reflect" + "testing" + "time" + + "github.com/google/uuid" + "golang.org/x/image/webp" +) + +func pipelineS3Gate(t *testing.T, suffix string) (string, func(string) string) { + t.Helper() + proxy := "pipeline-gate-" + uuid.NewString() + workerContainer := workerCommand(t, "compose", "ps", "-a", "-q", "worker") + network := workerCommand(t, "inspect", "--format", + "{{range $name, $value := .NetworkSettings.Networks}}{{$name}}{{end}}", workerContainer) + t.Cleanup(func() { workerCommand(t, "rm", "-f", proxy) }) + const proxyScript = ` +import base64 +import http.client +import http.server +import threading +import sys + +waiting = threading.Event() +release = threading.Event() +written = threading.Event() +held_body = b'' + +class Proxy(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + if self.path == '/_body': + self.send_response(200) + self.end_headers() + self.wfile.write(base64.b64encode(held_body)) + return + if self.path == '/_state': + data = f'{int(waiting.is_set())}:{int(written.is_set())}'.encode() + self.send_response(200) + self.end_headers() + self.wfile.write(data) + return + if self.path == '/_release': + release.set() + self.send_response(200) + self.end_headers() + return + self.forward() + + def do_PUT(self): + self.forward() + + def forward(self): + global held_body + body = self.rfile.read(int(self.headers.get('Content-Length', 0))) + gated = self.command == 'PUT' and self.path.split('?')[0].endswith(sys.argv[1]) + if gated: + held_body = body + waiting.set() + if not release.wait(90): + self.send_error(504) + return + conn = http.client.HTTPConnection('s3', 9000, timeout=20) + try: + conn.request(self.command, self.path, body, dict(self.headers)) + response = conn.getresponse() + data = response.read() + if gated and response.status == 200: + written.set() + self.send_response(response.status) + for name, value in response.getheaders(): + if name.lower() not in ('connection', 'transfer-encoding', 'content-length'): + self.send_header(name, value) + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + finally: + conn.close() + +http.server.ThreadingHTTPServer(('0.0.0.0', 9000), Proxy).serve_forever() +` + workerCommand(t, "run", "-d", "--name", proxy, "--network", network, + "python:3.13.9-alpine3.22", "python", "-u", "-c", proxyScript, suffix) + control := func(path string) string { + t.Helper() + return workerCommand(t, "exec", proxy, "python", "-c", + "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:9000/"+path+"').read().decode())") + } + return proxy, control +} + +func TestPipelineStaleProcessing(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + att, source := workerUpload(t, user, chat.ID) + id := att.ID.String() + where := "attachment_id='" + id + "'" + jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") + + // Hold the last v1 PUT while v2 completes, without a DB row lock. + proxy, control := pipelineS3Gate(t, "/v1/optimized") + oldWorker := "pipeline-v1-" + uuid.NewString() + t.Cleanup(func() { workerCommand(t, "rm", "-f", oldWorker) }) + workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", oldWorker, + "-e", "WORKER_CONCURRENCY=1", "-e", "JOB_TIMEOUT_SECONDS=120", + "-e", "S3_ENDPOINT=http://"+proxy+":9000", "worker") + workerWait(t, "v1 waiting before optimized PUT", 20*time.Second, func() bool { + return control("_state") == "1:0" + }) + if workerSQL(t, "SELECT pipeline_version||':'||status||':'||attempts FROM attachments WHERE id='"+id+"'") != "1:processing:1" { + t.Fatal("v1 was not processing before upgrade") + } + + workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id) + compose(t, "start", "worker") + ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second) + if len(ready.Variants) != 3 || + workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" { + t.Fatal("v2 did not become ready while v1 was held") + } + content := make(map[string][]byte) + for _, name := range []string{"original", "thumbnail", "crop", "optimized"} { + content[name] = workerContent(t, user, att.ID, name) + } + if !bytes.Equal(content["original"], source) { + t.Fatal("v2 changed original bytes") + } + v1, err := base64.StdEncoding.DecodeString(control("_body")) + if err != nil { + t.Fatal(err) + } + for _, data := range [][]byte{v1, content["optimized"]} { + cfg, err := webp.DecodeConfig(bytes.NewReader(data)) + if err != nil || cfg.Width != 320 || cfg.Height != 200 { + t.Fatal("expected valid optimized WebP from both versions") + } + } + if bytes.Equal(v1, content["optimized"]) { + t.Fatal("fixture must produce different v1 and v2 optimized bytes") + } + + control("_release") + workerWait(t, "late v1 S3 write", 20*time.Second, func() bool { + return control("_state") == "1:1" + }) + workerWait(t, "stale v1 redelivery acknowledged", 15*time.Second, func() bool { + return workerQueue(t) == "0:0" + }) + after := waitAttachment(t, user, att.ID, "ready", 5*time.Second) + if !reflect.DeepEqual(ready, after) || + workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID || + workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=1") != "0" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" { + t.Fatal("late v1 processing changed current metadata") + } + for name, before := range content { + if !bytes.Equal(before, workerContent(t, user, att.ID, name)) { + t.Fatalf("late v1 processing overwrote %s", name) + } + } + t.Logf("PASS attachment=%s: held v1 PUT; v2 ready; late v1 wrote S3 but could not replace v2; stale redelivery acknowledged", id) +} + +func TestPipelineReorderAndDuplicate(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + // Keep v1 durable in outbox, but delay its publication until v2 is ready. + stopService(t, "rabbitmq") + att, source := workerUpload(t, user, chat.ID) + id := att.ID.String() + where := "attachment_id='" + id + "'" + jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") + workerSQL(t, "UPDATE outbox SET available_at=now()+interval '1 hour' WHERE "+where) + if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND published_at IS NULL") != "1" { + t.Fatal("v1 was published before the reorder injection") + } + workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id) + compose(t, "start", "rabbitmq", "worker") + ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second) + workerWait(t, "v2 acknowledgement", 15*time.Second, func() bool { + return workerQueue(t) == "0:0" + }) + if len(ready.Variants) != 3 || + workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:1" || + workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND pipeline_version=1 AND published_at IS NULL") != "1" { + t.Fatal("v2 did not finish before v1 publication") + } + content := make(map[string][]byte) + for _, name := range []string{"original", "thumbnail", "crop", "optimized"} { + content[name] = workerContent(t, user, att.ID, name) + } + if !bytes.Equal(content["original"], source) { + t.Fatal("v2 changed original bytes") + } + + for _, injection := range []struct { + name, query, version string + }{ + {"reordered v1", "UPDATE outbox SET available_at=now() WHERE " + where + " AND pipeline_version=1", "1"}, + {"duplicate v2", "UPDATE outbox SET published_at=NULL WHERE " + where + " AND pipeline_version=2", "2"}, + } { + compose(t, "stop", "worker") + workerSQL(t, injection.query) + workerWait(t, injection.name+" published", 15*time.Second, func() bool { + return workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+ + " AND pipeline_version="+injection.version+" AND published_at IS NOT NULL") == "1" && + workerQueue(t) == "1:0" + }) + compose(t, "start", "worker") + workerWait(t, injection.name+" acknowledged", 15*time.Second, func() bool { + return workerQueue(t) == "0:0" + }) + after := waitAttachment(t, user, att.ID, "ready", 5*time.Second) + if !reflect.DeepEqual(ready, after) || + workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID || + workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:1" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=1") != "0" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" || + workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "2" { + t.Fatalf("%s changed metadata or created extra work", injection.name) + } + for name, before := range content { + if !bytes.Equal(before, workerContent(t, user, att.ID, name)) { + t.Fatalf("%s changed %s bytes", injection.name, name) + } + } + } + t.Logf("PASS attachment=%s: v2 completed before v1 delivery; stale v1 and duplicate v2 acknowledged without changes", id) +} + +func TestPipelineCrashBeforeWrite(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + att, source := workerUpload(t, user, chat.ID) + id := att.ID.String() + where := "attachment_id='" + id + "'" + jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") + workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id) + + // Original is the first result PUT. Neither it nor any variant reaches S3. + proxy, control := pipelineS3Gate(t, "/attachments/"+id) + testWorker := "pipeline-crash-" + uuid.NewString() + t.Cleanup(func() { workerCommand(t, "rm", "-f", testWorker) }) + workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker, + "-e", "WORKER_CONCURRENCY=1", "-e", "JOB_TIMEOUT_SECONDS=15", + "-e", "S3_ENDPOINT=http://"+proxy+":9000", "worker") + workerWait(t, "v2 held before first result PUT", 10*time.Second, func() bool { + return control("_state") == "1:0" + }) + if workerSQL(t, "SELECT pipeline_version||':'||status||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:processing:1" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "0" { + t.Fatal("expected v2 processing without a committed result") + } + workerCommand(t, "kill", "--signal", "SIGKILL", testWorker) + // Kill the held request too: it must never be forwarded after the crash. + workerCommand(t, "kill", "--signal", "SIGKILL", proxy) + workerWait(t, "crashed v2 job returned to broker", 10*time.Second, func() bool { + return workerQueue(t) == "1:0" + }) + compose(t, "start", "worker") + // Recovery must use the natural lease expiry; no status/lease SQL injection. + ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second) + workerWait(t, "recovered v2 acknowledgement", 15*time.Second, func() bool { + return workerQueue(t) == "0:0" + }) + if len(ready.Variants) != 3 || + !bytes.Equal(workerContent(t, user, att.ID, "original"), source) || + workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID || + workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "3" || + workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND pipeline_version=2 AND attempt=2 AND published_at IS NOT NULL") != "1" { + t.Fatal("crash recovery lost the accepted job or changed its identity or result") + } + for _, name := range []string{"thumbnail", "crop", "optimized"} { + if len(workerContent(t, user, att.ID, name)) == 0 { + t.Fatalf("recovered v2 has empty %s", name) + } + } + t.Logf("PASS attachment=%s: SIGKILL before first result PUT; natural lease recovery; same job ready on v2 attempt2", id) +} diff --git a/student-tests/race_test.go b/student-tests/race_test.go new file mode 100644 index 0000000..a7cabcd --- /dev/null +++ b/student-tests/race_test.go @@ -0,0 +1,100 @@ +//go:build race + +package studenttests_test + +import ( + "net/http" + "sync" + "testing" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +func TestConcurrentMessages(t *testing.T) { + const clients = 10 + const messagesPerClient = 10 + const total = clients * messagesPerClient + + user1 := createUser(t) + user2 := createUser(t) + chat := createChat(t, user1, user1.ID, user2.ID) + + var wg sync.WaitGroup + var mu sync.Mutex + sentIDs := make(map[string]bool, total) + + start := make(chan struct{}) + + for worker := 0; worker < clients; worker++ { + wg.Add(1) + + go func(workerID int) { + defer wg.Done() + + actor := user1 + if workerID%2 == 1 { + actor = user2 + } + + <-start + + for i := 0; i < messagesPerClient; i++ { + resp := sendMessage(t, actor, chat.ID, "race-msg") + if resp.StatusCode != http.StatusCreated { + t.Errorf("worker %d msg %d: expected 201, got %d", workerID, i, resp.StatusCode) + resp.Body.Close() + continue + } + + var m dto.MessageResponse + mustDecode(t, resp, &m) + + mu.Lock() + sentIDs[m.ID.String()] = true + mu.Unlock() + } + }(worker) + } + + close(start) + wg.Wait() + + if t.Failed() { + t.Fatal("one or more send requests failed, see errors above") + } + + if len(sentIDs) != total { + t.Fatalf("expected %d successful sends, got %d unique ids", total, len(sentIDs)) + } + + seen := make(map[string]bool, total) + + path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=100" + resp := doRequest(t, http.MethodGet, path, user1.Token, nil) + requireStatus(t, resp, http.StatusOK) + + var page dto.MessagePageResponse + mustDecode(t, resp, &page) + + if page.NextCursor != nil { + t.Fatalf("expected next_cursor to be nil, history may contain more than %d messages", total) + } + + for _, msg := range page.Items { + id := msg.ID.String() + if seen[id] { + t.Fatalf("duplicate message id in history: %s", id) + } + if !sentIDs[id] { + t.Fatalf("message %s in history was never sent by this test", id) + } + seen[id] = true + } + + if len(seen) != total { + t.Fatalf("expected exactly %d unique messages in history, got %d", total, len(seen)) + } + + t.Logf("PASS: %d concurrent clients sent %d messages, exactly %d unique messages persisted", + clients, total, len(seen)) +} diff --git a/student-tests/reconcile_test.go b/student-tests/reconcile_test.go new file mode 100644 index 0000000..f428b21 --- /dev/null +++ b/student-tests/reconcile_test.go @@ -0,0 +1,161 @@ +//go:build reconcile + +package studenttests_test + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "os" + "os/exec" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "gavrilenko-sxdees/lab7/internal/reconcile" +) + +func reconcileDB(t *testing.T) *pgx.Conn { + t.Helper() + secret, err := os.ReadFile("../secrets/test_database_url.txt") + if err != nil { + t.Fatalf("read test database URL: %v", err) + } + conn, err := pgx.Connect(context.Background(), strings.TrimSpace(string(secret))) + if err != nil { + t.Fatalf("connect to test database: %v", err) + } + t.Cleanup(func() { conn.Close(context.Background()) }) + return conn +} + +func reconcileSQL(t *testing.T, conn *pgx.Conn, query string, args ...any) { + t.Helper() + if _, err := conn.Exec(context.Background(), query, args...); err != nil { + t.Fatalf("prepare/check reconcile fixture: %v", err) + } +} + +func runReconcile(t *testing.T, dryRun bool, grace string) reconcile.Report { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + dry := "false" + if dryRun { + dry = "true" + } + cmd := exec.CommandContext(ctx, "docker", "compose", "--env-file", ".env", "run", "--rm", "--no-deps", "reconcile", "-json", "-dry-run="+dry, "-grace="+grace) + cmd.Dir = ".." + var stderr bytes.Buffer + cmd.Stderr = &stderr + output, err := cmd.Output() + if err != nil { + t.Fatalf("run reconciler: %v\n%s", err, stderr.String()) + } + var report reconcile.Report + if err := json.Unmarshal(output, &report); err != nil { + t.Fatalf("decode reconcile report: %v\n%s", err, output) + } + t.Logf("dry_run=%t objects=%d rows=%d list_pages=%d duration_ms=%d orphan=%d missing=%d skipped_fresh=%d skipped_inactive=%d deleted_objects=%d marked_failed=%d errors=%v", report.DryRun, report.ScannedObjects, report.ScannedRows, report.ListPages, report.DurationMS, len(report.OrphanObjects), len(report.MissingAttachments), report.SkippedFresh, report.SkippedInactive, report.DeletedObjects, report.MarkedFailed, report.Errors) + if len(report.Errors) != 0 { + t.Fatal("reconciler reported errors") + } + return report +} + +func TestReconcileRepair(t *testing.T) { + conn := reconcileDB(t) + user := createUser(t) + chat := createChat(t, user, user.ID) + att := uploadPNG(t, user, chat.ID) + var originalKey string + if err := conn.QueryRow(context.Background(), "SELECT s3_key FROM attachments WHERE id=$1", att.ID).Scan(&originalKey); err != nil { + t.Fatal(err) + } + // Simulate lost metadata for the original object and metadata pointing at a missing object. + reconcileSQL(t, conn, "UPDATE attachments SET s3_key=$2 WHERE id=$1", att.ID, "chats/reconcile-missing/"+uuid.NewString()) + // Only this experiment uses a shortened grace period, to avoid waiting an hour. + time.Sleep(1100 * time.Millisecond) + dry := runReconcile(t, true, "1s") + if !slices.Contains(dry.OrphanObjects, originalKey) || !slices.Contains(dry.MissingAttachments, att.ID) { + t.Fatal("dry-run did not detect both injected inconsistencies") + } + if dry.DeletedObjects != 0 || dry.MarkedFailed != 0 { + t.Fatal("dry-run changed data") + } + var status, code string + if err := conn.QueryRow(context.Background(), "SELECT status::text FROM attachments WHERE id=$1", att.ID).Scan(&status); err != nil { + t.Fatal(err) + } + if status != "ready" { + t.Fatalf("dry-run changed status: %s", status) + } + repair := runReconcile(t, false, "1s") + if repair.DeletedObjects < 1 || repair.MarkedFailed < 1 { + t.Fatal("repair did not apply fixes") + } + if err := conn.QueryRow(context.Background(), "SELECT status::text, error_code FROM attachments WHERE id=$1", att.ID).Scan(&status, &code); err != nil { + t.Fatal(err) + } + if status != "failed" || code != "object_missing" { + t.Fatalf("unexpected repaired state: %s %s", status, code) + } + again := runReconcile(t, false, "1s") + if slices.Contains(again.OrphanObjects, originalKey) || slices.Contains(again.MissingAttachments, att.ID) { + t.Fatal("fixture still requires repair on repeat") + } + if again.DeletedObjects != 0 || again.MarkedFailed != 0 { + t.Fatal("repeat repair changed data; run on an idle test stand") + } + t.Log("PASS: dry-run preserved data; orphan deleted; missing marked failed; repeat made no changes") +} + +func TestReconcileSafety(t *testing.T) { + conn := reconcileDB(t) + user := createUser(t) + chat := createChat(t, user, user.ID) + fresh := uploadPNG(t, user, chat.ID) + used := uploadPNG(t, user, chat.ID) + resp := postMessage(t, user, chat.ID, "", []uuid.UUID{used.ID}) + requireStatus(t, resp, http.StatusCreated) + resp.Body.Close() + // Queued attachments must be preserved regardless of age or message references. + reconcileSQL(t, conn, "UPDATE attachments SET status='queued' WHERE id=$1", fresh.ID) + reconcileSQL(t, conn, "UPDATE attachments SET status='queued', created_at=now()-interval '2 hours' WHERE id=$1", used.ID) + t.Cleanup(func() { + if _, err := conn.Exec(context.Background(), "UPDATE attachments SET status='ready' WHERE id=ANY($1::uuid[])", []uuid.UUID{fresh.ID, used.ID}); err != nil { + t.Errorf("restore fixture status: %v", err) + } + }) + for _, dryRun := range []bool{true, false} { + report := runReconcile(t, dryRun, "1h") + if report.SkippedInactive < 2 { + t.Fatal("queued attachment protection was not exercised") + } + for _, att := range []uuid.UUID{fresh.ID, used.ID} { + var status string + if err := conn.QueryRow(context.Background(), "SELECT status::text FROM attachments WHERE id=$1", att).Scan(&status); err != nil { + t.Fatal(err) + } + if status != "queued" { + t.Fatalf("protected fixture changed status: %s", status) + } + resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.String()+"/content", user.Token, nil) + requireStatus(t, resp, http.StatusConflict) + resp.Body.Close() + } + } + t.Log("PASS: queued uploads preserved regardless of age or references; content remains unavailable") +} + +func TestReconcileCost(t *testing.T) { + for i := 1; i <= 3; i++ { + t.Logf("scan %d/3", i) + runReconcile(t, true, "1h") + } +} diff --git a/student-tests/registration_race_test.go b/student-tests/registration_race_test.go new file mode 100644 index 0000000..1f49203 --- /dev/null +++ b/student-tests/registration_race_test.go @@ -0,0 +1,77 @@ +//go:build race + +package studenttests_test + +import ( + "bytes" + "encoding/json" + "net/http" + "strings" + "sync" + "testing" + + "github.com/google/uuid" +) + +func TestConcurrentRegistration(t *testing.T) { + const workers = 20 + + username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12] + + body, err := json.Marshal(map[string]string{ + "username": username, + "display_name": "Racer", + "password": testPassword, + }) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + + start := make(chan struct{}) + statuses := make(chan int, workers) + + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + + req, err := http.NewRequest(http.MethodPost, *baseURL+"/api/v1/users", bytes.NewReader(body)) + if err != nil { + t.Errorf("build request: %v", err) + return + } + req.Header.Set("Content-Type", "application/json") + + resp, err := httpClient.Do(req) + if err != nil { + t.Errorf("request failed: %v", err) + return + } + defer resp.Body.Close() + + statuses <- resp.StatusCode + }() + } + + close(start) + wg.Wait() + close(statuses) + + created, conflict := 0, 0 + for s := range statuses { + switch s { + case http.StatusCreated: + created++ + case http.StatusConflict: + conflict++ + default: + t.Errorf("unexpected status %d", s) + } + } + + if created != 1 || conflict != workers-1 { + t.Fatalf("expected 1 created and %d conflict, got %d created and %d conflict", workers-1, created, conflict) + } +} diff --git a/student-tests/session_expiry_test.go b/student-tests/session_expiry_test.go new file mode 100644 index 0000000..99eb098 --- /dev/null +++ b/student-tests/session_expiry_test.go @@ -0,0 +1,42 @@ +//go:build failure + +package studenttests_test + +import ( + "net/http" + "os/exec" + "testing" + "time" +) + +const shortTTLContainer = "api-short-ttl" +const shortTTLURL = "http://localhost:8081" + +func TestSessionExpiry(t *testing.T) { + _ = exec.Command("docker", "rm", "-f", shortTTLContainer).Run() + + compose(t, "run", "-d", "--no-deps", "--name", shortTTLContainer, + "-e", "SESSION_TTL_SECONDS=3", + "-p", "127.0.0.1:8081:8080", "api") + t.Cleanup(func() { + _ = exec.Command("docker", "rm", "-f", shortTTLContainer).Run() + }) + + old := *baseURL + *baseURL = shortTTLURL + t.Cleanup(func() { *baseURL = old }) + + waitReady(t) + + user := createUser(t) + + resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusOK) + resp.Body.Close() + + time.Sleep(4 * time.Second) + + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} diff --git a/student-tests/session_test.go b/student-tests/session_test.go new file mode 100644 index 0000000..d72097e --- /dev/null +++ b/student-tests/session_test.go @@ -0,0 +1,58 @@ +//go:build contract + +package studenttests_test + +import ( + "net/http" + "testing" +) + +func basicLogin(t *testing.T, username, password string) *http.Response { + t.Helper() + + req, err := http.NewRequest(http.MethodPost, *baseURL+"/api/v1/auth/sessions", nil) + if err != nil { + t.Fatalf("build login request: %v", err) + } + req.SetBasicAuth(username, password) + + resp, err := httpClient.Do(req) + if err != nil { + t.Fatalf("login request failed: %v", err) + } + return resp +} + +func TestLoginWrongPassword(t *testing.T) { + user := createUser(t) + + resp := basicLogin(t, user.Username, "wrong-"+testPassword) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() + + resp = basicLogin(t, "no_such_user_"+user.Username, testPassword) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} + +func TestLogout(t *testing.T) { + user := createUser(t) + + resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusOK) + resp.Body.Close() + + resp = doRequest(t, http.MethodDelete, "/api/v1/auth/sessions/current", user.Token, nil) + if resp.StatusCode >= 300 { + t.Fatalf("logout: unexpected status %d", resp.StatusCode) + } + resp.Body.Close() + + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() + + resp = doRequest(t, http.MethodDelete, "/api/v1/auth/sessions/current", user.Token, nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} diff --git a/student-tests/worker_test.go b/student-tests/worker_test.go new file mode 100644 index 0000000..18e8514 --- /dev/null +++ b/student-tests/worker_test.go @@ -0,0 +1,426 @@ +//go:build worker + +package studenttests_test + +import ( + "bytes" + "context" + "encoding/json" + "image/jpeg" + "net/http" + "os" + "os/exec" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "golang.org/x/image/webp" + + "gavrilenko-sxdees/lab7/internal/dto" +) + +func TestWorkerPersistenceAndDuplicate(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + att, source := workerUpload(t, user, chat.ID) + where := "attachment_id='" + att.ID.String() + "'" + resp := postMessage(t, user, chat.ID, "", []uuid.UUID{att.ID}) + requireStatus(t, resp, http.StatusCreated) + var message dto.MessageResponse + mustDecode(t, resp, &message) + resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil) + requireStatus(t, resp, http.StatusConflict) + resp.Body.Close() + resp = sendMessage(t, user, chat.ID, "worker is stopped") + requireStatus(t, resp, http.StatusCreated) + resp.Body.Close() + workerWait(t, "confirmed publication", 15*time.Second, func() bool { + return workerSQL(t, "SELECT published_at IS NOT NULL FROM outbox WHERE "+where) == "t" + }) + stopService(t, "api") + if workerQueue(t) != "1:0" { + t.Fatal("accepted job is not pending in broker") + } + before := workerCommand(t, "compose", "ps", "-q", "rabbitmq") + compose(t, "up", "-d", "--no-deps", "--force-recreate", "rabbitmq") + after := workerCommand(t, "compose", "ps", "-q", "rabbitmq") + if before == after { + t.Fatal("broker was not recreated") + } + workerWait(t, "broker health", 30*time.Second, func() bool { + return workerCommand(t, "inspect", "--format", "{{.State.Health.Status}}", after) == "healthy" + }) + if workerQueue(t) != "1:0" { + t.Fatal("job lost after broker recreation with existing volume") + } + compose(t, "start", "api") + waitReady(t) + att = waitAttachment(t, user, att.ID, "queued", 15*time.Second) + resp = doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String()+"/messages", user.Token, nil) + requireStatus(t, resp, http.StatusOK) + var page dto.MessagePageResponse + mustDecode(t, resp, &page) + found := false + for _, item := range page.Items { + if item.ID == message.ID && reflect.DeepEqual(item.AttachmentIDs, message.AttachmentIDs) { + found = true + } + } + if !found { + t.Fatal("message with attachment lost after API restart") + } + compose(t, "start", "worker") + ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second) + if !bytes.Equal(workerContent(t, user, att.ID, "original"), source) { + t.Fatal("original changed") + } + thumb := workerContent(t, user, att.ID, "thumbnail") + cfg, err := jpeg.DecodeConfig(bytes.NewReader(thumb)) + if err != nil || cfg.Width != 256 || cfg.Height != 160 { + t.Fatal("invalid JPEG thumbnail") + } + crop := workerContent(t, user, att.ID, "crop") + cfg, err = jpeg.DecodeConfig(bytes.NewReader(crop)) + if err != nil || cfg.Width != 128 || cfg.Height != 128 { + t.Fatal("invalid JPEG crop") + } + optimized := workerContent(t, user, att.ID, "optimized") + cfg, err = webp.DecodeConfig(bytes.NewReader(optimized)) + if err != nil || cfg.Width != 320 || cfg.Height != 200 { + t.Fatal("invalid optimized WebP") + } + + workerSQL(t, "UPDATE outbox SET published_at=NULL WHERE "+where) + workerWait(t, "duplicate publication", 15*time.Second, func() bool { + return workerSQL(t, "SELECT published_at IS NOT NULL FROM outbox WHERE "+where) == "t" + }) + workerWait(t, "duplicate acknowledgement", 15*time.Second, func() bool { return workerQueue(t) == "0:0" }) + duplicate := waitAttachment(t, user, att.ID, "ready", 30*time.Second) + if !reflect.DeepEqual(ready, duplicate) || workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "3" { + t.Fatal("duplicate job changed metadata or duplicated variants") + } + if !bytes.Equal(workerContent(t, user, att.ID, "optimized"), optimized) || + !bytes.Equal(workerContent(t, user, att.ID, "crop"), crop) || + !bytes.Equal(workerContent(t, user, att.ID, "thumbnail"), thumb) || + !bytes.Equal(workerContent(t, user, att.ID, "original"), source) { + t.Fatal("duplicate changed content") + } + t.Logf("PASS attachment=%s: queued survives API/broker restart; ready; duplicate acknowledged with unchanged result", att.ID) +} + +func TestWorkerRetryExhausted(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + att, _ := workerUpload(t, user, chat.ID) + workerID := workerCommand(t, "compose", "ps", "-a", "-q", "worker") + var env []string + if err := json.Unmarshal([]byte(workerCommand(t, "inspect", "--format", "{{json .Config.Env}}", workerID)), &env); err != nil { + t.Fatal(err) + } + maxAttempts := 5 + for _, entry := range env { + if value, ok := strings.CutPrefix(entry, "JOB_MAX_ATTEMPTS="); ok { + n, err := strconv.Atoi(value) + if err != nil || n < 1 { + t.Fatal("invalid JOB_MAX_ATTEMPTS") + } + maxAttempts = n + } + } + // A separate worker gets an unreachable S3 endpoint and a short attempt timeout. + // Keep the configured attempt count and normal backoff; leave the shared S3 running. + testWorker := "worker-retry-" + uuid.NewString() + t.Cleanup(func() { + workerCommand(t, "rm", "-f", testWorker) + }) + workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker, + "-e", "JOB_TIMEOUT_SECONDS=3", "-e", "S3_ENDPOINT=http://127.0.0.1:1", "worker") + failed := waitAttachment(t, user, att.ID, "failed", 90*time.Second) + if failed.ErrorCode == nil || *failed.ErrorCode != "retry_exhausted" { + t.Fatal("expected safe retry_exhausted error") + } + attempts := workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+att.ID.String()+"'") + if attempts != strconv.Itoa(maxAttempts) { + t.Fatalf("expected %d attempts, got %s", maxAttempts, attempts) + } + resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil) + requireStatus(t, resp, http.StatusConflict) + resp.Body.Close() + resp = postMessage(t, user, chat.ID, "", []uuid.UUID{att.ID}) + requireStatus(t, resp, http.StatusConflict) + resp.Body.Close() + t.Logf("PASS attachment=%s: %d attempts, failed/retry_exhausted, content/link rejected", att.ID, maxAttempts) +} + +func TestWorkerProcessingTimeout(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + + // Decode and resize of 36 million pixels must be interrupted by the short deadline. + resp := uploadAttachment(t, user, chat.ID, "large.png", "image/png", makePNG(t, 6000, 6000)) + requireStatus(t, resp, http.StatusAccepted) + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + + testWorker := "worker-timeout-" + uuid.NewString() + t.Cleanup(func() { + workerCommand(t, "rm", "-f", testWorker) + }) + workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker, + "-e", "JOB_TIMEOUT_SECONDS=1", "-e", "JOB_MAX_ATTEMPTS=1", "worker") + parentPID := workerCommand(t, "inspect", "--format", "{{.State.Pid}}", testWorker) + workerWait(t, "image child process", 5*time.Second, func() bool { + return strings.Contains(workerCommand(t, "top", testWorker, "-eo", "pid,args"), "-process-image") + }) + failed := waitAttachment(t, user, att.ID, "failed", 5*time.Second) + if failed.ErrorCode == nil || *failed.ErrorCode != "retry_exhausted" { + t.Fatal("expected retry_exhausted after processing deadline") + } + if strings.Contains(workerCommand(t, "top", testWorker, "-eo", "pid,args"), "-process-image") { + t.Fatal("image process survived its deadline") + } + if workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE attachment_id='"+att.ID.String()+"'") != "0" { + t.Fatal("timed-out processing published variants") + } + + // The same parent process must remain usable after terminating the image child. + uploadPNG(t, user, chat.ID) + after := workerCommand(t, "inspect", "--format", "{{.State.Pid}}", testWorker) + if parentPID != after || parentPID == "0" { + t.Fatal("parent worker restarted after the image timeout") + } +} + +func TestWorkerReplay(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + att, source := workerUpload(t, user, chat.ID) + id := att.ID.String() + where := "attachment_id='" + id + "'" + + testWorker := "worker-replay-" + uuid.NewString() + t.Cleanup(func() { + if testWorker != "" { + workerCommand(t, "rm", "-f", testWorker) + } + }) + workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker, + "-e", "JOB_TIMEOUT_SECONDS=3", "-e", "JOB_MAX_ATTEMPTS=1", + "-e", "S3_ENDPOINT=http://127.0.0.1:1", "worker") + waitAttachment(t, user, att.ID, "failed", 15*time.Second) + workerCommand(t, "rm", "-f", testWorker) + testWorker = "" + + runCLI := func(args ...string) (string, error) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "docker", append([]string{ + "compose", "run", "--rm", "--no-deps", "worker", + }, args...)...) + cmd.Dir = ".." + out, err := cmd.CombinedOutput() + return string(out), err + } + replayArgs := []string{"-replay", id, "-operator", "synthetic-operator", "-reason", "S3 restored"} + if out, err := runCLI("-list-failed"); err != nil || !strings.Contains(out, id) { + t.Fatalf("failed registry did not list attachment: %v\n%s", err, out) + } + if out, err := runCLI("-replay", id); err == nil || !strings.Contains(out, "nonempty operator and reason") { + t.Fatalf("replay without audit details was accepted: %v\n%s", err, out) + } + + // A stale DB key must not make a missing S3 source replayable. + key := workerSQL(t, "SELECT staging_key FROM attachments WHERE id='"+id+"'") + workerSQL(t, "UPDATE attachments SET staging_key='staging/"+uuid.NewString()+"' WHERE id='"+id+"'") + out, err := runCLI(replayArgs...) + workerSQL(t, "UPDATE attachments SET staging_key='"+key+"' WHERE id='"+id+"'") + if err == nil || !strings.Contains(out, "verify replay source") { + t.Fatalf("missing S3 source was accepted: %v\n%s", err, out) + } + if workerSQL(t, "SELECT status||':'||attempts||':'||retry_base FROM attachments WHERE id='"+id+"'") != "failed:1:0" || + workerSQL(t, "SELECT count(*) FROM attachment_replays WHERE "+where) != "0" || + workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "1" { + t.Fatal("rejected replay changed attachment, audit or outbox") + } + + if out, err := runCLI(replayArgs...); err != nil { + t.Fatalf("replay failed: %v\n%s", err, out) + } + if workerSQL(t, "SELECT status||':'||attempts||':'||retry_base FROM attachments WHERE id='"+id+"'") != "queued:1:1" || + workerSQL(t, "SELECT attempt||':'||operator||':'||reason||':'||previous_error_code FROM attachment_replays WHERE "+where) != + "2:synthetic-operator:S3 restored:retry_exhausted" || + workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "2" { + t.Fatal("replay did not atomically queue the next attempt with audit and outbox") + } + if out, err := runCLI(replayArgs...); err == nil || !strings.Contains(out, "not replayable") { + t.Fatalf("queued replay was accepted twice: %v\n%s", err, out) + } + + compose(t, "start", "worker") + ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second) + if len(ready.Variants) != 3 || !bytes.Equal(workerContent(t, user, att.ID, "original"), source) { + t.Fatal("replay did not complete the same attachment with unchanged original") + } + if out, err := runCLI(replayArgs...); err == nil || !strings.Contains(out, "not replayable") { + t.Fatalf("ready replay was accepted: %v\n%s", err, out) + } + if workerSQL(t, "SELECT count(*) FROM attachment_replays WHERE "+where) != "1" || + workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+id+"'") != "2" { + t.Fatal("duplicate replay changed audit or attempt counter") + } +} + +func TestWorkerOutboxRecovery(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + + stopService(t, "rabbitmq") + att, source := workerUpload(t, user, chat.ID) + id := att.ID.String() + where := "attachment_id='" + id + "'" + jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") + if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND attempt=1 AND published_at IS NULL") != "1" { + t.Fatal("upload 202 did not persist an unpublished intent") + } + + t.Cleanup(func() { + compose(t, "start", "api") + waitReady(t) + }) + compose(t, "kill", "-s", "SIGKILL", "api") + if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND attempt=1 AND published_at IS NULL") != "1" { + t.Fatal("committed intent lost after API crash") + } + + compose(t, "start", "api") + waitReady(t) + waitAttachment(t, user, att.ID, "queued", 15*time.Second) + compose(t, "up", "-d", "--no-deps", "--wait", "--wait-timeout", "30", "rabbitmq") + workerWait(t, "outbox publication after API crash", 15*time.Second, func() bool { + return workerSQL(t, "SELECT published_at IS NOT NULL FROM outbox WHERE "+where) == "t" + }) + if workerQueue(t) != "1:0" { + t.Fatal("recovered intent was not delivered to broker") + } + + compose(t, "start", "worker") + ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second) + if len(ready.Variants) != 3 || !bytes.Equal(workerContent(t, user, att.ID, "original"), source) { + t.Fatal("recovered attachment has incomplete variants or changed original") + } + workerWait(t, "recovered job acknowledgement", 15*time.Second, func() bool { + return workerQueue(t) == "0:0" + }) + if workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID || + workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+id+"'") != "1" || + workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "1" { + t.Fatal("recovery replaced the job or created another attempt") + } + + t.Logf("PASS attachment=%s: commit, API SIGKILL before publication, automatic outbox recovery, same job ready", id) +} + +func TestWorkerLeaseRecovery(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + secret, err := os.ReadFile("../secrets/test_database_url.txt") + if err != nil { + t.Fatal("read test database URL") + } + conn, err := pgx.Connect(ctx, strings.TrimSpace(string(secret))) + if err != nil { + t.Fatal("connect to test database") + } + t.Cleanup(func() { conn.Close(context.Background()) }) + + user := createUser(t) + chat := createChat(t, user, user.ID) + stopService(t, "worker") + if workerQueue(t) != "0:0" { + t.Fatal("run on an idle stand with an empty attachment queue") + } + att, source := workerUpload(t, user, chat.ID) + id := att.ID.String() + where := "attachment_id='" + id + "'" + jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") + + testWorker := "worker-lease-" + uuid.NewString() + t.Cleanup(func() { workerCommand(t, "rm", "-f", testWorker) }) + tx, err := conn.Begin(ctx) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { tx.Rollback(context.Background()) }) + // S3 writes finish before variant metadata is inserted. Block that INSERT + // to kill the worker before the result COMMIT and broker acknowledgement. + if _, err := tx.Exec(ctx, "LOCK TABLE attachment_variants IN SHARE MODE"); err != nil { + t.Fatal(err) + } + workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker, + "-e", "JOB_TIMEOUT_SECONDS=15", "worker") + workerWait(t, "variant INSERT blocked after S3 writes", 10*time.Second, func() bool { + var blocked bool + if _, err := conn.Exec(ctx, "SELECT pg_stat_clear_snapshot()"); err != nil { + t.Fatal(err) + } + err := conn.QueryRow(ctx, `SELECT EXISTS ( + SELECT 1 FROM pg_stat_activity + WHERE $1::int = ANY(pg_blocking_pids(pid)) + AND query LIKE '%INSERT INTO attachment_variants%' + )`, int32(conn.PgConn().PID())).Scan(&blocked) + if err != nil { + t.Fatal(err) + } + return blocked + }) + workerCommand(t, "kill", "--signal", "SIGKILL", testWorker) + if err := tx.Rollback(ctx); err != nil { + t.Fatal(err) + } + if workerSQL(t, "SELECT status||':'||attempts FROM attachments WHERE id='"+id+"'") != "processing:1" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "0" { + t.Fatal("crashed worker committed a result") + } + workerWait(t, "unacknowledged job returned to broker", 10*time.Second, func() bool { + return workerQueue(t) == "1:0" + }) + + // Leave lease_until unchanged: recovery must wait for its natural expiry. + compose(t, "start", "worker") + ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second) + if len(ready.Variants) != 3 || !bytes.Equal(workerContent(t, user, att.ID, "original"), source) { + t.Fatal("lease recovery lost variants or changed original") + } + workerWait(t, "recovered job acknowledgement", 15*time.Second, func() bool { + return workerQueue(t) == "0:0" + }) + if workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID || + workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+id+"'") != "2" || + workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "3" || + workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND attempt=2 AND published_at IS NOT NULL") != "1" { + t.Fatal("lease recovery replaced the job, duplicated variants or skipped retry publication") + } + t.Logf("PASS attachment=%s: SIGKILL after S3 writes, expired lease recovered, same job ready on attempt 2", id) +} diff --git a/student.mk b/student.mk new file mode 100644 index 0000000..c36e9a6 --- /dev/null +++ b/student.mk @@ -0,0 +1,52 @@ +LOAD_ARGS = $(if $(LOAD_WORKERS),-workers=$(LOAD_WORKERS),) \ + $(if $(LOAD_DURATION),-duration=$(LOAD_DURATION),) \ + $(if $(LOAD_RATE),-rate=$(LOAD_RATE),) \ + $(if $(LOAD_CSV),-csv=$(LOAD_CSV),) \ + $(if $(LOAD_LABEL),-label=$(LOAD_LABEL),) +REPLICA ?= 1 +ACTION ?= stop-one.sh +ACTION_AT ?= 10s +DRY_RUN ?= true + +.PHONY: help-go contract-go race-go load-go failure-go load-action-go reconcile reconcile-test-go worker-go pipeline-go + +help-go: + @echo "contract-go: contract tests" + @echo "worker-go: worker persistence, duplicate and bounded retry (stops shared services)" + @echo "race-go: concurrency tests (-race)" + @echo "load-go: load test" + @echo "failure-go: dependency failure tests (stops redis/postgres/s3 containers)" + @echo "reconcile: attachment audit; DRY_RUN=false to repair" + @echo "pipeline-go: versioned pipeline tests (requires Compose; stops worker)" + +contract-go: + go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL) + +race-go: + go test -tags=race ./student-tests/... -race -v -args -base-url=$(BASE_URL) + +load-go: + go test -count=1 -tags=load ./student-tests/... -v -args -base-url=$(BASE_URL) $(LOAD_ARGS) + +failure-go: + go test -tags=failure ./student-tests/... -v -args -base-url=$(BASE_URL) + +load-action-go: + go test -tags=load,action ./student-tests/... -run TestLoadWithAction -v -args \ + -base-url=$(BASE_URL) $(LOAD_ARGS) \ + -replica=$(REPLICA) \ + -action=$(CURDIR)/scripts/$(ACTION) \ + -action-at=$(ACTION_AT) + +reconcile: + docker compose --env-file .env run --rm --no-deps reconcile -dry-run=$(DRY_RUN) + +reconcile-test-go: + docker compose --env-file .env build reconcile + go test -count=1 -tags=reconcile ./student-tests/... -v -args -base-url=$(BASE_URL) + +worker-go: + go test -count=1 -tags=worker ./student-tests/... -v -args -base-url=$(BASE_URL) + +pipeline-go: + go test -count=1 -tags=nodynamic,pipeline ./student-tests/... -v -args -base-url=$(BASE_URL) diff --git a/web/swagger/index.html b/web/swagger/index.html new file mode 100644 index 0000000..c498b1b --- /dev/null +++ b/web/swagger/index.html @@ -0,0 +1,21 @@ + + + + + MTUSI Messenger API + + + +
+ + + + + \ No newline at end of file