Files
mtusi2026lab4/backend/src/main/java/ru/mtuci/messenger/service/ImageFiles.java
T
ivanstorozhev 0450ba42ad ЛР 4 — БВТ2304 — ivanstorozhev — на 3
Байты вложения лежат в общем S3, метаданные — в PostgreSQL, поэтому остановка загрузившей реплики не мешает другой отдать тот же файл. Idempotency-Key не даёт повторной отправке создать второе сообщение.

Автор / группа: ivanstorozhev, БВТ2304
Целевая оценка (3/4/5): 3
Трек 5, если заявлен: не заявлен

Что реализовано и что перенесено: из lab3 перенесены Spring Boot API, PostgreSQL, Redis-кэш сессий, Argon2id, Liquibase через одноразовый сервис migrate, HAProxy без sticky session, две реплики, X-Instance-Id, обязательный Idempotency-Key, scripts/stop-one.sh и scripts/restart.sh. Добавлены приватный SeaweedFS, таблица attachments, связь сообщения с вложениями и скачивание оригинала через API. Ключ объекта назначает сервер, имя файла только отображается.

Команды запуска из чистого clone:
cp .env.example .env
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build
curl -fsS http://127.0.0.1:8080/health/ready
make test
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
docker compose --env-file .env start api

Результаты проверок и ссылка на REPORT.md: подробности и числа в REPORT.md
make check — PASS: offline skeleton structure, local refs and Python syntax.
make test — PASS: lab4 public API scenario.
make test-persistence ACTION_SCRIPT=scripts/restart.sh — PASS: persistence preserved confirmed data and existing session.
make test-failover ACTION_SCRIPT=scripts/stop-one.sh — PASS: две реплики до отказа, восстановление записи за 1.665 с, 119 успешных записей и 1 ошибка перехода.
mvn -q test в backend/ — 16 тестов без ошибок, включая PNG по содержимому, подмену MIME, опасное имя файла и чужое вложение.
Анонимный GET объекта в сети стенда — HTTP 403.

Ограничения / известные ошибки: трек 5 и полный уровень 4 не делались. Один Docker-хост, единственные PostgreSQL, Redis, SeaweedFS и HAProxy остаются точками отказа. Если процесс умер после PUT и до COMMIT, объект может остаться без строки в БД. Ключ S3 один, с правами Admin. Пик памяти при параллельных загрузках не измерялся. Пока HAProxy не снял backend, часть запросов на останавливаемую реплику завершается ошибкой соединения; повтор с тем же Idempotency-Key безопасен для отправки сообщения.

Источники и использование ИИ: контракт contracts/openapi.json и contracts/README.md; код lab3; Spring Boot 4.1.1, Spring Data JPA, spring-security-crypto, Spring Data Redis, Liquibase, Actuator, MapStruct 1.6.3, OpenAPI Generator 7.17.0, AWS SDK for Java 2.31.50, Bouncy Castle, PostgreSQL 16.10, Redis 7.4.6, HAProxy 3.2.6, SeaweedFS 4.52, Testcontainers. Реализация собрана в Cursor.

Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
Контракт и публичные тесты не ослаблены.
make check и make test выполнены; приложен реальный вывод.
Сценарии отказов своего уровня воспроизведены.
Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
2026-11-05 22:02:47 +03:00

172 lines
6.0 KiB
Java

