Защита стенда и управление секретами через OpenBao
This commit is contained in:
@@ -0,0 +1,368 @@
|
||||
package com.example.mtusi_messenger;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class MtusiMessengerApplicationTests {
|
||||
|
||||
private static final String USERS_URL = "/api/v1/users";
|
||||
private static final String CHATS_URL = "/api/v1/chats";
|
||||
private static final String SESSIONS_URL = "/api/v1/auth/sessions";
|
||||
private static final String TEST_PASSWORD = "correct horse battery staple";
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
private User alice;
|
||||
private User bob;
|
||||
private User eve;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
String suffix = UUID.randomUUID()
|
||||
.toString()
|
||||
.replace("-", "")
|
||||
.substring(0, 12);
|
||||
|
||||
alice = registerUser("alice_" + suffix, "Alice");
|
||||
bob = registerUser("bob_" + suffix, "Bob");
|
||||
eve = registerUser("eve_" + suffix, "Eve");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturn400WhenJsonIsMalformed() throws Exception {
|
||||
mockMvc.perform(post(USERS_URL)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{ \"username\": "))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andExpect(jsonPath("$.error.code")
|
||||
.value("invalid_request"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturn400WhenPasswordContainsOnlyWhitespace() throws Exception {
|
||||
String requestBody = objectMapper.writeValueAsString(
|
||||
Map.of(
|
||||
"username", "blank_password_" + UUID.randomUUID().toString().substring(0, 8),
|
||||
"display_name", "Blank password probe",
|
||||
"password", " "
|
||||
)
|
||||
);
|
||||
|
||||
mockMvc.perform(post(USERS_URL)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(requestBody))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andExpect(jsonPath("$.error.code")
|
||||
.value("invalid_request"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotAllowNonMemberToReadChatMessages() throws Exception {
|
||||
String chatId = createChat(alice, bob);
|
||||
|
||||
mockMvc.perform(get(CHATS_URL + "/" + chatId + "/messages")
|
||||
.header("Authorization", bearer(eve))
|
||||
.param("limit", "10"))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andExpect(jsonPath("$.error.code")
|
||||
.value("not_found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotAllowNonMemberToSendMessage() throws Exception {
|
||||
String chatId = createChat(alice, bob);
|
||||
|
||||
String requestBody = """
|
||||
{
|
||||
"text": "Hello from Eve"
|
||||
}
|
||||
""";
|
||||
|
||||
mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages")
|
||||
.header("Authorization", bearer(eve))
|
||||
.header("Idempotency-Key", UUID.randomUUID().toString())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(requestBody))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andExpect(jsonPath("$.error.code")
|
||||
.value("not_found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturn400WhenMessageTextIsEmpty() throws Exception {
|
||||
String chatId = createChat(alice, bob);
|
||||
|
||||
String requestBody = """
|
||||
{
|
||||
"text": ""
|
||||
}
|
||||
""";
|
||||
|
||||
mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages")
|
||||
.header("Authorization", bearer(alice))
|
||||
.header("Idempotency-Key", UUID.randomUUID().toString())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(requestBody))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andExpect(jsonPath("$.error.code")
|
||||
.value("invalid_request"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturn400WhenMessageTextIsMissing() throws Exception {
|
||||
String chatId = createChat(alice, bob);
|
||||
|
||||
mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages")
|
||||
.header("Authorization", bearer(alice))
|
||||
.header("Idempotency-Key", UUID.randomUUID().toString())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andExpect(jsonPath("$.error.code")
|
||||
.value("invalid_request"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturn409WhenUsernameAlreadyExists() throws Exception {
|
||||
String requestBody = """
|
||||
{
|
||||
"username": "%s",
|
||||
"display_name": "Another Alice",
|
||||
"password": "correct horse battery staple"
|
||||
}
|
||||
""".formatted(alice.username());
|
||||
|
||||
mockMvc.perform(post(USERS_URL)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(requestBody))
|
||||
.andExpect(status().isConflict())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andExpect(jsonPath("$.error.code")
|
||||
.value("conflict"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnAllMessagesAcrossMultiplePagesWithoutDuplicates()
|
||||
throws Exception {
|
||||
|
||||
String chatId = createChat(alice, bob);
|
||||
|
||||
int messageCount = 5;
|
||||
int pageSize = 2;
|
||||
int expectedPageCount = 3;
|
||||
|
||||
List<String> expectedTexts = new ArrayList<>();
|
||||
|
||||
for (int i = 1; i <= messageCount; i++) {
|
||||
String text = "Message " + i;
|
||||
sendMessage(chatId, alice, text);
|
||||
expectedTexts.add(text);
|
||||
}
|
||||
|
||||
List<String> actualIds = new ArrayList<>();
|
||||
List<String> actualTexts = new ArrayList<>();
|
||||
|
||||
String cursor = null;
|
||||
int pageCount = 0;
|
||||
|
||||
while (true) {
|
||||
var request = get(CHATS_URL + "/" + chatId + "/messages")
|
||||
.header("Authorization", bearer(alice))
|
||||
.param("limit", String.valueOf(pageSize));
|
||||
|
||||
if (cursor != null) {
|
||||
request.param("cursor", cursor);
|
||||
}
|
||||
|
||||
MvcResult result = mockMvc.perform(request)
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andExpect(jsonPath("$.items").isArray())
|
||||
.andReturn();
|
||||
|
||||
JsonNode response = objectMapper.readTree(
|
||||
result.getResponse().getContentAsString()
|
||||
);
|
||||
|
||||
JsonNode items = response.get("items");
|
||||
|
||||
assertNotNull(items);
|
||||
assertTrue(items.size() <= pageSize);
|
||||
|
||||
for (JsonNode item : items) {
|
||||
actualIds.add(item.get("id").asText());
|
||||
actualTexts.add(item.get("text").asText());
|
||||
}
|
||||
|
||||
pageCount++;
|
||||
|
||||
JsonNode nextCursor = response.get("next_cursor");
|
||||
|
||||
if (nextCursor.isNull()) {
|
||||
break;
|
||||
}
|
||||
|
||||
cursor = nextCursor.asText();
|
||||
|
||||
assertFalse(cursor.isBlank(),
|
||||
"next_cursor must not be blank when more pages exist");
|
||||
|
||||
assertTrue(pageCount <= messageCount,
|
||||
"Pagination did not terminate");
|
||||
}
|
||||
|
||||
assertEquals(expectedPageCount, pageCount);
|
||||
|
||||
assertEquals(messageCount, actualIds.size());
|
||||
assertEquals(messageCount, actualTexts.size());
|
||||
|
||||
assertEquals(actualIds.size(), new HashSet<>(actualIds).size());
|
||||
|
||||
assertEquals(expectedTexts, actualTexts);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldIgnoreXUserIdForProtectedEndpoints() throws Exception {
|
||||
mockMvc.perform(get(USERS_URL + "/me")
|
||||
.header("X-User-Id", alice.id()))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(header().string("WWW-Authenticate", "Bearer realm=\"messenger\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRevokeCurrentSession() throws Exception {
|
||||
mockMvc.perform(delete(SESSIONS_URL + "/current")
|
||||
.header("Authorization", bearer(alice)))
|
||||
.andExpect(status().isNoContent());
|
||||
|
||||
mockMvc.perform(get(USERS_URL + "/me")
|
||||
.header("Authorization", bearer(alice)))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(header().string("WWW-Authenticate", "Bearer realm=\"messenger\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectWrongPasswordWithBasicChallenge() throws Exception {
|
||||
String basic = Base64.getEncoder().encodeToString(
|
||||
(alice.username() + ":definitely-wrong-password")
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
|
||||
mockMvc.perform(post(SESSIONS_URL)
|
||||
.header("Authorization", "Basic " + basic))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(header().string(
|
||||
"WWW-Authenticate",
|
||||
"Basic realm=\"messenger\", charset=\"UTF-8\""));
|
||||
}
|
||||
|
||||
private User registerUser(String username, String displayName)
|
||||
throws Exception {
|
||||
|
||||
String requestBody = objectMapper.writeValueAsString(
|
||||
Map.of(
|
||||
"username", username,
|
||||
"display_name", displayName,
|
||||
"password", TEST_PASSWORD
|
||||
)
|
||||
);
|
||||
|
||||
MvcResult result = mockMvc.perform(post(USERS_URL)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(requestBody))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andReturn();
|
||||
|
||||
JsonNode response = objectMapper.readTree(
|
||||
result.getResponse().getContentAsString()
|
||||
);
|
||||
|
||||
String basic = Base64.getEncoder().encodeToString(
|
||||
(username + ":" + TEST_PASSWORD).getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
MvcResult loginResult = mockMvc.perform(post(SESSIONS_URL)
|
||||
.header("Authorization", "Basic " + basic))
|
||||
.andExpect(status().isCreated())
|
||||
.andReturn();
|
||||
JsonNode session = objectMapper.readTree(loginResult.getResponse().getContentAsString());
|
||||
|
||||
return new User(
|
||||
response.get("id").asText(),
|
||||
response.get("username").asText(),
|
||||
session.get("token").asText()
|
||||
);
|
||||
}
|
||||
|
||||
private String createChat(User owner, User member)
|
||||
throws Exception {
|
||||
|
||||
String requestBody = objectMapper.writeValueAsString(
|
||||
java.util.Map.of(
|
||||
"title", "Test chat " + UUID.randomUUID(),
|
||||
"member_ids", List.of(owner.id(), member.id())
|
||||
)
|
||||
);
|
||||
|
||||
MvcResult result = mockMvc.perform(post(CHATS_URL)
|
||||
.header("Authorization", bearer(owner))
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(requestBody))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andReturn();
|
||||
|
||||
JsonNode response = objectMapper.readTree(
|
||||
result.getResponse().getContentAsString()
|
||||
);
|
||||
|
||||
return response.get("id").asText();
|
||||
}
|
||||
|
||||
private void sendMessage(String chatId, User sender, String text)
|
||||
throws Exception {
|
||||
|
||||
String requestBody = objectMapper.writeValueAsString(
|
||||
java.util.Map.of("text", text)
|
||||
);
|
||||
|
||||
mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages")
|
||||
.header("Authorization", bearer(sender))
|
||||
.header("Idempotency-Key", UUID.randomUUID().toString())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(requestBody))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(header().exists("X-Request-Id"));
|
||||
}
|
||||
|
||||
private static String bearer(User user) {
|
||||
return "Bearer " + user.token();
|
||||
}
|
||||
|
||||
private record User(String id, String username, String token) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.example.mtusi_messenger.cache;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class UserCacheTest {
|
||||
|
||||
@Test
|
||||
void shouldEvictJsonNullAndReturnCacheMiss() {
|
||||
UUID userId = UUID.randomUUID();
|
||||
String key = "messenger:user:" + userId;
|
||||
StringRedisTemplate redis = mock(StringRedisTemplate.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ValueOperations<String, String> values = mock(ValueOperations.class);
|
||||
when(redis.opsForValue()).thenReturn(values);
|
||||
when(values.get(key)).thenReturn("null");
|
||||
UserCache cache = new UserCache(redis, new ObjectMapper(), 300);
|
||||
|
||||
assertTrue(cache.find(userId).isEmpty());
|
||||
verify(redis).delete(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.example.mtusi_messenger.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class PasswordConfigTest {
|
||||
@Test
|
||||
void usesArgon2idWithTheDocumentedBaseline() {
|
||||
var encoder = new PasswordConfig().passwordEncoder(19456, 2, 1);
|
||||
String encoded = encoder.encode("correct horse battery staple");
|
||||
|
||||
assertTrue(encoded.startsWith("$argon2id$v=19$m=19456,t=2,p=1$"));
|
||||
assertTrue(encoder.matches("correct horse battery staple", encoded));
|
||||
assertFalse(encoder.matches("wrong password", encoded));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestsUpgradeForWeakerArgon2idHash() {
|
||||
var baseline = new PasswordConfig().passwordEncoder(19456, 2, 1);
|
||||
var weak = new PasswordConfig().passwordEncoder(19456, 2, 1);
|
||||
// A hash with one iteration is created directly to model a legacy row;
|
||||
// PasswordConfig itself deliberately refuses such a weak runtime setup.
|
||||
var legacy = new org.springframework.security.crypto.argon2.Argon2PasswordEncoder(
|
||||
16, 32, 1, 19456, 1);
|
||||
assertTrue(baseline.upgradeEncoding(legacy.encode("legacy password")));
|
||||
assertFalse(baseline.upgradeEncoding(weak.encode("current password")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.example.mtusi_messenger.queue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RetryPolicyTest {
|
||||
@Test
|
||||
void appliesExponentialBackoffWithBoundedJitter() {
|
||||
RetryPolicy policy = new RetryPolicy(Duration.ofSeconds(1), Duration.ofSeconds(30));
|
||||
|
||||
for (int attempt = 2; attempt <= 8; attempt++) {
|
||||
long ceiling = Math.min(30_000L, 1_000L << (attempt - 2));
|
||||
long delay = policy.delayForAttempt(attempt).toMillis();
|
||||
assertTrue(delay >= Math.max(1, ceiling / 2));
|
||||
assertTrue(delay <= ceiling);
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.example.mtusi_messenger.security;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class TrustedClientCertificateFilterTest {
|
||||
private final TrustedClientCertificateFilter filter =
|
||||
new TrustedClientCertificateFilter("spiffe://hla-lab7/lb");
|
||||
|
||||
@Test
|
||||
void rejectsWrongUriEvenWhenTlsAlreadyTrustedTheCertificate() throws Exception {
|
||||
MockHttpServletResponse response = invoke("spiffe://hla-lab7/worker");
|
||||
assertEquals(403, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsExactLoadBalancerUri() throws Exception {
|
||||
MockHttpServletResponse response = invoke("spiffe://hla-lab7/lb");
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
private MockHttpServletResponse invoke(String uri) throws Exception {
|
||||
X509Certificate certificate = mock(X509Certificate.class);
|
||||
when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, uri)));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/health/ready");
|
||||
request.setAttribute("jakarta.servlet.request.X509Certificate",
|
||||
new X509Certificate[]{certificate});
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, new MockFilterChain());
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.repository.AttachmentRepository;
|
||||
import com.example.mtusi_messenger.storage.ObjectStorage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AttachmentReconcilerTest {
|
||||
private static final Instant NOW = Instant.parse("2026-11-11T12:00:00Z");
|
||||
|
||||
@Test
|
||||
void deletesOnlyOrphansOlderThanGracePeriodAndReportsMissingObjects() {
|
||||
AttachmentRepository repository = mock(AttachmentRepository.class);
|
||||
when(repository.findAllObjectKeys()).thenReturn(Set.of(
|
||||
"attachments/present/original", "attachments/missing/original"));
|
||||
FakeStorage storage = new FakeStorage(List.of(
|
||||
object("attachments/present/original", NOW.minusSeconds(7200)),
|
||||
object("attachments/old-orphan/original", NOW.minusSeconds(7200)),
|
||||
object("attachments/fresh-orphan/original", NOW.minusSeconds(30))));
|
||||
AttachmentReconciler reconciler = new AttachmentReconciler(repository, storage,
|
||||
Duration.ofHours(1), false, Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
|
||||
AttachmentReconciler.Report report = reconciler.reconcile();
|
||||
|
||||
assertEquals(List.of("attachments/old-orphan/original"), storage.deleted);
|
||||
assertEquals(1, report.orphanObjects());
|
||||
assertEquals(1, report.deletedObjects());
|
||||
assertEquals(1, report.missingObjects());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dryRunNeverDeletesOldOrphan() {
|
||||
AttachmentRepository repository = mock(AttachmentRepository.class);
|
||||
when(repository.findAllObjectKeys()).thenReturn(Set.of());
|
||||
FakeStorage storage = new FakeStorage(List.of(
|
||||
object("attachments/old-orphan/original", NOW.minusSeconds(7200))));
|
||||
AttachmentReconciler reconciler = new AttachmentReconciler(repository, storage,
|
||||
Duration.ofHours(1), true, Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
|
||||
AttachmentReconciler.Report report = reconciler.reconcile();
|
||||
|
||||
assertEquals(List.of(), storage.deleted);
|
||||
assertEquals(1, report.orphanObjects());
|
||||
assertEquals(0, report.deletedObjects());
|
||||
}
|
||||
|
||||
private static ObjectStorage.StoredObject object(String key, Instant modified) {
|
||||
return new ObjectStorage.StoredObject(key, modified, 100);
|
||||
}
|
||||
|
||||
private static final class FakeStorage implements ObjectStorage {
|
||||
private final List<StoredObject> objects;
|
||||
private final List<String> deleted = new ArrayList<>();
|
||||
|
||||
private FakeStorage(List<StoredObject> objects) {
|
||||
this.objects = objects;
|
||||
}
|
||||
|
||||
@Override public void put(String objectKey, byte[] bytes, String contentType) { }
|
||||
@Override public byte[] get(String objectKey) { return new byte[0]; }
|
||||
@Override public void delete(String objectKey) { deleted.add(objectKey); }
|
||||
@Override public List<StoredObject> list(String prefix) { return objects; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.exception.ApiException;
|
||||
import com.example.mtusi_messenger.model.Attachment;
|
||||
import com.example.mtusi_messenger.model.Chat;
|
||||
import com.example.mtusi_messenger.repository.AttachmentRepository;
|
||||
import com.example.mtusi_messenger.queue.AttachmentJobPublisher;
|
||||
import com.example.mtusi_messenger.storage.ObjectStorage;
|
||||
import com.example.mtusi_messenger.storage.ObjectStorageException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
import org.springframework.transaction.support.TransactionCallback;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class AttachmentServiceTest {
|
||||
private final UUID chatId = UUID.randomUUID();
|
||||
private final UUID ownerId = UUID.randomUUID();
|
||||
private AttachmentRepository repository;
|
||||
private ChatService chats;
|
||||
private InMemoryStorage storage;
|
||||
private AttachmentJobPublisher publisher;
|
||||
private AttachmentService service;
|
||||
private byte[] png;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
repository = mock(AttachmentRepository.class);
|
||||
chats = mock(ChatService.class);
|
||||
storage = new InMemoryStorage();
|
||||
publisher = mock(AttachmentJobPublisher.class);
|
||||
TransactionTemplate transaction = mock(TransactionTemplate.class);
|
||||
when(transaction.execute(any())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
TransactionCallback<Object> callback = invocation.getArgument(0);
|
||||
return callback.doInTransaction(mock(TransactionStatus.class));
|
||||
});
|
||||
when(chats.getAccessible(chatId, ownerId)).thenReturn(
|
||||
new Chat(chatId, "test", List.of(ownerId), Instant.now()));
|
||||
when(repository.saveQueued(any(), any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
service = new AttachmentService(repository, chats, storage, publisher, transaction,
|
||||
10_485_760, 40_000_000, 3, 10_000, false, 2);
|
||||
png = Files.readAllBytes(Path.of("tests", "fixtures", "sample.png"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stagesValidPngAndPublishesDurableJob() {
|
||||
Attachment attachment = service.upload(chatId, ownerId, "photo.png", "image/png",
|
||||
png.length, new ByteArrayInputStream(png));
|
||||
|
||||
assertEquals("photo.png", attachment.filename());
|
||||
assertEquals("image/png", attachment.contentType());
|
||||
assertEquals(png.length, attachment.sizeBytes());
|
||||
assertTrue(attachment.objectKey().matches("attachments/[0-9a-f-]+/original"));
|
||||
assertTrue(attachment.stagingKey().matches("staging/[0-9a-f-]+/original"));
|
||||
assertEquals("queued", attachment.status());
|
||||
assertFalse(attachment.objectKey().contains("photo.png"));
|
||||
assertArrayEquals(png, storage.objects.get(attachment.stagingKey()));
|
||||
assertFalse(storage.objects.containsKey(attachment.objectKey()));
|
||||
verify(repository).saveQueued(eq(attachment), argThat(job -> job.pipelineVersion() == 2));
|
||||
verify(publisher).publish(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMimeSpoofingBeforeS3Write() {
|
||||
ApiException error = assertThrows(ApiException.class, () -> service.upload(
|
||||
chatId, ownerId, "photo.jpg", "image/jpeg", png.length,
|
||||
new ByteArrayInputStream(png)));
|
||||
|
||||
assertEquals(HttpStatus.UNSUPPORTED_MEDIA_TYPE, error.status());
|
||||
assertTrue(storage.objects.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsOversizedBodyBeforeReadingIt() {
|
||||
ApiException error = assertThrows(ApiException.class, () -> service.upload(
|
||||
chatId, ownerId, "photo.png", "image/png", 10_485_761,
|
||||
new ByteArrayInputStream(png)));
|
||||
|
||||
assertEquals(HttpStatus.PAYLOAD_TOO_LARGE, error.status());
|
||||
assertTrue(storage.objects.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAttachmentFromAnotherChat() {
|
||||
UUID attachmentId = UUID.randomUUID();
|
||||
when(repository.findAllByIdsInChat(chatId, List.of(attachmentId))).thenReturn(List.of());
|
||||
|
||||
ApiException error = assertThrows(ApiException.class,
|
||||
() -> service.validateForMessage(chatId, List.of(attachmentId)));
|
||||
|
||||
assertEquals(HttpStatus.NOT_FOUND, error.status());
|
||||
}
|
||||
|
||||
@Test
|
||||
void surfacesS3OutageWithoutWritingMetadata() {
|
||||
storage.failure = true;
|
||||
|
||||
assertThrows(ObjectStorageException.class, () -> service.upload(
|
||||
chatId, ownerId, "photo.png", "image/png", png.length,
|
||||
new ByteArrayInputStream(png)));
|
||||
verify(repository, never()).saveQueued(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void interruptedRequestDoesNotCreateS3Object() {
|
||||
java.io.InputStream source = new java.io.InputStream() {
|
||||
private int position;
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
if (position >= 16_384) {
|
||||
throw new IOException("client disconnected");
|
||||
}
|
||||
return png[position++];
|
||||
}
|
||||
};
|
||||
|
||||
ApiException error = assertThrows(ApiException.class, () -> service.upload(
|
||||
chatId, ownerId, "photo.png", "image/png", -1, source));
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, error.status());
|
||||
assertTrue(storage.objects.isEmpty());
|
||||
verify(repository, never()).saveQueued(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void databaseFailureCompensatesAlreadyWrittenS3Object() {
|
||||
when(repository.saveQueued(any(), any())).thenThrow(new IllegalStateException("database commit failed"));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> service.upload(
|
||||
chatId, ownerId, "photo.png", "image/png", png.length,
|
||||
new ByteArrayInputStream(png)));
|
||||
|
||||
assertTrue(storage.objects.isEmpty(), "compensating delete must remove the orphan");
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadsOnlyAfterChatAuthorization() {
|
||||
Attachment attachment = new Attachment(UUID.randomUUID(), chatId, ownerId, "photo.png",
|
||||
"image/png", png.length, "a".repeat(64), "attachments/key/original",
|
||||
Instant.now(), Instant.now());
|
||||
when(repository.findById(attachment.id())).thenReturn(Optional.of(attachment));
|
||||
storage.objects.put(attachment.objectKey(), png);
|
||||
|
||||
AttachmentService.Download download = service.download(attachment.id(), ownerId);
|
||||
|
||||
verify(chats).getAccessible(chatId, ownerId);
|
||||
assertArrayEquals(png, download.bytes());
|
||||
}
|
||||
|
||||
private static final class InMemoryStorage implements ObjectStorage {
|
||||
private final Map<String, byte[]> objects = new HashMap<>();
|
||||
private boolean failure;
|
||||
|
||||
@Override
|
||||
public void put(String objectKey, byte[] bytes, String contentType) {
|
||||
if (failure) throw new ObjectStorageException("S3 unavailable", new IOExceptionForTest());
|
||||
objects.put(objectKey, bytes.clone());
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] get(String objectKey) {
|
||||
if (failure) throw new ObjectStorageException("S3 unavailable", new IOExceptionForTest());
|
||||
return objects.get(objectKey).clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String objectKey) {
|
||||
objects.remove(objectKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<StoredObject> list(String prefix) {
|
||||
return objects.entrySet().stream()
|
||||
.filter(entry -> entry.getKey().startsWith(prefix))
|
||||
.map(entry -> new StoredObject(entry.getKey(), Instant.now(), entry.getValue().length))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class IOExceptionForTest extends RuntimeException {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.cache.UserCache;
|
||||
import com.example.mtusi_messenger.model.Session;
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import com.example.mtusi_messenger.repository.SessionRepository;
|
||||
import com.example.mtusi_messenger.repository.UserRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AuthenticationServiceTest {
|
||||
@Test
|
||||
void serializesIssuanceAndRevokesSessionsBeyondConfiguredMaximum() {
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
SessionRepository sessions = mock(SessionRepository.class);
|
||||
UserCache cache = mock(UserCache.class);
|
||||
User user = new User(UUID.randomUUID(), "alice", "Alice", Instant.now());
|
||||
when(sessions.save(any(Session.class))).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
AuthenticationService service = new AuthenticationService(users, sessions, cache, 3600, 3);
|
||||
AuthenticationService.IssuedSession issued = service.issueSession(user);
|
||||
|
||||
var order = inOrder(sessions);
|
||||
order.verify(sessions).lockUserSessions(user.id());
|
||||
order.verify(sessions).save(any(Session.class));
|
||||
order.verify(sessions).revokeExcessActive(user.id(), 3);
|
||||
assertEquals(43, issued.token().length());
|
||||
assertTrue(issued.expiresAt().isAfter(Instant.now().plusSeconds(3500)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.repository.AttachmentRepository;
|
||||
import com.example.mtusi_messenger.storage.ObjectStorage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class StagingCleanerTest {
|
||||
private static final Instant NOW = Instant.parse("2026-11-18T12:00:00Z");
|
||||
|
||||
@Test
|
||||
void keepsActiveAndFreshStagingButDeletesExpiredUnreferencedObject() {
|
||||
AttachmentRepository repository = mock(AttachmentRepository.class);
|
||||
when(repository.findActiveStagingKeys()).thenReturn(Set.of("staging/active/original"));
|
||||
FakeStorage storage = new FakeStorage(List.of(
|
||||
object("staging/active/original", NOW.minusSeconds(172800)),
|
||||
object("staging/failed/original", NOW.minusSeconds(172800)),
|
||||
object("staging/fresh/original", NOW.minusSeconds(60))));
|
||||
StagingCleaner cleaner = new StagingCleaner(repository, storage, Duration.ofDays(1),
|
||||
Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
|
||||
cleaner.cleanup();
|
||||
|
||||
assertEquals(List.of("staging/failed/original"), storage.deleted);
|
||||
}
|
||||
|
||||
private static ObjectStorage.StoredObject object(String key, Instant modified) {
|
||||
return new ObjectStorage.StoredObject(key, modified, 100);
|
||||
}
|
||||
|
||||
private static final class FakeStorage implements ObjectStorage {
|
||||
private final List<StoredObject> objects;
|
||||
private final List<String> deleted = new ArrayList<>();
|
||||
|
||||
private FakeStorage(List<StoredObject> objects) {
|
||||
this.objects = objects;
|
||||
}
|
||||
|
||||
@Override public void put(String objectKey, byte[] bytes, String contentType) { }
|
||||
@Override public byte[] get(String objectKey) { return new byte[0]; }
|
||||
@Override public void delete(String objectKey) { deleted.add(objectKey); }
|
||||
@Override public List<StoredObject> list(String prefix) { return objects; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.example.mtusi_messenger.web;
|
||||
|
||||
import com.example.mtusi_messenger.service.ReadinessService;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ReadinessGuardFilterTest {
|
||||
private final ReadinessService readiness = mock(ReadinessService.class);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final ReadinessGuardFilter filter = new ReadinessGuardFilter(readiness, mapper);
|
||||
|
||||
@Test
|
||||
void refusingReplicaRejectsBusinessTrafficBeforeItReachesTheChain() throws Exception {
|
||||
when(readiness.acceptsBusinessTraffic()).thenReturn(false);
|
||||
var request = new MockHttpServletRequest("GET", "/api/v1/users/me");
|
||||
request.setAttribute(RequestIdFilter.ATTRIBUTE, "request-1");
|
||||
var response = new MockHttpServletResponse();
|
||||
var chain = new MockFilterChain();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertEquals(503, response.getStatus());
|
||||
assertNull(chain.getRequest());
|
||||
JsonNode body = mapper.readTree(response.getContentAsByteArray());
|
||||
assertEquals("unavailable", body.at("/error/code").asText());
|
||||
assertEquals("request-1", body.at("/error/request_id").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readyReplicaPassesBusinessTrafficToTheChain() throws Exception {
|
||||
when(readiness.acceptsBusinessTraffic()).thenReturn(true);
|
||||
var request = new MockHttpServletRequest("GET", "/api/v1/users/me");
|
||||
var response = new MockHttpServletResponse();
|
||||
var chain = new MockFilterChain();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertSame(request, chain.getRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void healthProbeIsNeverBlockedByTheBusinessGuard() throws Exception {
|
||||
when(readiness.acceptsBusinessTraffic()).thenReturn(false);
|
||||
var request = new MockHttpServletRequest("GET", "/health/ready");
|
||||
var response = new MockHttpServletResponse();
|
||||
var chain = new MockFilterChain();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertSame(request, chain.getRequest());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.example.mtusi_messenger.worker;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ImageVariantProcessorTest {
|
||||
private final byte[] original;
|
||||
|
||||
ImageVariantProcessorTest() throws Exception {
|
||||
original = Files.readAllBytes(Path.of("tests", "fixtures", "sample.png"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsThumbnailCropAndOptimizedWebp() throws Exception {
|
||||
ImageVariantProcessor processor = new ImageVariantProcessor(
|
||||
40_000_000, 512L * 1024 * 1024, Duration.ofSeconds(1));
|
||||
|
||||
Map<String, ImageVariantProcessor.GeneratedVariant> variants = processor
|
||||
.createVariants(original, 2).stream()
|
||||
.collect(Collectors.toMap(ImageVariantProcessor.GeneratedVariant::name,
|
||||
Function.identity()));
|
||||
|
||||
assertEquals(3, variants.size());
|
||||
assertImage(variants.get("thumbnail"), "image/jpeg", 256, 160);
|
||||
assertImage(variants.get("crop"), "image/jpeg", 128, 128);
|
||||
assertImage(variants.get("optimized"), "image/webp", 320, 200);
|
||||
byte[] webp = variants.get("optimized").bytes();
|
||||
assertEquals("RIFF", new String(webp, 0, 4, StandardCharsets.US_ASCII));
|
||||
assertEquals("WEBP", new String(webp, 8, 4, StandardCharsets.US_ASCII));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsImageWhoseEstimateExceedsWorkerMemoryBudget() {
|
||||
ImageVariantProcessor processor = new ImageVariantProcessor(
|
||||
40_000_000, 1L * 1024 * 1024, Duration.ofSeconds(1));
|
||||
|
||||
var error = assertThrows(ImageVariantProcessor.ProcessingException.class,
|
||||
() -> processor.createVariants(original, 2));
|
||||
|
||||
assertTrue(error.permanent());
|
||||
assertEquals("image_too_large", error.errorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionsProduceSeparateDeterministicProfiles() {
|
||||
ImageVariantProcessor processor = new ImageVariantProcessor(
|
||||
40_000_000, 512L * 1024 * 1024, Duration.ofSeconds(1));
|
||||
|
||||
Map<String, ImageVariantProcessor.GeneratedVariant> version1 = processor
|
||||
.createVariants(original, 1).stream()
|
||||
.collect(Collectors.toMap(ImageVariantProcessor.GeneratedVariant::name,
|
||||
Function.identity()));
|
||||
Map<String, ImageVariantProcessor.GeneratedVariant> version2 = processor
|
||||
.createVariants(original, 2).stream()
|
||||
.collect(Collectors.toMap(ImageVariantProcessor.GeneratedVariant::name,
|
||||
Function.identity()));
|
||||
|
||||
assertFalse(Arrays.equals(version1.get("optimized").bytes(),
|
||||
version2.get("optimized").bytes()));
|
||||
assertTrue(Arrays.equals(version2.get("optimized").bytes(),
|
||||
processor.createVariants(original, 2).stream()
|
||||
.filter(item -> item.name().equals("optimized"))
|
||||
.findFirst().orElseThrow().bytes()));
|
||||
}
|
||||
|
||||
private static void assertImage(
|
||||
ImageVariantProcessor.GeneratedVariant variant,
|
||||
String contentType, int width, int height) throws Exception {
|
||||
assertNotNull(variant);
|
||||
assertEquals(contentType, variant.contentType());
|
||||
assertEquals(width, variant.width());
|
||||
assertEquals(height, variant.height());
|
||||
var decoded = ImageIO.read(new ByteArrayInputStream(variant.bytes()));
|
||||
assertNotNull(decoded);
|
||||
assertEquals(width, decoded.getWidth());
|
||||
assertEquals(height, decoded.getHeight());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user