Add photo attachments to chat messages
- message_attachments table (cascade with messages); files stored under
chat/{chatId}/ in the images bucket
- POST /api/v1/chats/{chatId}/messages (multipart, up to 10 photos + text);
message is broadcast over WebSocket as before
- photos are always re-encoded so EXIF (geotag, device) never reaches storage
- presigned links (6h) only in participant-checked responses, refresh via
GET /api/v1/chats/{chatId}/attachments/{id}/url
- public /api/v1/files no longer serves or deletes chat/ keys
- chat deletion removes files; orphan cleanup keeps referenced attachments
- rate limit chat-photo: 60/hour
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.startsWith;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
class ChatAttachmentServiceTest {
|
||||
|
||||
private static final byte[] JPEG = {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, 0x00};
|
||||
|
||||
private FileStorageService storage;
|
||||
private ImageOptimizer optimizer;
|
||||
private ChatAttachmentService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
storage = mock(FileStorageService.class);
|
||||
optimizer = mock(ImageOptimizer.class);
|
||||
service = new ChatAttachmentService(storage, optimizer);
|
||||
when(optimizer.reencode(any(), anyString()))
|
||||
.thenReturn(new ImageOptimizer.ReencodedImage(new byte[] {1, 2}, "image/jpeg", ".jpg", 640, 480));
|
||||
}
|
||||
|
||||
private static MultipartFile photo(byte[] content) {
|
||||
return new MockMultipartFile("files", "IMG_0001.jpg", "image/jpeg", content);
|
||||
}
|
||||
|
||||
@Test
|
||||
void photosAreReencodedAndStoredUnderChatPrefix() {
|
||||
List<ChatAttachmentService.StoredPhoto> stored = service.storePhotos(7L, List.of(photo(JPEG)));
|
||||
|
||||
assertThat(stored).singleElement().satisfies(p -> {
|
||||
assertThat(p.objectKey()).startsWith("chat/7/").endsWith(".jpg");
|
||||
assertThat(p.width()).isEqualTo(640);
|
||||
assertThat(p.height()).isEqualTo(480);
|
||||
assertThat(p.sizeBytes()).isEqualTo(2);
|
||||
});
|
||||
verify(storage).putObject(startsWith("chat/7/"), eq(new byte[] {1, 2}), eq("image/jpeg"), eq("IMG_0001.jpg"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tooManyPhotosAreRejectedBeforeUpload() {
|
||||
List<MultipartFile> files = new ArrayList<>();
|
||||
for (int i = 0; i <= ChatAttachmentService.MAX_PHOTOS_PER_MESSAGE; i++) {
|
||||
files.add(photo(JPEG));
|
||||
}
|
||||
|
||||
assertThatThrownBy(() -> service.storePhotos(7L, files))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
verify(storage, never()).putObject(anyString(), any(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void notAnImageIsRejected() {
|
||||
assertThatThrownBy(() -> service.storePhotos(7L, List.of(photo("<svg/>".getBytes()))))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
verify(storage, never()).putObject(anyString(), any(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyUploadedPhotosAreRemovedWhenNextOneFails() {
|
||||
// Первое фото загружается, второе — нет: первое не должно остаться в бакете
|
||||
doNothing().doThrow(new ApiException(ErrorCode.INTERNAL_ERROR, "s3", HttpStatus.INTERNAL_SERVER_ERROR))
|
||||
.when(storage).putObject(anyString(), any(), anyString(), anyString());
|
||||
|
||||
assertThatThrownBy(() -> service.storePhotos(7L, List.of(photo(JPEG), photo(JPEG))))
|
||||
.isInstanceOf(ApiException.class);
|
||||
verify(storage).deleteFile(startsWith("chat/7/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatKeysAreRecognised() {
|
||||
assertThat(ChatAttachmentService.isChatKey("chat/7/a.jpg")).isTrue();
|
||||
assertThat(ChatAttachmentService.isChatKey("avatars/a.jpg")).isFalse();
|
||||
assertThat(ChatAttachmentService.isChatKey(null)).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -10,14 +10,19 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.krylov.refound.dto.ChatDto;
|
||||
import com.krylov.refound.dto.MessageAttachmentDto;
|
||||
import com.krylov.refound.dto.MessageDto;
|
||||
import com.krylov.refound.entity.Chat;
|
||||
import com.krylov.refound.entity.Message;
|
||||
import com.krylov.refound.entity.MessageAttachment;
|
||||
import com.krylov.refound.enums.AttachmentKind;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import com.krylov.refound.enums.PostType;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.ChatRepository;
|
||||
import com.krylov.refound.repository.MessageAttachmentRepository;
|
||||
import com.krylov.refound.repository.MessageRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
@@ -27,6 +32,10 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.transaction.support.TransactionCallback;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.krylov.refound.config.ClusterMessaging;
|
||||
|
||||
class ChatServiceTest {
|
||||
@@ -35,6 +44,8 @@ class ChatServiceTest {
|
||||
private UserRepository userRepository;
|
||||
private PostRepository postRepository;
|
||||
private MessageRepository messageRepository;
|
||||
private MessageAttachmentRepository attachmentRepository;
|
||||
private ChatAttachmentService attachmentService;
|
||||
private ChatService chatService;
|
||||
|
||||
@BeforeEach
|
||||
@@ -43,8 +54,12 @@ class ChatServiceTest {
|
||||
userRepository = mock(UserRepository.class);
|
||||
postRepository = mock(PostRepository.class);
|
||||
messageRepository = mock(MessageRepository.class);
|
||||
attachmentRepository = mock(MessageAttachmentRepository.class);
|
||||
attachmentService = mock(ChatAttachmentService.class);
|
||||
TransactionTemplate tx = mock(TransactionTemplate.class);
|
||||
when(tx.execute(any())).thenAnswer(inv -> inv.<TransactionCallback<?>>getArgument(0).doInTransaction(null));
|
||||
chatService = new ChatService(chatRepository, messageRepository, mock(ClusterMessaging.class),
|
||||
userRepository, postRepository);
|
||||
userRepository, postRepository, attachmentRepository, attachmentService, tx);
|
||||
|
||||
when(userRepository.existsById(anyLong())).thenReturn(true);
|
||||
when(chatRepository.findByUsersAndPost(any(), any(), any())).thenReturn(List.of());
|
||||
@@ -184,4 +199,106 @@ class ChatServiceTest {
|
||||
assertThat(second.getPostId()).isEqualTo(42L);
|
||||
assertThat(second.getPost()).isNull();
|
||||
}
|
||||
|
||||
private Chat chatBetween(long chatId, long userOne, long userTwo) {
|
||||
Chat chat = new Chat();
|
||||
chat.setId(chatId);
|
||||
chat.setUserOneId(userOne);
|
||||
chat.setUserTwoId(userTwo);
|
||||
when(chatRepository.findById(chatId)).thenReturn(Optional.of(chat));
|
||||
return chat;
|
||||
}
|
||||
|
||||
private static MultipartFile photo(String name) {
|
||||
return new MockMultipartFile("files", name, "image/jpeg", new byte[] {1, 2, 3});
|
||||
}
|
||||
|
||||
@Test
|
||||
void photoMessageSavesAttachmentsInOrderAndReturnsLinks() {
|
||||
chatBetween(7L, 14L, 19L);
|
||||
List<MultipartFile> files = List.of(photo("a.jpg"), photo("b.jpg"));
|
||||
when(attachmentService.storePhotos(7L, files)).thenReturn(List.of(
|
||||
new ChatAttachmentService.StoredPhoto("chat/7/a.jpg", "image/jpeg", 100, 800, 600),
|
||||
new ChatAttachmentService.StoredPhoto("chat/7/b.jpg", "image/jpeg", 200, 600, 800)));
|
||||
when(attachmentRepository.saveAll(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(attachmentService.toDto(any())).thenAnswer(inv -> {
|
||||
MessageAttachment a = inv.getArgument(0);
|
||||
return new MessageAttachmentDto(a.getId(), a.getKind(), "https://minio/" + a.getObjectKey(), a.getWidth(), a.getHeight());
|
||||
});
|
||||
|
||||
MessageDto dto = chatService.sendMessageWithPhotos(14L, 7L, null, files);
|
||||
|
||||
assertThat(dto.getContent()).isEmpty();
|
||||
assertThat(dto.getAttachments()).extracting(MessageAttachmentDto::getUrl)
|
||||
.containsExactly("https://minio/chat/7/a.jpg", "https://minio/chat/7/b.jpg");
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<MessageAttachment>> saved = ArgumentCaptor.forClass(List.class);
|
||||
verify(attachmentRepository).saveAll(saved.capture());
|
||||
assertThat(saved.getValue()).extracting(MessageAttachment::getPosition).containsExactly(0, 1);
|
||||
assertThat(saved.getValue()).allSatisfy(a -> {
|
||||
assertThat(a.getMessageId()).isEqualTo(500L);
|
||||
assertThat(a.getChatId()).isEqualTo(7L);
|
||||
assertThat(a.getKind()).isEqualTo(AttachmentKind.PHOTO);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void outsiderCannotUploadPhotosToChat() {
|
||||
chatBetween(7L, 14L, 19L);
|
||||
|
||||
assertThatThrownBy(() -> chatService.sendMessageWithPhotos(99L, 7L, "привет", List.of(photo("a.jpg"))))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||
// Проверка прав — до загрузки, иначе посторонний клал бы файлы в хранилище
|
||||
verify(attachmentService, never()).storePhotos(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void messageWithoutPhotosAndTextIsRejected() {
|
||||
chatBetween(7L, 14L, 19L);
|
||||
|
||||
assertThatThrownBy(() -> chatService.sendMessageWithPhotos(14L, 7L, " ", List.of()))
|
||||
.isInstanceOf(ApiException.class);
|
||||
verify(attachmentService, never()).storePhotos(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadedPhotosAreDeletedWhenMessageIsNotSaved() {
|
||||
chatBetween(7L, 14L, 19L);
|
||||
List<MultipartFile> files = List.of(photo("a.jpg"));
|
||||
when(attachmentService.storePhotos(7L, files)).thenReturn(List.of(
|
||||
new ChatAttachmentService.StoredPhoto("chat/7/a.jpg", "image/jpeg", 100, 800, 600)));
|
||||
when(messageRepository.save(any(Message.class))).thenThrow(new IllegalStateException("db down"));
|
||||
|
||||
assertThatThrownBy(() -> chatService.sendMessageWithPhotos(14L, 7L, "", files))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
verify(attachmentService).deleteQuietly(List.of("chat/7/a.jpg"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingChatDeletesItsFiles() {
|
||||
chatBetween(7L, 14L, 19L);
|
||||
when(attachmentRepository.findObjectKeysByChatId(7L)).thenReturn(List.of("chat/7/a.jpg"));
|
||||
|
||||
chatService.deleteChat(7L, 19L);
|
||||
|
||||
verify(chatRepository).deleteById(7L);
|
||||
// Без активной транзакции afterCommit выполняется сразу
|
||||
verify(attachmentService).deleteQuietly(List.of("chat/7/a.jpg"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachmentLinkOnlyForParticipantsAndOwnChat() {
|
||||
chatBetween(7L, 14L, 19L);
|
||||
MessageAttachment attachment = new MessageAttachment();
|
||||
attachment.setObjectKey("chat/7/a.jpg");
|
||||
when(attachmentRepository.findByIdAndChatId(3L, 7L)).thenReturn(Optional.of(attachment));
|
||||
when(attachmentService.url("chat/7/a.jpg")).thenReturn("https://minio/signed");
|
||||
|
||||
assertThat(chatService.getAttachmentUrl(7L, 3L, 14L)).isEqualTo("https://minio/signed");
|
||||
assertThatThrownBy(() -> chatService.getAttachmentUrl(7L, 3L, 99L))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||
// Вложение другого чата по id своего чата не достать
|
||||
assertThatThrownBy(() -> chatService.getAttachmentUrl(7L, 4L, 14L))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import javax.imageio.ImageIO;
|
||||
@@ -66,6 +68,59 @@ class ImageOptimizerTest {
|
||||
assertThat(optimizer.optimize(garbage, "image/jpeg")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void reencodeStripsMetadataEvenFromSmallPhoto() throws IOException {
|
||||
byte[] plain = encode(noise(200, 150, BufferedImage.TYPE_INT_RGB), "jpg");
|
||||
byte[] withExif = withExifSegment(plain, "GPS-55.7558-37.6173");
|
||||
assertThat(new String(withExif, StandardCharsets.ISO_8859_1)).contains("GPS-55.7558");
|
||||
|
||||
ImageOptimizer.ReencodedImage result = optimizer.reencode(withExif, "image/jpeg");
|
||||
|
||||
assertThat(result.contentType()).isEqualTo("image/jpeg");
|
||||
assertThat(result.width()).isEqualTo(200);
|
||||
assertThat(result.height()).isEqualTo(150);
|
||||
String content = new String(result.content(), StandardCharsets.ISO_8859_1);
|
||||
assertThat(content).doesNotContain("GPS-55.7558").doesNotContain("Exif");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reencodeDownscalesLargePhoto() throws IOException {
|
||||
byte[] source = encode(noise(4032, 3024, BufferedImage.TYPE_INT_RGB), "jpg");
|
||||
|
||||
ImageOptimizer.ReencodedImage result = optimizer.reencode(source, "image/jpeg");
|
||||
|
||||
assertThat(result.width()).isEqualTo(ImageOptimizer.MAX_DIMENSION);
|
||||
assertThat(result.height()).isEqualTo(1200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reencodeRejectsUnreadableFile() {
|
||||
byte[] garbage = new byte[1024];
|
||||
new Random(1).nextBytes(garbage);
|
||||
|
||||
assertThatThrownBy(() -> optimizer.reencode(garbage, "image/jpeg")).isInstanceOf(IOException.class);
|
||||
}
|
||||
|
||||
/** Вставляет после SOI сегмент APP1 с минимальным EXIF (пустой IFD) и текстом-меткой. */
|
||||
private static byte[] withExifSegment(byte[] jpeg, String marker) {
|
||||
ByteArrayOutputStream payload = new ByteArrayOutputStream();
|
||||
payload.writeBytes("Exif\0\0".getBytes(StandardCharsets.ISO_8859_1));
|
||||
payload.writeBytes(new byte[] {'M', 'M', 0, 42, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0});
|
||||
payload.writeBytes(marker.getBytes(StandardCharsets.ISO_8859_1));
|
||||
byte[] data = payload.toByteArray();
|
||||
int length = data.length + 2;
|
||||
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.write(jpeg, 0, 2);
|
||||
out.write(0xFF);
|
||||
out.write(0xE1);
|
||||
out.write(length >> 8);
|
||||
out.write(length & 0xFF);
|
||||
out.writeBytes(data);
|
||||
out.write(jpeg, 2, jpeg.length - 2);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
/** Шум плохо сжимается — так файл гарантированно тяжелее порога. */
|
||||
private static BufferedImage noise(int width, int height, int type) {
|
||||
BufferedImage image = new BufferedImage(width, height, type);
|
||||
|
||||
@@ -9,6 +9,7 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import com.krylov.refound.config.MinioProperties;
|
||||
import com.krylov.refound.repository.ImageRepository;
|
||||
import com.krylov.refound.repository.MessageAttachmentRepository;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
@@ -30,6 +31,8 @@ class OrphanFileCleanupServiceTest {
|
||||
S3Object.builder().key("used.jpg").lastModified(old).build(),
|
||||
S3Object.builder().key("avatars/legacy.jpg").lastModified(old).build(),
|
||||
S3Object.builder().key("orphan.jpg").lastModified(old).build(),
|
||||
S3Object.builder().key("chat/5/photo.jpg").lastModified(old).build(),
|
||||
S3Object.builder().key("chat/5/deleted-chat.jpg").lastModified(old).build(),
|
||||
S3Object.builder().key("fresh.jpg").lastModified(Instant.now()).build()).build();
|
||||
when(s3.listObjectsV2Paginator(any(ListObjectsV2Request.class)))
|
||||
.thenReturn(new ListObjectsV2Iterable(s3, ListObjectsV2Request.builder().build()));
|
||||
@@ -41,15 +44,20 @@ class OrphanFileCleanupServiceTest {
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
// Старая запись аватара хранит полный URL
|
||||
when(users.findAllAvatarUrls()).thenReturn(List.of("http://minio:9010/refound-images/avatars/legacy.jpg?x=1"));
|
||||
MessageAttachmentRepository attachments = mock(MessageAttachmentRepository.class);
|
||||
when(attachments.findAllObjectKeys()).thenReturn(List.of("chat/5/photo.jpg"));
|
||||
FileStorageService storage = mock(FileStorageService.class);
|
||||
|
||||
new OrphanFileCleanupService(s3, properties, images, users, storage, true, Duration.ofHours(24), 100)
|
||||
new OrphanFileCleanupService(s3, properties, images, users, attachments, storage, true, Duration.ofHours(24), 100)
|
||||
.cleanupOrphanFiles();
|
||||
|
||||
verify(storage).deleteFile("orphan.jpg");
|
||||
verify(storage, never()).deleteFile("used.jpg");
|
||||
verify(storage, never()).deleteFile("avatars/legacy.jpg");
|
||||
verify(storage, never()).deleteFile("fresh.jpg");
|
||||
// Фото чата живёт, пока на него ссылается вложение; файл удалённого чата — сирота
|
||||
verify(storage, never()).deleteFile("chat/5/photo.jpg");
|
||||
verify(storage).deleteFile("chat/5/deleted-chat.jpg");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -58,7 +66,7 @@ class OrphanFileCleanupServiceTest {
|
||||
FileStorageService storage = mock(FileStorageService.class);
|
||||
|
||||
new OrphanFileCleanupService(s3, mock(MinioProperties.class), mock(ImageRepository.class),
|
||||
mock(UserRepository.class), storage, false, Duration.ofHours(24), 100).cleanupOrphanFiles();
|
||||
mock(UserRepository.class), mock(MessageAttachmentRepository.class), storage, false, Duration.ofHours(24), 100).cleanupOrphanFiles();
|
||||
|
||||
verify(storage, never()).deleteFile(anyString());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user