diff --git a/REPORT.md b/REPORT.md index 050eb6f3..e8e94daa 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,8 +1,8 @@ # Отчёт — лабораторная 4 - Автор, группа: Кучерявенко Максим, БВТ2303 -- Целевая оценка: **4**. Уровень 3 сохранён; исследовательский трек 5 не заявлен. -- Commit/PR: после просмотра и публикации. +- Целевая оценка: **4** +- 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). @@ -69,15 +69,15 @@ MinIO RELEASE.2025-09-07T16-13-09Z и mc RELEASE.2025-08-13T08-35-41Z закре 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. +Сообщение допускает пустой текст с 1–10 уникальными вложениями этого чата. Член чата может прикрепить загруженный другим участником файл. Создание сообщения, связей и результата Idempotency-Key выполняется в одной транзакции. Отсутствующий attachment_ids и [] равнозначны; повтор возвращает тот же Message. Hash дополнен вложениями, при replay дополнительно сравниваются исходный текст и список ID. Старые текстовые ключи lab3 остаются пригодны для replay. Сохраняются keyset-пагинация, отзыв сессий между репликами и graceful shutdown. Вложения всей страницы выбираются одним дополнительным DSL-запросом и группируются по message_id; тест страницы из 100 сообщений проверяет ровно два SQL-запроса и сохранение порядка вложений. ### Ограничения входных данных - Тело читается из канала порциями до 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. -- Приём 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. +- Затем выполняется полное декодирование, чтобы одного корректного заголовка было недостаточно. Ошибки/предупреждения декодера — 415. Для PNG дополнительно проверяются границы chunks, CRC и IEND, для JPEG — завершающий EOI. ImageIO использует `ignoreMetadata=true`: сжатые zTXt/iTXt не накапливаются. Регрессионный тест покрывает 5000 текстовых chunks. +- Filename: 1–255 Unicode code points, не только пробелы; `/`, `\`, NUL и управляющие символы — 400. +- Приём HTTP и S3 PUT потоковые: тело поступает в уникальный временный файл, AWS SDK читает его через `asByteStream()`. `withTemporaryUpload` создаёт файл и выполняет весь жизненный цикл внутри `Dispatchers.IO`; `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 после передачи запроса не включается. ## Доказательства критериев @@ -87,11 +87,12 @@ Upload: Bearer-аутентификация → проверка членств | Критерий | Команда/сценарий | Наблюдение | Доказательство | | --- | --- | --- | --- | | Контракт, 201 ready, checksum, сообщение с вложением, ACL | `make test` | PASS публичного сценария lab4 | [smoke.txt](evidence/smoke.txt) | -| Возможности lab3 и новые проверки | `./gradlew test` | 76 тестов, 0 failures/errors/skipped | [gradle-tests.txt](evidence/gradle-tests.txt) | +| Возможности lab3 и новые проверки | `./gradlew test` | 80 тестов, 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) | +| Ошибочный Content-Type и пробельное имя | AttachmentControllerTest | 400 вместо 500/201 | [gradle-tests.txt](evidence/gradle-tests.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) | @@ -130,4 +131,4 @@ Bootstrap повторно создаёт/обновляет пользоват Вход и 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). +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). \ No newline at end of file diff --git a/evidence/gradle-tests.txt b/evidence/gradle-tests.txt index 41ab5ef6..62ca73ed 100644 --- a/evidence/gradle-tests.txt +++ b/evidence/gradle-tests.txt @@ -1,6 +1,6 @@ Command: ./gradlew test BUILD SUCCESSFUL -Tests: 76; failures: 0; errors: 0; skipped: 0 +Tests: 80; 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() @@ -14,9 +14,12 @@ 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.repositories.message.MessageAttachmentsQueryTest: tests=1 failures=0 + history loads ordered attachment links in one query for the entire page() 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 +com.mtusi.messenger.main.infrastructure.services.attachment.ImageValidatorTest: tests=3 failures=0 + compressed text metadata does not consume the decoded image memory budget() 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 @@ -27,3 +30,6 @@ com.mtusi.messenger.main.plugins.DatabaseMigrationTest: tests=1 failures=0 com.mtusi.messenger.main.plugins.DependencyFailureTest: tests=5 failures=0 com.mtusi.messenger.main.plugins.InstanceIdTest: tests=1 failures=0 com.mtusi.messenger.main.plugins.SessionCacheTest: tests=3 failures=0 +com.mtusi.messenger.main.utils.TemporaryUploadTest: tests=2 failures=0 + temporary file is removed when upload is cancelled() + temporary file is removed on success and failure() 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 48176763..6ae1f5a8 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,7 +15,7 @@ import io.ktor.server.routing.* import io.ktor.utils.io.readAvailable import kotlinx.coroutines.withTimeoutOrNull import org.koin.ktor.ext.inject -import java.nio.file.Files +import com.mtusi.messenger.main.utils.withTemporaryUpload import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Semaphore @@ -39,11 +39,15 @@ fun Routing.configureAttachmentRouting() { val filename = call.request.queryParameters["filename"] ?: throw ApiException(ErrorCode.INVALID_REQUEST, "filename is required") - if (filename.codePointCount(0, filename.length) !in 1..255 || filename.any { it == '/' || it == '\\' || it.isISOControl() }) { + if (filename.isBlank() || filename.codePointCount(0, filename.length) !in 1..255 || filename.any { it == '/' || it == '\\' || it.isISOControl() }) { throw ApiException(ErrorCode.INVALID_REQUEST, "invalid filename") } - val type = call.request.contentType().withoutParameters().toString() + val type = try { + call.request.contentType().withoutParameters().toString().lowercase() + } catch (_: BadContentTypeFormatException) { + throw ApiException(ErrorCode.INVALID_REQUEST, "invalid Content-Type") + } if (type !in setOf("image/png", "image/jpeg")) { throw ApiException(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "expected PNG or JPEG") } @@ -53,8 +57,7 @@ fun Routing.configureAttachmentRouting() { } uploads.withPermit { - val file = Files.createTempFile("messenger-upload-", ".bin").toFile() - try { + withTemporaryUpload { file -> withTimeoutOrNull(15_000.milliseconds) { withContext(Dispatchers.IO) { val input = call.receiveChannel() @@ -76,8 +79,6 @@ fun Routing.configureAttachmentRouting() { val attachment = service.upload(chatId, actor.id, filename, type, file) call.respond(HttpStatusCode.Created, attachment) - } finally { - file.delete() } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/AttachmentRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/AttachmentRepository.kt index 7afb7dfb..1487d761 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/AttachmentRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/AttachmentRepository.kt @@ -15,4 +15,6 @@ interface AttachmentRepository { ) fun idsForMessage(messageId: UUID): List + + fun idsForMessages(messageIds: List): Map> } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/ExposedAttachmentRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/ExposedAttachmentRepository.kt index 4c1ebb0e..024c6330 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/ExposedAttachmentRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/attachment/ExposedAttachmentRepository.kt @@ -6,6 +6,7 @@ import com.mtusi.messenger.main.infrastructure.models.attachment.MessageAttachme import org.jetbrains.exposed.v1.jdbc.insert import org.jetbrains.exposed.v1.jdbc.selectAll import org.jetbrains.exposed.v1.core.ResultRow +import org.jetbrains.exposed.v1.core.inList import org.jetbrains.exposed.v1.core.eq import org.jetbrains.exposed.v1.core.SortOrder import org.koin.core.annotation.Single @@ -53,13 +54,24 @@ class ExposedAttachmentRepository : AttachmentRepository { override fun idsForMessage( messageId: UUID ): List { + return idsForMessages(listOf(messageId))[messageId].orEmpty() + } + + override fun idsForMessages( + messageIds: List + ): Map> { + if (messageIds.isEmpty()) { + return emptyMap() + } + return MessageAttachmentModel .selectAll() - .where(MessageAttachmentModel.messageId eq messageId) + .where(MessageAttachmentModel.messageId inList messageIds) .orderBy(MessageAttachmentModel.position to SortOrder.ASC) - .map { - it[MessageAttachmentModel.attachmentId].value - } + .groupBy( + keySelector = { it[MessageAttachmentModel.messageId].value }, + valueTransform = { it[MessageAttachmentModel.attachmentId].value } + ) } private fun ResultRow.toAttachment() = Attachment( diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt index 5456e181..0595efa7 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt @@ -52,7 +52,7 @@ class ExposedMessageRepository( .selectAll() .where(MessageModel.id eq id) .firstOrNull() - ?.toMessage() + ?.toMessage(attachments.idsForMessage(id)) } override fun findPageByChatId( @@ -73,22 +73,26 @@ class ExposedMessageRepository( ) } - return MessageModel + val rows = MessageModel .selectAll() .where(condition) .orderBy(MessageModel.createdAt to SortOrder.ASC, MessageModel.id to SortOrder.ASC) .limit(limit) - .map { - it.toMessage() - } + .toList() + + val attachmentIds = attachments.idsForMessages(rows.map { it[MessageModel.id].value }) + + return rows.map { + it.toMessage(attachmentIds[it[MessageModel.id].value].orEmpty()) + } } - private fun ResultRow.toMessage() = Message( + private fun ResultRow.toMessage(attachmentIds: List) = Message( id = this[MessageModel.id].value, chatId = this[MessageModel.chatId].value, senderId = this[MessageModel.senderId].value, text = this[MessageModel.text], - attachmentIds = attachments.idsForMessage(this[MessageModel.id].value), + attachmentIds = attachmentIds, createdAt = this[MessageModel.createdAt] ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/ImageValidator.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/ImageValidator.kt index 901490a4..c693f2c2 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/ImageValidator.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/ImageValidator.kt @@ -32,7 +32,8 @@ object ImageValidator { val reader = readers.next() try { - reader.input = input + // Ignore optional compressed text metadata to bound memory usage. + reader.setInput(input, false, true) val type = when (reader.formatName.lowercase()) { "png" -> "image/png" diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/TemporaryUpload.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/TemporaryUpload.kt new file mode 100644 index 00000000..9bee2e7e --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/TemporaryUpload.kt @@ -0,0 +1,17 @@ +package com.mtusi.messenger.main.utils + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.File +import java.nio.file.Files + +suspend fun withTemporaryUpload(block: suspend (File) -> T): T = withContext(Dispatchers.IO) { + // Own creation and cleanup in the same context: cancellation during dispatch back + // must not lose a newly created file before a caller can enter its finally block. + val file = Files.createTempFile("messenger-upload-", ".bin").toFile() + try { + block(file) + } finally { + Files.deleteIfExists(file.toPath()) + } +} 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 a4f16ad9..c8181d20 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 @@ -7,12 +7,14 @@ import com.mtusi.messenger.main.support.* import io.ktor.client.call.body import io.ktor.client.request.* import io.ktor.http.* +import io.ktor.http.content.OutgoingContent import java.awt.image.BufferedImage import java.io.ByteArrayOutputStream import javax.imageio.ImageIO import kotlin.test.* class AttachmentControllerTest { + @Test fun `upload originals ACL message links and idempotency`() = runApp { client -> @@ -84,10 +86,21 @@ class AttachmentControllerTest { contentType(ContentType.parse(type)) setBody(bytes) } + val malformedMime = client.post("/api/v1/chats/${chat.id}/attachments?filename=photo.png") { + auth(user) + // Keep the invalid header in raw content so the client does not parse it first. + setBody(object : OutgoingContent.ByteArrayContent() { + override val headers = Headers.build { + append(HttpHeaders.ContentType, "image") + } + override fun bytes() = image("png") + }) + } + assertEquals(HttpStatusCode.BadRequest, malformedMime.status) assertEquals(HttpStatusCode.UnsupportedMediaType, upload("not an image".toByteArray()).status) assertEquals(HttpStatusCode.UnsupportedMediaType, upload(image("png"), "image/jpeg").status) assertEquals(HttpStatusCode.UnsupportedMediaType, upload(image("png").copyOf(40)).status) - for (name in listOf("../x.png", "a\\b.png", "a\n.png", "a\u0000.png", "x".repeat(256))) + for (name in listOf("", " ", "\u2003", "../x.png", "a\\b.png", "a\n.png", "a\u0000.png", "x".repeat(256))) assertEquals(HttpStatusCode.BadRequest, upload(image("png"), name = name).status) assertEquals(HttpStatusCode.PayloadTooLarge, upload(ByteArray(10 * 1024 * 1024 + 1)).status) } diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageAttachmentsQueryTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageAttachmentsQueryTest.kt new file mode 100644 index 00000000..306d23ff --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageAttachmentsQueryTest.kt @@ -0,0 +1,58 @@ +package com.mtusi.messenger.main.infrastructure.repositories.message + +import com.mtusi.messenger.main.infrastructure.dto.Attachment +import com.mtusi.messenger.main.infrastructure.repositories.attachment.ExposedAttachmentRepository +import com.mtusi.messenger.main.plugins.suspendedTransaction +import com.mtusi.messenger.main.support.createChat +import com.mtusi.messenger.main.support.register +import com.mtusi.messenger.main.support.runApp +import java.util.UUID +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.time.Clock + +class MessageAttachmentsQueryTest { + + @Test + fun `history loads ordered attachment links in one query for the entire page`() = runApp { client -> + val user = client.register("historyfiles") + val chat = client.createChat(user, "history", listOf(user.id)) + val attachments = ExposedAttachmentRepository() + val messages = ExposedMessageRepository(attachments) + + suspendedTransaction { + val ids = List(2) { + val id = UUID.randomUUID() + attachments.create(Attachment( + id = id, + chatId = chat.id, + ownerId = user.id, + filename = "file.png", + contentType = "image/png", + sizeBytes = 1, + sha256 = "0".repeat(64), + createdAt = Clock.System.now() + )) + id + } + val created = List(100) { index -> + val message = messages.create(chat.id, user.id, "message $index") + if (index % 2 == 0) { + attachments.attach(message.id, ids.reversed()) + } + message + } + val before = statementCount + val page = messages.findPageByChatId(chat.id, null, 100) + assertEquals(2, statementCount - before) + assertEquals(100, page.size) + val expected = created.mapIndexed { index, message -> + message.id to if (index % 2 == 0) ids.reversed() else emptyList() + }.toMap() + page.forEach { message -> + assertEquals(expected[message.id], message.attachmentIds) + } + assertEquals(ids.reversed(), messages.findById(created.first().id)?.attachmentIds) + } + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/ImageValidatorTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/ImageValidatorTest.kt index 11595fe1..9d627861 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/ImageValidatorTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/attachment/ImageValidatorTest.kt @@ -4,6 +4,8 @@ import com.mtusi.messenger.main.infrastructure.types.ApiException import com.mtusi.messenger.main.infrastructure.types.ErrorCode import java.awt.image.BufferedImage import java.io.ByteArrayOutputStream +import java.io.DataOutputStream +import java.util.zip.DeflaterOutputStream import java.nio.ByteBuffer import java.util.zip.CRC32 import javax.imageio.ImageIO @@ -34,4 +36,49 @@ class ImageValidatorTest { }.code) } } + @Test + fun `compressed text metadata does not consume the decoded image memory budget`() { + val compressed = ByteArrayOutputStream().also { output -> + DeflaterOutputStream(output).use { + it.write(ByteArray(262144) { 65 }) + } + }.toByteArray() + + for (imageType in listOf(BufferedImage.TYPE_INT_RGB, BufferedImage.TYPE_BYTE_INDEXED)) { + val original = ByteArrayOutputStream().also { + ImageIO.write(BufferedImage(2, 2, imageType), "png", it) + }.toByteArray() + val text = "Comment".toByteArray() + byteArrayOf(0, 0) + compressed + val internationalText = "Comment".toByteArray() + byteArrayOf(0, 1, 0, 0, 0) + compressed + val bytes = ByteArrayOutputStream().also { output -> + output.write(original, 0, 33) + repeat(2500) { + output.write(chunk("zTXt", text)) + output.write(chunk("iTXt", internationalText)) + } + output.write(original, 33, original.size - 33) + }.toByteArray() + + // Less than 2 MiB on the wire, over 1 GiB if all text is retained after inflation. + assertTrue(bytes.size < MAX_ATTACHMENT_BYTES) + assertEquals("image/png", ImageValidator.validate(bytes, "image/png")) + } + } + + private fun chunk(type: String, data: ByteArray): ByteArray { + val name = type.toByteArray(Charsets.US_ASCII) + val crc = CRC32().apply { + update(name) + update(data) + } + return ByteArrayOutputStream().also { output -> + DataOutputStream(output).use { + it.writeInt(data.size) + it.write(name) + it.write(data) + it.writeInt(crc.value.toInt()) + } + }.toByteArray() + } + } diff --git a/src/test/kotlin/com/mtusi/messenger/main/utils/TemporaryUploadTest.kt b/src/test/kotlin/com/mtusi/messenger/main/utils/TemporaryUploadTest.kt new file mode 100644 index 00000000..2f942b40 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/utils/TemporaryUploadTest.kt @@ -0,0 +1,43 @@ +package com.mtusi.messenger.main.utils + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import java.io.File +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertFailsWith + +class TemporaryUploadTest { + + @Test + fun `temporary file is removed when upload is cancelled`() = runBlocking { + val created = CompletableDeferred() + val job = launch { + withTemporaryUpload { file -> + created.complete(file) + awaitCancellation() + } + } + val file = created.await() + job.cancelAndJoin() + assertFalse(file.exists()) + } + + @Test + fun `temporary file is removed on success and failure`() = runBlocking { + val completed = withTemporaryUpload { it } + assertFalse(completed.exists()) + + val failure = assertFailsWith { + withTemporaryUpload { + throw UploadFailure(it) + } + } + assertFalse(failure.file.exists()) + } + + private class UploadFailure(val file: File) : IllegalStateException("injected failure") +}