fix(api): use configurable upload limit for author photo / book cover (#783)

This commit is contained in:
James Ward
2026-04-24 03:04:48 -04:00
committed by GitHub
parent 1e197e2868
commit 8765a3e63c
6 changed files with 136 additions and 8 deletions
@@ -12,11 +12,13 @@ import org.booklore.model.dto.CoverImage;
import org.booklore.model.dto.Library; import org.booklore.model.dto.Library;
import org.booklore.model.dto.request.AuthorMatchRequest; import org.booklore.model.dto.request.AuthorMatchRequest;
import org.booklore.model.dto.request.AuthorUpdateRequest; import org.booklore.model.dto.request.AuthorUpdateRequest;
import org.booklore.model.dto.settings.AppSettings;
import org.booklore.model.entity.AuthorEntity; import org.booklore.model.entity.AuthorEntity;
import org.booklore.model.entity.BookMetadataEntity; import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.model.enums.AuditAction; import org.booklore.model.enums.AuditAction;
import org.booklore.model.enums.AuthorMetadataSource; import org.booklore.model.enums.AuthorMetadataSource;
import org.booklore.repository.AuthorRepository; import org.booklore.repository.AuthorRepository;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.audit.AuditService; import org.booklore.service.audit.AuditService;
import org.booklore.service.metadata.DuckDuckGoCoverService; import org.booklore.service.metadata.DuckDuckGoCoverService;
import org.booklore.service.metadata.parser.AuthorParser; import org.booklore.service.metadata.parser.AuthorParser;
@@ -52,6 +54,7 @@ public class AuthorMetadataService {
private final FileService fileService; private final FileService fileService;
private final DuckDuckGoCoverService duckDuckGoCoverService; private final DuckDuckGoCoverService duckDuckGoCoverService;
private final AuthenticationService authenticationService; private final AuthenticationService authenticationService;
private final AppSettingService appSettingService;
public List<AuthorSummary> getAllAuthors() { public List<AuthorSummary> getAllAuthors() {
BookLoreUser user = authenticationService.getAuthenticatedUser(); BookLoreUser user = authenticationService.getAuthenticatedUser();
@@ -211,11 +214,37 @@ public class AuthorMetadataService {
} }
} }
private long getMaxFileUploadSizeMb() {
AppSettings appSettings = this.appSettingService.getAppSettings();
Integer maxFileUploadSizeMb = appSettings.getMaxFileUploadSizeInMb();
if (maxFileUploadSizeMb == null) {
log.warn("Max File Upload Size is unset, defaulting to 0");
return 0L;
}
return maxFileUploadSizeMb.longValue();
}
private void validatePhoto(MultipartFile file) {
if (file.isEmpty()) {
throw ApiError.INVALID_INPUT.createException("Uploaded file is empty");
}
long maxSizeMb = getMaxFileUploadSizeMb();
long maxFileSize = maxSizeMb * 1024 * 1024;
if (file.getSize() > maxFileSize) {
throw ApiError.FILE_TOO_LARGE.createException(maxSizeMb);
}
}
@Transactional @Transactional
public void uploadAuthorPhoto(Long authorId, MultipartFile file) { public void uploadAuthorPhoto(Long authorId, MultipartFile file) {
AuthorEntity author = authorRepository.findById(authorId) AuthorEntity author = authorRepository.findById(authorId)
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId)); .orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
validatePhoto(file);
try { try {
java.awt.image.BufferedImage image = FileService.readImage(file.getInputStream()); java.awt.image.BufferedImage image = FileService.readImage(file.getInputStream());
if (image == null) { if (image == null) {
@@ -3,6 +3,7 @@ package org.booklore.service.metadata;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.booklore.exception.ApiError; import org.booklore.exception.ApiError;
import org.booklore.model.dto.settings.AppSettings;
import org.booklore.model.dto.settings.MetadataPersistenceSettings; import org.booklore.model.dto.settings.MetadataPersistenceSettings;
import org.booklore.model.entity.AuthorEntity; import org.booklore.model.entity.AuthorEntity;
import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookEntity;
@@ -502,13 +503,27 @@ public class BookCoverService {
// SECTION: INTERNAL HELPERS // SECTION: INTERNAL HELPERS
// ========================= // =========================
private long getMaxFileUploadSizeMb() {
AppSettings appSettings = this.appSettingService.getAppSettings();
Integer maxFileUploadSizeMb = appSettings.getMaxFileUploadSizeInMb();
if (maxFileUploadSizeMb == null) {
log.warn("Max File Upload Size is unset, cannot continue");
throw ApiError.INTERNAL_SERVER_ERROR.createException("Max File Upload Size is Unset");
}
return maxFileUploadSizeMb.longValue();
}
private void validateCoverFile(MultipartFile file) { private void validateCoverFile(MultipartFile file) {
if (file.isEmpty()) { if (file.isEmpty()) {
throw ApiError.INVALID_INPUT.createException("Uploaded file is empty"); throw ApiError.INVALID_INPUT.createException("Uploaded file is empty");
} }
long maxFileSize = 5L * 1024 * 1024; long maxSizeMb = getMaxFileUploadSizeMb();
long maxFileSize = maxSizeMb * 1024 * 1024;
if (file.getSize() > maxFileSize) { if (file.getSize() > maxFileSize) {
throw ApiError.FILE_TOO_LARGE.createException(5); throw ApiError.FILE_TOO_LARGE.createException(maxSizeMb);
} }
// Detect MIME from content byte never trust the client-supplied Content-Type header // Detect MIME from content byte never trust the client-supplied Content-Type header
try (var inputStream = file.getInputStream()) { try (var inputStream = file.getInputStream()) {
@@ -2,6 +2,7 @@ package org.booklore.util;
import org.booklore.config.AppProperties; import org.booklore.config.AppProperties;
import org.booklore.exception.ApiError; import org.booklore.exception.ApiError;
import org.booklore.model.dto.settings.AppSettings;
import org.booklore.model.dto.settings.CoverCroppingSettings; import org.booklore.model.dto.settings.CoverCroppingSettings;
import org.booklore.model.entity.BookMetadataEntity; import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.service.appsettings.AppSettingService; import org.booklore.service.appsettings.AppSettingService;
@@ -187,7 +188,20 @@ public class FileService {
// VALIDATION // VALIDATION
// ======================================== // ========================================
private static void validateCoverFile(MultipartFile file) { private long getMaxFileUploadSizeMb() {
AppSettings appSettings = this.appSettingService.getAppSettings();
Integer maxFileUploadSizeMb = appSettings.getMaxFileUploadSizeInMb();
if (maxFileUploadSizeMb == null) {
log.warn("Max File Upload Size is unset, cannot continue");
throw ApiError.INTERNAL_SERVER_ERROR.createException("Max File Upload Size is Unset");
}
return maxFileUploadSizeMb.longValue();
}
private void validateCoverFile(MultipartFile file) {
if (file.isEmpty()) { if (file.isEmpty()) {
throw new IllegalArgumentException("Uploaded file is empty"); throw new IllegalArgumentException("Uploaded file is empty");
} }
@@ -199,8 +213,10 @@ public class FileService {
if (!lowerType.startsWith(JPEG_MIME_TYPE) && !lowerType.startsWith(PNG_MIME_TYPE)) { if (!lowerType.startsWith(JPEG_MIME_TYPE) && !lowerType.startsWith(PNG_MIME_TYPE)) {
throw new IllegalArgumentException("Only JPEG and PNG files are allowed"); throw new IllegalArgumentException("Only JPEG and PNG files are allowed");
} }
if (file.getSize() > MAX_FILE_SIZE_BYTES) { long maxSizeMb = getMaxFileUploadSizeMb();
throw new IllegalArgumentException("File size must not exceed 5 MB"); long maxFileSize = maxSizeMb * 1024 * 1024;
if (file.getSize() > maxFileSize) {
throw ApiError.FILE_TOO_LARGE.createException(maxSizeMb);
} }
} }
@@ -10,6 +10,7 @@ import org.booklore.model.entity.AuthorEntity;
import org.booklore.model.enums.AuditAction; import org.booklore.model.enums.AuditAction;
import org.booklore.model.enums.AuthorMetadataSource; import org.booklore.model.enums.AuthorMetadataSource;
import org.booklore.repository.AuthorRepository; import org.booklore.repository.AuthorRepository;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.audit.AuditService; import org.booklore.service.audit.AuditService;
import org.booklore.service.metadata.DuckDuckGoCoverService; import org.booklore.service.metadata.DuckDuckGoCoverService;
import org.booklore.service.metadata.parser.AuthorParser; import org.booklore.service.metadata.parser.AuthorParser;
@@ -41,6 +42,7 @@ class AuthorMetadataServiceTest {
@Mock private FileService fileService; @Mock private FileService fileService;
@Mock private DuckDuckGoCoverService duckDuckGoCoverService; @Mock private DuckDuckGoCoverService duckDuckGoCoverService;
@Mock private AuthenticationService authenticationService; @Mock private AuthenticationService authenticationService;
@Mock private AppSettingService appSettingService;
private AuthorMetadataService service; private AuthorMetadataService service;
@@ -49,7 +51,16 @@ class AuthorMetadataServiceTest {
Map<AuthorMetadataSource, AuthorParser> authorParserMap = Map.of( Map<AuthorMetadataSource, AuthorParser> authorParserMap = Map.of(
AuthorMetadataSource.AUDNEXUS, authorParser AuthorMetadataSource.AUDNEXUS, authorParser
); );
service = new AuthorMetadataService(authorRepository, authorParserMap, auditService, fileService, duckDuckGoCoverService, authenticationService);
service = new AuthorMetadataService(
authorRepository,
authorParserMap,
auditService,
fileService,
duckDuckGoCoverService,
authenticationService,
appSettingService
);
BookLoreUser.UserPermissions adminPermissions = new BookLoreUser.UserPermissions(); BookLoreUser.UserPermissions adminPermissions = new BookLoreUser.UserPermissions();
adminPermissions.setAdmin(true); adminPermissions.setAdmin(true);
@@ -57,6 +57,7 @@ class BookCoverServiceTest {
@Mock private TransactionTemplate transactionTemplate; @Mock private TransactionTemplate transactionTemplate;
@Mock private Executor taskExecutor; @Mock private Executor taskExecutor;
@Mock private AuthenticationService authenticationService; @Mock private AuthenticationService authenticationService;
@Mock private AppSettings appSettings;
@InjectMocks @InjectMocks
private BookCoverService service; private BookCoverService service;
@@ -396,6 +397,9 @@ class BookCoverServiceTest {
@Test @Test
void filtersOutLockedBooksForBulkOperations() { void filtersOutLockedBooksForBulkOperations() {
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(appSettings.getMaxFileUploadSizeInMb()).thenReturn(5);
BookEntity unlocked = buildBook(1L, false); BookEntity unlocked = buildBook(1L, false);
BookEntity locked = buildBook(2L, true); BookEntity locked = buildBook(2L, true);
@@ -431,6 +435,9 @@ class BookCoverServiceTest {
@Test @Test
void rejectsNonImageContentType() throws Exception { void rejectsNonImageContentType() throws Exception {
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(appSettings.getMaxFileUploadSizeInMb()).thenReturn(5);
MultipartFile file = mock(MultipartFile.class); MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false); when(file.isEmpty()).thenReturn(false);
when(file.getSize()).thenReturn(1024L); when(file.getSize()).thenReturn(1024L);
@@ -442,7 +449,10 @@ class BookCoverServiceTest {
} }
@Test @Test
void rejectsFileLargerThan5MB() { void rejectsFileLargerThanLimit() {
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(appSettings.getMaxFileUploadSizeInMb()).thenReturn(5);
MultipartFile file = mock(MultipartFile.class); MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false); when(file.isEmpty()).thenReturn(false);
when(file.getSize()).thenReturn(6L * 1024 * 1024); when(file.getSize()).thenReturn(6L * 1024 * 1024);
@@ -454,6 +464,9 @@ class BookCoverServiceTest {
@Test @Test
void acceptsJpegFile() { void acceptsJpegFile() {
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(appSettings.getMaxFileUploadSizeInMb()).thenReturn(5);
MultipartFile file = mock(MultipartFile.class); MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false); when(file.isEmpty()).thenReturn(false);
when(file.getSize()).thenReturn(1024L); when(file.getSize()).thenReturn(1024L);
@@ -469,6 +482,9 @@ class BookCoverServiceTest {
@Test @Test
void acceptsPngFile() { void acceptsPngFile() {
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(appSettings.getMaxFileUploadSizeInMb()).thenReturn(5);
MultipartFile file = mock(MultipartFile.class); MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false); when(file.isEmpty()).thenReturn(false);
when(file.getSize()).thenReturn(1024L); when(file.getSize()).thenReturn(1024L);
@@ -484,6 +500,9 @@ class BookCoverServiceTest {
@Test @Test
void rejectsIOExceptionOnRead() throws Exception { void rejectsIOExceptionOnRead() throws Exception {
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(appSettings.getMaxFileUploadSizeInMb()).thenReturn(5);
MultipartFile file = mock(MultipartFile.class); MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false); when(file.isEmpty()).thenReturn(false);
when(file.getSize()).thenReturn(1024L); when(file.getSize()).thenReturn(1024L);
@@ -712,6 +731,9 @@ class BookCoverServiceTest {
@Test @Test
void processesOnlyUnlockedBooks() throws Exception { void processesOnlyUnlockedBooks() throws Exception {
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(appSettings.getMaxFileUploadSizeInMb()).thenReturn(5);
BookEntity unlocked = buildBook(1L, false); BookEntity unlocked = buildBook(1L, false);
BookEntity locked = buildBook(2L, true); BookEntity locked = buildBook(2L, true);
@@ -959,7 +981,6 @@ class BookCoverServiceTest {
book.setLibrary(LibraryEntity.builder().build()); book.setLibrary(LibraryEntity.builder().build());
book.setLibraryPath(LibraryPathEntity.builder().path("/lib").build()); book.setLibraryPath(LibraryPathEntity.builder().path("/lib").build());
AppSettings appSettings = mock(AppSettings.class);
MetadataPersistenceSettings persistSettings = mock(MetadataPersistenceSettings.class); MetadataPersistenceSettings persistSettings = mock(MetadataPersistenceSettings.class);
when(appSettingService.getAppSettings()).thenReturn(appSettings); when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(appSettings.getMetadataPersistenceSettings()).thenReturn(persistSettings); when(appSettings.getMetadataPersistenceSettings()).thenReturn(persistSettings);
@@ -972,6 +972,12 @@ class FileServiceTest {
@Test @Test
void validJpegFile_succeeds() throws IOException { void validJpegFile_succeeds() throws IOException {
when(appSettingService.getAppSettings()).thenReturn(
AppSettings.builder()
.maxFileUploadSizeInMb(5)
.build()
);
BufferedImage image = createTestImage(300, 400); BufferedImage image = createTestImage(300, 400);
byte[] imageBytes = imageToBytes(image); byte[] imageBytes = imageToBytes(image);
MockMultipartFile file = new MockMultipartFile( MockMultipartFile file = new MockMultipartFile(
@@ -984,6 +990,12 @@ class FileServiceTest {
@Test @Test
void validPngFile_succeeds() throws IOException { void validPngFile_succeeds() throws IOException {
when(appSettingService.getAppSettings()).thenReturn(
AppSettings.builder()
.maxFileUploadSizeInMb(5)
.build()
);
BufferedImage image = createTestImage(300, 400); BufferedImage image = createTestImage(300, 400);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", baos); ImageIO.write(image, "PNG", baos);
@@ -1021,6 +1033,12 @@ class FileServiceTest {
@Test @Test
void fileTooLarge_throwsRuntimeException() { void fileTooLarge_throwsRuntimeException() {
when(appSettingService.getAppSettings()).thenReturn(
AppSettings.builder()
.maxFileUploadSizeInMb(5)
.build()
);
byte[] largeData = new byte[6 * 1024 * 1024]; // 6MB byte[] largeData = new byte[6 * 1024 * 1024]; // 6MB
MockMultipartFile largeFile = new MockMultipartFile( MockMultipartFile largeFile = new MockMultipartFile(
"file", "large.jpg", "image/jpeg", largeData); "file", "large.jpg", "image/jpeg", largeData);
@@ -1035,6 +1053,12 @@ class FileServiceTest {
@Test @Test
void fileExactlyAtSizeLimit_succeeds() throws IOException { void fileExactlyAtSizeLimit_succeeds() throws IOException {
when(appSettingService.getAppSettings()).thenReturn(
AppSettings.builder()
.maxFileUploadSizeInMb(5)
.build()
);
BufferedImage image = createTestImage(100, 100); BufferedImage image = createTestImage(100, 100);
byte[] imageBytes = imageToBytes(image); byte[] imageBytes = imageToBytes(image);
// Ensure it's under 5MB // Ensure it's under 5MB
@@ -1049,6 +1073,12 @@ class FileServiceTest {
@Test @Test
void caseInsensitiveMimeType_succeeds() throws IOException { void caseInsensitiveMimeType_succeeds() throws IOException {
when(appSettingService.getAppSettings()).thenReturn(
AppSettings.builder()
.maxFileUploadSizeInMb(5)
.build()
);
BufferedImage image = createTestImage(100, 100); BufferedImage image = createTestImage(100, 100);
byte[] imageBytes = imageToBytes(image); byte[] imageBytes = imageToBytes(image);
MockMultipartFile file = new MockMultipartFile( MockMultipartFile file = new MockMultipartFile(
@@ -1083,6 +1113,12 @@ class FileServiceTest {
@Test @Test
void mimeTypeWithExtraParameters_succeeds() throws IOException { void mimeTypeWithExtraParameters_succeeds() throws IOException {
when(appSettingService.getAppSettings()).thenReturn(
AppSettings.builder()
.maxFileUploadSizeInMb(5)
.build()
);
BufferedImage image = createTestImage(100, 100); BufferedImage image = createTestImage(100, 100);
byte[] imageBytes = imageToBytes(image); byte[] imageBytes = imageToBytes(image);
MockMultipartFile file = new MockMultipartFile( MockMultipartFile file = new MockMultipartFile(