From e9f0fde6f2db8e24b528c7e18b5ca17a36790e7a Mon Sep 17 00:00:00 2001 From: Vladislav Kunetskiy Date: Wed, 21 Oct 2026 23:25:11 +0300 Subject: [PATCH] =?UTF-8?q?lab4:=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BF=D0=BE=20=D1=80=D0=B5?= =?UTF-8?q?=D0=B2=D1=8C=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 2 + .env.example | 12 ++-- .gitignore | 2 + LAB4-PLAN.md | 39 ++++++------ REPORT.md | 38 +++++++----- compose.yaml | 14 +++-- docker-compose.local.yaml | 59 +++++++++++++++++- evidence/lab4/README.md | 4 +- evidence/lab4/failover.txt | 2 +- evidence/lab4/memory/samples.csv | 10 +-- evidence/lab4/memory/summary.txt | 10 +-- evidence/lab4/s3-init.txt | 12 ++-- evidence/lab4/s3-outage.txt | 4 +- evidence/lab4/sweep.txt | 5 +- evidence/lab4/track1/results.csv | 40 ++++++------ evidence/lab4/track1/summary.txt | 8 +-- infra/lb/haproxy.cfg | 9 ++- infra/s3/README.md | 4 +- internal/config/config.go | 6 +- internal/platform/objectstore/objectstore.go | 2 +- internal/platform/objectstore/s3.go | 19 +++--- internal/platform/objectstore/s3_test.go | 26 ++++++++ internal/service/attachment/service.go | 16 +++-- internal/service/attachment/service_test.go | 47 +++++++++++++- internal/service/attachment/sweeper.go | 12 +++- internal/service/attachment/sweeper_test.go | 36 +++++++++++ internal/transport/rest/extensions.go | 4 +- internal/transport/rest/extensions_test.go | 64 ++++++++++++++++++++ internal/transport/rest/handler.go | 17 +++--- internal/transport/rest/handler_test.go | 39 ++++++++++++ scripts/check_s3_creds.py | 7 ++- student-tests/presign_flow.py | 13 ++-- 32 files changed, 451 insertions(+), 131 deletions(-) create mode 100644 internal/platform/objectstore/s3_test.go create mode 100644 internal/transport/rest/extensions_test.go create mode 100644 internal/transport/rest/handler_test.go diff --git a/.dockerignore b/.dockerignore index e607a046..a2472942 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,6 +18,8 @@ __pycache__ node_modules evidence .DS_Store +messenger +s3init bin coverage.out .cache diff --git a/.env.example b/.env.example index 2cddf490..eb8a4a0f 100644 --- a/.env.example +++ b/.env.example @@ -66,7 +66,7 @@ IDEMPOTENCY_TTL_SECONDS=86400 # budget, e.g. API_REPLICAS=4 API_CPU_LIMIT=0.25 API_MEM_LIMIT=192M. API_REPLICAS=2 API_CPU_LIMIT=0.50 -API_MEM_LIMIT=384M +API_MEM_LIMIT=256M # Connections of ONE API replica to PostgreSQL; the total is replicas × value. # Track 1 checks whether the shared connection budget becomes the saturation @@ -79,14 +79,16 @@ POSTGRES_CPU_LIMIT=0.50 # Memory quota of the shared database. The track 1 series r/g/pool were measured # with 512M, the db1cpu control — with 384M (see evidence/track1/profile-*.json). -POSTGRES_MEM_LIMIT=384M +POSTGRES_MEM_LIMIT=192M # Loopback port of the HAProxy operator page (UP/DOWN of every replica). LB_STATS_PORT=8404 # --- Lab4: private S3 object store (SeaweedFS) ------------------------------- -# Synthetic local credentials. infra/s3/s3.json must contain the same values; -# scripts/check_s3_creds.py enforces that before the stand starts. +# Synthetic local application credentials. infra/s3/s3.json must contain the +# same app values; scripts/check_s3_creds.py enforces that before the stand starts. +# Admin credentials live only in infra/s3/s3.json and s3-init defaults; never put +# them in .env, because the API service loads this file. S3_ENDPOINT=http://localhost:8333 S3_PUBLIC_ENDPOINT=http://127.0.0.1:8333 S3_PORT=8333 @@ -94,8 +96,6 @@ S3_REGION=us-east-1 S3_BUCKET=messenger-attachments S3_ACCESS_KEY_ID=lab4app S3_SECRET_ACCESS_KEY=lab4app-secret -S3_ADMIN_ACCESS_KEY=lab4admin -S3_ADMIN_SECRET_ACCESS_KEY=lab4admin-secret # Attachment limits from contract 1.4.0. MAX_UPLOAD_BYTES=10485760 diff --git a/.gitignore b/.gitignore index ad511f63..6c6271ba 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,8 @@ dist/ build/ target/ bin/ +/messenger +/s3init obj/ coverage/ coverage.out diff --git a/LAB4-PLAN.md b/LAB4-PLAN.md index f87bbe2a..127edc22 100644 --- a/LAB4-PLAN.md +++ b/LAB4-PLAN.md @@ -555,7 +555,7 @@ type Store interface { Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error Delete(ctx context.Context, key string) error List(ctx context.Context, prefix string) ([]Object, error) - PresignPut(ctx context.Context, key string, ttl time.Duration) (string, time.Time, error) + PresignPut(ctx context.Context, key string, size int64, ttl time.Duration) (string, time.Time, error) } ``` @@ -570,11 +570,10 @@ type Store interface { - `Head`: `HeadObject`; `NotFound` → `domain.ErrNotFound`. - `Copy`: `CopyObject` с `MetadataDirective=REPLACE`, `ContentType`, `Metadata`. - `List`: пагинация `ListObjectsV2` (`ContinuationToken`), вернуть все объекты. -- `PresignPut`: `s3.NewPresignClient(publicClient).PresignPutObject(ctx, &s3.PutObjectInput{Bucket, Key}, ...)`, - `Expires=ttl`. В input передавать **только** Bucket/Key: если передать ContentType/ChecksumSHA256, - SDK может добавить их в `X-Amz-SignedHeaders`, и клиент будет обязан прислать точные заголовки - (AWS docs прямо предупреждают об этом). Меньше связанных заголовков — меньше `SignatureDoesNotMatch`. - Content-Type и SHA проверяются на complete по фактическим байтам. +- `PresignPut`: `s3.NewPresignClient(publicClient).PresignPutObject(ctx, &s3.PutObjectInput{Bucket, Key, ContentLength: size}, ...)`, + `Expires=ttl`. `ContentLength` попадает в `X-Amz-SignedHeaders` (проверено), поэтому S3 отклоняет + PUT другого размера с 403 — write-time лимит. ContentType/ChecksumSHA256 не подписывать: + Content-Type не нужен, а checksums SeaweedFS не валидирует; complete проверяет фактические байты. Проверено: SeaweedFS не валидирует `x-amz-checksum-sha256` и не возвращает его в HeadObject, поэтому complete обязан пересчитать SHA. - Все ошибки оборачивать `%w`, логировать без ключей. @@ -665,8 +664,8 @@ payload, _ := json.Marshal(struct { }{req.Text, ids}) ``` -Сортировка делает порядок вложений незначащим для идемпотентности; набор отличается — 409. -Отсутствующий `attachment_ids` и `[]` дают одинаковый fingerprint. +Порядок вложений входит в payload: перестановка — другой body и 409. Отсутствующий +`attachment_ids` и `[]` дают одинаковый fingerprint. Замечание: записи lab3 в `message_idempotency` хранят старый hash; повтор такого ключа в течение TTL даст 409. Отразить в REPORT. @@ -847,7 +846,7 @@ Content-Type: application/json {"attachment_id":"...","method":"PUT","upload_url":"http://127.0.0.1:8333/...", "expires_at":"2026-10-21T19:00:00Z","sha256":"<64 hex>","size_bytes":12345} ``` -Клиенту не нужно присылать специальные заголовки: URL подписывает только host+key. +Клиент обязан отправить ровно `size_bytes` (Content-Length подписан); остальные заголовки не обязательны. ```http POST /api/v1/attachments/{attachment_id}/complete @@ -865,12 +864,12 @@ Content-Type: application/json - `size_bytes` 1..maxUpload; - `sha256` — 64 lowercase hex; - membership чата → 404; создать pending-строку с ключом `staging/presign//`; -- `PresignPut(publicClient, key, presign_ttl)`; URL и `expires_at` вернуть. +- `PresignPut(publicClient, key, size_bytes, presign_ttl)`; URL и `expires_at` вернуть. + URL подписывает `content-length`, поэтому клиент обязан отправить ровно `size_bytes`. Ограничения presigned PUT (зафиксировать в REPORT): -- S3 не умеет ограничивать размер при PUT: `size_bytes` проверяется на complete, объект-нарушитель - удаляется. Это соответствует формулировке трека («проверка размера/checksum при complete»); - временное хранение ограничено TTL + grace + приватным bucket. +- Write-time лимит обеспечен подписанным `Content-Length`: PUT другого размера получает 403. + Complete дополнительно сверяет размер, SHA и структуру; это соответствует формулировке трека. - URL — bearer-токен: он многоразовый до `expires_at` и перезаписывает объект по тому же ключу (AWS docs). Complete проверяет фактические байты; повторный PUT после complete создаёт staging-orphan, который удалит sweeper. @@ -1018,7 +1017,7 @@ Complete: ### 12.5. Негативные сценарии трека - просроченный URL → 403; -- PUT с другим размером → complete 400 и объект удалён; +- PUT с другим размером → 403 от S3, complete — 409 (объекта нет); - PUT с другим SHA → complete 400 и объект удалён; - PUT в чужой ключ (без подписи) → 403; - complete чужого attachment → 404; @@ -1043,7 +1042,7 @@ Complete: - `memory/` — CSV + summary (≥10 одновременных загрузок по 10 MiB; пик `anon`, `memory.current` и `docker stats` с объяснением вклада page cache). - `track1/` — `results.csv`, `summary.txt`, команды, p50/p95, трафик LB и API, RAM, а также - отдельный вывод: presigned PUT не ограничивает размер на стороне S3, проверка на complete. + отдельный вывод: Content-Length подписан, oversized PUT отклоняется S3; complete перепроверяет. - `defense.md` — краткие ответы на вопросы README (см. §13.3). Никаких секретов и токенов в evidence. @@ -1091,7 +1090,7 @@ Complete: 11. **`variants=[]`**, не nil. 12. **Membership в SQL** — не выбирать объект, а потом проверять (лишний 403/404 и утечка). 13. **201 только после S3+БД**; pending-строка не должна отдаваться как ready. -14. **Fingerprint идемпотентности** включает отсортированные attachment_ids; старые записи дадут 409. +14. **Fingerprint идемпотентности** включает attachment_ids в порядке запроса (перестановка — другой payload, 409); отсутствующий список = []. 15. **Claim ключа после валидации**, иначе неудачный запрос оставит занятый ключ без message_id. 16. **Транзакция message + links**; FK и статус вложения проверять до claim. 17. **S3 ключи/креды не логировать**; ошибки наружу — общий `Error`. @@ -1129,7 +1128,8 @@ Complete: на цикл точечных запросов (≤10 вложений) или `pgtype.Array`. 44. **`GET /attachments/{id}` не должен отдавать 409** для pending/failed: контракт требует наблюдаемые `status`/`error_code`; 409 — только `/content`. -45. **Presigned PUT не ограничивает размер**; проверка на complete + sweep, зафиксировать в REPORT. +45. **Presigned PUT**: подписывать `Content-Length` (S3 вернёт 403 на другой размер); + complete всё равно перепроверяет размер/SHA. 46. **Presigned URL многоразовый и перезаписывает объект**; complete проверяет фактические байты, после complete повторный PUT создаёт staging-orphan → sweep. 47. **Не подписывать Content-Type в presign** — SDK может добавить его в SignedHeaders, клиент @@ -1249,9 +1249,8 @@ make test-persistence ACTION_SCRIPT=scripts/restart.sh 1. **Readiness не включает S3.** S3 общий для всех реплик; его недоступность убрала бы весь стенд из ротации. Вместо этого attachment-endpoint дают 503, остальные работают. Зафиксировать в REPORT. -2. **Presigned PUT не ограничивает размер на стороне S3.** Проверка на complete + sweep; это ровно - формулировка трека. Для production лучший вариант — presigned POST policy с `content-length-range`, - но SeaweedFS PostObject и его условия сложнее; в lab4 не нужен. +2. **Presigned PUT ограничен подписанным `Content-Length`.** S3 отклоняет другой размер (403); + complete повторно проверяет размер/SHA/структуру. Квоты и rate limiting не входят в lab4. 3. **Complete перечитывает объект из S3.** SeaweedFS не валидирует и не хранит checksum, поэтому честная проверка SHA требует чтения. Трафик API при этом ≈ размеру файла; выигрыш presign — в клиентском плече и отсутствии приёма тела API. Отражено в §12.4. diff --git a/REPORT.md b/REPORT.md index b818f406..39554c0c 100644 --- a/REPORT.md +++ b/REPORT.md @@ -55,7 +55,7 @@ flowchart LR - **Источник истины:** метаданные (`users`, `chats`, `messages`, `attachments`, `message_attachments`) — PostgreSQL; оригиналы — только приватный bucket SeaweedFS. Redis используется для кэша списка чатов и не является источником истины. - **201 честный:** upload сначала валидирует изображение, пишет объект в S3, затем переводит pending-строку в ready. 201 возвращается только после обоих шагов. Если процесс умер между ними, строка остаётся pending, объект уже в S3; sweeper либо восстанавливает ready, либо удаляет пару после grace. - **Границы транзакций:** сообщение и связи `message_attachments` вставляются в одной транзакции вместе с Idempotency-Key; вложения проверяются до claim. Сам S3 не транзакционен, поэтому используется pending/ready + компенсация. -- **Идемпотентность сообщений:** fingerprint включает `text` и отсортированный набор `attachment_ids`; отсутствующий `attachment_ids` и `[]` эквивалентны. Повтор с другим набором — 409. +- **Идемпотентность сообщений:** fingerprint включает `text` и `attachment_ids` в исходном порядке; отсутствующий `attachment_ids` и `[]` эквивалентны. Повтор с другим набором или порядком — 409. - **Sweeper:** один владелец через `pg_try_advisory_lock`, grace period. Удаляет только объекты старше grace и только не ready; pending с валидным объектом восстанавливает в ready. Повторный запуск идемпотентен. - **Readiness:** проверяет PostgreSQL, но не S3. S3 общий для всех реплик; его недоступность не должна убирать из ротации весь стенд. Attachment-endpoint при этом отвечают 503, остальные продолжают работать. Это осознанное решение зафиксировано здесь. - **Перенесено из lab3:** пользователи, сессии, чаты, сообщения, идемпотентность, LB, PostgreSQL, Redis, Compose/Swarm-подход, HAProxy active checks. Добавлено: S3-стенд, `s3-init`, миграция `00004`, вложения, presign-расширение, sweeper. @@ -71,7 +71,8 @@ flowchart LR Преимущества и ограничения: - тело не проходит через API/LB (в замере LB RX падает с 9,49 МБ до 3,8 КБ для 9 МиБ); - complete перечитывает объект из S3 для проверки SHA, поэтому API RX остаётся около размера файла; выигрыш — в клиентском плече и в отказе от приёма тела; -- presigned PUT не умеет ограничивать размер на стороне S3; размер проверяется на complete, нарушитель удаляется. Брошенные объекты удаляет sweeper после grace; +- `Content-Length` подписан в URL, поэтому S3 отклоняет PUT другого размера с 403 ещё до сохранения; + complete повторно сверяет размер, SHA-256 и структуру. Брошенные объекты удаляет sweeper после grace; - URL — bearer-токен, многоразовый до `expires_at`; подпись привязана к host+key, Content-Type не подписывается. ## Доказательства критериев @@ -99,8 +100,9 @@ flowchart LR ## Эксперименты и отказы -Стенд: Apple Silicon (arm64), Docker Desktop, Compose; API 2 реплики × 384 МБ, SeaweedFS 768 МБ, -PostgreSQL 384 МБ, Redis 192 МБ. Все замеры — локальные, без внешней сети. +Стенд: Apple Silicon (arm64), Docker Desktop с VM 1,9 ГБ, Compose; API 2 реплики × 256 МБ, +SeaweedFS 640 МБ (GOMEMLIMIT 512 MiB), PostgreSQL 192 МБ, Redis 96 МБ, HAProxy 48 МБ. +Все замеры — локальные, без внешней сети. | Воздействие | Что ожидали | Что наблюдали | Восстановление / потери | | --- | --- | --- | --- | @@ -108,7 +110,7 @@ PostgreSQL 384 МБ, Redis 192 МБ. Все замеры — локальные, | Restart PostgreSQL/Redis/SeaweedFS/API с volumes | метаданные, сессия и оригинал сохраняются | PASS | 43,9 с до readiness; потерь нет | | Остановка SeaweedFS | upload/download 503, остальное 200 | `/health/ready` 200, чаты 200, upload/download 503 | после старта upload снова 201 | | Брошенный presign без PUT | удаление после grace, ready не трогать | pending исчез после ~2 с grace; ready скачан | sweeper, потерь ready нет | -| 10 одновременных загрузок по 9 454 448 Б, 3 раунда | API не OOM, RAM ограничена | 30 загрузок за 2,10 с; anon baseline 279,9 МБ, peak 281,8 МБ (+1,97 МБ); `memory.current` peak 386,9 МБ на две реплики | без OOM после подъёма лимита SeaweedFS до 768 МБ | +| 10 одновременных загрузок по 9 454 448 Б, 3 раунда | API не OOM, RAM ограничена | 30 загрузок за 2,98 с; anon baseline 280,3 МБ, peak 281,7 МБ (+1,34 МБ); `memory.current` peak 411,8 МБ на две реплики; SeaweedFS restarts=0, OOM=false | без OOM после подбора лимитов под 1,9 ГБ VM | | Presigned URL с TTL=3 с | 403 после истечения | 403 через 4 с | — | | Неверный SHA на complete | отказ и очистка | 409/400, объект удалён | повторная загрузка возможна | @@ -116,10 +118,10 @@ PostgreSQL 384 МБ, Redis 192 МБ. Все замеры — локальные, | Размер | Поток | Медиана, с | p95, с | LB RX, Б | API RX, Б | API anon peak, Б | |---|---|---:|---:|---:|---:|---:| -| ~1 МиБ | proxy | 0,227 | 0,244 | 1 057 728 | 1 058 827 | 282 771 456 | -| ~1 МиБ | presign | 0,225 | 0,233 | 3 808 | 1 057 848 | 282 877 952 | -| ~9 МиБ | proxy | 0,235 | 0,237 | 9 490 698 | 9 501 643 | 282 918 912 | -| ~9 МиБ | presign | 0,236 | 0,250 | 3 795 | 9 473 399 | 283 054 080 | +| ~1 МиБ | proxy | 0,228 | 0,233 | 1 058 392 | 1 061 729 | 285 638 656 | +| ~1 МиБ | presign | 0,230 | 0,239 | 3 755 | 1 058 061 | 286 216 192 | +| ~9 МиБ | proxy | 0,237 | 0,240 | 9 490 341 | 9 494 663 | 286 285 824 | +| ~9 МиБ | presign | 0,239 | 0,246 | 3 879 | 9 472 840 | 286 367 744 | Методика: 5 итераций на сценарий без прогрева (стенд уже прогрет), PNG фиксированного размера, клиент — тот же хост. `lb_rx` — сумма по LB; `api_rx` — сумма по двум API; `anon` — cgroup @@ -132,20 +134,26 @@ PostgreSQL 384 МБ, Redis 192 МБ. Все замеры — локальные, - **Readiness не включает S3.** Это выбрано, чтобы недоступность общего S3 не убирала из ротации все API-реплики; attachment-endpoint деградируют в 503. Если политика требует fail-closed, добавьте S3 в readiness отдельным флагом. -- **Presigned PUT не ограничивает размер на стороне storage.** Размер проверяется на complete; - злоупотребить можно только в пределах TTL+grace, после чего sweeper удаляет объект. Production- - вариант — POST policy с `content-length-range`. +- **Presigned PUT ограничен подписанным `Content-Length`.** Клиент обязан прислать ровно + заявленный размер; иначе SeaweedFS отвечает 403 (проверено). Это защищает от записи огромного + staging-объекта, но не заменяет rate limiting: число готовых вложений и pending-строк + по-прежнему не квотируется. - **Complete перечитывает объект из S3.** SeaweedFS не валидирует и не хранит checksum, поэтому честная проверка SHA требует чтения. Для больших файлов это удваивает внутренний трафик. - **S3 — одна нода SeaweedFS.** Это учебный стенд; HA/replication не настроены. Потеря volume - означает потерю байтов; метаданные в PostgreSQL при этом остаются. + означает потерю байтов; метаданные в PostgreSQL при этом остаются. Лимиты контейнеров подобраны + под Docker Desktop VM 1,9 ГБ; HAProxy `timeout server` увеличен до 45 с для 10 MiB загрузок, + readiness-проба по-прежнему 1 с. - **lab5 не реализован:** thumbnail, варианты, queued/processing/202, worker. Поле `variants` всегда `[]`, `status` — только `ready`. - **Старые Idempotency-Key lab3** имеют fingerprint без `attachment_ids`; повтор такого ключа в пределах TTL даст 409. Это осознанное изменение формата, данные не мигрируются. -- **Rate limiting (429)** не реализован; контракт его не требует. +- **Rate limiting (429) и квоты не реализованы**; контракт их не требует. Локальный + `docker-compose.local.yaml` публикует PostgreSQL/Redis на loopback с учебными паролями, а + HAProxy stats на 8404 не требует аутентификации — это операторские порты, не публичный стенд. - **Секреты:** локальные S3-креды синтетические и лежат в `infra/s3/s3.json`/`.env.example`; - для production нужны отдельные секреты и отзыв URL через ротацию кредов. + admin-креды не входят в `.env` и не попадают в API-контейнер (проверено `docker compose exec api env`). + Для production нужны отдельные секреты и отзыв URL через ротацию кредов. - **Проверка изображений структурная**, без decode+re-encode (OWASP рекомендует re-encode для недоверенных изображений). В lab4 изображения не обрабатываются и не исполняются; lab5 добавит контролируемый decode для thumbnail. diff --git a/compose.yaml b/compose.yaml index 93917d71..8d1a3adf 100644 --- a/compose.yaml +++ b/compose.yaml @@ -38,7 +38,7 @@ services: # runs at its quota while API replicas idle. Raise this knob to give the # shared dependency more of the host CPU. cpus: "${POSTGRES_CPU_LIMIT:-0.50}" - memory: ${POSTGRES_MEM_LIMIT:-384M} + memory: ${POSTGRES_MEM_LIMIT:-192M} restart: unless-stopped redis: @@ -64,7 +64,7 @@ services: resources: limits: cpus: "0.25" - memory: 192M + memory: 96M restart: unless-stopped # Private S3-compatible object store. Only the S3 API is published, on @@ -81,6 +81,10 @@ services: volumes: - ./infra/s3/s3.json:/etc/seaweedfs/s3.json:ro - seaweedfs-data:/data + environment: + # Keep the Go runtime below the container limit under concurrent PUTs. + GOGC: "50" + GOMEMLIMIT: "512MiB" ports: - "127.0.0.1:${S3_PORT:-8333}:8333" healthcheck: @@ -93,7 +97,7 @@ services: resources: limits: cpus: "1.00" - memory: 768M + memory: 640M restart: unless-stopped # One-shot, idempotent bucket bootstrap and identity probe. @@ -188,7 +192,7 @@ services: resources: limits: cpus: "${API_CPU_LIMIT:-0.50}" - memory: ${API_MEM_LIMIT:-384M} + memory: ${API_MEM_LIMIT:-256M} # The app drains on SIGTERM within SERVER_SHUTDOWN_TIMEOUT; keep the grace # period above it so Docker does not SIGKILL an in-flight request. stop_grace_period: 15s @@ -230,7 +234,7 @@ services: resources: limits: cpus: "${LB_CPU_LIMIT:-0.25}" - memory: 64M + memory: 48M restart: unless-stopped volumes: diff --git a/docker-compose.local.yaml b/docker-compose.local.yaml index 0707f55b..f61ef202 100644 --- a/docker-compose.local.yaml +++ b/docker-compose.local.yaml @@ -1,9 +1,7 @@ name: mtusi-messenger-lab4 +# Built once by the api service; migrate and s3-init consume the same image. x-app: &app - build: - context: . - dockerfile: Dockerfile image: mtusi-messenger:lab4 services: @@ -46,6 +44,45 @@ services: retries: 10 start_period: 3s restart: unless-stopped + seaweedfs: + image: chrislusf/seaweedfs:3.80@sha256:1055999e08eed1789b0ae45d235126e4495e23d3fb9d6396293fd42539b1ae6a + command: + - server + - -s3 + - -s3.config=/etc/seaweedfs/s3.json + - -dir=/data + - -master.volumeSizeLimitMB=64 + volumes: + - ./infra/s3/s3.json:/etc/seaweedfs/s3.json:ro + - seaweedfs-data:/data + ports: + - "127.0.0.1:${S3_PORT:-8333}:8333" + healthcheck: + test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8333/healthz || exit 1"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 60s + restart: unless-stopped + + s3-init: + <<: *app + entrypoint: ["/usr/local/bin/s3init"] + environment: + S3_ENDPOINT: http://seaweedfs:8333 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ADMIN_ACCESS_KEY: ${S3_ADMIN_ACCESS_KEY:-lab4admin} + S3_ADMIN_SECRET_ACCESS_KEY: ${S3_ADMIN_SECRET_ACCESS_KEY:-lab4admin-secret} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-lab4app} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-lab4app-secret} + depends_on: + seaweedfs: + condition: service_healthy + healthcheck: + disable: true + restart: "no" + migrate: <<: *app entrypoint: ["/usr/local/bin/migrate"] @@ -65,6 +102,9 @@ services: api: <<: *app + build: + context: . + dockerfile: Dockerfile env_file: - path: .env required: false @@ -80,6 +120,15 @@ services: REDIS_HOST: redis REDIS_PORT: "6379" CACHE_ENABLED: "${CACHE_ENABLED:-true}" + S3_ENDPOINT: http://seaweedfs:8333 + S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://127.0.0.1:8333} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-lab4app} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-lab4app-secret} + S3_USE_PATH_STYLE: "true" + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} ports: - "127.0.0.1:${SERVER_PORT:-8080}:8080" depends_on: @@ -89,6 +138,8 @@ services: condition: service_healthy migrate: condition: service_completed_successfully + s3-init: + condition: service_completed_successfully healthcheck: test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"] interval: 10s @@ -102,3 +153,5 @@ volumes: name: mtusi-messenger-lab4-postgres18-data redis7-data: name: mtusi-messenger-lab4-redis7-data + seaweedfs-data: + name: mtusi-messenger-lab4-seaweedfs-data diff --git a/evidence/lab4/README.md b/evidence/lab4/README.md index e61060ba..d83321e6 100644 --- a/evidence/lab4/README.md +++ b/evidence/lab4/README.md @@ -14,7 +14,7 @@ with SeaweedFS 3.80, two API replicas and HAProxy. | `s3-init.txt` | Idempotent bucket bootstrap, app/forbidden prefix probes | `docker compose run --rm s3-init` (twice) | | `private-bucket.txt` | Anonymous S3 GET and published ports | `docker compose exec seaweedfs wget ...` | | `s3-outage.txt` | S3 down: attachments 503, other endpoints 200 | `docker compose stop seaweedfs` | -| `sweep.txt` | Abandoned presign cleanup after grace; ready survives | `S3_SWEEP_GRACE=2s S3_SWEEP_INTERVAL=1s` | +| `sweep.txt` | Abandoned presign cleanup after grace; ready survives | `S3_SWEEP_GRACE=2s S3_SWEEP_INTERVAL=1s S3_PRESIGN_TTL=1s` | | `memory/` | 10 concurrent 9.4 MiB uploads, cgroup memory samples | `python3 scripts/lab4_memory_experiment.py` | | `track1/` | Proxy vs presigned upload: traffic, latency, memory | `python3 scripts/lab4_track1.py` | @@ -26,3 +26,5 @@ Notes: the primary RAM metric. - Presigned completion re-reads the object once to verify SHA-256, so API RX stays close to the file size. The client-facing LB leg is the actual saving. +- Presigned URLs sign `Content-Length`: an oversized PUT is rejected by S3 with 403 + before anything is stored. diff --git a/evidence/lab4/failover.txt b/evidence/lab4/failover.txt index 49a38b21..0ff58fe4 100644 --- a/evidence/lab4/failover.txt +++ b/evidence/lab4/failover.txt @@ -1 +1 @@ -PASS: lab4 attachment failover; served by cbc4cbeea6da +PASS: lab4 attachment failover; served by 7fd3e5df907d diff --git a/evidence/lab4/memory/samples.csv b/evidence/lab4/memory/samples.csv index 3fd1bf51..ed28341b 100644 --- a/evidence/lab4/memory/samples.csv +++ b/evidence/lab4/memory/samples.csv @@ -1,5 +1,7 @@ elapsed,phase,anon,current -0.367,during,281419776,386904064 -1.063,during,281698304,384315392 -1.689,during,281784320,369328128 -2.139,during,281849856,290664448 +0.378,during,281362432,400949248 +0.804,during,281423872,381423616 +1.395,during,281542656,403361792 +1.827,during,281542656,371871744 +2.376,during,281632768,411824128 +2.81,during,281653248,381726720 diff --git a/evidence/lab4/memory/summary.txt b/evidence/lab4/memory/summary.txt index c28beb4b..5a33ddaa 100644 --- a/evidence/lab4/memory/summary.txt +++ b/evidence/lab4/memory/summary.txt @@ -3,9 +3,9 @@ concurrency: 10 file_size_bytes: 9454448 uploads: 30 rounds: 3 -elapsed_seconds: 2.097 -baseline_anon_bytes: 279879680 -peak_anon_bytes: 281849856 -anon_delta_bytes: 1970176 -peak_memory_current_bytes: 386904064 +elapsed_seconds: 2.980 +baseline_anon_bytes: 280317952 +peak_anon_bytes: 281653248 +anon_delta_bytes: 1335296 +peak_memory_current_bytes: 411824128 note: memory.current includes page cache from temporary spool files; anon is the primary metric diff --git a/evidence/lab4/s3-init.txt b/evidence/lab4/s3-init.txt index a6733f22..f5d16ef9 100644 --- a/evidence/lab4/s3-init.txt +++ b/evidence/lab4/s3-init.txt @@ -2,13 +2,13 @@ Container mtusi-messenger-lab4-seaweedfs-1 Running Container mtusi-messenger-lab4-seaweedfs-1 Waiting Container mtusi-messenger-lab4-seaweedfs-1 Healthy - Container mtusi-messenger-lab4-s3-init-run-6d633e58a067 Creating - Container mtusi-messenger-lab4-s3-init-run-6d633e58a067 Created -{"time":"2026-10-21T19:37:16.099886123Z","level":"INFO","msg":"s3 bucket ready","endpoint":"http://seaweedfs:8333","bucket":"messenger-attachments"} + Container mtusi-messenger-lab4-s3-init-run-77217672cba1 Creating + Container mtusi-messenger-lab4-s3-init-run-77217672cba1 Created +{"time":"2026-10-21T20:24:44.714991263Z","level":"INFO","msg":"s3 bucket ready","endpoint":"http://seaweedfs:8333","bucket":"messenger-attachments"} === run 2 (idempotent) === Container mtusi-messenger-lab4-seaweedfs-1 Running Container mtusi-messenger-lab4-seaweedfs-1 Waiting Container mtusi-messenger-lab4-seaweedfs-1 Healthy - Container mtusi-messenger-lab4-s3-init-run-a60a52baaf22 Creating - Container mtusi-messenger-lab4-s3-init-run-a60a52baaf22 Created -{"time":"2026-10-21T19:37:16.941920617Z","level":"INFO","msg":"s3 bucket ready","endpoint":"http://seaweedfs:8333","bucket":"messenger-attachments"} + Container mtusi-messenger-lab4-s3-init-run-33ccde88f9aa Creating + Container mtusi-messenger-lab4-s3-init-run-33ccde88f9aa Created +{"time":"2026-10-21T20:24:45.578062247Z","level":"INFO","msg":"s3 bucket ready","endpoint":"http://seaweedfs:8333","bucket":"messenger-attachments"} diff --git a/evidence/lab4/s3-outage.txt b/evidence/lab4/s3-outage.txt index 00c7375c..65268216 100644 --- a/evidence/lab4/s3-outage.txt +++ b/evidence/lab4/s3-outage.txt @@ -1,8 +1,8 @@ -created attachment before outage: 01a15ff7-e2fe-7a6c-b896-c61c3451a6c5 +created attachment before outage: 01a1601e-9947-753c-8085-65db29e8a909 seaweedfs stopped health/ready during outage: {'status': 'ok'} chat list during outage: 200 download during outage: 503 upload during outage: 503 seaweedfs restarted -upload after recovery: ready 01a15ff8-6610-7628-a06a-26e590c6186b +upload after recovery: ready 01a1601f-1c45-793b-bb59-281781ea8482 diff --git a/evidence/lab4/sweep.txt b/evidence/lab4/sweep.txt index d32a472c..a5f8fe32 100644 --- a/evidence/lab4/sweep.txt +++ b/evidence/lab4/sweep.txt @@ -1,5 +1,4 @@ -ready attachment created: 01a15ff8-9634-77d1-b7e2-cd5831a19d49 -abandoned presign attachment: 01a15ff8-9639-7e03-a71c-2971e9425972 (no PUT) +ready attachment created: 01a16022-78dc-7349-b3da-2937b2faf1f0 +abandoned presign attachment: 01a16022-78e3-733f-861b-0443011dcfc8 (no PUT) abandoned pending row removed after grace ready attachment survived sweep: ready 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75 -sweeper settings restored (10m/1m) diff --git a/evidence/lab4/track1/results.csv b/evidence/lab4/track1/results.csv index e4142b9c..850470a6 100644 --- a/evidence/lab4/track1/results.csv +++ b/evidence/lab4/track1/results.csv @@ -1,21 +1,21 @@ size,bytes,flow,iteration,latency_s,lb_rx_bytes,lb_tx_bytes,api_rx_bytes,api_tx_bytes,api_anon_peak -~1MiB,1050888,proxy,0,0.2246,1059079,1059227,1059155,1060779,282734592 -~1MiB,1050888,proxy,1,0.2436,1057539,1058793,1058440,1058956,282742784 -~1MiB,1050888,proxy,2,0.2276,1058111,1058605,1059413,1060497,282763264 -~1MiB,1050888,proxy,3,0.2225,1056087,1058199,1058375,1058314,282767360 -~1MiB,1050888,proxy,4,0.2267,1057825,1059425,1058752,1059718,282771456 -~1MiB,1050888,presign,0,0.2196,3464,3596,1058037,9166,282787840 -~1MiB,1050888,presign,1,0.2249,3465,3729,1057424,9073,282836992 -~1MiB,1050888,presign,2,0.2171,4015,3833,1058301,8969,282849280 -~1MiB,1050888,presign,3,0.2276,3465,3597,1057489,8774,282865664 -~1MiB,1050888,presign,4,0.2327,4631,4333,1057989,9060,282877952 -~9MiB,9454448,proxy,0,0.2375,9490073,9512447,9506779,9489274,282886144 -~9MiB,9454448,proxy,1,0.2365,9488841,9503073,9493951,9486796,282882048 -~9MiB,9454448,proxy,2,0.2353,9489017,9505121,9505811,9490554,282890240 -~9MiB,9454448,proxy,3,0.2282,9491723,9501595,9500701,9493150,282906624 -~9MiB,9454448,proxy,4,0.229,9493835,9509411,9500971,9489868,282918912 -~9MiB,9454448,presign,0,0.2359,3465,3663,9473260,11216,282935296 -~9MiB,9454448,presign,1,0.235,4014,3832,9473694,11664,282968064 -~9MiB,9454448,presign,2,0.2391,3465,3795,9473579,13975,283009024 -~9MiB,9454448,presign,3,0.2504,4564,4068,9473083,14572,283045888 -~9MiB,9454448,presign,4,0.2353,3465,3597,9473381,12391,283054080 +~1MiB,1050888,proxy,0,0.2291,1058727,1075375,1074306,1059556,284934144 +~1MiB,1050888,proxy,1,0.2253,1058659,1058991,1060120,1061998,285270016 +~1MiB,1050888,proxy,2,0.2328,1058925,1059123,1058798,1059912,285433856 +~1MiB,1050888,proxy,3,0.227,1058485,1058633,1058297,1059591,285433856 +~1MiB,1050888,proxy,4,0.2284,1057165,1057115,1057126,1058104,285638656 +~1MiB,1050888,presign,0,0.2249,4098,3850,1058691,10486,285917184 +~1MiB,1050888,presign,1,0.2262,4163,3981,1058060,9274,286142464 +~1MiB,1050888,presign,2,0.2356,3548,3680,1057677,9240,286138368 +~1MiB,1050888,presign,3,0.2297,3482,3614,1058397,10146,286183424 +~1MiB,1050888,presign,4,0.2388,3482,3680,1057479,8382,286216192 +~9MiB,9454448,proxy,0,0.2374,9491811,9511561,9503858,9488878,286212096 +~9MiB,9454448,proxy,1,0.2397,9498015,9511259,9498331,9490528,286228480 +~9MiB,9454448,proxy,2,0.2247,9492207,9511759,9493573,9486286,286261248 +~9MiB,9454448,proxy,3,0.2273,9486399,9496645,9483662,9481323,286285824 +~9MiB,9454448,proxy,4,0.237,9483275,9494891,9493892,9482709,286285824 +~9MiB,9454448,presign,0,0.2431,4098,3916,9473045,12060,286306304 +~9MiB,9454448,presign,1,0.246,3552,3680,9472208,9451,286318592 +~9MiB,9454448,presign,2,0.2347,4164,3982,9473447,11088,286326784 +~9MiB,9454448,presign,3,0.2346,3482,3614,9471731,9174,286343168 +~9MiB,9454448,presign,4,0.2389,4098,3916,9473771,14040,286367744 diff --git a/evidence/lab4/track1/summary.txt b/evidence/lab4/track1/summary.txt index 8fbe269e..0ee049d8 100644 --- a/evidence/lab4/track1/summary.txt +++ b/evidence/lab4/track1/summary.txt @@ -2,10 +2,10 @@ Lab4 track 1: proxy vs presigned upload | size | flow | median latency, s | p95 latency, s | LB rx, bytes | API rx, bytes | API anon peak, bytes | |---|---|---:|---:|---:|---:|---:| -| ~1MiB | proxy | 0.227 | 0.244 | 1057728 | 1058827 | 282771456 | -| ~1MiB | presign | 0.225 | 0.233 | 3808 | 1057848 | 282877952 | -| ~9MiB | proxy | 0.235 | 0.237 | 9490698 | 9501643 | 282918912 | -| ~9MiB | presign | 0.236 | 0.250 | 3795 | 9473399 | 283054080 | +| ~1MiB | proxy | 0.228 | 0.233 | 1058392 | 1061729 | 285638656 | +| ~1MiB | presign | 0.230 | 0.239 | 3755 | 1058061 | 286216192 | +| ~9MiB | proxy | 0.237 | 0.240 | 9490341 | 9494663 | 286285824 | +| ~9MiB | presign | 0.239 | 0.246 | 3879 | 9472840 | 286367744 | Note: presigned upload keeps the file body off the API request path and off the load balancer. Completion still streams the object from S3 once to verify its SHA-256, so api_rx stays close to diff --git a/infra/lb/haproxy.cfg b/infra/lb/haproxy.cfg index 4521326e..597f09dd 100644 --- a/infra/lb/haproxy.cfg +++ b/infra/lb/haproxy.cfg @@ -21,11 +21,16 @@ defaults option httplog option dontlognull timeout connect 1s - timeout client 30s - timeout server 5s + timeout client 70s + timeout server 45s # Проверка готовности: одна проба не может висеть дольше 1 с, поэтому при # inter 2s fall 2 реплика уходит из ротации максимум за ~4 с, даже если она # держит соединение открытым и не отвечает. + # + # timeout server увеличен для 10 MiB загрузок: spool + S3 Put не всегда + # укладываются в прежние 5 с под конкурентной нагрузкой. Readiness-проба + # остаётся с timeout check 1s, поэтому обнаружение мёртвой реплики не + # замедляется. timeout check 1s retry-on conn-failure retries 2 diff --git a/infra/s3/README.md b/infra/s3/README.md index c6c36598..bf9216c4 100644 --- a/infra/s3/README.md +++ b/infra/s3/README.md @@ -4,7 +4,9 @@ the single source of truth for S3 credentials and permissions. - `admin` is used only by the one-shot `s3-init` service (bucket creation and - probing). It is never given to the API. + probing). It is never given to the API and must not be placed in `.env`: + the API service loads `.env` as an environment file. Compose supplies the + synthetic admin values to `s3-init` directly. - `app` is used by the API and by presigned uploads. It can read/write only `messenger-attachments/attachments/*` and `messenger-attachments/staging/*`, and list the bucket for the orphan sweeper. diff --git a/internal/config/config.go b/internal/config/config.go index 7b18ec54..addb8c10 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -54,7 +54,7 @@ type S3 struct { MaxUploadBytes int64 `mapstructure:"max_upload_bytes" validate:"required,gt=0,lte=10485760"` MaxImagePixels int64 `mapstructure:"max_image_pixels" validate:"required,gt=0,lte=40000000"` - PresignTTL time.Duration `mapstructure:"presign_ttl" validate:"required,gt=0"` + PresignTTL time.Duration `mapstructure:"presign_ttl" validate:"required,gt=0,lte=168h"` SweepInterval time.Duration `mapstructure:"sweep_interval" validate:"required,gt=0"` SweepGrace time.Duration `mapstructure:"sweep_grace" validate:"required,gt=0"` } @@ -229,6 +229,10 @@ func (c Config) validateDependencies() error { return errors.New("validate config: cache.enabled requires redis.enabled") } + if c.S3.SweepGrace <= c.S3.PresignTTL { + return errors.New("validate config: s3.sweep_grace must exceed s3.presign_ttl") + } + return nil } diff --git a/internal/platform/objectstore/objectstore.go b/internal/platform/objectstore/objectstore.go index a45f9b81..8d5aa62c 100644 --- a/internal/platform/objectstore/objectstore.go +++ b/internal/platform/objectstore/objectstore.go @@ -28,5 +28,5 @@ type Store interface { Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error Delete(ctx context.Context, key string) error List(ctx context.Context, prefix string) ([]Object, error) - PresignPut(ctx context.Context, key string, ttl time.Duration) (string, time.Time, error) + PresignPut(ctx context.Context, key string, size int64, ttl time.Duration) (string, time.Time, error) } diff --git a/internal/platform/objectstore/s3.go b/internal/platform/objectstore/s3.go index 6b288180..ff708c66 100644 --- a/internal/platform/objectstore/s3.go +++ b/internal/platform/objectstore/s3.go @@ -229,13 +229,15 @@ func (s *S3) List(ctx context.Context, prefix string) ([]Object, error) { return objects, nil } -// PresignPut signs only the bucket, key and host. Deliberately no Content-Type -// or checksum: adding them to the signed headers forces every client to send -// exactly those headers, and SeaweedFS does not validate checksums anyway. -// Completion verifies the actual bytes instead. +// PresignPut signs the bucket, key, host and exact Content-Length. The size is +// therefore enforced by S3 at write time: a client that uploads a different +// number of bytes gets 403 SignatureDoesNotMatch. Content-Type and checksums +// are not signed (SeaweedFS does not validate checksums); completion verifies +// the actual bytes and their structure. func (s *S3) PresignPut( ctx context.Context, key string, + size int64, ttl time.Duration, ) (string, time.Time, error) { expiresAt := time.Now().UTC().Add(ttl) @@ -243,8 +245,9 @@ func (s *S3) PresignPut( presigned, err := s3.NewPresignClient(s.public).PresignPutObject( ctx, &s3.PutObjectInput{ - Bucket: aws.String(s.bucket), - Key: aws.String(key), + Bucket: aws.String(s.bucket), + Key: aws.String(key), + ContentLength: aws.Int64(size), }, func(options *s3.PresignOptions) { options.Expires = ttl @@ -270,7 +273,9 @@ func mapObjectError(operation, subject string, err error) error { if errors.As(err, &apiErr) { switch apiErr.ErrorCode() { - case "NotFound", "NoSuchKey", "NoSuchBucket": + case "NoSuchBucket": + return fmt.Errorf("%w: %s %q: %w", domain.ErrUnavailable, operation, subject, err) + case "NotFound", "NoSuchKey": return fmt.Errorf("%s %q: %w", operation, subject, domain.ErrNotFound) } } diff --git a/internal/platform/objectstore/s3_test.go b/internal/platform/objectstore/s3_test.go new file mode 100644 index 00000000..3383a26b --- /dev/null +++ b/internal/platform/objectstore/s3_test.go @@ -0,0 +1,26 @@ +package objectstore + +import ( + "testing" + + "github.com/aws/smithy-go" + "github.com/stretchr/testify/require" + + "mtusi-messenger/internal/domain" +) + +func TestMapObjectErrorBucketIsUnavailable(t *testing.T) { + err := mapObjectError("put object", "key", &smithy.GenericAPIError{ + Code: "NoSuchBucket", + Message: "bucket is missing", + }) + require.ErrorIs(t, err, domain.ErrUnavailable) +} + +func TestMapObjectErrorMissingKeyIsNotFound(t *testing.T) { + err := mapObjectError("open object", "key", &smithy.GenericAPIError{ + Code: "NoSuchKey", + Message: "object is missing", + }) + require.ErrorIs(t, err, domain.ErrNotFound) +} diff --git a/internal/service/attachment/service.go b/internal/service/attachment/service.go index aadf3c17..fd25c682 100644 --- a/internal/service/attachment/service.go +++ b/internal/service/attachment/service.go @@ -207,7 +207,11 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d return domain.PresignResult{}, fmt.Errorf("%w: content type %q", domain.ErrUnsupportedMedia, request.ContentType) } - if request.SizeBytes < 1 || request.SizeBytes > s.config.MaxUploadBytes { + if request.SizeBytes < 1 { + return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrValidation, request.SizeBytes) + } + + if request.SizeBytes > s.config.MaxUploadBytes { return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrTooLarge, request.SizeBytes) } @@ -244,7 +248,7 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d return domain.PresignResult{}, err } - url, expiresAt, err := s.store.PresignPut(ctx, stagingKey, s.config.PresignTTL) + url, expiresAt, err := s.store.PresignPut(ctx, stagingKey, request.SizeBytes, s.config.PresignTTL) if err != nil { s.cleanupPending(ctx, id, "") @@ -346,8 +350,8 @@ func (s *Service) Complete( } if requestSHA != attachment.SHA256 { - s.cleanupPending(ctx, id, attachment.ObjectKey) - + // The object is valid; only the completion request is inconsistent. + // Keep the pending row and staging object so a retry can succeed. return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict) } @@ -454,6 +458,10 @@ func ValidateFilename(name string) error { return fmt.Errorf("%w: filename length is %d, want 1-255 code points", domain.ErrValidation, length) } + if strings.TrimSpace(name) == "" { + return fmt.Errorf("%w: filename consists of whitespace only", domain.ErrValidation) + } + if strings.ContainsAny(name, "/\\\x00") { return fmt.Errorf("%w: filename contains a path separator or NUL", domain.ErrValidation) } diff --git a/internal/service/attachment/service_test.go b/internal/service/attachment/service_test.go index 22f917c1..1e9839b9 100644 --- a/internal/service/attachment/service_test.go +++ b/internal/service/attachment/service_test.go @@ -112,7 +112,7 @@ func (f *fakeStore) List(_ context.Context, prefix string) ([]objectstore.Object return objects, nil } -func (f *fakeStore) PresignPut(_ context.Context, key string, ttl time.Duration) (string, time.Time, error) { +func (f *fakeStore) PresignPut(_ context.Context, key string, _ int64, ttl time.Duration) (string, time.Time, error) { return "http://s3.example/" + key, time.Now().UTC().Add(ttl), nil } @@ -156,7 +156,7 @@ func TestValidateFilename(t *testing.T) { require.NoError(t, attachment.ValidateFilename(name), name) } - invalid := []string{"", strings.Repeat("x", 256), "a/b.png", `a\b.png`, "a\x00b.png", "a\nb.png"} + invalid := []string{"", " ", "\t\n", strings.Repeat("x", 256), "a/b.png", `a\b.png`, "a\x00b.png", "a\nb.png"} for _, name := range invalid { require.ErrorIs(t, attachment.ValidateFilename(name), domain.ErrValidation, name) } @@ -316,3 +316,46 @@ func TestCompleteRejectsChecksumMismatch(t *testing.T) { require.ErrorIs(t, err, domain.ErrValidation) require.NotContains(t, store.objects, stagingKey) } + +func TestCompleteKeepsObjectOnWrongRequestChecksum(t *testing.T) { + repo := mocks.NewMockRepository(t) + store := newFakeStore() + service := attachment.NewService(repo, store, serviceConfig(), slog.Default()) + + id := uuid.New() + chatID := uuid.New() + ownerID := uuid.New() + content := pngBytes(t, 10, 10) + sum := sha256.Sum256(content) + digest := hex.EncodeToString(sum[:]) + stagingKey := "staging/presign/" + chatID.String() + "/" + id.String() + + store.objects[stagingKey] = storedObject{ + data: content, + contentType: "image/png", + metadata: map[string]string{"sha256": digest}, + } + pending := domain.Attachment{ + ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey, + ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest, + Status: domain.AttachmentPending, + } + + repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once() + + _, err := service.Complete(t.Context(), ownerID, id, strings.Repeat("0", 64)) + require.ErrorIs(t, err, domain.ErrConflict) + require.Contains(t, store.objects, stagingKey) +} + +func TestPresignRejectsNonPositiveSize(t *testing.T) { + repo := mocks.NewMockRepository(t) + service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default()) + + _, err := service.Presign(t.Context(), domain.PresignRequest{ + ChatID: uuid.New(), OwnerID: uuid.New(), + Filename: "photo.png", ContentType: "image/png", + SizeBytes: 0, SHA256: strings.Repeat("a", 64), + }) + require.ErrorIs(t, err, domain.ErrValidation) +} diff --git a/internal/service/attachment/sweeper.go b/internal/service/attachment/sweeper.go index cc12552d..36eec1d6 100644 --- a/internal/service/attachment/sweeper.go +++ b/internal/service/attachment/sweeper.go @@ -151,10 +151,18 @@ func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) { } if head.Size == row.SizeBytes && head.Metadata["sha256"] == row.SHA256 { - if _, err := s.repo.MarkReady(ctx, row.ID, row.ObjectKey); err == nil { - stats.Recovered++ + if _, err := s.repo.MarkReady(ctx, row.ID, row.ObjectKey); err != nil { + // A transient database failure must not destroy a valid object. + // Leave both the row and the object for the next sweep. + s.log.WarnContext(ctx, "sweep recovery failed", + slog.String("attachment_id", row.ID.String()), + slog.Any("error", err), + ) continue } + + stats.Recovered++ + continue } if s.deleteObject(ctx, row.ObjectKey) { diff --git a/internal/service/attachment/sweeper_test.go b/internal/service/attachment/sweeper_test.go index 6c19cdd2..8952b00e 100644 --- a/internal/service/attachment/sweeper_test.go +++ b/internal/service/attachment/sweeper_test.go @@ -1,6 +1,7 @@ package attachment_test import ( + "context" "log/slog" "testing" "time" @@ -88,3 +89,38 @@ func TestSweepSkipsWhenAnotherReplicaHoldsTheLock(t *testing.T) { require.NoError(t, err) require.Zero(t, stats) } + +func TestSweepKeepsObjectWhenMarkReadyFails(t *testing.T) { + repo := mocks.NewMockRepository(t) + locker := mocks.NewMockLockStore(t) + store := newFakeStore() + + stale := time.Now().UTC().Add(-time.Hour) + row := domain.Attachment{ + ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(), + SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + Status: domain.AttachmentPending, CreatedAt: stale, + } + + store.objects[row.ObjectKey] = storedObject{ + data: []byte("abc"), + lastModified: stale, + metadata: map[string]string{"sha256": row.SHA256}, + } + + repo.EXPECT().ListStalePending(mock.Anything, mock.Anything, int32(100)). + Return([]domain.Attachment{row}, nil).Once() + repo.EXPECT().MarkReady(mock.Anything, row.ID, row.ObjectKey). + Return(domain.Attachment{}, context.DeadlineExceeded).Once() + repo.EXPECT().ListKeys(mock.Anything, int32(1000), int32(0)). + Return([]domain.AttachmentKey{{ID: row.ID, ObjectKey: row.ObjectKey, Status: domain.AttachmentPending}}, nil).Once() + locker.EXPECT().AcquireSweepLock(mock.Anything).Return(func() {}, true, nil).Once() + + sweeper := attachment.NewSweeper(repo, store, locker, time.Minute, time.Hour, slog.Default()) + + stats, err := sweeper.SweepOnce(t.Context()) + require.NoError(t, err) + require.Zero(t, stats.Recovered) + require.Zero(t, stats.RowsDeleted) + require.Contains(t, store.objects, row.ObjectKey) +} diff --git a/internal/transport/rest/extensions.go b/internal/transport/rest/extensions.go index 5a08b789..5ff6b7d7 100644 --- a/internal/transport/rest/extensions.go +++ b/internal/transport/rest/extensions.go @@ -105,7 +105,9 @@ func (e *Extensions) authenticate(r *http.Request) (uuid.UUID, error) { user, err := e.sessions.Resolve(r.Context(), token) if err != nil { - return uuid.Nil, fmt.Errorf("%w: %w", domain.ErrUnauthenticated, err) + // session.Resolve already distinguishes an invalid session (401) from a + // database outage (503); do not collapse both into 401 here. + return uuid.Nil, err } return user.ID, nil diff --git a/internal/transport/rest/extensions_test.go b/internal/transport/rest/extensions_test.go new file mode 100644 index 00000000..1e5e1564 --- /dev/null +++ b/internal/transport/rest/extensions_test.go @@ -0,0 +1,64 @@ +package rest + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" + + "mtusi-messenger/internal/domain" +) + +type resolverFunc func(ctx context.Context, token string) (domain.User, error) + +func (f resolverFunc) Resolve(ctx context.Context, token string) (domain.User, error) { + return f(ctx, token) +} + +func TestExtensionPreservesDependencyErrors(t *testing.T) { + extensions := NewExtensions(nil, resolverFunc(func(context.Context, string) (domain.User, error) { + return domain.User{}, domain.ErrUnavailable + }), nil) + + request := httptest.NewRequestWithContext( + t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil, + ) + request.Header.Set("Authorization", "Bearer token") + recorder := httptest.NewRecorder() + + extensions.Presign().ServeHTTP(recorder, request) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code) +} + +func TestExtensionInvalidSessionIsUnauthorized(t *testing.T) { + extensions := NewExtensions(nil, resolverFunc(func(context.Context, string) (domain.User, error) { + return domain.User{}, domain.ErrUnauthenticated + }), nil) + + request := httptest.NewRequestWithContext( + t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil, + ) + request.Header.Set("Authorization", "Bearer token") + recorder := httptest.NewRecorder() + + extensions.Presign().ServeHTTP(recorder, request) + + require.Equal(t, http.StatusUnauthorized, recorder.Code) +} + +func TestExtensionWrongMethodIsNotAllowed(t *testing.T) { + extensions := NewExtensions(nil, nil, nil) + + request := httptest.NewRequestWithContext( + t.Context(), http.MethodGet, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil, + ) + recorder := httptest.NewRecorder() + + extensions.Presign().ServeHTTP(recorder, request) + + require.Equal(t, http.StatusMethodNotAllowed, recorder.Code) + require.Equal(t, http.MethodPost, recorder.Header().Get("Allow")) +} diff --git a/internal/transport/rest/handler.go b/internal/transport/rest/handler.go index a6493bf5..705d3d73 100644 --- a/internal/transport/rest/handler.go +++ b/internal/transport/rest/handler.go @@ -9,7 +9,6 @@ import ( "fmt" "io" "net/http" - "slices" "time" "github.com/google/uuid" @@ -271,15 +270,15 @@ func (h *Handler) CreateMessage( }, nil } -// messageFingerprint canonicalises the create-message payload so that the key -// order of the client JSON cannot change the fingerprint, while a different -// payload with the same Idempotency-Key can (contract 1.3.0). +// messageFingerprint canonicalises the create-message payload so that JSON key +// order cannot change the fingerprint, while a different payload (including a +// different attachment order) with the same Idempotency-Key can. Absent +// attachment_ids and [] are equivalent, as required by the contract. func messageFingerprint(req *oas.CreateMessage) ([sha256.Size]byte, error) { - ids := make([]uuid.UUID, 0, len(req.AttachmentIds)) - ids = append(ids, req.AttachmentIds...) - slices.SortFunc(ids, func(left, right uuid.UUID) int { - return bytes.Compare(left[:], right[:]) - }) + ids := req.AttachmentIds + if ids == nil { + ids = []uuid.UUID{} + } payload, err := json.Marshal(struct { Text string `json:"text"` diff --git a/internal/transport/rest/handler_test.go b/internal/transport/rest/handler_test.go new file mode 100644 index 00000000..09279a5e --- /dev/null +++ b/internal/transport/rest/handler_test.go @@ -0,0 +1,39 @@ +package rest + +import ( + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/require" + + "mtusi-messenger/internal/transport/rest/internal/oas" +) + +func TestMessageFingerprintPreservesAttachmentOrder(t *testing.T) { + first, second := uuid.New(), uuid.New() + + forward, err := messageFingerprint(&oas.CreateMessage{ + Text: "x", + AttachmentIds: []uuid.UUID{first, second}, + }) + require.NoError(t, err) + + reverse, err := messageFingerprint(&oas.CreateMessage{ + Text: "x", + AttachmentIds: []uuid.UUID{second, first}, + }) + require.NoError(t, err) + + require.NotEqual(t, forward, reverse, + "reordered attachment_ids are a different payload and must not replay") +} + +func TestMessageFingerprintTreatsAbsentAndEmptyAsEqual(t *testing.T) { + absent, err := messageFingerprint(&oas.CreateMessage{Text: "x"}) + require.NoError(t, err) + + empty, err := messageFingerprint(&oas.CreateMessage{Text: "x", AttachmentIds: []uuid.UUID{}}) + require.NoError(t, err) + + require.Equal(t, absent, empty) +} diff --git a/scripts/check_s3_creds.py b/scripts/check_s3_creds.py index a1e78d98..68b083d5 100755 --- a/scripts/check_s3_creds.py +++ b/scripts/check_s3_creds.py @@ -36,7 +36,6 @@ def main() -> int: env = parse_env(source) expected = { - "admin": ("S3_ADMIN_ACCESS_KEY", "S3_ADMIN_SECRET_ACCESS_KEY"), "app": ("S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"), } @@ -63,7 +62,11 @@ def main() -> int: print(" -", failure) return 1 - print(f"PASS: S3 identities match {source.name} (admin + app)") + if "admin" not in by_name: + print("FAIL: infra/s3/s3.json has no admin identity for s3-init") + return 1 + + print(f"PASS: S3 app identity matches {source.name}; admin stays in s3.json/s3-init") return 0 diff --git a/student-tests/presign_flow.py b/student-tests/presign_flow.py index 8713fde5..e79eca37 100755 --- a/student-tests/presign_flow.py +++ b/student-tests/presign_flow.py @@ -69,6 +69,7 @@ def main(): # Happy path: direct PUT, completion, message, download. presigned = presign(client, alice, chat, content) check(presigned['method'] == 'PUT', 'presign method must be PUT') + check('content-length' in presigned['upload_url'], 'content-length must be signed into the URL') check(put(presigned['upload_url'], content) == 200, 'direct PUT failed') attachment = complete(client, alice, presigned['attachment_id'], digest)['json'] check(attachment['sha256'] == digest and attachment['size_bytes'] == len(content), 'completed metadata mismatch') @@ -94,14 +95,18 @@ def main(): check(put(mismatch['upload_url'], content) == 200, 'direct PUT failed') complete(client, alice, mismatch['attachment_id'], '0' * 64, expected=409) - # Declared size is enforced at completion, after the direct PUT. + # Content-Length is signed, so S3 rejects a different number of bytes at + # write time instead of storing an oversized staging object. oversized = presign(client, alice, chat, content) - check(put(oversized['upload_url'], content + b'x') == 200, 'direct PUT failed') - complete(client, alice, oversized['attachment_id'], digest, expected=400) + check(put(oversized['upload_url'], content + b'x') == 403, 'oversized PUT must be rejected by S3') + complete(client, alice, oversized['attachment_id'], digest, expected=409) # Last PUT wins before completion; the declared checksum must describe it. + # The replacement is the same length because Content-Length is signed. overwrite = presign(client, alice, chat, content) - check(put(overwrite['upload_url'], b'not an image') == 200, 'first PUT failed') + corrupt = bytearray(content) + corrupt[0] ^= 0xFF + check(put(overwrite['upload_url'], bytes(corrupt)) == 200, 'first PUT failed') check(put(overwrite['upload_url'], content) == 200, 'second PUT failed') overwritten = complete(client, alice, overwrite['attachment_id'], digest)['json'] check(overwritten['sha256'] == digest, 'last PUT was not the completed object')