forked from mtusi2026/mtusi2026lab4
ЛР 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 содержит инструкцию именно моего решения.
This commit is contained in:
@@ -0,0 +1,281 @@
|
||||
package ru.mtuci.messenger;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import ru.mtuci.messenger.repository.ChatRepository;
|
||||
import ru.mtuci.messenger.service.UserService;
|
||||
import ru.mtuci.messenger.support.ApiClient;
|
||||
import ru.mtuci.messenger.support.LabContainers;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
class ApiIntegrationTest {
|
||||
|
||||
@LocalServerPort
|
||||
int port;
|
||||
|
||||
@Autowired
|
||||
JsonMapper jsonMapper;
|
||||
|
||||
@Autowired
|
||||
ChatRepository chatRepository;
|
||||
|
||||
@Autowired
|
||||
StringRedisTemplate redis;
|
||||
|
||||
private ApiClient api;
|
||||
|
||||
@DynamicPropertySource
|
||||
static void containers(DynamicPropertyRegistry registry) {
|
||||
LabContainers.register(registry);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void client() {
|
||||
api = new ApiClient(port, jsonMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void healthAndActuatorReportProcessAndDatabase() {
|
||||
ApiClient.Result live = api.get("/health/live", null);
|
||||
assertEquals(200, live.status());
|
||||
assertEquals("ok", live.body().get("status").asString());
|
||||
assertFalse(live.requestId().isBlank());
|
||||
ApiClient.Result ready = api.get("/health/ready", null);
|
||||
assertEquals(200, ready.status());
|
||||
assertEquals("ok", ready.body().get("status").asString());
|
||||
ApiClient.Result actuator = api.get("/actuator/health/readiness", null);
|
||||
assertEquals(200, actuator.status());
|
||||
assertEquals("UP", actuator.body().get("status").asString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void registrationConflictValidationAndRace() throws Exception {
|
||||
String username = name("reg");
|
||||
ApiClient.Result created = api.post("/api/v1/users", api.user(username, "Алиса", "Example-only-not-a-real-secret-123"));
|
||||
assertEquals(201, created.status());
|
||||
assertEquals(username, created.body().get("username").asString());
|
||||
assertTrue(created.body().get("created_at").asString().endsWith("Z"));
|
||||
assertFalse(created.raw().contains("password"));
|
||||
assertEquals(created.requestId(), created.requestId());
|
||||
|
||||
ApiClient.Result conflict = api.post("/api/v1/users", api.user(username, "Алиса", "Example-only-not-a-real-secret-123"));
|
||||
assertEquals(409, conflict.status());
|
||||
assertEquals("conflict", conflict.body().get("error").get("code").asString());
|
||||
assertEquals(conflict.requestId(), conflict.body().get("error").get("request_id").asString());
|
||||
|
||||
ApiClient.Result blank = api.post("/api/v1/users", api.user(name("blank"), " ", "Example-only-not-a-real-secret-123"));
|
||||
assertEquals(400, blank.status());
|
||||
ApiClient.Result extra = api.post("/api/v1/users", Map.of("username", name("extra"), "display_name", "Имя", "password", "Example-only-not-a-real-secret-123", "role", "admin"));
|
||||
assertEquals(400, extra.status());
|
||||
|
||||
String raced = name("race");
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
|
||||
List<Future<Integer>> results = List.of(
|
||||
pool.submit(() -> once(latch, raced)),
|
||||
pool.submit(() -> once(latch, raced))
|
||||
);
|
||||
latch.countDown();
|
||||
int createdCount = 0;
|
||||
int conflictCount = 0;
|
||||
for (Future<Integer> result : results) {
|
||||
int status = result.get();
|
||||
if (status == 201) {
|
||||
createdCount++;
|
||||
} else if (status == 409) {
|
||||
conflictCount++;
|
||||
}
|
||||
}
|
||||
assertEquals(1, createdCount);
|
||||
assertEquals(1, conflictCount);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionLoginLogoutAndIgnoredUserHeader() {
|
||||
String username = name("sess");
|
||||
String password = "Example-only-not-a-real-secret-123";
|
||||
JsonNode user = api.post("/api/v1/users", api.user(username, "Алиса", password)).body();
|
||||
JsonNode other = api.post("/api/v1/users", api.user(name("oth"), "Боб", password)).body();
|
||||
String basic = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
|
||||
ApiClient.Result bad = api.postBasic("/api/v1/auth/sessions", Base64.getEncoder().encodeToString((username + ":wrong-password-xx").getBytes()));
|
||||
assertEquals(401, bad.status());
|
||||
assertTrue(bad.authenticate().toLowerCase().startsWith("basic"));
|
||||
|
||||
ApiClient.Result session = api.postBasic("/api/v1/auth/sessions", basic);
|
||||
assertEquals(201, session.status());
|
||||
assertEquals("Bearer", session.body().get("token_type").asString());
|
||||
assertTrue(session.body().get("token").asString().length() >= 32);
|
||||
assertNotEquals(user.get("id").asString(), session.body().get("token").asString());
|
||||
assertEquals(user.get("id").asString(), session.body().get("user").get("id").asString());
|
||||
String token = session.body().get("token").asString();
|
||||
|
||||
ApiClient.Result basicOnApi = api.postBasic("/api/v1/users/me", basic);
|
||||
assertEquals(401, basicOnApi.status());
|
||||
assertTrue(basicOnApi.authenticate().toLowerCase().startsWith("bearer"));
|
||||
ApiClient.Result headerOnly = api.get("/api/v1/users/me", null, Map.of("X-User-Id", user.get("id").asString()));
|
||||
assertEquals(401, headerOnly.status());
|
||||
ApiClient.Result me = api.get("/api/v1/users/me", token, Map.of("X-User-Id", other.get("id").asString()));
|
||||
assertEquals(200, me.status());
|
||||
assertEquals(user.get("id").asString(), me.body().get("id").asString());
|
||||
|
||||
assertTrue(Boolean.TRUE.equals(redis.hasKey("session:" + UserService.tokenHash(token))));
|
||||
ApiClient.Result logout = api.delete("/api/v1/auth/sessions/current", token);
|
||||
assertEquals(204, logout.status());
|
||||
assertTrue(logout.raw().isBlank());
|
||||
assertFalse(Boolean.TRUE.equals(redis.hasKey("session:" + UserService.tokenHash(token))));
|
||||
assertEquals(401, api.get("/api/v1/users/me", token).status());
|
||||
assertEquals(401, api.delete("/api/v1/auth/sessions/current", token).status());
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatsAreAtomicAndHiddenFromOutsiders() {
|
||||
String password = "Example-only-not-a-real-secret-123";
|
||||
JsonNode alice = register(name("alice"), "Алиса", password);
|
||||
JsonNode bob = register(name("bob"), "Боб", password);
|
||||
String aliceToken = login(alice.get("username").asString(), password);
|
||||
String bobToken = login(bob.get("username").asString(), password);
|
||||
String eveToken = login(register(name("eve"), "Ева", password).get("username").asString(), password);
|
||||
|
||||
String title = "rollback-" + UUID.randomUUID();
|
||||
ApiClient.Result unknown = api.post("/api/v1/chats", aliceToken, Map.of(
|
||||
"title", title,
|
||||
"member_ids", List.of(alice.get("id").asString(), UUID.randomUUID().toString())
|
||||
));
|
||||
assertEquals(400, unknown.status());
|
||||
assertEquals(0, chatRepository.countByTitle(title));
|
||||
|
||||
ApiClient.Result duplicates = api.post("/api/v1/chats", aliceToken, Map.of(
|
||||
"title", "dup-" + UUID.randomUUID(),
|
||||
"member_ids", List.of(alice.get("id").asString(), alice.get("id").asString())
|
||||
));
|
||||
assertEquals(400, duplicates.status());
|
||||
ApiClient.Result withoutSelf = api.post("/api/v1/chats", aliceToken, Map.of(
|
||||
"title", "self-" + UUID.randomUUID(),
|
||||
"member_ids", List.of(bob.get("id").asString())
|
||||
));
|
||||
assertEquals(400, withoutSelf.status());
|
||||
|
||||
ApiClient.Result created = api.post("/api/v1/chats", aliceToken, Map.of(
|
||||
"title", "Контрактный тест",
|
||||
"member_ids", List.of(alice.get("id").asString(), bob.get("id").asString())
|
||||
));
|
||||
assertEquals(201, created.status());
|
||||
String chatId = created.body().get("id").asString();
|
||||
assertEquals(404, api.get("/api/v1/chats/" + chatId, eveToken).status());
|
||||
JsonNode bobList = api.get("/api/v1/chats?limit=100", bobToken).body();
|
||||
assertTrue(containsId(bobList.get("items"), chatId));
|
||||
JsonNode eveList = api.get("/api/v1/chats?limit=100", eveToken).body();
|
||||
assertFalse(containsId(eveList.get("items"), chatId));
|
||||
|
||||
ApiClient.Result second = api.post("/api/v1/chats", aliceToken, Map.of(
|
||||
"title", "Второй",
|
||||
"member_ids", List.of(alice.get("id").asString())
|
||||
));
|
||||
assertEquals(201, second.status());
|
||||
JsonNode page = api.get("/api/v1/chats?limit=1", aliceToken).body();
|
||||
assertEquals(1, page.get("items").size());
|
||||
assertFalse(page.get("next_cursor").isNull());
|
||||
JsonNode next = api.get("/api/v1/chats?limit=1&cursor=" + page.get("next_cursor").asString(), aliceToken).body();
|
||||
assertEquals(1, next.get("items").size());
|
||||
assertNotEquals(page.get("items").get(0).get("id").asString(), next.get("items").get(0).get("id").asString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void messageHistoryUsesKeysetCursor() {
|
||||
String password = "Example-only-not-a-real-secret-123";
|
||||
JsonNode alice = register(name("ma"), "Алиса", password);
|
||||
JsonNode bob = register(name("mb"), "Боб", password);
|
||||
String aliceToken = login(alice.get("username").asString(), password);
|
||||
String bobToken = login(bob.get("username").asString(), password);
|
||||
String eveToken = login(register(name("me"), "Ева", password).get("username").asString(), password);
|
||||
String chatId = api.post("/api/v1/chats", aliceToken, Map.of(
|
||||
"title", "История",
|
||||
"member_ids", List.of(alice.get("id").asString(), bob.get("id").asString())
|
||||
)).body().get("id").asString();
|
||||
String otherChat = api.post("/api/v1/chats", aliceToken, Map.of(
|
||||
"title", "Другой",
|
||||
"member_ids", List.of(alice.get("id").asString())
|
||||
)).body().get("id").asString();
|
||||
|
||||
ApiClient.Result first = sendMessage(aliceToken, chatId, "Привет, мир");
|
||||
ApiClient.Result second = sendMessage(bobToken, chatId, "Сообщение Боба");
|
||||
assertEquals(201, first.status());
|
||||
assertTrue(first.body().get("created_at").asString().matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{6}Z"));
|
||||
assertFalse(first.instanceId().isBlank());
|
||||
assertEquals(first.instanceId(), api.get("/api/v1/users/me", aliceToken).instanceId());
|
||||
assertEquals(alice.get("id").asString(), first.body().get("sender_id").asString());
|
||||
assertEquals(201, second.status());
|
||||
assertEquals(400, sendMessage(aliceToken, chatId, "").status());
|
||||
assertEquals(400, sendMessage(aliceToken, chatId, " ").status());
|
||||
assertEquals(404, sendMessage(eveToken, chatId, "чужое").status());
|
||||
assertEquals(400, api.get("/api/v1/chats/" + chatId + "/messages?limit=0", aliceToken).status());
|
||||
|
||||
JsonNode page = api.get("/api/v1/chats/" + chatId + "/messages?limit=1", bobToken).body();
|
||||
assertEquals(1, page.get("items").size());
|
||||
assertEquals(first.body().get("id").asString(), page.get("items").get(0).get("id").asString());
|
||||
String cursor = page.get("next_cursor").asString();
|
||||
JsonNode rest = api.get("/api/v1/chats/" + chatId + "/messages?limit=1&cursor=" + cursor, aliceToken).body();
|
||||
assertEquals(second.body().get("id").asString(), rest.get("items").get(0).get("id").asString());
|
||||
assertTrue(rest.get("next_cursor").isNull());
|
||||
assertEquals(400, api.get("/api/v1/chats/" + otherChat + "/messages?cursor=" + cursor, aliceToken).status());
|
||||
}
|
||||
|
||||
private int once(CountDownLatch latch, String username) throws Exception {
|
||||
latch.await();
|
||||
return api.post("/api/v1/users", api.user(username, "Гонка", "Example-only-not-a-real-secret-123")).status();
|
||||
}
|
||||
|
||||
private JsonNode register(String username, String displayName, String password) {
|
||||
ApiClient.Result result = api.post("/api/v1/users", api.user(username, displayName, password));
|
||||
assertEquals(201, result.status());
|
||||
return result.body();
|
||||
}
|
||||
|
||||
private String login(String username, String password) {
|
||||
String basic = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
|
||||
ApiClient.Result session = api.postBasic("/api/v1/auth/sessions", basic);
|
||||
assertEquals(201, session.status());
|
||||
return session.body().get("token").asString();
|
||||
}
|
||||
|
||||
private static boolean containsId(JsonNode items, String id) {
|
||||
for (JsonNode item : items) {
|
||||
if (id.equals(item.get("id").asString())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private ApiClient.Result sendMessage(String token, String chatId, String text) {
|
||||
return api.post("/api/v1/chats/" + chatId + "/messages", token, Map.of("text", text),
|
||||
Map.of("Idempotency-Key", UUID.randomUUID().toString()));
|
||||
}
|
||||
|
||||
private static String name(String prefix) {
|
||||
return (prefix + UUID.randomUUID().toString().replace("-", "")).substring(0, 20);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package ru.mtuci.messenger;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import ru.mtuci.messenger.support.ApiClient;
|
||||
import ru.mtuci.messenger.support.LabContainers;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
class AttachmentIntegrationTest {
|
||||
|
||||
@LocalServerPort
|
||||
int port;
|
||||
|
||||
@Autowired
|
||||
JsonMapper jsonMapper;
|
||||
|
||||
private ApiClient api;
|
||||
private final HttpClient http = HttpClient.newHttpClient();
|
||||
|
||||
@DynamicPropertySource
|
||||
static void containers(DynamicPropertyRegistry registry) {
|
||||
LabContainers.register(registry);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void client() {
|
||||
api = new ApiClient(port, jsonMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadIsPrivateAndReadableByAnotherMember() throws Exception {
|
||||
String password = "Example-only-not-a-real-secret-123";
|
||||
JsonNode alice = register("at", password);
|
||||
JsonNode bob = register("bt", password);
|
||||
JsonNode eve = register("et", password);
|
||||
String aliceToken = login(alice.get("username").asString(), password);
|
||||
String bobToken = login(bob.get("username").asString(), password);
|
||||
String eveToken = login(eve.get("username").asString(), password);
|
||||
String chatId = chat(aliceToken, List.of(alice.get("id").asString(), bob.get("id").asString()));
|
||||
String otherChat = chat(aliceToken, List.of(alice.get("id").asString()));
|
||||
byte[] png = Files.readAllBytes(Path.of("../tests/fixtures/sample.png"));
|
||||
|
||||
HttpResponse<String> created = upload(aliceToken, chatId, "sample.png", "image/png", png);
|
||||
assertEquals(201, created.statusCode());
|
||||
JsonNode attachment = jsonMapper.readTree(created.body());
|
||||
assertEquals("ready", attachment.get("status").asString());
|
||||
assertEquals(sha256(png), attachment.get("sha256").asString());
|
||||
assertEquals(png.length, attachment.get("size_bytes").asInt());
|
||||
assertEquals(false, attachment.has("object_key"));
|
||||
|
||||
HttpResponse<byte[]> download = download(bobToken, attachment.get("id").asString());
|
||||
assertEquals(200, download.statusCode());
|
||||
assertEquals("image/png", download.headers().firstValue("Content-Type").orElse(""));
|
||||
assertArrayEquals(png, download.body());
|
||||
assertEquals(404, api.get("/api/v1/attachments/" + attachment.get("id").asString(), eveToken).status());
|
||||
assertEquals(404, download(eveToken, attachment.get("id").asString()).statusCode());
|
||||
|
||||
ApiClient.Result message = api.post("/api/v1/chats/" + chatId + "/messages", aliceToken,
|
||||
Map.of("text", "", "attachment_ids", List.of(attachment.get("id").asString())),
|
||||
Map.of("Idempotency-Key", UUID.randomUUID().toString()));
|
||||
assertEquals(201, message.status());
|
||||
assertEquals(attachment.get("id").asString(), message.body().get("attachment_ids").get(0).asString());
|
||||
|
||||
HttpResponse<String> badName = upload(aliceToken, chatId, "../secret.png", "image/png", png);
|
||||
assertEquals(400, badName.statusCode());
|
||||
HttpResponse<String> spoofed = upload(aliceToken, chatId, "photo.png", "image/png", new byte[] {1, 2, 3, 4});
|
||||
assertEquals(415, spoofed.statusCode());
|
||||
ApiClient.Result foreign = api.post("/api/v1/chats/" + otherChat + "/messages", aliceToken,
|
||||
Map.of("text", "", "attachment_ids", List.of(attachment.get("id").asString())),
|
||||
Map.of("Idempotency-Key", UUID.randomUUID().toString()));
|
||||
assertEquals(404, foreign.status());
|
||||
}
|
||||
|
||||
private HttpResponse<String> upload(String token, String chatId, String filename, String type, byte[] body) throws Exception {
|
||||
String name = URLEncoder.encode(filename, StandardCharsets.UTF_8);
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(base() + "/api/v1/chats/" + chatId + "/attachments?filename=" + name))
|
||||
.header("Authorization", "Bearer " + token)
|
||||
.header("Content-Type", type)
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(body))
|
||||
.build();
|
||||
return http.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private HttpResponse<byte[]> download(String token, String attachmentId) throws Exception {
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(base() + "/api/v1/attachments/" + attachmentId + "/content"))
|
||||
.header("Authorization", "Bearer " + token)
|
||||
.GET()
|
||||
.build();
|
||||
return http.send(request, HttpResponse.BodyHandlers.ofByteArray());
|
||||
}
|
||||
|
||||
private String base() {
|
||||
return "http://127.0.0.1:" + port;
|
||||
}
|
||||
|
||||
private String chat(String token, List<String> members) {
|
||||
return api.post("/api/v1/chats", token, Map.of("title", "Вложения", "member_ids", members)).body().get("id").asString();
|
||||
}
|
||||
|
||||
private JsonNode register(String prefix, String password) {
|
||||
String username = (prefix + UUID.randomUUID().toString().replace("-", "")).substring(0, 20);
|
||||
ApiClient.Result result = api.post("/api/v1/users", api.user(username, "Алиса", password));
|
||||
assertEquals(201, result.status());
|
||||
return result.body();
|
||||
}
|
||||
|
||||
private String login(String username, String password) {
|
||||
String basic = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
|
||||
ApiClient.Result session = api.postBasic("/api/v1/auth/sessions", basic);
|
||||
assertEquals(201, session.status());
|
||||
return session.body().get("token").asString();
|
||||
}
|
||||
|
||||
private static String sha256(byte[] bytes) throws Exception {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package ru.mtuci.messenger;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import org.testcontainers.postgresql.PostgreSQLContainer;
|
||||
import ru.mtuci.messenger.support.ApiClient;
|
||||
import ru.mtuci.messenger.support.LabContainers;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
|
||||
"spring.data.redis.host=127.0.0.1",
|
||||
"spring.data.redis.port=1",
|
||||
"spring.data.redis.timeout=200ms",
|
||||
"spring.data.redis.connect-timeout=200ms",
|
||||
"spring.datasource.hikari.connection-timeout=1000",
|
||||
"spring.datasource.hikari.validation-timeout=500",
|
||||
"spring.datasource.hikari.maximum-pool-size=2"
|
||||
})
|
||||
@DirtiesContext
|
||||
class DatabaseOutageIntegrationTest {
|
||||
|
||||
private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:16.10");
|
||||
|
||||
static {
|
||||
POSTGRES.start();
|
||||
}
|
||||
|
||||
@LocalServerPort
|
||||
int port;
|
||||
|
||||
@Autowired
|
||||
JsonMapper jsonMapper;
|
||||
|
||||
private ApiClient api;
|
||||
|
||||
@DynamicPropertySource
|
||||
static void database(DynamicPropertyRegistry registry) {
|
||||
registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);
|
||||
registry.add("spring.datasource.username", POSTGRES::getUsername);
|
||||
registry.add("spring.datasource.password", POSTGRES::getPassword);
|
||||
LabContainers.registerS3(registry);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void client() {
|
||||
api = new ApiClient(port, jsonMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(40)
|
||||
void readinessAndWritesFailWhenDatabaseStops() {
|
||||
assertEquals(200, api.get("/health/ready", null).status());
|
||||
POSTGRES.stop();
|
||||
ApiClient.Result ready = api.get("/health/ready", null);
|
||||
assertEquals(503, ready.status());
|
||||
assertEquals("unavailable", ready.body().get("error").get("code").asString());
|
||||
ApiClient.Result register = api.post("/api/v1/users", api.user(
|
||||
("db" + UUID.randomUUID().toString().replace("-", "")).substring(0, 16),
|
||||
"База",
|
||||
"Example-only-not-a-real-secret-123"
|
||||
));
|
||||
assertEquals(503, register.status());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package ru.mtuci.messenger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import ru.mtuci.messenger.support.LabContainers;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@SpringBootTest
|
||||
class HistoryIndexIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
JdbcTemplate jdbc;
|
||||
|
||||
@DynamicPropertySource
|
||||
static void containers(DynamicPropertyRegistry registry) {
|
||||
LabContainers.register(registry);
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyPageUsesCompositeIndex() throws Exception {
|
||||
UUID userId = UUID.randomUUID();
|
||||
UUID chatId = UUID.randomUUID();
|
||||
Instant created = Instant.parse("2026-01-01T00:00:00Z");
|
||||
jdbc.update("insert into users (id, username, display_name, password_hash, created_at) values (?, ?, ?, ?, ?)",
|
||||
userId, ("idx" + userId.toString().replace("-", "")).substring(0, 16), "Индекс", "hash", Timestamp.from(created));
|
||||
jdbc.update("insert into chats (id, title, created_at) values (?, ?, ?)", chatId, "Индекс", Timestamp.from(created));
|
||||
jdbc.update("insert into chat_members (chat_id, user_id, ordinal) values (?, ?, 0)", chatId, userId);
|
||||
|
||||
List<Object[]> batch = new ArrayList<>();
|
||||
for (int index = 0; index < 10_000; index++) {
|
||||
batch.add(new Object[]{UUID.randomUUID(), chatId, userId, "m" + index, Timestamp.from(created.plusMillis(index))});
|
||||
}
|
||||
jdbc.batchUpdate("insert into messages (id, chat_id, sender_id, text, created_at) values (?, ?, ?, ?, ?)", batch);
|
||||
jdbc.execute("analyze messages");
|
||||
String plan = String.join("\n", jdbc.query("""
|
||||
explain (analyze, buffers)
|
||||
select id from messages
|
||||
where chat_id = ?
|
||||
and (created_at, id) > (?, ?)
|
||||
order by created_at asc, id asc
|
||||
limit 50
|
||||
""", (rs, row) -> rs.getString(1), chatId, Timestamp.from(created.plusMillis(5000)), UUID.randomUUID()));
|
||||
Path evidence = Files.isDirectory(Path.of("evidence")) ? Path.of("evidence") : Path.of("..", "evidence");
|
||||
Files.createDirectories(evidence);
|
||||
Files.writeString(evidence.resolve("explain-messages.txt"), plan + "\n");
|
||||
assertTrue(plan.contains("messages_history_idx"), plan);
|
||||
assertTrue(plan.contains("Index Cond"), plan);
|
||||
assertFalse(plan.contains("Seq Scan on messages"), plan);
|
||||
assertFalse(plan.contains("Rows Removed by Filter"), plan);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package ru.mtuci.messenger;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import ru.mtuci.messenger.repository.MessageRepository;
|
||||
import ru.mtuci.messenger.support.ApiClient;
|
||||
import ru.mtuci.messenger.support.LabContainers;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
class IdempotencyIntegrationTest {
|
||||
|
||||
@LocalServerPort
|
||||
int port;
|
||||
|
||||
@Autowired
|
||||
JsonMapper jsonMapper;
|
||||
|
||||
@Autowired
|
||||
MessageRepository messages;
|
||||
|
||||
private ApiClient api;
|
||||
|
||||
@DynamicPropertySource
|
||||
static void containers(DynamicPropertyRegistry registry) {
|
||||
LabContainers.register(registry);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void client() {
|
||||
api = new ApiClient(port, jsonMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void replayConflictAndRejectedKey() {
|
||||
String password = "Example-only-not-a-real-secret-123";
|
||||
JsonNode alice = register(name("ia"), password);
|
||||
String token = login(alice.get("username").asString(), password);
|
||||
String chatId = chat(token, List.of(alice.get("id").asString()));
|
||||
String key = "same-" + UUID.randomUUID();
|
||||
|
||||
ApiClient.Result rejected = send(token, chatId, "ещё не записано", key.replace("same", "bad key"));
|
||||
assertEquals(400, rejected.status());
|
||||
assertFalse(rejected.instanceId().isBlank());
|
||||
assertEquals(400, api.post("/api/v1/chats/" + chatId + "/messages", token, Map.of("text", "без ключа")).status());
|
||||
|
||||
String recover = "recover-" + UUID.randomUUID();
|
||||
assertEquals(400, send(token, chatId, "", recover).status());
|
||||
ApiClient.Result first = send(token, chatId, "Привет, мир", recover);
|
||||
assertEquals(201, first.status());
|
||||
ApiClient.Result replay = send(token, chatId, "Привет, мир", recover);
|
||||
assertEquals(201, replay.status());
|
||||
assertEquals(first.body(), replay.body());
|
||||
assertEquals(409, send(token, chatId, "другой body", recover).status());
|
||||
assertEquals(1, messages.countByChatId(UUID.fromString(chatId)));
|
||||
|
||||
ApiClient.Result fresh = send(token, chatId, "Привет, мир", key);
|
||||
assertEquals(201, fresh.status());
|
||||
assertNotEquals(first.body().get("id").asString(), fresh.body().get("id").asString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameKeyIsIndependentAcrossUsersAndChats() {
|
||||
String password = "Example-only-not-a-real-secret-123";
|
||||
JsonNode alice = register(name("ib"), password);
|
||||
JsonNode bob = register(name("ic"), password);
|
||||
String aliceToken = login(alice.get("username").asString(), password);
|
||||
String bobToken = login(bob.get("username").asString(), password);
|
||||
String shared = chat(aliceToken, List.of(alice.get("id").asString(), bob.get("id").asString()));
|
||||
String other = chat(aliceToken, List.of(alice.get("id").asString()));
|
||||
String key = "shared-" + UUID.randomUUID();
|
||||
|
||||
ApiClient.Result aliceMessage = send(aliceToken, shared, "общий ключ", key);
|
||||
ApiClient.Result bobMessage = send(bobToken, shared, "общий ключ", key);
|
||||
ApiClient.Result otherChat = send(aliceToken, other, "общий ключ", key);
|
||||
assertEquals(201, aliceMessage.status());
|
||||
assertEquals(201, bobMessage.status());
|
||||
assertEquals(201, otherChat.status());
|
||||
assertNotEquals(aliceMessage.body().get("id").asString(), bobMessage.body().get("id").asString());
|
||||
assertNotEquals(aliceMessage.body().get("id").asString(), otherChat.body().get("id").asString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parallelSameKeyCreatesOneMessage() throws Exception {
|
||||
String password = "Example-only-not-a-real-secret-123";
|
||||
JsonNode alice = register(name("ip"), password);
|
||||
String token = login(alice.get("username").asString(), password);
|
||||
String chatId = chat(token, List.of(alice.get("id").asString()));
|
||||
String key = "parallel-" + UUID.randomUUID();
|
||||
int threads = 8;
|
||||
ExecutorService pool = Executors.newFixedThreadPool(threads);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
try {
|
||||
List<Future<ApiClient.Result>> futures = new ArrayList<>();
|
||||
for (int i = 0; i < threads; i++) {
|
||||
futures.add(pool.submit(() -> {
|
||||
start.await();
|
||||
return send(token, chatId, "одно сообщение", key);
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
JsonNode body = null;
|
||||
for (Future<ApiClient.Result> future : futures) {
|
||||
ApiClient.Result result = future.get();
|
||||
assertEquals(201, result.status());
|
||||
if (body == null) {
|
||||
body = result.body();
|
||||
} else {
|
||||
assertEquals(body, result.body());
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
assertEquals(1, messages.countByChatId(UUID.fromString(chatId)));
|
||||
}
|
||||
|
||||
private ApiClient.Result send(String token, String chatId, String text, String key) {
|
||||
return api.post("/api/v1/chats/" + chatId + "/messages", token, Map.of("text", text),
|
||||
Map.of("Idempotency-Key", key));
|
||||
}
|
||||
|
||||
private String chat(String token, List<String> members) {
|
||||
return api.post("/api/v1/chats", token, Map.of("title", "Идемпотентность", "member_ids", members))
|
||||
.body().get("id").asString();
|
||||
}
|
||||
|
||||
private JsonNode register(String username, String password) {
|
||||
ApiClient.Result result = api.post("/api/v1/users", api.user(username, "Алиса", password));
|
||||
assertEquals(201, result.status());
|
||||
return result.body();
|
||||
}
|
||||
|
||||
private String login(String username, String password) {
|
||||
String basic = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
|
||||
ApiClient.Result session = api.postBasic("/api/v1/auth/sessions", basic);
|
||||
assertEquals(201, session.status());
|
||||
return session.body().get("token").asString();
|
||||
}
|
||||
|
||||
private static String name(String prefix) {
|
||||
return (prefix + UUID.randomUUID().toString().replace("-", "")).substring(0, 20);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package ru.mtuci.messenger;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import ru.mtuci.messenger.support.ApiClient;
|
||||
import ru.mtuci.messenger.support.LabContainers;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
|
||||
"spring.data.redis.host=127.0.0.1",
|
||||
"spring.data.redis.port=1",
|
||||
"spring.data.redis.timeout=200ms",
|
||||
"spring.data.redis.connect-timeout=200ms"
|
||||
})
|
||||
class RedisOutageIntegrationTest {
|
||||
|
||||
@LocalServerPort
|
||||
int port;
|
||||
|
||||
@Autowired
|
||||
JsonMapper jsonMapper;
|
||||
|
||||
private ApiClient api;
|
||||
|
||||
@DynamicPropertySource
|
||||
static void database(DynamicPropertyRegistry registry) {
|
||||
registry.add("spring.datasource.url", LabContainers.POSTGRES::getJdbcUrl);
|
||||
registry.add("spring.datasource.username", LabContainers.POSTGRES::getUsername);
|
||||
registry.add("spring.datasource.password", LabContainers.POSTGRES::getPassword);
|
||||
LabContainers.registerS3(registry);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void client() {
|
||||
api = new ApiClient(port, jsonMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void databaseSessionWorksWhenRedisIsDown() {
|
||||
assertEquals(200, api.get("/health/ready", null).status());
|
||||
String username = ("red" + UUID.randomUUID().toString().replace("-", "")).substring(0, 16);
|
||||
String password = "Example-only-not-a-real-secret-123";
|
||||
assertEquals(201, api.post("/api/v1/users", api.user(username, "Кэш", password)).status());
|
||||
String basic = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
|
||||
ApiClient.Result session = api.postBasic("/api/v1/auth/sessions", basic);
|
||||
assertEquals(201, session.status());
|
||||
ApiClient.Result me = api.get("/api/v1/users/me", session.body().get("token").asString());
|
||||
assertEquals(200, me.status());
|
||||
assertEquals(username, me.body().get("username").asString());
|
||||
assertEquals(200, api.get("/actuator/health", null).status());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package ru.mtuci.messenger;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import ru.mtuci.messenger.support.ApiClient;
|
||||
import ru.mtuci.messenger.support.LabContainers;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "app.session-ttl=2s")
|
||||
class SessionExpiryIntegrationTest {
|
||||
|
||||
@LocalServerPort
|
||||
int port;
|
||||
|
||||
@Autowired
|
||||
JsonMapper jsonMapper;
|
||||
|
||||
private ApiClient api;
|
||||
|
||||
@DynamicPropertySource
|
||||
static void containers(DynamicPropertyRegistry registry) {
|
||||
LabContainers.register(registry);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void client() {
|
||||
api = new ApiClient(port, jsonMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredTokenIsRejected() throws Exception {
|
||||
String username = ("exp" + UUID.randomUUID().toString().replace("-", "")).substring(0, 16);
|
||||
String password = "Example-only-not-a-real-secret-123";
|
||||
assertEquals(201, api.post("/api/v1/users", api.user(username, "Срок", password)).status());
|
||||
String basic = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
|
||||
String token = api.postBasic("/api/v1/auth/sessions", basic).body().get("token").asString();
|
||||
assertEquals(200, api.get("/api/v1/users/me", token).status());
|
||||
Thread.sleep(2500);
|
||||
ApiClient.Result expired = api.get("/api/v1/users/me", token);
|
||||
assertEquals(401, expired.status());
|
||||
assertEquals("unauthorized", expired.body().get("error").get("code").asString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package ru.mtuci.messenger.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.mtuci.messenger.exception.PayloadTooLargeException;
|
||||
import ru.mtuci.messenger.exception.UnsupportedMediaException;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class ImageFilesTest {
|
||||
|
||||
@Test
|
||||
void readsFixtureWithoutDecodingPixels() throws Exception {
|
||||
byte[] png = Files.readAllBytes(Path.of("../tests/fixtures/sample.png"));
|
||||
ImageFiles.Image image = ImageFiles.inspect(png, "image/png", 40_000_000);
|
||||
assertEquals("image/png", image.contentType());
|
||||
assertEquals(320, image.width());
|
||||
assertEquals(200, image.height());
|
||||
assertArrayEquals(png, ImageFiles.readLimited(new java.io.ByteArrayInputStream(png), 10_485_760));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSpoofedMimeCorruptAndPixelBomb() {
|
||||
byte[] jpeg = new byte[] {
|
||||
(byte) 0xff, (byte) 0xd8,
|
||||
(byte) 0xff, (byte) 0xc0, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00,
|
||||
(byte) 0xff, (byte) 0xd9
|
||||
};
|
||||
assertEquals(1, ImageFiles.inspect(jpeg, "image/jpeg", 40_000_000).width());
|
||||
assertThrows(UnsupportedMediaException.class, () -> ImageFiles.inspect(jpeg, "image/png", 40_000_000));
|
||||
assertThrows(UnsupportedMediaException.class, () -> ImageFiles.inspect(new byte[] {1, 2, 3}, "image/png", 40_000_000));
|
||||
byte[] bomb = png(8_000, 8_000);
|
||||
assertThrows(PayloadTooLargeException.class, () -> ImageFiles.inspect(bomb, "image/png", 40_000_000));
|
||||
byte[] huge = new byte[8];
|
||||
assertThrows(PayloadTooLargeException.class, () -> ImageFiles.readLimited(new java.io.ByteArrayInputStream(huge), 7));
|
||||
}
|
||||
|
||||
private static byte[] png(int width, int height) {
|
||||
byte[] data = new byte[8 + 12 + 13 + 12];
|
||||
byte[] signature = new byte[] {(byte) 137, 80, 78, 71, 13, 10, 26, 10};
|
||||
System.arraycopy(signature, 0, data, 0, 8);
|
||||
data[11] = 13;
|
||||
data[12] = 'I';
|
||||
data[13] = 'H';
|
||||
data[14] = 'D';
|
||||
data[15] = 'R';
|
||||
putInt(data, 16, width);
|
||||
putInt(data, 20, height);
|
||||
data[24] = 8;
|
||||
data[25] = 2;
|
||||
data[37] = 'I';
|
||||
data[38] = 'E';
|
||||
data[39] = 'N';
|
||||
data[40] = 'D';
|
||||
return data;
|
||||
}
|
||||
|
||||
private static void putInt(byte[] data, int offset, int value) {
|
||||
data[offset] = (byte) (value >>> 24);
|
||||
data[offset + 1] = (byte) (value >>> 16);
|
||||
data[offset + 2] = (byte) (value >>> 8);
|
||||
data[offset + 3] = (byte) value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package ru.mtuci.messenger.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.mtuci.messenger.exception.InvalidRequestException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class TextRulesTest {
|
||||
|
||||
@Test
|
||||
void rejectsBlankAndTooShortPassword() {
|
||||
assertThrows(InvalidRequestException.class, () -> TextRules.displayName(" "));
|
||||
assertThrows(InvalidRequestException.class, () -> TextRules.message(" \n "));
|
||||
assertThrows(InvalidRequestException.class, () -> TextRules.password("short"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package ru.mtuci.messenger.support;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class ApiClient {
|
||||
|
||||
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
|
||||
private final String base;
|
||||
private final JsonMapper json;
|
||||
|
||||
public ApiClient(int port, JsonMapper json) {
|
||||
this.base = "http://127.0.0.1:" + port;
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
public Result get(String path, String token) {
|
||||
return send("GET", path, token, null, null, null);
|
||||
}
|
||||
|
||||
public Result get(String path, String token, Map<String, String> headers) {
|
||||
return send("GET", path, token, null, null, headers);
|
||||
}
|
||||
|
||||
public Result post(String path, Object body) {
|
||||
return send("POST", path, null, null, body, null);
|
||||
}
|
||||
|
||||
public Result post(String path, String token, Object body) {
|
||||
return send("POST", path, token, null, body, null);
|
||||
}
|
||||
|
||||
public Result post(String path, String token, Object body, Map<String, String> headers) {
|
||||
return send("POST", path, token, null, body, headers);
|
||||
}
|
||||
|
||||
public Result postBasic(String path, String basic) {
|
||||
return send("POST", path, null, basic, null, null);
|
||||
}
|
||||
|
||||
public Result delete(String path, String token) {
|
||||
return send("DELETE", path, token, null, null, null);
|
||||
}
|
||||
|
||||
private Result send(String method, String path, String token, String basic, Object body, Map<String, String> extra) {
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(base + path)).timeout(Duration.ofSeconds(20));
|
||||
if (body == null) {
|
||||
builder.method(method, HttpRequest.BodyPublishers.noBody());
|
||||
} else {
|
||||
builder.method(method, HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body), StandardCharsets.UTF_8));
|
||||
builder.header("Content-Type", "application/json");
|
||||
}
|
||||
if (token != null) {
|
||||
builder.header("Authorization", "Bearer " + token);
|
||||
}
|
||||
if (basic != null) {
|
||||
builder.header("Authorization", "Basic " + basic);
|
||||
}
|
||||
if (extra != null) {
|
||||
extra.forEach(builder::header);
|
||||
}
|
||||
try {
|
||||
HttpResponse<String> response = http.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
String raw = response.body() == null ? "" : response.body();
|
||||
JsonNode tree = raw.isBlank() ? null : json.readTree(raw);
|
||||
return new Result(response.statusCode(), response.headers().firstValue("X-Request-Id").orElse(""),
|
||||
response.headers().firstValue("X-Instance-Id").orElse(""),
|
||||
response.headers().firstValue("WWW-Authenticate").orElse(""), tree, raw);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException(method + " " + path, exception);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> user(String username, String displayName, String password) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("username", username);
|
||||
body.put("display_name", displayName);
|
||||
body.put("password", password);
|
||||
return body;
|
||||
}
|
||||
|
||||
public record Result(int status, String requestId, String instanceId, String authenticate, JsonNode body, String raw) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package ru.mtuci.messenger.support;
|
||||
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.testcontainers.containers.GenericContainer;
|
||||
import org.testcontainers.containers.wait.strategy.Wait;
|
||||
import org.testcontainers.postgresql.PostgreSQLContainer;
|
||||
import org.testcontainers.utility.MountableFile;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
public final class LabContainers {
|
||||
|
||||
public static final String S3_ACCESS_KEY = "messenger-test";
|
||||
public static final String S3_SECRET_KEY = "messenger-test-secret";
|
||||
public static final String S3_BUCKET = "messenger-attachments";
|
||||
|
||||
public static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:16.10");
|
||||
public static final GenericContainer<?> REDIS = new GenericContainer<>("redis:7.4.6").withExposedPorts(6379);
|
||||
public static final GenericContainer<?> S3 = new GenericContainer<>("chrislusf/seaweedfs:4.52")
|
||||
.withCopyToContainer(MountableFile.forClasspathResource("s3.json"), "/etc/seaweedfs/s3.json")
|
||||
.withCommand("server", "-ip.bind=0.0.0.0", "-s3", "-s3.config=/etc/seaweedfs/s3.json",
|
||||
"-filer.exposeDirectoryData=false")
|
||||
.withExposedPorts(8333)
|
||||
.waitingFor(Wait.forListeningPort().withStartupTimeout(Duration.ofSeconds(120)));
|
||||
|
||||
static {
|
||||
POSTGRES.start();
|
||||
REDIS.start();
|
||||
S3.start();
|
||||
}
|
||||
|
||||
private LabContainers() {
|
||||
}
|
||||
|
||||
public static void register(DynamicPropertyRegistry registry) {
|
||||
registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);
|
||||
registry.add("spring.datasource.username", POSTGRES::getUsername);
|
||||
registry.add("spring.datasource.password", POSTGRES::getPassword);
|
||||
registry.add("spring.data.redis.host", REDIS::getHost);
|
||||
registry.add("spring.data.redis.port", () -> REDIS.getMappedPort(6379));
|
||||
registerS3(registry);
|
||||
}
|
||||
|
||||
public static void registerS3(DynamicPropertyRegistry registry) {
|
||||
registry.add("app.s3.endpoint", () -> "http://" + S3.getHost() + ":" + S3.getMappedPort(8333));
|
||||
registry.add("app.s3.region", () -> "us-east-1");
|
||||
registry.add("app.s3.bucket", () -> S3_BUCKET);
|
||||
registry.add("app.s3.access-key", () -> S3_ACCESS_KEY);
|
||||
registry.add("app.s3.secret-key", () -> S3_SECRET_KEY);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user