fix(upload): truncate long filenames to safe length while preserving extension for bookdrop and additional files (#2059)
Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
+8
-6
@@ -89,28 +89,29 @@ public class FileUploadService {
|
||||
public AdditionalFile uploadAdditionalFile(Long bookId, MultipartFile file, AdditionalFileType additionalFileType, String description) {
|
||||
final BookEntity book = findBookById(bookId);
|
||||
final String originalFileName = getValidatedFileName(file);
|
||||
final String sanitizedFileName = PathPatternResolver.truncateFilenameWithExtension(originalFileName);
|
||||
|
||||
Path tempPath = null;
|
||||
try {
|
||||
tempPath = createTempFile(UPLOAD_TEMP_PREFIX, originalFileName);
|
||||
tempPath = createTempFile(UPLOAD_TEMP_PREFIX, sanitizedFileName);
|
||||
file.transferTo(tempPath);
|
||||
|
||||
final String fileHash = FileFingerprint.generateHash(tempPath);
|
||||
validateAlternativeFormatDuplicate(additionalFileType, fileHash);
|
||||
|
||||
final Path finalPath = buildAdditionalFilePath(book, originalFileName);
|
||||
final Path finalPath = buildAdditionalFilePath(book, sanitizedFileName);
|
||||
validateFinalPath(finalPath);
|
||||
moveFileToFinalLocation(tempPath, finalPath);
|
||||
|
||||
log.info("Additional file uploaded to final location: {}", finalPath);
|
||||
|
||||
final BookAdditionalFileEntity entity = createAdditionalFileEntity(book, originalFileName, additionalFileType, file.getSize(), fileHash, description);
|
||||
final BookAdditionalFileEntity entity = createAdditionalFileEntity(book, sanitizedFileName, additionalFileType, file.getSize(), fileHash, description);
|
||||
final BookAdditionalFileEntity savedEntity = additionalFileRepository.save(entity);
|
||||
|
||||
return additionalFileMapper.toAdditionalFile(savedEntity);
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to upload additional file for book {}: {}", bookId, originalFileName, e);
|
||||
log.error("Failed to upload additional file for book {}: {}", bookId, sanitizedFileName, e);
|
||||
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
|
||||
} finally {
|
||||
cleanupTempFile(tempPath);
|
||||
@@ -124,13 +125,14 @@ public class FileUploadService {
|
||||
Files.createDirectories(dropFolder);
|
||||
|
||||
final String originalFilename = getValidatedFileName(file);
|
||||
final String sanitizedFilename = PathPatternResolver.truncateFilenameWithExtension(originalFilename);
|
||||
Path tempPath = null;
|
||||
|
||||
try {
|
||||
tempPath = createTempFile(BOOKDROP_TEMP_PREFIX, originalFilename);
|
||||
tempPath = createTempFile(BOOKDROP_TEMP_PREFIX, sanitizedFilename);
|
||||
file.transferTo(tempPath);
|
||||
|
||||
final Path finalPath = dropFolder.resolve(originalFilename);
|
||||
final Path finalPath = dropFolder.resolve(sanitizedFilename);
|
||||
validateFinalPath(finalPath);
|
||||
Files.move(tempPath, finalPath);
|
||||
|
||||
|
||||
@@ -238,7 +238,7 @@ public class PathPatternResolver {
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private String truncatePathComponent(String component, int maxBytes) {
|
||||
public String truncatePathComponent(String component, int maxBytes) {
|
||||
if (component == null || component.isEmpty()) {
|
||||
return component;
|
||||
}
|
||||
@@ -288,7 +288,7 @@ public class PathPatternResolver {
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private String truncateFilenameWithExtension(String filename) {
|
||||
public String truncateFilenameWithExtension(String filename) {
|
||||
int lastDotIndex = filename.lastIndexOf('.');
|
||||
if (lastDotIndex == -1 || lastDotIndex == 0) {
|
||||
// No extension or dot is at start (hidden file), treat as normal component
|
||||
|
||||
+52
@@ -306,4 +306,56 @@ class FileUploadServiceTest {
|
||||
|
||||
assertDoesNotThrow(() -> service.uploadFile(file, 10L, 3L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should truncate long filenames in uploadFileBookDrop")
|
||||
void uploadFileBookDrop_truncatesLongFilename() throws IOException {
|
||||
byte[] content = "data".getBytes();
|
||||
String longName = "A".repeat(300) + ".pdf";
|
||||
MockMultipartFile file = new MockMultipartFile("file", longName, "application/pdf", content);
|
||||
|
||||
service.uploadFileBookDrop(file);
|
||||
|
||||
File[] files = tempDir.toFile().listFiles();
|
||||
assertThat(files).isNotNull();
|
||||
assertThat(files).hasSize(1);
|
||||
String savedName = files[0].getName();
|
||||
|
||||
assertThat(savedName.length()).isLessThan(longName.length());
|
||||
assertThat(savedName).endsWith(".pdf");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should truncate long filenames in uploadAdditionalFile")
|
||||
void uploadAdditionalFile_truncatesLongFilename() {
|
||||
long bookId = 11L;
|
||||
String longName = "B".repeat(300) + ".pdf";
|
||||
MockMultipartFile file = new MockMultipartFile("file", longName, "application/pdf", "payload".getBytes());
|
||||
|
||||
LibraryPathEntity libPath = new LibraryPathEntity();
|
||||
libPath.setId(1L);
|
||||
libPath.setPath(tempDir.toString());
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(bookId);
|
||||
book.setLibraryPath(libPath);
|
||||
book.setFileSubPath(".");
|
||||
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
|
||||
when(bookAdditionalFileRepository.save(any(BookAdditionalFileEntity.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(additionalFileMapper.toAdditionalFile(any(BookAdditionalFileEntity.class))).thenReturn(mock(AdditionalFile.class));
|
||||
|
||||
try (MockedStatic<FileFingerprint> fp = mockStatic(FileFingerprint.class)) {
|
||||
fp.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash");
|
||||
|
||||
service.uploadAdditionalFile(bookId, file, AdditionalFileType.ALTERNATIVE_FORMAT, "desc");
|
||||
|
||||
File[] files = tempDir.toFile().listFiles();
|
||||
assertThat(files).isNotNull();
|
||||
assertThat(files).hasSize(1);
|
||||
String savedName = files[0].getName();
|
||||
|
||||
assertThat(savedName.length()).isLessThan(longName.length());
|
||||
assertThat(savedName).endsWith(".pdf");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+62
@@ -821,4 +821,66 @@ class PathPatternResolverTest {
|
||||
MAX_AUTHORS_BYTES, authorsBytes));
|
||||
assertTrue(authorsPart.contains("et al."), "Should add 'et al.' when truncating");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should truncate long filename while preserving extension")
|
||||
void testTruncateFilenameWithExtension_truncatesLongFilename() {
|
||||
String longName = "A".repeat(300);
|
||||
String extension = ".pdf";
|
||||
String filename = longName + extension;
|
||||
|
||||
String result = PathPatternResolver.truncateFilenameWithExtension(filename);
|
||||
|
||||
assertTrue(result.length() < filename.length(), "Filename should be truncated");
|
||||
assertTrue(result.endsWith(extension), "Extension should be preserved");
|
||||
assertTrue(result.getBytes(StandardCharsets.UTF_8).length <= MAX_FILENAME_BYTES,
|
||||
"Result bytes should be <= " + MAX_FILENAME_BYTES);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not truncate short filename")
|
||||
void testTruncateFilenameWithExtension_shortFilename() {
|
||||
String filename = "short_filename.pdf";
|
||||
String result = PathPatternResolver.truncateFilenameWithExtension(filename);
|
||||
|
||||
assertEquals(filename, result, "Short filename should not be modified");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should truncate filename without extension if too long")
|
||||
void testTruncateFilenameWithExtension_noExtension() {
|
||||
String longName = "A".repeat(300);
|
||||
String result = PathPatternResolver.truncateFilenameWithExtension(longName);
|
||||
|
||||
assertTrue(result.length() < longName.length(), "Filename should be truncated");
|
||||
assertTrue(result.getBytes(StandardCharsets.UTF_8).length <= MAX_FILENAME_BYTES,
|
||||
"Result bytes should be <= " + MAX_FILENAME_BYTES);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle long unicode filename with extension")
|
||||
void testTruncateFilenameWithExtension_unicode() {
|
||||
String longName = "测试".repeat(100); // 600 bytes
|
||||
String extension = ".txt";
|
||||
String filename = longName + extension;
|
||||
|
||||
String result = PathPatternResolver.truncateFilenameWithExtension(filename);
|
||||
|
||||
assertTrue(result.length() < filename.length(), "Filename should be truncated");
|
||||
assertTrue(result.endsWith(extension), "Extension should be preserved");
|
||||
assertTrue(result.getBytes(StandardCharsets.UTF_8).length <= MAX_FILENAME_BYTES,
|
||||
"Result bytes should be <= " + MAX_FILENAME_BYTES);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle hidden files (starting with dot)")
|
||||
void testTruncateFilenameWithExtension_hiddenFile() {
|
||||
String longName = ".config" + "A".repeat(300);
|
||||
|
||||
String result = PathPatternResolver.truncateFilenameWithExtension(longName);
|
||||
|
||||
assertTrue(result.startsWith(".config"), "Should still start with .config (or be treated as filename)");
|
||||
assertTrue(result.getBytes(StandardCharsets.UTF_8).length <= MAX_FILENAME_BYTES,
|
||||
"Result bytes should be <= " + MAX_FILENAME_BYTES);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user