package ru.mtuci.messenger.service;
import ru.mtuci.messenger.exception.PayloadTooLargeException;
import ru.mtuci.messenger.exception.UnsupportedMediaException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public final class ImageFiles {
private static final byte[] PNG_SIGNATURE = new byte[] {(byte) 137, 80, 78, 71, 13, 10, 26, 10};
private ImageFiles() {
}
public record Image(String contentType, long width, long height) {
}
public static byte[] readLimited(InputStream input, int maxBytes) throws IOException {
byte[] buffer = new byte[8192];
ByteArrayOutputStream body = new ByteArrayOutputStream(Math.min(maxBytes, 64 * 1024));
int total = 0;
int read;
while ((read = input.read(buffer)) >= 0) {
if (read == 0) {
continue;
}
if (total > maxBytes - read) {
throw new PayloadTooLargeException();
}
body.write(buffer, 0, read);
total += read;
}
return body.toByteArray();
}
public static Image inspect(byte[] data, String declaredType, long maxPixels) {
if (data.length == 0) {
throw new UnsupportedMediaException();
}
Image image = "image/png".equals(declaredType) ? png(data) : jpeg(data);
if (image == null || !declaredType.equals(image.contentType()) || image.width() <= 0 || image.height() <= 0) {
throw new UnsupportedMediaException();
}
if (image.width() > maxPixels || image.height() > maxPixels || image.width() * image.height() > maxPixels) {
throw new PayloadTooLargeException();
}
return image;
}
private static Image png(byte[] data) {
if (data.length < 33 || !startsWith(data, PNG_SIGNATURE)) {
return null;
}
int offset = 8;
Long width = null;
Long height = null;
boolean end = false;
while (offset + 12 <= data.length) {
long length = u32(data, offset);
if (length > data.length || offset + 12L + length > data.length) {
return null;
}
String type = new String(data, offset + 4, 4, StandardCharsets.US_ASCII);
if (!type.chars().allMatch(Character::isLetter)) {
return null;
}
if ("IHDR".equals(type)) {
if (length != 13 || width != null || !validPngHeader(data, offset + 8)) {
return null;
}
width = u32(data, offset + 8);
height = u32(data, offset + 12);
}
offset += 12 + (int) length;
if ("IEND".equals(type)) {
end = length == 0;
break;
}
}
if (!end || width == null || offset != data.length) {
return null;
}
return new Image("image/png", width, height);
}
private static boolean validPngHeader(byte[] data, int offset) {
int bitDepth = data[offset + 8] & 0xff;
int color = data[offset + 9] & 0xff;
int compression = data[offset + 10] & 0xff;
int filter = data[offset + 11] & 0xff;
int interlace = data[offset + 12] & 0xff;
if (compression != 0 || filter != 0 || (interlace != 0 && interlace != 1)) {
return false;
}
return switch (color) {
case 0 -> bitDepth == 1 || bitDepth == 2 || bitDepth == 4 || bitDepth == 8 || bitDepth == 16;
case 3 -> bitDepth == 1 || bitDepth == 2 || bitDepth == 4 || bitDepth == 8;
case 2, 4, 6 -> bitDepth == 8 || bitDepth == 16;
default -> false;
};
}
private static Image jpeg(byte[] data) {
if (data.length < 4 || (data[0] & 0xff) != 0xff || (data[1] & 0xff) != 0xd8) {
return null;
}
int offset = 2;
Long width = null;
Long height = null;
while (offset + 1 < data.length) {
if ((data[offset] & 0xff) != 0xff) {
return null;
}
while (offset < data.length && (data[offset] & 0xff) == 0xff) {
offset++;
}
if (offset >= data.length) {
return null;
}
int marker = data[offset++] & 0xff;
if (marker == 0xd9) {
return width == null ? null : new Image("image/jpeg", width, height);
}
if (marker == 0xd8 || marker == 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
continue;
}
if (offset + 1 >= data.length) {
return null;
}
int length = ((data[offset] & 0xff) << 8) | (data[offset + 1] & 0xff);
if (length < 2 || offset + length > data.length) {
return null;
}
if (isStartOfFrame(marker)) {
if (length < 7) {
return null;
}
height = (long) ((data[offset + 3] & 0xff) << 8) | (data[offset + 4] & 0xff);
width = (long) ((data[offset + 5] & 0xff) << 8) | (data[offset + 6] & 0xff);
}
offset += length;
}
return null;
}
private static boolean isStartOfFrame(int marker) {
return marker >= 0xc0 && marker <= 0xcf && marker != 0xc4 && marker != 0xc8 && marker != 0xcc;
}
private static boolean startsWith(byte[] data, byte[] prefix) {
if (data.length < prefix.length) {
return false;
}
for (int i = 0; i < prefix.length; i++) {
if (data[i] != prefix[i]) {
return false;
}
}
return true;
}
private static long u32(byte[] data, int offset) {
return ((data[offset] & 0xffL) << 24)
| ((data[offset + 1] & 0xffL) << 16)
| ((data[offset + 2] & 0xffL) << 8)
| (data[offset + 3] & 0xffL);
}
}