From b4834572a7c471c72d1978eea618c4fc048fd1f8 Mon Sep 17 00:00:00 2001 From: Mraksimus Date: Thu, 5 Nov 2026 17:49:35 +0300 Subject: [PATCH] Completed for a grade of four --- .env.example | 4 +- REPORT.md | 53 +++++-- compose.yaml | 21 ++- evidence/attachment-failover.txt | 4 +- evidence/attachment-interrupt.txt | 1 + evidence/attachment-load.json | 131 ++++++++++++++++++ evidence/gradle-tests.txt | 13 +- evidence/persistence.txt | 24 ++-- evidence/s3-permissions.txt | 10 ++ infra/s3/bootstrap.sh | 14 ++ run/_template/config/storage.conf | 4 +- scripts/attachment-interrupt.py | 39 ++++++ scripts/attachment-load.py | 84 +++++++++++ scripts/check-s3-permissions.sh | 21 +++ scripts/init-secrets.sh | 2 +- .../kotlin/com/mtusi/messenger/main/App.kt | 2 + .../attachment/AttachmentController.kt | 49 ++++--- .../models/attachment/UploadJournalModel.kt | 18 +++ .../ExposedUploadJournalRepository.kt | 77 ++++++++++ .../attachment/UploadJournalRepository.kt | 13 ++ .../storage/ObjectStorageRepository.kt | 3 +- .../storage/S3ObjectStorageRepository.kt | 9 +- .../attachment/AttachmentCleanupService.kt | 34 +++++ .../services/attachment/AttachmentService.kt | 3 +- .../attachment/DefaultAttachmentService.kt | 24 +++- .../main/plugins/AttachmentCleanup.kt | 29 ++++ .../mtusi/messenger/main/plugins/Database.kt | 2 + .../exposed/operations/InstantPlusSeconds.kt | 25 ++++ .../migrations/V5__attachment_uploads.sql | 7 + .../attachment/AttachmentControllerTest.kt | 7 + .../attachment/AttachmentCleanupTest.kt | 124 +++++++++++++++++ 31 files changed, 785 insertions(+), 66 deletions(-) create mode 100644 evidence/attachment-interrupt.txt create mode 100644 evidence/attachment-load.json create mode 100644 evidence/s3-permissions.txt create mode 100644 scripts/attachment-interrupt.py create mode 100644 scripts/attachment-load.py create mode 100755 scripts/check-s3-permissions.sh create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/attachment/UploadJournalModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/ExposedUploadJournalRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/UploadJournalRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentCleanupService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/AttachmentCleanup.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/InstantPlusSeconds.kt create mode 100644 src/main/resources/migrations/V5__attachment_uploads.sql create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentCleanupTest.kt diff --git a/.env.example b/.env.example index d99d26a..1a29d8a 100644 --- a/.env.example +++ b/.env.example @@ -14,7 +14,7 @@ IDEMPOTENCY_TTL_SECONDS=86400 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_ACCESS_KEY_ID_FILE=/run/secrets/s3_api_access_key_id +S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_api_secret_access_key MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 diff --git a/REPORT.md b/REPORT.md index b86f00d..050eb6f 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,7 +1,7 @@ # Отчёт — лабораторная 4 - Автор, группа: Кучерявенко Максим, БВТ2303 -- Целевая оценка: **3**. Критерии 4/5 не заявлены. +- Целевая оценка: **4**. Уровень 3 сохранён; исследовательский трек 5 не заявлен. - Commit/PR: после просмотра и публикации. - Основа: собственный lab3; структура конфигураций, controllers → services → repositories. Для S3 используется AWS SDK for Kotlin 1.6.41; изображения проверяет JDK ImageIO. ИИ использован как парный разработчик. - Источники: [AWS SDK for Kotlin](https://github.com/awslabs/aws-sdk-kotlin), [релиз MinIO](https://github.com/minio/minio/releases/tag/RELEASE.2025-09-07T16-13-09Z), [ImageReader](https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/imageio/ImageReader.html), [S3 uploads](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html). @@ -34,13 +34,18 @@ docker compose start api # Перезапуск LB, обеих API-реплик, PostgreSQL, Redis и MinIO без удаления volumes. make test-persistence ACTION_SCRIPT=scripts/restart.sh +# Проверки уровня 4: +scripts/check-s3-permissions.sh +python3 scripts/attachment-interrupt.py +python3 scripts/attachment-load.py > evidence/attachment-load.json + # Безопасная остановка, данные сохраняются: docker compose down # Только для намеренного удаления всех учебных данных: # docker compose down -v ``` -Compose собирает общий образ `mtusi-messenger:lab4` через `api`; одноразовый `migrate` использует тот же образ и применяет Flyway V1–V4 до старта реплик. `s3-init` ждёт MinIO, создаёт bucket через `mc mb --ignore-existing` и закрывает анонимный доступ через `mc anonymous set none`. Повторный запуск сохраняет bucket и объекты. Секреты создаются локально, существующие файлы не перезаписываются; `.env`, `secrets/` и `run/development/` не входят в Git. +Compose собирает общий образ `mtusi-messenger:lab4` через `api`; одноразовый `migrate` использует тот же образ и применяет Flyway V1–V5 до старта реплик. `s3-init` ждёт MinIO, создаёт bucket через `mc mb --ignore-existing` и закрывает анонимный доступ через `mc anonymous set none`. Повторный запуск сохраняет bucket и объекты. Секреты создаются локально, существующие файлы не перезаписываются; `.env`, `secrets/` и `run/development/` не входят в Git. MinIO RELEASE.2025-09-07T16-13-09Z и mc RELEASE.2025-08-13T08-35-41Z закреплены digest в Compose. PostgreSQL 17.6, Redis 8.4.0, HAProxy 3.2.4 — из lab3. API использует Kotlin 2.3.20, Ktor 3.3.0, JDK 21. Проверено на macOS arm64 с Docker 28.4.0. MinIO S3 и console не публикуются на host; наружу доступен только LB на loopback. @@ -62,17 +67,17 @@ MinIO RELEASE.2025-09-07T16-13-09Z и mc RELEASE.2025-08-13T08-35-41Z закре `attachments` содержит ID, chat_id, owner_id, отображаемое имя, MIME, размер, SHA-256 и время создания. `message_attachments` хранит порядок вложений сообщения, уникальность и внешние ключи. S3 key — `originals/`; filename никогда не используется как путь. В API нет ключей S3 и credentials. В lab4 все опубликованные метаданные уже ready, updated_at равен created_at, variants=[], error_code=null. -Upload: Bearer-аутентификация → проверка членства → filename/MIME/размер → ограниченное чтение тела → проверка изображения → S3 PUT → INSERT/COMMIT метаданных → 201. Нет долгой DB-транзакции во время HTTP upload или S3 PUT. Оригинальные bytes не перекодируются. Download: аутентификация → доступ через chat_id в PostgreSQL → S3 GET → bytes с истинным MIME через API без redirect. Посторонний и неизвестный ID получают одинаковый 404. +Upload: Bearer-аутентификация → проверка членства → filename/MIME/размер → ограниченное чтение тела → проверка изображения → COMMIT записи журнала → S3 PUT → INSERT метаданных и удаление записи журнала в одной транзакции → 201. Нет долгой DB-транзакции во время HTTP upload или S3 PUT. Оригинальные bytes не перекодируются. Download: аутентификация → доступ через chat_id в PostgreSQL → S3 GET → bytes с истинным MIME через API без redirect. Посторонний и неизвестный ID получают одинаковый 404. Сообщение допускает пустой текст с 1–10 уникальными вложениями этого чата. Член чата может прикрепить загруженный другим участником файл. Создание сообщения, связей и результата Idempotency-Key выполняется в одной транзакции. Отсутствующий attachment_ids и [] равнозначны; повтор возвращает тот же Message. Hash дополнен вложениями, при replay дополнительно сравниваются исходный текст и список ID. Старые текстовые ключи lab3 остаются пригодны для replay. Сохраняются keyset-пагинация, отзыв сессий между репликами и graceful shutdown. ### Ограничения входных данных -- Тело читается из канала порциями до 8192 bytes, с проверкой лимита до добавления в буфер. Превышение Content-Length отсекается сразу; при отсутствии длины применяется тот же счётчик bytes. Максимум — 10 MiB, превышение — 413; приём тела ограничен 15 секундами. +- Тело читается из канала порциями до 8192 bytes, с проверкой лимита до записи во временный файл. Превышение Content-Length отсекается сразу; при отсутствии длины применяется тот же счётчик bytes. Максимум — 10 MiB, превышение — 413; приём тела ограничен 15 секундами. - ImageIO определяет реальный формат, допускаются PNG/JPEG и совпадение MIME. Размеры считываются из заголовка до `reader.read`; произведение считается в Long, более 40 млн пикселей — 413. - Затем выполняется полное декодирование, чтобы одного корректного заголовка было недостаточно. Ошибки/предупреждения декодера — 415. Для PNG дополнительно проверяются границы chunks, CRC и IEND, для JPEG — завершающий EOI. - Filename: 1–255 Unicode code points; `/`, `\`, NUL и управляющие символы — 400. -- Временные файлы в API не создаются: ограниченный массив оригинала и декодированный raster находятся в RAM. ImageIO использует MemoryCacheImageInputStream. У download также есть предел 10 MiB. +- Приём HTTP и S3 PUT потоковые: тело поступает в уникальный временный файл, AWS SDK читает его через `asByteStream()`. `finally` удаляет файл при успехе, ошибке и отмене. В Compose `/tmp` — tmpfs 32 MiB, очищаемый при restart; это не постоянное хранилище оригиналов. Семафор допускает одну загрузку на реплику, остальные ждут без собственного буфера файла. Валидация всё ещё использует ограниченный массив ≤10 MiB и raster ≤40 млн пикселей; это честная граница потоковой обработки, а не обещание zero-copy. API ограничен 1 GiB и 1 CPU. У download также есть предел 10 MiB. - S3-вызов ограничен coroutine timeout в 8 с, включая получение тела ответа. HAProxy server timeout увеличен до 30 с для синхронной загрузки. Автоматическое повторение POST после передачи запроса не включается. ## Доказательства критериев @@ -82,19 +87,47 @@ Upload: Bearer-аутентификация → проверка членств | Критерий | Команда/сценарий | Наблюдение | Доказательство | | --- | --- | --- | --- | | Контракт, 201 ready, checksum, сообщение с вложением, ACL | `make test` | PASS публичного сценария lab4 | [smoke.txt](evidence/smoke.txt) | -| Возможности lab3 и новые проверки | `./gradlew test` | 75 тестов, 0 failures/errors/skipped | [gradle-tests.txt](evidence/gradle-tests.txt) | +| Возможности lab3 и новые проверки | `./gradlew test` | 76 тестов, 0 failures/errors/skipped | [gradle-tests.txt](evidence/gradle-tests.txt) | | PNG/JPEG, MIME, опасное имя, лимиты bytes/pixels до декодирования | AttachmentControllerTest, ImageValidatorTest | Оба формата скачиваются побайтно; 400/413/415 на неверный ввод | [gradle-tests.txt](evidence/gradle-tests.txt) | | Приватное S3, чужой чат, отказ именно загрузившей реплики | `python3 scripts/attachment-failover.py` | 403 для anonymous S3 GET известного объекта; 404 постороннему; иной X-Instance-Id и те же bytes после отказа | [attachment-failover.txt](evidence/attachment-failover.txt) | | Сохранность после restart всех компонентов | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS, прежняя сессия, метаданные и оригинал доступны; StartedAt всех процессов изменился | [persistence.txt](evidence/persistence.txt) | | Запись сообщений во время отказа API | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | Проверка восстановления записи, отсутствия дублей и сохранности данных | [failover.txt](evidence/failover.txt) | | Недоступность S3 | AttachmentControllerTest: pause MinIO | Upload/content/ready → 503, live → 200; после unpause исходные bytes доступны | [gradle-tests.txt](evidence/gradle-tests.txt) | +| Негативные запросы уровня 4 | AttachmentControllerTest | 413 для большого файла, 415 для повреждения/MIME, 404 для чужого ID и другого чата | [gradle-tests.txt](evidence/gradle-tests.txt) | +| Сбой между S3 и БД, grace и повторная очистка | AttachmentCleanupTest | Свежие/готовые объекты сохранены, orphan и поздний PUT удалены, публикация abandoned запрещена | [gradle-tests.txt](evidence/gradle-tests.txt) | +| Обрыв клиента | `python3 scripts/attachment-interrupt.py` | Нет опубликованных метаданных и временных файлов после закрытия соединения | [attachment-interrupt.txt](evidence/attachment-interrupt.txt) | +| 10 одновременных загрузок, память | `python3 scripts/attachment-load.py` | 10 успешных upload/download, sampled peak ниже лимита реплик | [attachment-load.json](evidence/attachment-load.json) | +| Отдельные права и повторяемый bootstrap | `scripts/check-s3-permissions.sh` | Запрещённые операции отклонены, console недоступна из общей сети | [s3-permissions.txt](evidence/s3-permissions.txt) | -## Согласованность и ограничения уровня 3 +## Согласованность и очистка уровня 4 -201 подтверждается только после успешных S3 PUT и COMMIT PostgreSQL. Между этими хранилищами нет общей транзакции. При падении после PUT, до COMMIT, возможен объект без метаданных. Автоматическая сверка/очистка таких объектов и безопасная компенсация пока не реализованы — это следующий этап на 4. При потере ответа upload его повтор может создать ещё одно вложение, как разрешено контрактом. +Миграция V5 добавляет `attachment_uploads`. Перед S3 PUT в PostgreSQL фиксируется ID будущего объекта и срок действия (время БД + 1 час). После PUT публикация берёт строку `FOR UPDATE`, проверяет срок и отсутствие признака `abandoned`, затем атомарно создаёт Attachment и удаляет запись журнала. Поэтому подтверждённый объект не попадает в очистку. -На 3 API использует те же локальные S3 credentials, что и bootstrap; отдельная учётная запись с ограниченной policy ещё не реализована. Bucket приватен, порты S3/console наружу не опубликованы. Это локальный учебный стенд, не production hardening. +Каждая реплика раз в 30 секунд выбирает до 100 просроченных записей через `FOR UPDATE SKIP LOCKED`, помечает их abandoned и переносит следующую попытку на минуту вперёд. После COMMIT, без долгой DB-транзакции, удаляет соответствующие S3-объекты. Ошибка S3 оставляет запись для повтора. Публикация и очистка сериализуются блокировкой одной строки: либо метаданные опубликованы, либо загрузка окончательно abandoned. -Память одной загрузки ограничена размером bytes и raster до 40 млн пикселей; потоковой обработки до S3, ограничения числа одновременно декодируемых изображений и эксперимента на ≥10 параллельных загрузках пока нет. Такие нагрузки могут исчерпать память реплики. Они относятся к следующему этапу, уровень 4 не заявляется. +Записи abandoned сохраняются и периодически обрабатываются повторно даже после успешного DELETE. Это намеренно: процесс, замороженный дольше grace period, может поздно закончить PUT. Опубликовать метаданные он уже не сможет, а повторная очистка удалит поздний объект. Без сохранения такой записи первая уборка могла бы пропустить позднюю запись навсегда. Плата — рост журнала неудачных загрузок и повторные DELETE отсутствующих объектов; политика удаления tombstone требует отдельного ограничения максимального времени жизни загрузчика. Успешные загрузки строки журнала не накапливают. + +Тест `AttachmentCleanupTest` воспроизводит сбой после фактического PUT до записи метаданных, сохраняет свежий объект внутри grace, сдвигает срок записи для проверки уборки без часового ожидания, моделирует отказ DELETE и повтор, поздний PUT и отказ публикации. Подтверждённый объект остаётся доступен. Глобального обхода всего bucket и восстановления вручную удалённых объектов нет — это отдельный исследовательский трек 5. + +## S3-права + +`secrets/s3_access_key_id` и `s3_secret_access_key` используются только MinIO и bootstrap. API получает отдельные `s3_api_access_key_id` и `s3_api_secret_access_key`, административные файлы в него не монтируются. Прикладная policy разрешает `ListBucket` для рабочего bucket (нужен HeadBucket/readiness) и только Get/Put/DeleteObject для `originals/*`. API не может управлять пользователями, политиками, создавать buckets или записывать другие prefixes. Console слушает только `127.0.0.1:9001` внутри контейнера MinIO, поэтому недоступна даже из общей сети Compose. + +Bootstrap повторно создаёт/обновляет пользователя и policy с теми же локальными credentials и не трогает объекты. `check-s3-permissions.sh` запускает bootstrap дважды и проверяет реальные отказы запрещённых операций. Анонимный GET известного существующего объекта отдельно получает 403 в `attachment-failover.py`. + +## Эксперимент с параллельными загрузками + +`attachment-load.py` синхронно выпускает 10 клиентов через Barrier. Каждый отправляет реальный PNG 1600×1600, 7 684 003 bytes (псевдослучайные RGB-пиксели, seed 42), затем скачивает оригинал вторым участником и проверяет SHA-256. Профиль — один burst без повторов, две API-реплики, по одной активной обработке на реплику; очередь включена во время HTTP-ответа. Docker 28.4.0, macOS arm64, лимиты каждой API: 1 CPU / 1 GiB. Это функциональная проверка ограничения памяти, не определение предельного throughput. + +Память измеряется через `memory.current` cgroup v2 каждой API, с паузой 0,2 с между обходами (плюс время docker exec). Включает JVM/native и tmpfs, не только heap. Замер дискретный, поэтому краткие пики между отсчётами могут быть пропущены. Raw-отсчёты, исходные значения и результаты всех запросов: [attachment-load.json](evidence/attachment-load.json). + +Все 10 upload вернули 201, все 10 download совпали по SHA-256. Наблюдаемые пики по репликам: 335579ab19d6: 282.4 MiB, a8ee56f6ec22: 259.0 MiB. Время upload с ожиданием очереди — от 1.030 до 2.973 с; ошибок не было. + +## Ограничения + + +201 подтверждается только после успешных S3 PUT и COMMIT PostgreSQL. Между этими хранилищами нет общей транзакции. При падении после PUT, до COMMIT, возможен объект без метаданных. Такой объект учтён в журнале и удаляется после grace period описанным выше механизмом. При потере ответа upload его повтор может создать ещё одно вложение, как разрешено контрактом. + +Вход и S3 PUT ограничены по bytes и времени; валидация допускает до 40 млн пикселей и только один декодер на реплику. Проведённый burst не доказывает работу при любом количестве соединений, любой комбинации размеров и намеренном истощении ресурсов. Очередь не обещает фиксированное время ответа при перегрузке; HAProxy сохраняет свои таймауты. Случайные orphan-объекты, созданные вручную или прежней версией до журнала V5, автоматическая очистка журнала не обнаруживает. Readiness требует PostgreSQL и S3, Redis допускает fallback. При отказе S3 HAProxy выведет обе реплики из ротации; LB может вернуть собственный 503 вместо JSON API. Прямые обращения к API при отказе S3 проверены тестом. Одноузловые PostgreSQL, MinIO и LB остаются точками отказа: volumes переживают restart, но не заменяют репликацию и backup. Сохраняются ограничения конкурентной keyset-пагинации и часов из [отчёта lab3](archive/lab3/REPORT.md). diff --git a/compose.yaml b/compose.yaml index 0ab2292..f79fa59 100644 --- a/compose.yaml +++ b/compose.yaml @@ -58,7 +58,7 @@ services: s3: # MinIO RELEASE.2025-09-07T16-13-09Z, pinned multi-platform image. image: quay.io/minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e - command: ["server", "/data", "--console-address", ":9001"] + command: ["server", "/data", "--console-address", "127.0.0.1:9001"] environment: MINIO_ROOT_USER_FILE: /run/secrets/s3_access_key_id MINIO_ROOT_PASSWORD_FILE: /run/secrets/s3_secret_access_key @@ -91,6 +91,8 @@ services: secrets: - s3_access_key_id - s3_secret_access_key + - s3_api_access_key_id + - s3_api_secret_access_key volumes: - ./infra/s3/bootstrap.sh:/bootstrap.sh:ro restart: "no" @@ -129,7 +131,7 @@ services: resources: limits: cpus: "1.0" - memory: 512m + memory: 1g depends_on: migrate: condition: service_completed_successfully @@ -157,15 +159,17 @@ services: SHUTDOWN_DRAIN_DELAY_MS: "3000" S3_ENDPOINT: http://s3:9000 S3_BUCKET: ${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_ACCESS_KEY_ID_FILE: /run/secrets/s3_api_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_api_secret_access_key secrets: - db_password - redis_password - - s3_access_key_id - - s3_secret_access_key + - s3_api_access_key_id + - s3_api_secret_access_key # SIGTERM: readiness 503 and 3 s drain (HAProxy needs <= 2 s to notice), then Ktor closes the socket and # finishes requests in flight within 5 s. 3 + 5 = 8 s < 10 s before Docker sends SIGKILL. + tmpfs: + - /tmp:size=32m,mode=1777 stop_grace_period: 10s restart: unless-stopped @@ -202,6 +206,11 @@ secrets: s3_secret_access_key: file: ./secrets/s3_secret_access_key + s3_api_access_key_id: + file: ./secrets/s3_api_access_key_id + s3_api_secret_access_key: + file: ./secrets/s3_api_secret_access_key + volumes: postgres-data: s3-data: diff --git a/evidence/attachment-failover.txt b/evidence/attachment-failover.txt index ff683d4..d88491c 100644 --- a/evidence/attachment-failover.txt +++ b/evidence/attachment-failover.txt @@ -1,6 +1,6 @@ -Upload: 201 ready; instance=ecbe49d85c82 +Upload: 201 ready; instance=335579ab19d6 Anonymous S3 GET of known object: 403 Outsider metadata/content: 404 -Download: 200; instance=9440528ba703 +Download: 200; instance=a8ee56f6ec22 SHA-256: 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75 PASS: uploading replica stopped; original served by another replica; stopped replica restored diff --git a/evidence/attachment-interrupt.txt b/evidence/attachment-interrupt.txt new file mode 100644 index 0000000..a0be318 --- /dev/null +++ b/evidence/attachment-interrupt.txt @@ -0,0 +1 @@ +PASS: connection closed mid-body; temporary files removed on both replicas; metadata absent diff --git a/evidence/attachment-load.json b/evidence/attachment-load.json new file mode 100644 index 0000000..57f5eec --- /dev/null +++ b/evidence/attachment-load.json @@ -0,0 +1,131 @@ +{ + "concurrency": 10, + "file_bytes": 7684003, + "pixels": 2560000, + "sha256": "de56c853868dc1ee1d4b0046023ed484ecd1e4d2ce2d403fbb661d81a414995b", + "baseline_bytes": { + "335579ab19d6": 193679360, + "a8ee56f6ec22": 204886016 + }, + "sampled_peak_bytes": { + "335579ab19d6": 296071168, + "a8ee56f6ec22": 271552512 + }, + "results": [ + { + "upload": 0, + "seconds": 2.591, + "instance": "a8ee56f6ec22" + }, + { + "upload": 1, + "seconds": 2.834, + "instance": "335579ab19d6" + }, + { + "upload": 2, + "seconds": 2.52, + "instance": "335579ab19d6" + }, + { + "upload": 3, + "seconds": 1.634, + "instance": "a8ee56f6ec22" + }, + { + "upload": 4, + "seconds": 1.03, + "instance": "335579ab19d6" + }, + { + "upload": 5, + "seconds": 2.973, + "instance": "a8ee56f6ec22" + }, + { + "upload": 6, + "seconds": 2.087, + "instance": "335579ab19d6" + }, + { + "upload": 7, + "seconds": 1.056, + "instance": "a8ee56f6ec22" + }, + { + "upload": 8, + "seconds": 1.593, + "instance": "335579ab19d6" + }, + { + "upload": 9, + "seconds": 2.096, + "instance": "a8ee56f6ec22" + } + ], + "samples": [ + { + "seconds": 0.0, + "bytes": { + "335579ab19d6": 196050944, + "a8ee56f6ec22": 210128896 + } + }, + { + "seconds": 0.404, + "bytes": { + "335579ab19d6": 212848640, + "a8ee56f6ec22": 223256576 + } + }, + { + "seconds": 0.749, + "bytes": { + "335579ab19d6": 241385472, + "a8ee56f6ec22": 242810880 + } + }, + { + "seconds": 1.075, + "bytes": { + "335579ab19d6": 248864768, + "a8ee56f6ec22": 259260416 + } + }, + { + "seconds": 1.489, + "bytes": { + "335579ab19d6": 266833920, + "a8ee56f6ec22": 249815040 + } + }, + { + "seconds": 1.838, + "bytes": { + "335579ab19d6": 290893824, + "a8ee56f6ec22": 257802240 + } + }, + { + "seconds": 2.244, + "bytes": { + "335579ab19d6": 293588992, + "a8ee56f6ec22": 271036416 + } + }, + { + "seconds": 2.607, + "bytes": { + "335579ab19d6": 296071168, + "a8ee56f6ec22": 271552512 + } + }, + { + "seconds": 3.007, + "bytes": { + "335579ab19d6": 284782592, + "a8ee56f6ec22": 263704576 + } + } + ] +} diff --git a/evidence/gradle-tests.txt b/evidence/gradle-tests.txt index 9f5065a..41ab5ef 100644 --- a/evidence/gradle-tests.txt +++ b/evidence/gradle-tests.txt @@ -1,7 +1,10 @@ -Command: ./gradlew test --rerun-tasks -AWS SDK for Kotlin 1.6.41; BUILD SUCCESSFUL -Tests: 75; failures: 0; errors: 0; skipped: 0 +Command: ./gradlew test +BUILD SUCCESSFUL +Tests: 76; failures: 0; errors: 0; skipped: 0 com.mtusi.messenger.main.infrastructure.controllers.attachment.AttachmentControllerTest: tests=3 failures=0 + upload originals ACL message links and idempotency() + invalid images filenames and byte limit return client errors() + S3 outage fails upload download and readiness without losing the original() com.mtusi.messenger.main.infrastructure.controllers.authentication.AuthenticationControllerTest: tests=9 failures=0 com.mtusi.messenger.main.infrastructure.controllers.chat.ChatControllerTest: tests=6 failures=0 com.mtusi.messenger.main.infrastructure.controllers.health.HealthControllerTest: tests=2 failures=0 @@ -11,7 +14,11 @@ com.mtusi.messenger.main.infrastructure.controllers.message.MessageIdempotencyTe com.mtusi.messenger.main.infrastructure.controllers.user.UserControllerTest: tests=11 failures=0 com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.RedisSessionCacheRepositoryTest: tests=3 failures=0 com.mtusi.messenger.main.infrastructure.repositories.chat.ExposedChatRepositoryTest: tests=2 failures=0 +com.mtusi.messenger.main.infrastructure.services.attachment.AttachmentCleanupTest: tests=1 failures=0 + orphan cleanup respects grace and fences late publishers() com.mtusi.messenger.main.infrastructure.services.attachment.ImageValidatorTest: tests=2 failures=0 + corrupted CRC and missing end chunk are rejected() + pixel limit is enforced on header before decoding() com.mtusi.messenger.main.infrastructure.services.authentication.CrossReplicaRevocationTest: tests=2 failures=0 com.mtusi.messenger.main.infrastructure.services.authentication.SessionLookupSingleFlightTest: tests=4 failures=0 com.mtusi.messenger.main.infrastructure.services.hashing.DefaultHashingServiceTest: tests=4 failures=0 diff --git a/evidence/persistence.txt b/evidence/persistence.txt index 2f565c6..729af16 100644 --- a/evidence/persistence.txt +++ b/evidence/persistence.txt @@ -1,17 +1,17 @@ Before restart: -/mtusi-messenger-lab4-api-1 started=2026-11-04T23:04:21.983430629Z -/mtusi-messenger-lab4-api-2 started=2026-11-04T23:03:16.431601751Z -/mtusi-messenger-lab4-lb-1 started=2026-11-04T23:03:19.024302711Z -/mtusi-messenger-lab4-postgres-1 started=2026-11-04T23:03:06.139259385Z -/mtusi-messenger-lab4-redis-1 started=2026-11-04T23:03:06.148613844Z -/mtusi-messenger-lab4-s3-1 started=2026-11-04T23:03:06.148211344Z +/mtusi-messenger-lab4-api-1 started=2026-11-05T11:21:33.808216129Z +/mtusi-messenger-lab4-api-2 started=2026-11-05T11:19:40.744427424Z +/mtusi-messenger-lab4-lb-1 started=2026-11-04T23:04:59.215310882Z +/mtusi-messenger-lab4-postgres-1 started=2026-11-04T23:04:47.265519668Z +/mtusi-messenger-lab4-redis-1 started=2026-11-04T23:04:47.259546585Z +/mtusi-messenger-lab4-s3-1 started=2026-11-05T11:16:50.746732095Z python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8084" Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. After restart: -/mtusi-messenger-lab4-api-1 started=2026-11-04T23:04:56.021297464Z -/mtusi-messenger-lab4-api-2 started=2026-11-04T23:04:56.113348339Z -/mtusi-messenger-lab4-lb-1 started=2026-11-04T23:04:59.215310882Z -/mtusi-messenger-lab4-postgres-1 started=2026-11-04T23:04:47.265519668Z -/mtusi-messenger-lab4-redis-1 started=2026-11-04T23:04:47.259546585Z -/mtusi-messenger-lab4-s3-1 started=2026-11-04T23:04:47.267464335Z +/mtusi-messenger-lab4-api-1 started=2026-11-05T11:22:10.858998716Z +/mtusi-messenger-lab4-api-2 started=2026-11-05T11:22:10.784659257Z +/mtusi-messenger-lab4-lb-1 started=2026-11-05T11:22:13.944573717Z +/mtusi-messenger-lab4-postgres-1 started=2026-11-05T11:22:01.053742252Z +/mtusi-messenger-lab4-redis-1 started=2026-11-05T11:22:01.049022586Z +/mtusi-messenger-lab4-s3-1 started=2026-11-05T11:22:01.056079919Z diff --git a/evidence/s3-permissions.txt b/evidence/s3-permissions.txt new file mode 100644 index 0000000..48d1a15 --- /dev/null +++ b/evidence/s3-permissions.txt @@ -0,0 +1,10 @@ + Container mtusi-messenger-lab4-s3-1 Running +Bucket created successfully `local/messenger-attachments`. +Access permission for `local/messenger-attachments` is set to `private` + Container mtusi-messenger-lab4-s3-1 Running +Bucket created successfully `local/messenger-attachments`. +Access permission for `local/messenger-attachments` is set to `private` + Container mtusi-messenger-lab4-s3-1 Running +PASS: app cannot administer MinIO, create buckets, change policy or write outside originals/ +wget: can't connect to remote host (172.25.0.2): Connection refused +PASS: console unavailable from shared network diff --git a/infra/s3/bootstrap.sh b/infra/s3/bootstrap.sh index bce6a39..5ca311d 100644 --- a/infra/s3/bootstrap.sh +++ b/infra/s3/bootstrap.sh @@ -4,3 +4,17 @@ set -eu mc alias set local http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" "$(cat /run/secrets/s3_secret_access_key)" >/dev/null mc mb --ignore-existing "local/$S3_BUCKET" mc anonymous set none "local/$S3_BUCKET" + +api_user=$(cat /run/secrets/s3_api_access_key_id) +mc admin user add local "$api_user" "$(cat /run/secrets/s3_api_secret_access_key)" >/dev/null +cat > /tmp/attachment-policy.json </dev/null +mc admin policy attach local attachments-api --user "$api_user" >/dev/null diff --git a/run/_template/config/storage.conf b/run/_template/config/storage.conf index 4c00c88..2fb4828 100644 --- a/run/_template/config/storage.conf +++ b/run/_template/config/storage.conf @@ -1,6 +1,6 @@ storage { endpoint = "http://localhost:9000" bucket = "messenger-attachments" - accessKeyFile = "../../secrets/s3_access_key_id" - secretKeyFile = "../../secrets/s3_secret_access_key" + accessKeyFile = "../../secrets/s3_api_access_key_id" + secretKeyFile = "../../secrets/s3_api_secret_access_key" } diff --git a/scripts/attachment-interrupt.py b/scripts/attachment-interrupt.py new file mode 100644 index 0000000..f95385c --- /dev/null +++ b/scripts/attachment-interrupt.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Abort a binary request mid-body and verify temporary files and metadata are absent.""" +import os +from pathlib import Path +import socket +import subprocess +import sys +import time +import urllib.parse +import uuid + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from client import Client, check + +c = Client() +alice, bob, eve, chat = c.bootstrap() +name = 'interrupted-' + uuid.uuid4().hex + '.png' +base = urllib.parse.urlsplit(c.base) +body = (ROOT / 'tests/fixtures/sample.png').read_bytes() +headers = ('POST /api/v1/chats/' + chat['id'] + '/attachments?filename=' + name + ' HTTP/1.1\r\n' + 'Host: localhost\r\nAuthorization: Bearer ' + alice['token'] + '\r\n' + 'Content-Type: image/png\r\nContent-Length: 1048576\r\n\r\n') +with socket.create_connection((base.hostname, base.port or 80)) as connection: + connection.sendall(headers.encode() + body[:len(body)//2]) + time.sleep(0.5) +# Let the server observe EOF, or the bounded receive timeout. +ids = subprocess.check_output(['docker', 'compose', 'ps', '-q', 'api'], cwd=ROOT, text=True).split() +deadline = time.monotonic() + 20 +while True: + files = [subprocess.check_output(['docker', 'exec', cid, 'find', '/tmp', '-name', 'messenger-upload-*'], text=True).strip() for cid in ids] + if not any(files): + break + check(time.monotonic() < deadline, 'temporary upload file survived interruption/timeout') + time.sleep(0.2) +count = subprocess.check_output(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc', + "SELECT count(*) FROM attachments WHERE filename = '" + name + "'"], cwd=ROOT, text=True).strip() +check(count == '0', 'interrupted upload published metadata') +print('PASS: connection closed mid-body; temporary files removed on both replicas; metadata absent') diff --git a/scripts/attachment-load.py b/scripts/attachment-load.py new file mode 100644 index 0000000..ff021fb --- /dev/null +++ b/scripts/attachment-load.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Ten simultaneous binary uploads and sampled API cgroup memory, without tokens in output.""" +import concurrent.futures +import hashlib +import json +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +import threading +import time +import zlib + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from client import Client, check + + +def chunk(kind, data): + return struct.pack('!I', len(data)) + kind + data + struct.pack('!I', zlib.crc32(kind + data)) + + +def fixture(): + width = height = 1600 + rng = random.Random(42) + pixels = b''.join(b'\0' + rng.randbytes(width * 3) for _ in range(height)) + return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', width, height, 8, 2, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress(pixels, 1)) + chunk(b'IEND', b'')) + + +def memory(ids): + result = {} + for container in ids: + value = subprocess.check_output(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.current'], text=True) + result[container[:12]] = int(value) + return result + + +def main(): + c = Client(timeout=60) + alice, bob, eve, chat = c.bootstrap() + data = fixture() + expected = hashlib.sha256(data).hexdigest() + ids = subprocess.check_output(['docker', 'compose', 'ps', '-q', 'api'], cwd=ROOT, text=True).split() + baseline = memory(ids) + samples = [] + stop = threading.Event() + start = time.monotonic() + + def sample(): + while not stop.is_set(): + samples.append({'seconds': round(time.monotonic() - start, 3), 'bytes': memory(ids)}) + stop.wait(0.2) + + barrier = threading.Barrier(10) + + def upload(index): + client = Client(timeout=60) + barrier.wait(timeout=30) + result = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=load.png', + 201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment') + check(result['json']['sha256'] == expected, 'uploaded checksum mismatch') + downloaded = client.call('GET', '/api/v1/attachments/' + result['json']['id'] + '/content', actor=bob) + check(hashlib.sha256(downloaded['bytes']).hexdigest() == expected, 'download checksum mismatch') + return {'upload': index, 'seconds': round(result['elapsed'], 3), 'instance': result['headers']['X-Instance-Id']} + + sampler = threading.Thread(target=sample) + sampler.start() + try: + with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool: + results = list(pool.map(upload, range(10))) + finally: + stop.set() + sampler.join() + peak = {key: max([baseline[key]] + [s['bytes'][key] for s in samples]) for key in baseline} + print(json.dumps({'concurrency': 10, 'file_bytes': len(data), 'pixels': 1600 * 1600, + 'sha256': expected, 'baseline_bytes': baseline, 'sampled_peak_bytes': peak, + 'results': results, 'samples': samples}, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/scripts/check-s3-permissions.sh b/scripts/check-s3-permissions.sh new file mode 100755 index 0000000..416bdeb --- /dev/null +++ b/scripts/check-s3-permissions.sh @@ -0,0 +1,21 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +# Bootstrap is deliberately repeated; existing objects must survive both runs. +docker compose run --rm s3-init +docker compose run --rm s3-init +docker compose run --rm --entrypoint /bin/sh s3-init -ec ' +mc alias set app http://s3:9000 "$(cat /run/secrets/s3_api_access_key_id)" "$(cat /run/secrets/s3_api_secret_access_key)" >/dev/null +if mc admin info app >/dev/null 2>&1; then exit 1; fi +if mc mb app/forbidden-bucket >/dev/null 2>&1; then exit 1; fi +if mc anonymous set download "app/$S3_BUCKET" >/dev/null 2>&1; then exit 1; fi +printf test > /tmp/test-object +if mc cp /tmp/test-object "app/$S3_BUCKET/forbidden-prefix/object" >/dev/null 2>&1; then exit 1; fi +mc stat "app/$S3_BUCKET" >/dev/null +printf "PASS: app cannot administer MinIO, create buckets, change policy or write outside originals/\n" +' +if docker compose exec -T lb wget -q -T 2 -O /dev/null http://s3:9001; then + echo 'FAIL: console reachable from shared network' + exit 1 +fi +echo 'PASS: console unavailable from shared network' diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh index 0c2fa76..7a4f684 100755 --- a/scripts/init-secrets.sh +++ b/scripts/init-secrets.sh @@ -9,7 +9,7 @@ mkdir -p secrets # Readable by the non-root users inside the containers (bind-mounted as is). umask 022 -for name in db_password redis_password s3_access_key_id s3_secret_access_key; do +for name in db_password redis_password s3_access_key_id s3_secret_access_key s3_api_access_key_id s3_api_secret_access_key; do if [ ! -s "secrets/$name" ]; then openssl rand -hex 24 > "secrets/$name" echo "created secrets/$name" diff --git a/src/main/kotlin/com/mtusi/messenger/main/App.kt b/src/main/kotlin/com/mtusi/messenger/main/App.kt index e53a125..d2214cd 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/App.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/App.kt @@ -1,6 +1,7 @@ package com.mtusi.messenger.main import com.mtusi.messenger.main.plugins.authentication.configureAuthentication +import com.mtusi.messenger.main.plugins.configureAttachmentCleanup import com.mtusi.messenger.main.plugins.configureCallLogging import com.mtusi.messenger.main.plugins.configureContentNegotiation import com.mtusi.messenger.main.plugins.configureCors @@ -33,6 +34,7 @@ fun Application.module() { configureRedis() configureGracefulShutdown() configureSessionRevocationSync() + configureAttachmentCleanup() configureContentNegotiation() configureDefaultHeaders() diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/attachment/AttachmentController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/attachment/AttachmentController.kt index 8a8fce5..4817676 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/attachment/AttachmentController.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/attachment/AttachmentController.kt @@ -15,12 +15,17 @@ import io.ktor.server.routing.* import io.ktor.utils.io.readAvailable import kotlinx.coroutines.withTimeoutOrNull import org.koin.ktor.ext.inject -import java.io.ByteArrayOutputStream +import java.nio.file.Files +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.coroutines.sync.Semaphore +import kotlinx.coroutines.sync.withPermit import kotlin.time.Duration.Companion.milliseconds fun Routing.configureAttachmentRouting() { val service by inject() + val uploads = Semaphore(1) authenticate(SESSION_AUTH) { @@ -47,25 +52,35 @@ fun Routing.configureAttachmentRouting() { throw ApiException(ErrorCode.PAYLOAD_TOO_LARGE, "file exceeds 10 MiB") } - val bytes = withTimeoutOrNull(15_000.milliseconds) { + uploads.withPermit { + val file = Files.createTempFile("messenger-upload-", ".bin").toFile() + try { + withTimeoutOrNull(15_000.milliseconds) { + withContext(Dispatchers.IO) { + val input = call.receiveChannel() + val buffer = ByteArray(8192) + var size = 0L + file.outputStream().use { output -> + while (true) { + val count = input.readAvailable(buffer) + if (count == -1) break + size += count + if (size > MAX_ATTACHMENT_BYTES) { + throw ApiException(ErrorCode.PAYLOAD_TOO_LARGE, "file exceeds 10 MiB") + } + output.write(buffer, 0, count) + } + } + } + } ?: throw ApiException(ErrorCode.INVALID_REQUEST, "upload timed out") - val input = call.receiveChannel() - val output = ByteArrayOutputStream() - val buffer = ByteArray(8192) - - while (true) { - val count = input.readAvailable(buffer, 0, minOf(buffer.size, MAX_ATTACHMENT_BYTES + 1 - output.size())) - if (count == -1) break - if (output.size() + count > MAX_ATTACHMENT_BYTES) { - throw ApiException(ErrorCode.PAYLOAD_TOO_LARGE, "file exceeds 10 MiB") - } - output.write(buffer, 0, count) + val attachment = service.upload(chatId, actor.id, filename, type, file) + call.respond(HttpStatusCode.Created, attachment) + } finally { + file.delete() } + } - output.toByteArray() - } ?: throw ApiException(ErrorCode.INVALID_REQUEST, "upload timed out") - - call.respond(HttpStatusCode.Created, service.upload(chatId, actor.id, filename, type, bytes)) } get("/api/v1/attachments/{id}") { diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/attachment/UploadJournalModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/attachment/UploadJournalModel.kt new file mode 100644 index 0000000..ae55f75 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/attachment/UploadJournalModel.kt @@ -0,0 +1,18 @@ +package com.mtusi.messenger.main.infrastructure.models.attachment + +import com.mtusi.messenger.main.utils.exposed.operations.plus +import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable +import org.jetbrains.exposed.v1.core.longLiteral +import org.jetbrains.exposed.v1.datetime.CurrentTimestamp +import org.jetbrains.exposed.v1.datetime.timestamp + +object UploadJournalModel : UUIDTable("attachment_uploads") { + + val expiresAt = timestamp("expires_at").defaultExpression(CurrentTimestamp + longLiteral(3600)) + val abandoned = bool("abandoned").default(false) + val nextAttemptAt = timestamp("next_attempt_at").defaultExpression(CurrentTimestamp + longLiteral(3600)) + + init { + index("attachment_uploads_next_attempt_idx", false, nextAttemptAt) + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/ExposedUploadJournalRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/ExposedUploadJournalRepository.kt new file mode 100644 index 0000000..edd2ef9 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/ExposedUploadJournalRepository.kt @@ -0,0 +1,77 @@ +package com.mtusi.messenger.main.infrastructure.repositories.attachment + +import com.mtusi.messenger.main.infrastructure.models.attachment.UploadJournalModel +import com.mtusi.messenger.main.utils.exposed.operations.plus +import org.jetbrains.exposed.v1.core.SortOrder +import org.jetbrains.exposed.v1.core.and +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.core.greater +import org.jetbrains.exposed.v1.core.inList +import org.jetbrains.exposed.v1.core.lessEq +import org.jetbrains.exposed.v1.core.longLiteral +import org.jetbrains.exposed.v1.core.vendors.ForUpdateOption +import org.jetbrains.exposed.v1.datetime.CurrentTimestamp +import org.jetbrains.exposed.v1.jdbc.deleteWhere +import org.jetbrains.exposed.v1.jdbc.insert +import org.jetbrains.exposed.v1.jdbc.select +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.jetbrains.exposed.v1.jdbc.update +import org.koin.core.annotation.Single +import java.util.UUID + +@Single +class ExposedUploadJournalRepository : UploadJournalRepository { + + override fun register( + id: UUID + ) { + UploadJournalModel.insert { + it[this.id] = id + } + } + + override fun lockForCompletion( + id: UUID + ): Boolean { + val canComplete = (UploadJournalModel.abandoned eq false) and + (UploadJournalModel.expiresAt greater CurrentTimestamp) + + return UploadJournalModel + .select(canComplete) + .where(UploadJournalModel.id eq id) + .forUpdate() + .firstOrNull() + ?.get(canComplete) + ?: false + } + + override fun complete( + id: UUID + ) { + UploadJournalModel.deleteWhere { + UploadJournalModel.id eq id + } + } + + override fun claimExpired(): List { + + val ids = UploadJournalModel + .selectAll() + .where(UploadJournalModel.nextAttemptAt lessEq CurrentTimestamp) + .orderBy(UploadJournalModel.nextAttemptAt to SortOrder.ASC) + .limit(100) + .forUpdate(ForUpdateOption.PostgreSQL.ForUpdate(ForUpdateOption.PostgreSQL.MODE.SKIP_LOCKED)) + .map { + it[UploadJournalModel.id].value + } + + if (ids.isNotEmpty()) { + UploadJournalModel.update({ UploadJournalModel.id inList ids }) { + it[abandoned] = true + it[nextAttemptAt] = CurrentTimestamp + longLiteral(60) + } + } + + return ids + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/UploadJournalRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/UploadJournalRepository.kt new file mode 100644 index 0000000..09fff45 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/UploadJournalRepository.kt @@ -0,0 +1,13 @@ +package com.mtusi.messenger.main.infrastructure.repositories.attachment + +import java.util.UUID + +interface UploadJournalRepository { + fun register(id: UUID) + + fun lockForCompletion(id: UUID): Boolean + + fun complete(id: UUID) + + fun claimExpired(): List +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/storage/ObjectStorageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/storage/ObjectStorageRepository.kt index f7bd488..42154b8 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/storage/ObjectStorageRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/storage/ObjectStorageRepository.kt @@ -1,12 +1,13 @@ package com.mtusi.messenger.main.infrastructure.repositories.attachment.storage +import java.io.File import java.util.UUID interface ObjectStorageRepository { suspend fun put( id: UUID, - bytes: ByteArray, + file: File, contentType: String ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/storage/S3ObjectStorageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/storage/S3ObjectStorageRepository.kt index 32ee039..72afac5 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/storage/S3ObjectStorageRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/storage/S3ObjectStorageRepository.kt @@ -6,7 +6,7 @@ import aws.sdk.kotlin.services.s3.deleteObject import aws.sdk.kotlin.services.s3.model.GetObjectRequest import aws.sdk.kotlin.services.s3.headBucket import aws.sdk.kotlin.services.s3.putObject -import aws.smithy.kotlin.runtime.content.ByteStream +import aws.smithy.kotlin.runtime.content.asByteStream import aws.smithy.kotlin.runtime.content.toByteArray import aws.smithy.kotlin.runtime.net.url.Url import com.mtusi.messenger.main.config.storage.StorageConfig @@ -17,6 +17,7 @@ import com.mtusi.messenger.main.utils.resolveSecret import kotlinx.coroutines.CancellationException import kotlinx.coroutines.withTimeoutOrNull import org.koin.core.annotation.Single +import java.io.File import java.util.UUID import kotlin.time.Duration.Companion.milliseconds @@ -40,16 +41,16 @@ class S3ObjectStorageRepository( override suspend fun put( id: UUID, - bytes: ByteArray, + file: File, contentType: String ) { request { client.putObject { bucket = config.bucket key = getObjectKey(id) - body = ByteStream.fromBytes(bytes) + body = file.asByteStream() this.contentType = contentType - contentLength = bytes.size.toLong() + contentLength = file.length() } } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentCleanupService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentCleanupService.kt new file mode 100644 index 0000000..125ac52 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentCleanupService.kt @@ -0,0 +1,34 @@ +package com.mtusi.messenger.main.infrastructure.services.attachment + +import com.mtusi.messenger.main.infrastructure.repositories.attachment.UploadJournalRepository +import com.mtusi.messenger.main.infrastructure.repositories.attachment.storage.ObjectStorageRepository +import com.mtusi.messenger.main.plugins.suspendedTransaction +import kotlinx.coroutines.CancellationException +import org.koin.core.annotation.Single + +@Single +class AttachmentCleanupService( + private val journalRepository: UploadJournalRepository, + private val objectStorageRepository: ObjectStorageRepository +) { + suspend fun cleanup(): Int { + + val ids = suspendedTransaction { + journalRepository.claimExpired() + } + + var deleted = 0 + ids.forEach { id -> + try { + objectStorageRepository.delete(id) + deleted++ + } catch (cause: CancellationException) { + throw cause + } catch (_: Exception) { + // The durable tombstone remains eligible for the next retry. + } + } + + return deleted + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentService.kt index d649f18..b4fffe5 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentService.kt @@ -1,6 +1,7 @@ package com.mtusi.messenger.main.infrastructure.services.attachment import com.mtusi.messenger.main.infrastructure.dto.Attachment +import java.io.File import java.util.UUID interface AttachmentService { @@ -15,7 +16,7 @@ interface AttachmentService { actorId: UUID, filename: String, contentType: String, - bytes: ByteArray + file: File ): Attachment suspend fun find( diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/DefaultAttachmentService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/DefaultAttachmentService.kt index 9ada44e..ea95a32 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/DefaultAttachmentService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/DefaultAttachmentService.kt @@ -1,6 +1,7 @@ package com.mtusi.messenger.main.infrastructure.services.attachment import com.mtusi.messenger.main.infrastructure.dto.Attachment +import com.mtusi.messenger.main.infrastructure.repositories.attachment.UploadJournalRepository import com.mtusi.messenger.main.infrastructure.repositories.attachment.AttachmentRepository import com.mtusi.messenger.main.infrastructure.repositories.attachment.storage.ObjectStorageRepository import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository @@ -12,11 +13,13 @@ import com.mtusi.messenger.main.utils.nowMicros import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.koin.core.annotation.Single +import java.io.File import java.util.UUID import kotlin.time.Clock @Single class DefaultAttachmentService( + private val journalRepository: UploadJournalRepository, private val attachmentRepository: AttachmentRepository, private val chatRepository: ChatRepository, private val objectStorageRepository: ObjectStorageRepository, @@ -36,27 +39,38 @@ class DefaultAttachmentService( actorId: UUID, filename: String, contentType: String, - bytes: ByteArray + file: File ): Attachment { requireMember(chatId, actorId) - val type = withContext(Dispatchers.IO) { ImageValidator.validate(bytes, contentType) } + val (type, hash) = withContext(Dispatchers.IO) { + val bytes = file.readBytes() + ImageValidator.validate(bytes, contentType) to bytes.computeSha256() + } + val attachment = Attachment( id = UUID.randomUUID(), chatId = chatId, ownerId = actorId, filename = filename, contentType = type, - sizeBytes = bytes.size.toLong(), - sha256 = bytes.computeSha256(), + sizeBytes = file.length(), + sha256 = hash, createdAt = Clock.System.nowMicros() ) - objectStorageRepository.put(attachment.id, bytes, type) + suspendedTransaction { + journalRepository.register(attachment.id) + } + objectStorageRepository.put(attachment.id, file, type) suspendedTransaction { + if (!journalRepository.lockForCompletion(attachment.id)) { + throw ApiException(ErrorCode.UNAVAILABLE, "upload expired") + } attachmentRepository.create(attachment) + journalRepository.complete(attachment.id) } return attachment } diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/AttachmentCleanup.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/AttachmentCleanup.kt new file mode 100644 index 0000000..76f6985 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/AttachmentCleanup.kt @@ -0,0 +1,29 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.infrastructure.services.attachment.AttachmentCleanupService +import io.ktor.server.application.Application +import io.ktor.server.application.log +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import org.koin.ktor.ext.inject +import kotlin.time.Duration.Companion.seconds + +fun Application.configureAttachmentCleanup() { + + val cleanupService by inject() + + launch { + while (isActive) { + delay(30.seconds) + try { + cleanupService.cleanup() + } catch (cause: CancellationException) { + throw cause + } catch (_: Exception) { + log.warn("Attachment cleanup journal is unavailable") + } + } + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt index b85cd6c..d54e0b8 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt @@ -1,6 +1,7 @@ package com.mtusi.messenger.main.plugins import com.mtusi.messenger.main.infrastructure.models.attachment.MessageAttachmentModel +import com.mtusi.messenger.main.infrastructure.models.attachment.UploadJournalModel import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentModel import com.mtusi.messenger.main.config.database.DatabaseConfig import com.mtusi.messenger.main.config.database.SerialDatabaseConfig @@ -120,6 +121,7 @@ private fun generateMigration(description: String) { val tables: Array = arrayOf( AttachmentModel, + UploadJournalModel, MessageAttachmentModel, UserModel, ChatModel, diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/InstantPlusSeconds.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/InstantPlusSeconds.kt new file mode 100644 index 0000000..4c0abd5 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/InstantPlusSeconds.kt @@ -0,0 +1,25 @@ +package com.mtusi.messenger.main.utils.exposed.operations + +import org.jetbrains.exposed.v1.core.Expression +import org.jetbrains.exposed.v1.core.ExpressionWithColumnType +import org.jetbrains.exposed.v1.core.QueryBuilder +import org.jetbrains.exposed.v1.datetime.KotlinInstantColumnType +import kotlin.time.Instant + +class InstantPlusSeconds( + private val instant: Expression, + private val seconds: Expression +) : ExpressionWithColumnType() { + + override val columnType = KotlinInstantColumnType() + + override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { + append("(") + append(instant) + append(" + (") + append(seconds) + append(" * INTERVAL '1 second'))") + } +} + +operator fun Expression.plus(seconds: Expression) = InstantPlusSeconds(this, seconds) diff --git a/src/main/resources/migrations/V5__attachment_uploads.sql b/src/main/resources/migrations/V5__attachment_uploads.sql new file mode 100644 index 0000000..881c871 --- /dev/null +++ b/src/main/resources/migrations/V5__attachment_uploads.sql @@ -0,0 +1,7 @@ +CREATE TABLE attachment_uploads ( + id UUID PRIMARY KEY, + expires_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP + INTERVAL '1 hour'), + abandoned BOOLEAN NOT NULL DEFAULT FALSE, + next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP + INTERVAL '1 hour') +); +CREATE INDEX attachment_uploads_next_attempt_idx ON attachment_uploads(next_attempt_at); diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/attachment/AttachmentControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/attachment/AttachmentControllerTest.kt index b337ae2..a4f16ad 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/attachment/AttachmentControllerTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/attachment/AttachmentControllerTest.kt @@ -39,6 +39,13 @@ class AttachmentControllerTest { assertEquals(HttpStatusCode.NotFound, client.get("$path/content") { auth(outsider) }.status) assertEquals(HttpStatusCode.Unauthorized, client.get("$path/content").status) assertEquals(HttpStatusCode.NotFound, client.get("$path/content?variant=thumbnail") { auth(bob) }.status) + val outsiderChat = client.createChat(outsider, "outsider", listOf(outsider.id)) + assertEquals(HttpStatusCode.NotFound, client.post("/api/v1/chats/${outsiderChat.id}/messages") { + auth(outsider) + idempotencyKey() + contentType(ContentType.Application.Json) + setBody(CreateMessageRequest("", listOf(attachment.id.toString()))) + }.status) val key = "file-$format" suspend fun send(ids: List) = client.post("/api/v1/chats/${chat.id}/messages") { auth(bob) diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentCleanupTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentCleanupTest.kt new file mode 100644 index 0000000..9f1a4ea --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/AttachmentCleanupTest.kt @@ -0,0 +1,124 @@ +package com.mtusi.messenger.main.infrastructure.services.attachment + +import com.mtusi.messenger.main.config.storage.SerialStorageConfig +import com.mtusi.messenger.main.infrastructure.repositories.attachment.ExposedAttachmentRepository +import com.mtusi.messenger.main.infrastructure.repositories.attachment.ExposedUploadJournalRepository +import com.mtusi.messenger.main.infrastructure.repositories.attachment.storage.ObjectStorageRepository +import com.mtusi.messenger.main.infrastructure.repositories.attachment.storage.S3ObjectStorageRepository +import com.mtusi.messenger.main.infrastructure.repositories.chat.ExposedChatRepository +import com.mtusi.messenger.main.infrastructure.types.ApiException +import com.mtusi.messenger.main.plugins.suspendedTransaction +import com.mtusi.messenger.main.support.TestStorage +import com.mtusi.messenger.main.support.createChat +import com.mtusi.messenger.main.support.register +import com.mtusi.messenger.main.support.runApp +import com.mtusi.messenger.main.infrastructure.models.attachment.UploadJournalModel +import com.mtusi.messenger.main.utils.exposed.operations.plus +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.core.longLiteral +import org.jetbrains.exposed.v1.datetime.CurrentTimestamp +import org.jetbrains.exposed.v1.jdbc.update +import java.awt.image.BufferedImage +import java.io.File +import java.nio.file.Files +import java.util.UUID +import javax.imageio.ImageIO +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class AttachmentCleanupTest { + + @Test + fun `orphan cleanup respects grace and fences late publishers`() = runApp { client -> + + val user = client.register("cleanup") + val chat = client.createChat(user, "cleanup", listOf(user.id)) + val journal = ExposedUploadJournalRepository() + val attachments = ExposedAttachmentRepository() + val storage = S3ObjectStorageRepository(SerialStorageConfig( + endpoint = TestStorage.endpoint, + bucket = TestStorage.BUCKET, + accessKey = TestStorage.ACCESS_KEY, + secretKey = TestStorage.SECRET_KEY + )) + val cleanup = AttachmentCleanupService(journal, storage) + + val file = withContext(Dispatchers.IO) { + Files.createTempFile("cleanup-test-", ".png") + }.toFile() + + withContext(Dispatchers.IO) { + ImageIO.write(BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), "png", file) + } + + var orphanId: UUID? = null + val failingStorage = object : ObjectStorageRepository by storage { + override suspend fun put(id: UUID, file: File, contentType: String) { + storage.put(id, file, contentType) + orphanId = id + error("injected failure after PUT, before metadata COMMIT") + } + } + try { + val failingService = DefaultAttachmentService(journal, attachments, ExposedChatRepository(), failingStorage) + + assertFailsWith { + failingService.upload(chat.id, user.id, "file.png", "image/png", file) + } + + val id = requireNotNull(orphanId) + assertEquals(null, suspendedTransaction { attachments.findById(id) }) + assertContentEquals(file.readBytes(), storage.get(id)) + cleanup.cleanup() + assertContentEquals(file.readBytes(), storage.get(id), "fresh upload must survive grace") + + val service = DefaultAttachmentService(journal, attachments, ExposedChatRepository(), storage) + val published = service.upload(chat.id, user.id, "ready.png", "image/png", file) + suspendedTransaction { + UploadJournalModel.update({ UploadJournalModel.id eq id }) { + it[expiresAt] = CurrentTimestamp + longLiteral(-1) + it[nextAttemptAt] = CurrentTimestamp + longLiteral(-1) + } + } + + val unavailableStorage = object : ObjectStorageRepository by storage { + override suspend fun delete(id: UUID) { + error("injected S3 delete outage") + } + } + + assertEquals(0, AttachmentCleanupService(journal, unavailableStorage).cleanup()) + assertContentEquals(file.readBytes(), storage.get(id)) + suspendedTransaction { + UploadJournalModel.update({ UploadJournalModel.id eq id }) { + it[nextAttemptAt] = CurrentTimestamp + longLiteral(-1) + } + } + + assertTrue(cleanup.cleanup() >= 1) + assertFailsWith { storage.get(id) } + assertFalse(suspendedTransaction { journal.lockForCompletion(id) }) + assertContentEquals(file.readBytes(), storage.get(published.id)) + + // A process suspended longer than grace can complete a late PUT, but cannot publish metadata. + storage.put(id, file, "image/png") + suspendedTransaction { + UploadJournalModel.update({ UploadJournalModel.id eq id }) { + it[nextAttemptAt] = CurrentTimestamp + longLiteral(-1) + } + } + + assertTrue(cleanup.cleanup() >= 1) + assertFailsWith { storage.get(id) } + assertContentEquals(file.readBytes(), storage.get(published.id)) + } finally { + file.delete() + } + } +}